Skip to content

scikit-bio

scikit-bio β€” sequence analysis, alignment, community diversity, ordination and phylogenetics

Connector software
Free and open source
Service credentials
Not needed
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/scikit-bio/index.md to help me query scikit-bio with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Compare GC content across DNA sequences

Example output Β· captured
Connector release
v0.4.1
Engine
2.0.1
VGI protocol
3.4.0
SELECT name, sequence, skbio.sequence.gc_content(sequence) AS gc_fraction
FROM (VALUES ('Sample A', 'ATGCGGATTACAGG'), ('Sample B', 'GCGCGCAATT'), ('Sample C', 'ATATATGC')) AS samples(name, sequence);
Result
name sequence gc_fraction
Sample A ATGCGGATTACAGG 0.5
Sample B GCGCGCAATT 0.6
Sample C ATATATGC 0.25

Quick start

Choose where to run scikit-bio, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

ATTACH 'skbio' AS skbio (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/[email protected] vgi-scikit-bio'
);

3. Run a query

query.sql
SELECT name, sequence, skbio.sequence.gc_content(sequence) AS gc_fraction
FROM (VALUES ('Sample A', 'ATGCGGATTACAGG'), ('Sample B', 'GCGCGCAATT'), ('Sample C', 'ATATATGC')) AS samples(name, sequence);
More example queries β†’
Technical details
Verified connector release
v0.4.1
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

ATTACH 'skbio' AS skbio (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/[email protected] vgi-scikit-bio'
);

Overview

scikit-bio for SQL: sequence analysis, community diversity, ordination, and phylogenetics in DuckDB

Catalog

Everything skbio exposes once attached β€” read straight from the worker's released build.

skbio 5 schemas
alignment 4 functions

Pairwise sequence alignment: scores and aligned strings.

Schema examples (2)
Examples (2)

Global alignment score of two DNA sequences

SELECT skbio.alignment.align_score_nucleotide('ACTGGT', 'ACTGT');

Percent identity of each read against its reference: align the pair, then count the identical columns of the two aligned strings with match_count and divide by the aligned length. r3 is a perfect match (1.0); r1 and r2 both reach 0.9, and has_gaps on the aligned strings tells them apart -- r1 lost a base (an indel), r2 carries a substitution.

SELECT a.read_id, a.aligned_1, a.aligned_2,
  round(skbio.sequence.match_count(a.aligned_1, a.aligned_2) / a.length, 4) AS identity,
  skbio.sequence.has_gaps(a.aligned_1) OR skbio.sequence.has_gaps(a.aligned_2) AS has_indel
FROM skbio.alignment.pairwise_align_nucleotide((SELECT * FROM (VALUES ('r1', 'ACTGGTACCA', 'ACTGTACCA'), ('r2', 'GATTACAGAT', 'GATTCCAGAT'), ('r3', 'TTGACCGTAA', 'TTGACCGTAA')) AS p(read_id, ref, read)), id := 'read_id', seq1 := 'ref', seq2 := 'read') AS a
ORDER BY identity DESC, a.read_id;
Scalar functions
align_score_nucleotide (seq1 VARCHAR, seq2 VARCHAR) 1 example

Optimal global alignment score between two DNA sequences

Arguments
seq1 VARCHAR
First DNA sequence
seq2 VARCHAR
Second DNA sequence
ReturnsDOUBLE
Example

Score how similar two DNA sequences are with a full Needleman-Wunsch alignment, which unlike hamming_distance tolerates the differing lengths here by opening a gap. Reach for this when you only need the number -- pairwise_align_nucleotide when you need to see where the gap fell.

SELECT skbio.alignment.align_score_nucleotide('ACTGGT', 'ACTGT') AS score;
Link
align_score_protein (seq1 VARCHAR, seq2 VARCHAR) 1 example

Optimal global alignment score between two protein sequences

Arguments
seq1 VARCHAR
First protein sequence
seq2 VARCHAR
Second protein sequence
ReturnsDOUBLE
Example

Score two protein sequences under a substitution matrix, so chemically similar amino acids cost less than unrelated ones -- the reason protein similarity cannot be measured by counting identities. Use pairwise_align_protein when the alignment itself matters.

SELECT skbio.alignment.align_score_protein('MRITMK', 'MRIMK') AS score;
Link
Table in-out functions
pairwise_align_nucleotide (data TABLE, id := VARCHAR, mode := VARCHAR, seq1 := VARCHAR, seq2 := VARCHAR) 2 examples

Pairwise align two DNA columns; emit aligned strings and score

Positional arguments
data TABLE
An optional id column and two sequence columns.
Named arguments
id := VARCHAR
Optional id column carried onto each row. Β· default ""
mode := VARCHAR
Alignment mode: 'global' or 'local'. Β· default "global"
seq1 := VARCHAR
First sequence column (defaults to the first non-id column). Β· default ""
seq2 := VARCHAR
Second sequence column (defaults to the second non-id column). Β· default ""
Returns columns
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
read_id VARCHAR
The named id column, carried through unchanged.
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
Returns columns Β· depends on the arguments
Default -- no `id :=`
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
With `id := 'read_id'` (a `VARCHAR` id column)
read_id VARCHAR
The named id column, carried through unchanged.
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
Examples (2)

Align each read against its reference and rank the reads by how well they match: the aligned strings show where the gaps ('-') fell, so you can see the indel that the score alone only hints at. Carrying read_id through (id := 'read_id') is what lets the alignment be joined back to the source rows.

SELECT read_id, aligned_1, aligned_2, score, length
FROM skbio.alignment.pairwise_align_nucleotide((SELECT * FROM (VALUES ('r1', 'ACTGGT', 'ACTGT'), ('r2', 'GATTACA', 'GATACA')) AS p(read_id, ref, read)), id := 'read_id', seq1 := 'ref', seq2 := 'read')
ORDER BY score DESC;

Percent identity of each read against its reference: align the pair, then count the identical columns of the two aligned strings with match_count and divide by the aligned length. r3 is a perfect match (1.0); r1 and r2 both reach 0.9, and has_gaps on the aligned strings tells them apart -- r1 lost a base (an indel), r2 carries a substitution.

SELECT a.read_id, a.aligned_1, a.aligned_2,
  round(skbio.sequence.match_count(a.aligned_1, a.aligned_2) / a.length, 4) AS identity,
  skbio.sequence.has_gaps(a.aligned_1) OR skbio.sequence.has_gaps(a.aligned_2) AS has_indel
FROM skbio.alignment.pairwise_align_nucleotide((SELECT * FROM (VALUES ('r1', 'ACTGGTACCA', 'ACTGTACCA'), ('r2', 'GATTACAGAT', 'GATTCCAGAT'), ('r3', 'TTGACCGTAA', 'TTGACCGTAA')) AS p(read_id, ref, read)), id := 'read_id', seq1 := 'ref', seq2 := 'read') AS a
ORDER BY identity DESC, a.read_id;
Link
pairwise_align_protein (data TABLE, id := VARCHAR, mode := VARCHAR, seq1 := VARCHAR, seq2 := VARCHAR) 1 example

Pairwise align two protein columns; emit aligned strings and score

Positional arguments
data TABLE
An optional id column and two sequence columns.
Named arguments
id := VARCHAR
Optional id column carried onto each row. Β· default ""
mode := VARCHAR
Alignment mode: 'global' or 'local'. Β· default "global"
seq1 := VARCHAR
First sequence column (defaults to the first non-id column). Β· default ""
seq2 := VARCHAR
Second sequence column (defaults to the second non-id column). Β· default ""
Returns columns
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
read_id VARCHAR
The named id column, carried through unchanged.
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
Returns columns Β· depends on the arguments
Default -- no `id :=`
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
With `id := 'read_id'` (a `VARCHAR` id column)
read_id VARCHAR
The named id column, carried through unchanged.
aligned_1 VARCHAR
First sequence with alignment gaps ('-').
aligned_2 VARCHAR
Second sequence with alignment gaps ('-').
score DOUBLE
Optimal alignment score.
length BIGINT
Aligned length (number of columns).
Example

Align candidate protein sequences against their references and inspect the gapped alignment beside the score. Comparing an imperfect pair with an identical one shows what a 'good' score looks like for this substitution matrix, which a bare score column cannot tell you.

SELECT read_id, aligned_1, aligned_2, score, length
FROM skbio.alignment.pairwise_align_protein((SELECT * FROM (VALUES ('p1', 'MRITMK', 'MRIMK'), ('p2', 'MKVLAA', 'MKVLAA')) AS p(read_id, ref, read)), id := 'read_id', seq1 := 'ref', seq2 := 'read')
ORDER BY read_id;
Link
diversity 36 functions

Community-ecology diversity from a long (sample, feature, count) table.

Schema examples (2)
Examples (2)

Shannon diversity per sample

SELECT sample_id, skbio.diversity.shannon(count)
FROM (VALUES (1,'a',4),(1,'b',2),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;

Depth-fair alpha diversity: rarefy every sample to 50 counts, then compute richness and Shannon diversity over the rarefied counts in one GROUP BY. Raw, s2 (sequenced about 9x deeper) shows five features to s1's four; at a common depth its rare feature e drops out, both samples show four, and the remaining Shannon gap reflects evenness, not sequencing effort.

SELECT r.sample_id, sum(r.count)::BIGINT AS depth,
  skbio.diversity.observed_features(r.count)::BIGINT AS richness,
  round(skbio.diversity.shannon(r.count), 4) AS shannon
FROM skbio.diversity.subsample_counts((SELECT * FROM (VALUES ('s1','a',40),('s1','b',30),('s1','c',2),('s1','d',1),('s2','a',300),('s2','b',200),('s2','c',90),('s2','d',60),('s2','e',5)) AS t(sample_id, feature_id, count)), depth := 50) AS r
GROUP BY r.sample_id
ORDER BY r.sample_id;
Aggregate functions
ace (abundance DOUBLE) 1 example

ace alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with ace in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the abundance-based coverage estimator of total richness, weighting the contribution of rare features. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.ace(count) AS ace
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
berger_parker_d (abundance DOUBLE) 1 example

berger_parker_d alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with berger_parker_d in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the proportional abundance of the single most abundant feature (Berger-Parker dominance). Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.berger_parker_d(count) AS berger_parker_d
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
brillouin_d (abundance DOUBLE) 1 example

brillouin_d alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with brillouin_d in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Brillouin's index, an entropy diversity for a fully-censused (not sampled) community. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.brillouin_d(count) AS brillouin_d
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
chao1 (abundance DOUBLE) 1 example

chao1 alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with chao1 in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It corrects observed richness with the singleton and doubleton counts to estimate unseen features. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.chao1(count) AS chao1
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
chao1_ci (abundance DOUBLE) 1 example

chao1_ci alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE[]
Example

Score two communities with chao1_ci in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the confidence interval around the Chao1 richness estimate, as [lower, upper]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.chao1_ci(count) AS chao1_ci
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
dominance (abundance DOUBLE) 1 example

dominance alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with dominance in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the chance two random individuals share a feature (Simpson's D); higher means a few dominate. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.dominance(count) AS dominance
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
doubles (abundance DOUBLE) 1 example

doubles alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with doubles in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the number of features observed exactly twice (doubletons). Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.doubles(count) AS doubles
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
enspie (abundance DOUBLE) 1 example

enspie alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with enspie in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the effective species count from the probability of interspecific encounter (= inverse Simpson). Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.enspie(count) AS enspie
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
esty_ci (abundance DOUBLE) 1 example

esty_ci alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE[]
Example

Score two communities with esty_ci in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Esty's confidence interval for the community coverage, as [lower, upper]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.esty_ci(count) AS esty_ci
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
fisher_alpha (abundance DOUBLE) 1 example

fisher_alpha alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with fisher_alpha in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Fisher's alpha, the parameter of the log-series model fitted to the abundance distribution. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.fisher_alpha(count) AS fisher_alpha
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
gini_index (abundance DOUBLE) 1 example

gini_index alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with gini_index in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the Gini coefficient of the abundance distribution β€” the inequality of abundances, in [0, 1]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.gini_index(count) AS gini_index
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
goods_coverage (abundance DOUBLE) 1 example

goods_coverage alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with goods_coverage in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Good's coverage estimate: the estimated proportion of the community that has actually been observed. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.goods_coverage(count) AS goods_coverage
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
heip_evenness (abundance DOUBLE) 1 example

heip_evenness alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with heip_evenness in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Heip's evenness index, a richness-corrected evenness in [0, 1]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.heip_evenness(count) AS heip_evenness
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
hill (abundance DOUBLE, q DOUBLE) 1 example

hill alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
q DOUBLE
Diversity order (0 = richness, 1 = Shannon-like, 2 = Simpson-like)
ReturnsDOUBLE
Example

Score two communities with hill in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the Hill number of order q (effective feature count): q=0 richness, q~1 exp(Shannon), q=2 inv-Simpson. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table. The diversity order `q` (2nd positional arg) is what tunes the metric: q = 0 counts features equally, higher q weights the abundant ones more.

SELECT sample_id, skbio.diversity.hill(count, 1) AS hill
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
inv_simpson (abundance DOUBLE) 1 example

inv_simpson alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with inv_simpson in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the reciprocal of Simpson's dominance β€” the effective number of equally-abundant features. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.inv_simpson(count) AS inv_simpson
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
kempton_taylor_q (abundance DOUBLE) 1 example

kempton_taylor_q alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with kempton_taylor_q in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the Kempton-Taylor Q index, the slope of the ranked log-abundance curve between its quartiles. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id,
  skbio.diversity.kempton_taylor_q(count) AS kempton_taylor_q
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
margalef (abundance DOUBLE) 1 example

margalef alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with margalef in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Margalef's richness index: richness scaled by the natural log of the total count. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.margalef(count) AS margalef
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
mcintosh_d (abundance DOUBLE) 1 example

mcintosh_d alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with mcintosh_d in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is McIntosh's dominance index, based on the Euclidean norm of the abundance vector. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.mcintosh_d(count) AS mcintosh_d
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
mcintosh_e (abundance DOUBLE) 1 example

mcintosh_e alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with mcintosh_e in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is McIntosh's evenness index, in [0, 1]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.mcintosh_e(count) AS mcintosh_e
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
menhinick (abundance DOUBLE) 1 example

menhinick alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with menhinick in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Menhinick's richness index: richness divided by the square root of the total count. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.menhinick(count) AS menhinick
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
observed_features (abundance DOUBLE) 1 example

observed_features alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with observed_features in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is plain richness: the number of features with a non-zero abundance. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id,
  skbio.diversity.observed_features(count) AS observed_features
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
osd (abundance DOUBLE) 1 example

osd alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE[]
Example

Score two communities with osd in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the (observed richness, singletons, doubletons) triple used by richness estimators. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.osd(count) AS osd
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
pielou_evenness (abundance DOUBLE) 1 example

pielou_evenness alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with pielou_evenness in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Shannon diversity over its maximum, measuring how evenly abundance spreads, in [0, 1]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.pielou_evenness(count) AS pielou_evenness
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
renyi (abundance DOUBLE, q DOUBLE) 1 example

renyi alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
q DOUBLE
Diversity order (0 = richness, 1 = Shannon-like, 2 = Simpson-like)
ReturnsDOUBLE
Example

Score two communities with renyi in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the Renyi entropy of order q, a family of diversity indices generalising richness/Shannon/Simpson. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table. The diversity order `q` (2nd positional arg) is what tunes the metric: q = 0 counts features equally, higher q weights the abundant ones more.

SELECT sample_id, skbio.diversity.renyi(count, 1) AS renyi
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
robbins (abundance DOUBLE) 1 example

robbins alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with robbins in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the Robbins estimator of the probability that the next individual sampled belongs to an unseen feature. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.robbins(count) AS robbins
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
shannon (abundance DOUBLE) 1 example

shannon alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with shannon in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the entropy of the abundance distribution (natural log); higher means richer and more even. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.shannon(count) AS shannon
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
simpson (abundance DOUBLE) 1 example

simpson alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with simpson in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the chance two random individuals belong to different features (1 minus dominance), in [0, 1]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.simpson(count) AS simpson
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
simpson_d (abundance DOUBLE) 1 example

simpson_d alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with simpson_d in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Simpson's dominance index D, the probability that two individuals share a feature. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.simpson_d(count) AS simpson_d
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
simpson_e (abundance DOUBLE) 1 example

simpson_e alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with simpson_e in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Simpson's evenness, the inverse-Simpson diversity divided by richness, in [0, 1]. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.simpson_e(count) AS simpson_e
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
singles (abundance DOUBLE) 1 example

singles alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with singles in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the number of features observed exactly once (singletons). Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.singles(count) AS singles
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
strong (abundance DOUBLE) 1 example

strong alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
ReturnsDOUBLE
Example

Score two communities with strong in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is Strong's dominance index (DW): the peak departure of the cumulative-abundance curve from evenness. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table.

SELECT sample_id, skbio.diversity.strong(count) AS strong
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
tsallis (abundance DOUBLE, q DOUBLE) 1 example

tsallis alpha-diversity metric over one sample's feature counts

Arguments
abundance DOUBLE
Abundance value for one (sample, feature) cell
q DOUBLE
Diversity order (0 = richness, 1 = Shannon-like, 2 = Simpson-like)
ReturnsDOUBLE
Example

Score two communities with tsallis in a single GROUP BY: sample 1 spreads 7 counts over three features, sample 2 puts 9 of its 10 into one, and the metric is what separates them. It is the Tsallis entropy of order q, a non-extensive generalisation of Shannon entropy. Being an aggregate rather than a table function is the point β€” one query scores every sample in the table. The diversity order `q` (2nd positional arg) is what tunes the metric: q = 0 counts features equally, higher q weights the abundant ones more.

SELECT sample_id, skbio.diversity.tsallis(count, 1) AS tsallis
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;
Link
Table in-out functions
beta_diversity (data TABLE, count := VARCHAR, feature := VARCHAR, metric := VARCHAR, sample := VARCHAR) 1 example

Between-sample distance matrix from a long feature table (long output)

Positional arguments
data TABLE
One row per (sample_id, feature_id, count).
Named arguments
count := VARCHAR
Abundance-count column (defaults to the third column). Β· default ""
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
metric := VARCHAR
Distance metric (e.g. braycurtis, jaccard). Β· default "braycurtis"
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
Returns columns
id_1 VARCHAR
First sample id.
id_2 VARCHAR
Second sample id.
distance DOUBLE
Distance between the two samples under the chosen metric.
Example

Rank the sample pairs from most to least similar under Bray-Curtis. The id_1 < id_2 filter keeps one row per unordered pair (the function emits the full square matrix, diagonal included) β€” drop the filter when feeding pcoa, permanova, or a tree builder, all of which want the whole matrix.

SELECT id_1, id_2, round(distance, 4) AS distance
FROM skbio.diversity.beta_diversity((SELECT * FROM (VALUES (1,'a',4),(1,'b',2),(2,'a',1),(2,'b',9),(3,'a',0),(3,'b',5)) AS t(sample_id, feature_id, count)), metric := 'braycurtis')
WHERE id_1 < id_2
ORDER BY distance;
Link
faith_pd (data TABLE, count := VARCHAR, feature := VARCHAR, sample := VARCHAR, tree := VARCHAR) 1 example

Faith's phylogenetic diversity per sample (needs a tree)

Positional arguments
data TABLE
One row per (sample_id, feature_id, count).
Named arguments
count := VARCHAR
Abundance-count column (defaults to the third column). Β· default ""
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
tree := VARCHAR
Newick tree whose tips match the feature ids. Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
faith_pd DOUBLE
Total branch length of the features present in the sample.
Example

Rank samples by how much evolutionary history they contain, not just how many features they have. s3 holds one feature from each clade and so spans more of the tree than s1 or s2, whose two features are siblings -- the distinction plain richness cannot make and the reason to pass a tree at all.

SELECT sample_id, round(faith_pd, 4) AS faith_pd
FROM skbio.diversity.faith_pd((SELECT * FROM (VALUES ('s1','f1',1),('s1','f2',1),('s2','f3',1),('s2','f4',1),('s3','f1',1),('s3','f3',1)) AS t(sample_id, feature_id, count)), tree := '((f1:0.1,f2:0.2):0.3,(f3:0.15,f4:0.25):0.35);')
ORDER BY faith_pd DESC;
Link
subsample_counts (data TABLE, count := VARCHAR, depth := BIGINT, feature := VARCHAR, sample := VARCHAR, seed := BIGINT, with_replacement := BOOLEAN) 2 examples

Rarefy each sample's feature counts to a fixed depth (long output)

Positional arguments
data TABLE
One row per (sample_id, feature_id, count).
Named arguments
count := VARCHAR
Abundance-count column (defaults to the third column). Β· default ""
depth := BIGINT
Number of counts to draw per sample (rarefaction depth). Β· default 0
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
seed := BIGINT
Random seed (fixed for reproducibility). Β· default 0
with_replacement := BOOLEAN
Sample with replacement. Β· default false
Returns columns
sample_id VARCHAR
Sample id.
feature_id VARCHAR
Feature id.
count BIGINT
Rarefied count (sums to the requested depth per sample).
Examples (2)

Level two samples sequenced to different depths (12 and 20 counts) down to a common 8, so a later richness or diversity comparison measures biology rather than sequencing effort. Every sample's counts now sum to 8; run this before the alpha metrics, which are all depth-sensitive.

SELECT sample_id, feature_id, count
FROM skbio.diversity.subsample_counts((SELECT * FROM (VALUES ('s1','a',4),('s1','b',2),('s1','c',6),('s2','a',10),('s2','b',5),('s2','c',5)) AS t(sample_id, feature_id, count)), depth := 8)
ORDER BY sample_id, feature_id;

Depth-fair alpha diversity: rarefy every sample to 50 counts, then compute richness and Shannon diversity over the rarefied counts in one GROUP BY. Raw, s2 (sequenced about 9x deeper) shows five features to s1's four; at a common depth its rare feature e drops out, both samples show four, and the remaining Shannon gap reflects evenness, not sequencing effort.

SELECT r.sample_id, sum(r.count)::BIGINT AS depth,
  skbio.diversity.observed_features(r.count)::BIGINT AS richness,
  round(skbio.diversity.shannon(r.count), 4) AS shannon
FROM skbio.diversity.subsample_counts((SELECT * FROM (VALUES ('s1','a',40),('s1','b',30),('s1','c',2),('s1','d',1),('s2','a',300),('s2','b',200),('s2','c',90),('s2','d',60),('s2','e',5)) AS t(sample_id, feature_id, count)), depth := 50) AS r
GROUP BY r.sample_id
ORDER BY r.sample_id;
Link
unifrac (data TABLE, count := VARCHAR, feature := VARCHAR, sample := VARCHAR, tree := VARCHAR, weighted := BOOLEAN) 1 example

UniFrac phylogenetic distance matrix between samples (needs a tree)

Positional arguments
data TABLE
One row per (sample_id, feature_id, count).
Named arguments
count := VARCHAR
Abundance-count column (defaults to the third column). Β· default ""
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
tree := VARCHAR
Newick tree whose tips match the feature ids. Β· default ""
weighted := BOOLEAN
Weight by abundance (weighted UniFrac). Β· default false
Returns columns
id_1 VARCHAR
First sample id.
id_2 VARCHAR
Second sample id.
distance DOUBLE
UniFrac distance between the two samples.
Example

Order sample pairs by how much evolutionary history they fail to share. Unlike Bray-Curtis, two samples holding different-but-closely-related features come out close together here, which is why UniFrac is the default beta metric for 16S data. Keep the full matrix (drop the filter) to feed pcoa or permanova.

SELECT id_1, id_2, round(distance, 4) AS distance
FROM skbio.diversity.unifrac((SELECT * FROM (VALUES ('s1','f1',1),('s1','f2',1),('s2','f3',1),('s2','f4',1),('s3','f1',1),('s3','f3',1)) AS t(sample_id, feature_id, count)), tree := '((f1:0.1,f2:0.2):0.3,(f3:0.15,f4:0.25):0.35);')
WHERE id_1 < id_2
ORDER BY distance;
Link
sequence 20 functions

Analyze DNA, RNA, and protein sequences held in VARCHAR columns.

Schema examples (3)
Examples (3)

GC content of a DNA sequence

SELECT skbio.sequence.gc_content('ATGCGGATTACAGG');

Classify point mutations in a coding sequence as synonymous or not: each variant changes exactly one base, translate both alleles, and score the two proteins with align_score_protein. v1 (CGG->CGT) still codes arginine, so the protein is unchanged and keeps the full score; v2 swaps threonine for proline and v3 arginine for tryptophan, and the substitution-matrix score drops further for the more radical change.

SELECT variant, skbio.sequence.mismatch_count(ref, alt) AS base_changes,
  skbio.sequence.translate(ref) AS ref_protein,
  skbio.sequence.translate(alt) AS alt_protein,
  skbio.sequence.translate(ref) = skbio.sequence.translate(alt) AS synonymous,
  skbio.alignment.align_score_protein(skbio.sequence.translate(ref), skbio.sequence.translate(alt)) AS protein_score
FROM (VALUES ('v1', 'ATGCGGATTACAAAA', 'ATGCGTATTACAAAA'), ('v2', 'ATGCGGATTACAAAA', 'ATGCGGATTCCAAAA'), ('v3', 'ATGCGGATTACAAAA', 'ATGTGGATTACAAAA')) AS v(variant, ref, alt)
ORDER BY variant;

Alignment-free read comparison: feed each read's 3-mer profile into beta_diversity as if reads were samples and k-mers were features, and rank the read pairs by Jaccard distance between their k-mer sets. r1 and r2 differ by a single base and share most 3-mers (distance 0.4), while r3 shares almost none with either (about 0.95). The same long distance matrix can go on to pcoa or neighbor_joining.

SELECT id_1, id_2, round(distance, 4) AS distance
FROM skbio.diversity.beta_diversity((SELECT read_id, kmer, count FROM skbio.sequence.kmer_frequencies((SELECT * FROM (VALUES ('r1', 'ATGCGGATTACAGG'), ('r2', 'ATGCGGATTACTGG'), ('r3', 'TTGCACGTTTGCAC')) AS reads(read_id, seq)), id := 'read_id', k := 3)), metric := 'jaccard')
WHERE id_1 < id_2
ORDER BY distance, id_1, id_2;
Scalar functions
complement (seq VARCHAR) 1 example

Complement of a DNA sequence (same 5'->3' order)

Arguments
seq VARCHAR
A DNA sequence
ReturnsVARCHAR
Example

Complement each base while keeping 5'->3' order β€” deliberately *not* the opposite strand. Compare it with reverse_complement on the same input to see the difference that trips people up: only the reversed form is what actually pairs with the original.

SELECT skbio.sequence.complement('ATGCGGATTACAGG') AS comp;
Link
count_subsequence (seq VARCHAR, subsequence VARCHAR) 1 example

Count occurrences of a subsequence within a sequence

Arguments
seq VARCHAR
The sequence to search
subsequence VARCHAR
The subsequence
ReturnsBIGINT
Example

Count how often a motif occurs in a sequence β€” here the ATG start codon, three times. This is the cheap way to screen a table of reads for a restriction site, primer binding site, or repeat before spending an alignment on them.

SELECT skbio.sequence.count_subsequence('ATGCGATGCATG', 'ATG') AS start_codons;
Link
degap (seq VARCHAR) 1 example

Remove gap characters from a sequence

Arguments
seq VARCHAR
A sequence, possibly with gaps
ReturnsVARCHAR
Example

Recover the original sequence from an aligned one by dropping the gap characters an alignment inserted. Run it before length, composition, or k-mer calculations, all of which would otherwise count '-' as if it were a residue.

SELECT skbio.sequence.degap('AC-GT--A') AS ungapped;
Link
gc_content (seq VARCHAR) 1 example

GC content of a DNA sequence as a fraction in [0, 1]

Arguments
seq VARCHAR
A DNA sequence
ReturnsDOUBLE
Example

Profile a read's base composition as a single number in [0, 1]. GC content is the first thing to check when reads look odd: an outlier flags contamination or a different organism, and it drives PCR and melting behaviour. Multiply by 100 for the percentage people usually quote.

SELECT skbio.sequence.gc_content('ATGCGGATTACAGG') AS gc;
Link
gc_frequency (seq VARCHAR) 1 example

Number of G/C bases in a DNA sequence

Arguments
seq VARCHAR
A DNA sequence
ReturnsBIGINT
Example

Count G and C bases outright rather than as a fraction. The raw count is what you want when summing across reads or weighting by length; gc_content gives the same information already divided by the sequence length.

SELECT skbio.sequence.gc_frequency('ATGCGGATTACAGG') AS gc_bases;
Link
hamming_distance (seq1 VARCHAR, seq2 VARCHAR) 1 example

Hamming distance (fraction of differing positions) between two sequences

Arguments
seq1 VARCHAR
First sequence
seq2 VARCHAR
Second sequence (same length as the first)
ReturnsDOUBLE
Example

Score how far a read has drifted from its reference as a length-normalised fraction, so reads of different lengths stay comparable. One substitution in eight bases gives 0.125; multiply by the length to recover the raw mismatch count. Requires equal lengths -- align first if there are indels.

SELECT skbio.sequence.hamming_distance('ACGTACGT', 'ACGAACGT') AS distance;
Link
has_degenerates (seq VARCHAR) 1 example

True if the DNA sequence contains degenerate (ambiguity) codes

Arguments
seq VARCHAR
A DNA sequence
ReturnsBOOLEAN
Example

Flag reads containing ambiguity codes (N, R, Y, ...), i.e. positions the basecaller could not resolve. Filtering these out is a standard quality step before variant calling or exact-match lookups, where an N would otherwise silently fail to match.

SELECT skbio.sequence.has_degenerates('ACGTN') AS ambiguous_read,
  skbio.sequence.has_degenerates('ACGT') AS clean_read;
Link
has_gaps (seq VARCHAR) 1 example

True if the sequence contains gap characters

Arguments
seq VARCHAR
A sequence
ReturnsBOOLEAN
Example

Tell aligned sequences apart from raw ones in a mixed column β€” the gapped row is the one that came out of an alignment. Use it to decide which rows need degap before a length or composition calculation.

SELECT skbio.sequence.has_gaps('AC-GT') AS aligned_row,
  skbio.sequence.has_gaps('ACGT') AS raw_row;
Link
is_reverse_complement (seq1 VARCHAR, seq2 VARCHAR) 1 example

True if the second DNA sequence is the reverse complement of the first

Arguments
seq1 VARCHAR
First DNA sequence
seq2 VARCHAR
Second DNA sequence
ReturnsBOOLEAN
Example

Decide whether two reads are the same sequence seen from opposite strands, in one predicate rather than reverse-complementing one side and comparing. Use it to collapse strand-duplicate reads or to check a primer pair points the right way.

SELECT skbio.sequence.is_reverse_complement('ATGC', 'GCAT') AS same_locus;
Link
is_valid_dna (seq VARCHAR) 1 example

True if the string is a valid IUPAC DNA sequence

Arguments
seq VARCHAR
A candidate DNA sequence
ReturnsBOOLEAN
Example

Screen a text column before running the DNA transforms over it. Contrasting a degenerate-but-valid read (N is a legal IUPAC code) with free text shows where the line is: use it in a WHERE clause so junk rows are filtered rather than silently turning into NULLs downstream.

SELECT skbio.sequence.is_valid_dna('ATGCN') AS looks_like_dna,
  skbio.sequence.is_valid_dna('HELLO') AS looks_like_dna_too;
Link
is_valid_protein (seq VARCHAR) 1 example

True if the string is a valid IUPAC protein sequence

Arguments
seq VARCHAR
A candidate protein sequence
ReturnsBOOLEAN
Example

Check a column really holds amino-acid sequences before feeding the protein aligners. Beware the asymmetry this example hints at: a pure A/C/G/T string is *also* valid protein, so pair this with is_valid_dna when you need to tell the two alphabets apart.

SELECT skbio.sequence.is_valid_protein('MRIT') AS looks_like_protein,
  skbio.sequence.is_valid_protein('ATGC1') AS looks_like_protein_too;
Link
match_count (seq1 VARCHAR, seq2 VARCHAR) 1 example

Number of agreeing positions between two equal-length sequences

Arguments
seq1 VARCHAR
First sequence
seq2 VARCHAR
Second sequence (same length)
ReturnsBIGINT
Example

Count agreeing positions between two equal-length sequences β€” the complement of mismatch_count (the two always sum to the length). Divide by the length for percent identity, the number most similarity thresholds are quoted in.

SELECT skbio.sequence.match_count('ACGTACGT', 'ACGAACGT') AS matches;
Link
mismatch_count (seq1 VARCHAR, seq2 VARCHAR) 1 example

Number of differing positions between two equal-length sequences

Arguments
seq1 VARCHAR
First sequence
seq2 VARCHAR
Second sequence (same length)
ReturnsBIGINT
Example

Count differing positions between a read and its reference as a whole number, which is what edit-distance thresholds are usually expressed in ('accept up to 2 mismatches'). hamming_distance gives the same comparison as a length-normalised fraction.

SELECT skbio.sequence.mismatch_count('ACGTACGT', 'ACGAACGT') AS mismatches;
Link
reverse_complement (seq VARCHAR) 1 example

Reverse complement of a DNA sequence

Arguments
seq VARCHAR
A DNA sequence
ReturnsVARCHAR
Example

Read a sequence off the opposite strand. Sequencing gives reads in either orientation, so normalising with this is what lets two reads of the same locus be compared or deduplicated at all; it is also how a reverse primer is written down.

SELECT skbio.sequence.reverse_complement('ATGCGGATTACAGG') AS rc;
Link
reverse_transcribe (seq VARCHAR) 1 example

Reverse transcribe an RNA sequence to DNA (U -> T)

Arguments
seq VARCHAR
An RNA sequence
ReturnsVARCHAR
Example

Bring RNA-alphabet sequences (U instead of T) back into DNA space so they can be compared against a DNA reference or run through the DNA-only functions. It is the exact inverse of transcribe.

SELECT skbio.sequence.reverse_transcribe('AUGCGGAUUACAGG') AS dna;
Link
transcribe (seq VARCHAR) 1 example

Transcribe a DNA sequence to RNA (T -> U)

Arguments
seq VARCHAR
A DNA sequence
ReturnsVARCHAR
Example

Produce the RNA transcript of a DNA template (every T becomes U). Use it when a downstream tool or reference is written in RNA alphabet, or as the explicit middle step of the DNA -> RNA -> protein chain that translate otherwise does in one hop.

SELECT skbio.sequence.transcribe('ATGCGGATTACAGG') AS rna;
Link
translate (seq VARCHAR) 2 examples

Translate a DNA sequence to protein (standard genetic code)

Arguments
seq VARCHAR
A DNA sequence
ReturnsVARCHAR
Examples (2)

Turn a coding sequence into its amino-acid sequence, reading codons from base 0 with the standard genetic code. Note the trailing base that does not complete a codon is simply dropped -- if the frame is unknown, use translate_six_frames instead of guessing this one.

SELECT skbio.sequence.translate('ATGCGGATTACAGGT') AS protein;

Classify point mutations in a coding sequence as synonymous or not: each variant changes exactly one base, translate both alleles, and score the two proteins with align_score_protein. v1 (CGG->CGT) still codes arginine, so the protein is unchanged and keeps the full score; v2 swaps threonine for proline and v3 arginine for tryptophan, and the substitution-matrix score drops further for the more radical change.

SELECT variant, skbio.sequence.mismatch_count(ref, alt) AS base_changes,
  skbio.sequence.translate(ref) AS ref_protein,
  skbio.sequence.translate(alt) AS alt_protein,
  skbio.sequence.translate(ref) = skbio.sequence.translate(alt) AS synonymous,
  skbio.alignment.align_score_protein(skbio.sequence.translate(ref), skbio.sequence.translate(alt)) AS protein_score
FROM (VALUES ('v1', 'ATGCGGATTACAAAA', 'ATGCGTATTACAAAA'), ('v2', 'ATGCGGATTACAAAA', 'ATGCGGATTCCAAAA'), ('v3', 'ATGCGGATTACAAAA', 'ATGTGGATTACAAAA')) AS v(variant, ref, alt)
ORDER BY variant;
Link
Table in-out functions
kmer_frequencies (data TABLE, id := VARCHAR, k := BIGINT, sequence := VARCHAR) 2 examples

Count overlapping k-mers per sequence (long format)

Positional arguments
data TABLE
An id column and a sequence column.
Named arguments
id := VARCHAR
Optional id column carried onto each emitted row. Β· default ""
k := BIGINT
k-mer length (number of residues per token). Β· default 3
sequence := VARCHAR
Sequence column to tokenize (defaults to the single non-id column). Β· default ""
Returns columns
kmer VARCHAR
A k-length subsequence (token).
count BIGINT
Number of overlapping occurrences in the sequence.
read_id VARCHAR
The named id column, repeated on every row for that sequence.
kmer VARCHAR
A k-length subsequence (token).
count BIGINT
Number of overlapping occurrences in the sequence.
Returns columns Β· depends on the arguments
Default -- no `id :=`
kmer VARCHAR
A k-length subsequence (token).
count BIGINT
Number of overlapping occurrences in the sequence.
With `id := 'read_id'` (a `VARCHAR` id column)
read_id VARCHAR
The named id column, repeated on every row for that sequence.
kmer VARCHAR
A k-length subsequence (token).
count BIGINT
Number of overlapping occurrences in the sequence.
Examples (2)

Profile the 3-mer composition of each read, most frequent k-mer first. This is the building block of alignment-free comparison: the long (read, kmer, count) output PIVOTs straight into a feature matrix for clustering or taxonomic classification.

SELECT read_id, kmer, count
FROM skbio.sequence.kmer_frequencies((SELECT * FROM (VALUES ('r1', 'ATGCGGATTACAGG'), ('r2', 'TTGCACGT')) AS reads(read_id, seq)), id := 'read_id', k := 3)
ORDER BY read_id, count DESC, kmer;

Alignment-free read comparison: feed each read's 3-mer profile into beta_diversity as if reads were samples and k-mers were features, and rank the read pairs by Jaccard distance between their k-mer sets. r1 and r2 differ by a single base and share most 3-mers (distance 0.4), while r3 shares almost none with either (about 0.95). The same long distance matrix can go on to pcoa or neighbor_joining.

SELECT id_1, id_2, round(distance, 4) AS distance
FROM skbio.diversity.beta_diversity((SELECT read_id, kmer, count FROM skbio.sequence.kmer_frequencies((SELECT * FROM (VALUES ('r1', 'ATGCGGATTACAGG'), ('r2', 'ATGCGGATTACTGG'), ('r3', 'TTGCACGTTTGCAC')) AS reads(read_id, seq)), id := 'read_id', k := 3)), metric := 'jaccard')
WHERE id_1 < id_2
ORDER BY distance, id_1, id_2;
Link
residue_frequencies (data TABLE, id := VARCHAR, sequence := VARCHAR) 1 example

Count single residues (bases or amino acids) per sequence (long format)

Positional arguments
data TABLE
An id column and a sequence column.
Named arguments
id := VARCHAR
Optional id column carried onto each emitted row. Β· default ""
sequence := VARCHAR
Sequence column to tokenize (defaults to the single non-id column). Β· default ""
Returns columns
residue VARCHAR
A single residue (base or amino acid).
count BIGINT
Number of occurrences in the sequence.
read_id VARCHAR
The named id column, repeated on every row for that sequence.
residue VARCHAR
A single residue (base or amino acid).
count BIGINT
Number of occurrences in the sequence.
Returns columns Β· depends on the arguments
Default -- no `id :=`
residue VARCHAR
A single residue (base or amino acid).
count BIGINT
Number of occurrences in the sequence.
With `id := 'read_id'` (a `VARCHAR` id column)
read_id VARCHAR
The named id column, repeated on every row for that sequence.
residue VARCHAR
A single residue (base or amino acid).
count BIGINT
Number of occurrences in the sequence.
Example

Break each read down into its per-base counts, in alphabetical order so the two reads line up column-for-column. Reading the A/C/G/T counts side by side is how you spot a skewed or low-complexity read before it distorts a downstream analysis.

SELECT read_id, residue, count
FROM skbio.sequence.residue_frequencies((SELECT * FROM (VALUES ('r1', 'ATGCGGATTACAGG'), ('r2', 'TTGCACGT')) AS reads(read_id, seq)), id := 'read_id')
ORDER BY read_id, residue;
Link
translate_six_frames (data TABLE, id := VARCHAR, sequence := VARCHAR) 1 example

Translate each DNA sequence in all six reading frames (long format)

Positional arguments
data TABLE
An id column and a sequence column.
Named arguments
id := VARCHAR
Optional id column carried onto each emitted row. Β· default ""
sequence := VARCHAR
Sequence column to tokenize (defaults to the single non-id column). Β· default ""
Returns columns
frame VARCHAR
Reading frame: +1/+2/+3 (forward) or -1/-2/-3 (reverse).
protein VARCHAR
The amino-acid translation for that frame (stops as '*').
read_id VARCHAR
The named id column, repeated on every row for that sequence.
frame VARCHAR
Reading frame: +1/+2/+3 (forward) or -1/-2/-3 (reverse).
protein VARCHAR
The amino-acid translation for that frame (stops as '*').
Returns columns Β· depends on the arguments
Default -- no `id :=`
frame VARCHAR
Reading frame: +1/+2/+3 (forward) or -1/-2/-3 (reverse).
protein VARCHAR
The amino-acid translation for that frame (stops as '*').
With `id := 'read_id'` (a `VARCHAR` id column)
read_id VARCHAR
The named id column, repeated on every row for that sequence.
frame VARCHAR
Reading frame: +1/+2/+3 (forward) or -1/-2/-3 (reverse).
protein VARCHAR
The amino-acid translation for that frame (stops as '*').
Example

Translate a read in all six reading frames and surface the stop-codon-free ones first β€” the practical way to find the open reading frame when the coding strand and offset are unknown. The residue count shows how long each candidate peptide is.

SELECT read_id, frame, protein, length(protein) AS residues
FROM skbio.sequence.translate_six_frames((SELECT * FROM (VALUES ('r1', 'ATGCGGATTACAGG')) AS reads(read_id, seq)), id := 'read_id')
ORDER BY protein NOT LIKE '%*%' DESC, frame;
Link
stats 20 functions

Ordination, distance-matrix hypothesis tests, and compositional transforms.

Schema examples (1)
Example

PCoA of a distance matrix

SELECT sample_id, round(pc_1, 4) AS pc_1, round(pc_2, 4) AS pc_2
FROM skbio.stats.pcoa((SELECT * FROM (VALUES ('a','a',0.0),('a','b',0.5),('a','c',0.7),('b','a',0.5),('b','b',0.0),('b','c',0.6),('c','a',0.7),('c','b',0.6),('c','c',0.0)) AS d(id_1, id_2, distance)), n_components := 2)
ORDER BY sample_id;
Table in-out functions
alr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, ref_idx := BIGINT, sample := VARCHAR, value := VARCHAR) 1 example

Additive log-ratio (ALR) transform of a long feature table (D-1 components)

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform. Β· default 0.0
ref_idx := BIGINT
Index of the reference part (0-based, sorted features). Β· default 0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
component BIGINT
ALR component index (1..D-1).
value DOUBLE
Log-ratio value.
Example

Express every part as a log-ratio against one chosen reference feature (here the first by sorted order, via the default ref_idx := 0). Use alr rather than clr or ilr when a genuine reference exists β€” a spike-in, a housekeeping gene β€” because then the coordinates stay directly interpretable.

SELECT sample_id, component, round(value, 4) AS value
FROM skbio.stats.alr((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)))
ORDER BY sample_id, component;
Link
alr_inv (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, ref_idx := BIGINT, sample := VARCHAR, value := VARCHAR) 1 example

alr_inv: inverse compositional transform back to proportions

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform. Β· default 0.0
ref_idx := BIGINT
Index of the reference part (0-based, sorted features). Β· default 0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature BIGINT
Output part index (1-based).
value DOUBLE
Proportion (parts sum to 1 per sample).
Example

Recover the proportions behind D-1 additive log-ratios, restoring the reference part that alr divided everything by. Use the same ref_idx := you transformed with, or the parts come back permuted.

SELECT sample_id, feature, round(value, 6) AS value
FROM skbio.stats.alr_inv((SELECT * FROM (VALUES ('s1',1,0.1),('s1',2,-0.2),('s2',1,0.3),('s2',2,-0.1)) AS t(sample_id, coordinate, value)))
ORDER BY sample_id, feature;
Link
ancom (data TABLE, feature := VARCHAR, group := VARCHAR, sample := VARCHAR, value := VARCHAR) 1 example

ANCOM differential-abundance test per feature between groups

Positional arguments
data TABLE
One row per (sample_id, feature_id, count, group).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
group := VARCHAR
Group label of the sample (defaults to the fourth column). Β· default ""
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Count column (defaults to the third column). Β· default ""
Returns columns
feature_id VARCHAR
Feature id.
w BIGINT
ANCOM W statistic (number of sub-hypotheses rejected).
significant BOOLEAN
Whether the feature is declared differentially abundant.
Example

Find which features differ between two groups of samples, strongest evidence first. The join is the part worth copying: a table function gets one input relation, so the per-sample group label has to ride in as a fourth column rather than a second argument.

SELECT feature_id, w, significant
FROM skbio.stats.ancom((SELECT s.sample_id, s.feature_id, s.count, g.grp FROM (VALUES ('s1','b1',12),('s1','b2',11),('s2','b1',9),('s2','b2',11),('s3','b1',1),('s3','b2',11),('s4','b1',22),('s4','b2',21),('s5','b1',20),('s5','b2',22),('s6','b1',23),('s6','b2',21)) AS s(sample_id, feature_id, count) JOIN (VALUES ('s1','x'),('s2','x'),('s3','x'),('s4','y'),('s5','y'),('s6','y')) AS g(sample, grp) ON s.sample_id = g.sample))
ORDER BY w DESC;
Link
anosim (data TABLE, distance := VARCHAR, group := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, permutations := BIGINT) 1 example

ANOSIM test: are within-group distances smaller than between-group?

Positional arguments
data TABLE
A long distance matrix with a group column: (id_1, id_2, distance, group).
Named arguments
distance := VARCHAR
Distance column (defaults to the third column). Β· default ""
group := VARCHAR
Group label of id_1 (defaults to the fourth column). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
permutations := BIGINT
Number of permutations for the p-value. Β· default 999
Returns columns
method VARCHAR
Test name.
test_statistic DOUBLE
The R statistic.
p_value DOUBLE
Permutation p-value.
sample_size BIGINT
Number of samples.
number_of_groups BIGINT
Number of distinct groups.
permutations BIGINT
Number of permutations used.
Example

Ask the same question as permanova but on ranked distances, which makes ANOSIM the more robust choice when the distances are skewed or the groups differ in spread. Its R statistic is directly interpretable on its own scale: near 1 means the groups are well separated, near 0 that the grouping explains nothing.

SELECT method, round(test_statistic, 4) AS r_statistic, p_value,
  number_of_groups
FROM skbio.stats.anosim((SELECT b.id_1, b.id_2, b.distance, g.grp FROM skbio.diversity.beta_diversity((SELECT * FROM (VALUES ('s1','a',4),('s1','b',1),('s2','a',3),('s2','b',2),('s3','a',1),('s3','b',8),('s4','a',0),('s4','b',9)) AS t(sample_id, feature_id, count))) AS b JOIN (VALUES ('s1','x'),('s2','x'),('s3','y'),('s4','y')) AS g(sample, grp) ON b.id_1 = g.sample));
Link
ca (data TABLE, feature := VARCHAR, n_components := BIGINT, sample := VARCHAR, value := VARCHAR) 1 example

Correspondence Analysis of a long feature (count) table (per-sample scores)

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
n_components := BIGINT
Number of ordination axes to return. Β· default 3
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
ca_1 DOUBLE
Score on correspondence axis 1 (axes are ordered by inertia explained).
ca_2 DOUBLE
Score on correspondence axis 2 (axes are ordered by inertia explained).
sample_id VARCHAR
Sample id.
ca_1 DOUBLE
Score on correspondence axis 1 (axes are ordered by inertia explained).
ca_2 DOUBLE
Score on correspondence axis 2 (axes are ordered by inertia explained).
ca_3 DOUBLE
Score on correspondence axis 3 (axes are ordered by inertia explained).
Returns columns Β· depends on the arguments
`n_components := 2`
sample_id VARCHAR
Sample id.
ca_1 DOUBLE
Score on correspondence axis 1 (axes are ordered by inertia explained).
ca_2 DOUBLE
Score on correspondence axis 2 (axes are ordered by inertia explained).
`n_components := 3`
sample_id VARCHAR
Sample id.
ca_1 DOUBLE
Score on correspondence axis 1 (axes are ordered by inertia explained).
ca_2 DOUBLE
Score on correspondence axis 2 (axes are ordered by inertia explained).
ca_3 DOUBLE
Score on correspondence axis 3 (axes are ordered by inertia explained).
Example

Ordinate a count table with correspondence analysis, the chi-square counterpart of PCA for abundance data. Sorting by ca_1 orders the samples along the strongest compositional gradient, which is what the axis means for count data.

SELECT sample_id, round(ca_1, 4) AS ca_1, round(ca_2, 4) AS ca_2
FROM skbio.stats.ca((SELECT * FROM (VALUES ('s1','a',4),('s1','b',2),('s2','a',1),('s2','b',9),('s3','a',3),('s3','b',5)) AS t(sample_id, feature_id, value)), n_components := 2)
ORDER BY ca_1;
Link
centralize (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

centralize compositional transform of a long feature table

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature_id VARCHAR
Feature id.
centered DOUBLE
Transformed value.
Example

Re-express each sample relative to the dataset's average composition rather than its own total: values above 1 are features enriched compared with the typical sample, below 1 depleted. This is the compositional equivalent of subtracting the mean before plotting.

SELECT sample_id, feature_id, round(centered, 4) AS centered
FROM skbio.stats.centralize((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)))
ORDER BY sample_id, feature_id;
Link
closure (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

closure compositional transform of a long feature table

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature_id VARCHAR
Feature id.
proportion DOUBLE
Transformed value.
Example

Normalise two samples with different totals (6 and 15 counts) onto a common scale, so their proportions can be compared directly. Closure is the first step of essentially every compositional workflow, and running it alone shows what the later transforms silently assume about their input.

SELECT sample_id, feature_id, round(proportion, 4) AS proportion
FROM skbio.stats.closure((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)))
ORDER BY sample_id, feature_id;
Link
clr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

Centred log-ratio (CLR) transform of a long feature table

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature_id VARCHAR
Feature id.
clr DOUBLE
Centred log-ratio value.
Example

Move a feature table out of the simplex and into real space, where ordinary statistics (correlation, regression, distance) are meaningful again. A negative clr value means the feature is below its sample's geometric mean, positive above β€” the sign, not the raw count, is what carries the signal.

SELECT sample_id, feature_id, round(clr, 4) AS clr
FROM skbio.stats.clr((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)))
ORDER BY sample_id, feature_id;
Link
clr_inv (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

clr_inv: inverse compositional transform back to proportions

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature BIGINT
Output part index (1-based).
value DOUBLE
Proportion (parts sum to 1 per sample).
Example

Map log-ratio coordinates back to readable proportions that sum to 1 per sample. This is the step that makes a model fitted in clr space reportable: predictions come out as log-ratios, and stakeholders want percentages.

SELECT sample_id, feature, round(value, 6) AS value
FROM skbio.stats.clr_inv((SELECT * FROM (VALUES ('s1',1,0.1),('s1',2,-0.2),('s2',1,0.3),('s2',2,-0.1)) AS t(sample_id, coordinate, value)))
ORDER BY sample_id, feature;
Link
dirmult_ttest (data TABLE, feature := VARCHAR, group := VARCHAR, sample := VARCHAR, value := VARCHAR) 1 example

Dirichlet-multinomial t-test for differential abundance per feature

Positional arguments
data TABLE
One row per (sample_id, feature_id, count, group).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
group := VARCHAR
Group label of the sample (defaults to the fourth column). Β· default ""
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Count column (defaults to the third column). Β· default ""
Returns columns
feature_id VARCHAR
Feature id.
t_statistic DOUBLE
T-statistic for the group difference.
log2_fold_change DOUBLE
Estimated log2 fold change between groups.
pvalue DOUBLE
Raw p-value.
qvalue DOUBLE
Multiple-comparison-adjusted p-value (Holm).
significant BOOLEAN
Whether the adjusted p-value is significant.
Example

Report an effect size and a multiple-testing-corrected q-value per feature, most significant first. Prefer this over ancom when you need a direction and magnitude (the log2 fold change) rather than just a ranked W statistic; the seed is fixed, so the numbers are reproducible.

SELECT feature_id, round(log2_fold_change, 4) AS log2_fold_change,
  round(qvalue, 4) AS qvalue, significant
FROM skbio.stats.dirmult_ttest((SELECT s.sample_id, s.feature_id, s.count, g.grp FROM (VALUES ('s1','b1',12),('s1','b2',11),('s2','b1',9),('s2','b2',11),('s3','b1',1),('s3','b2',11),('s4','b1',22),('s4','b2',21),('s5','b1',20),('s5','b2',22),('s6','b1',23),('s6','b2',21)) AS s(sample_id, feature_id, count) JOIN (VALUES ('s1','x'),('s2','x'),('s3','x'),('s4','y'),('s5','y'),('s6','y')) AS g(sample, grp) ON s.sample_id = g.sample))
ORDER BY qvalue;
Link
ilr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

Isometric log-ratio (ILR) transform of a long feature table (D-1 components)

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
component BIGINT
ILR component index (1..D-1).
value DOUBLE
Isometric log-ratio value on that component.
Example

Turn 3-part compositions into 2 orthonormal coordinates β€” note the count drops from D to D-1, which is the point: unlike clr, the ilr coordinates are not linearly dependent, so a covariance matrix built from them is invertible and methods like PCA or LDA behave.

SELECT sample_id, component, round(value, 4) AS value
FROM skbio.stats.ilr((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)))
ORDER BY sample_id, component;
Link
ilr_inv (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

ilr_inv: inverse compositional transform back to proportions

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature BIGINT
Output part index (1-based).
value DOUBLE
Proportion (parts sum to 1 per sample).
Example

Rebuild a full composition from its D-1 isometric coordinates β€” note that 2 input coordinates come back as 3 parts. Pair it with ilr to round-trip: transform, model or perturb in real space, then invert to get proportions again.

SELECT sample_id, feature, round(value, 6) AS value
FROM skbio.stats.ilr_inv((SELECT * FROM (VALUES ('s1',1,0.1),('s1',2,-0.2),('s2',1,0.3),('s2',2,-0.1)) AS t(sample_id, coordinate, value)))
ORDER BY sample_id, feature;
Link
mantel (data TABLE, distance_x := VARCHAR, distance_y := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, method := VARCHAR, permutations := BIGINT) 1 example

Mantel test: correlation between two distance matrices

Positional arguments
data TABLE
Two aligned distance matrices: (id_1, id_2, distance_x, distance_y).
Named arguments
distance_x := VARCHAR
First distance column (defaults to the third). Β· default ""
distance_y := VARCHAR
Second distance column (defaults to the fourth). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
method := VARCHAR
Correlation method: pearson or spearman. Β· default "pearson"
permutations := BIGINT
Number of permutations for the p-value. Β· default 999
Returns columns
method VARCHAR
Correlation method (pearson or spearman).
correlation DOUBLE
Mantel correlation coefficient (in [-1, 1]).
p_value DOUBLE
Permutation p-value.
n BIGINT
Number of samples compared.
permutations BIGINT
Number of permutations used.
Example

Test whether two dissimilarities measured over the same samples covary β€” community distance against geographic distance, say. Both matrices ride in as two aligned distance columns over the same id pairs, which is exactly what joining two beta_diversity results on (id_1, id_2) produces.

SELECT method, round(correlation, 4) AS correlation, p_value, n
FROM skbio.stats.mantel((SELECT * FROM (VALUES ('a','b',0.5,0.4),('a','c',0.7,0.9),('b','c',0.6,0.5)) AS d(id_1, id_2, distance_x, distance_y)));
Link
multi_replace (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

multi_replace compositional transform of a long feature table

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature_id VARCHAR
Feature id.
value DOUBLE
Transformed value.
Example

Fill in zeros with small positive values while holding every non-zero ratio fixed β€” the principled alternative to adding an arbitrary pseudocount. Run this before clr, ilr, or alr, all of which are undefined at zero.

SELECT sample_id, feature_id, round(value, 4) AS value
FROM skbio.stats.multi_replace((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)))
ORDER BY sample_id, feature_id;
Link
pairwise_vlr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

Pairwise variance of log-ratios between features (long matrix)

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
feature_1 VARCHAR
First feature id.
feature_2 VARCHAR
Second feature id.
vlr DOUBLE
Variance of log(feature_1 / feature_2) across samples.
Example

Rank feature pairs by how tightly they track each other across samples, smallest variance first β€” the pair at the top moves proportionally and is a candidate for co-occurring taxa. Filtering to feature_1 < feature_2 drops the zero diagonal and the mirrored half of the symmetric matrix.

SELECT feature_1, feature_2, round(vlr, 4) AS vlr
FROM skbio.stats.pairwise_vlr((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6),('s3','a',2),('s3','b',1),('s3','c',7)) AS t(sample_id, feature_id, value)))
WHERE feature_1 < feature_2
ORDER BY vlr;
Link
pca (data TABLE, feature := VARCHAR, n_components := BIGINT, sample := VARCHAR, value := VARCHAR) 1 example

Principal Components Analysis of a long feature table (per-sample scores)

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
n_components := BIGINT
Number of ordination axes to return. Β· default 3
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Score on principal component 1 (components are ordered by variance explained).
pc_2 DOUBLE
Score on principal component 2 (components are ordered by variance explained).
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Score on principal component 1 (components are ordered by variance explained).
pc_2 DOUBLE
Score on principal component 2 (components are ordered by variance explained).
pc_3 DOUBLE
Score on principal component 3 (components are ordered by variance explained).
Returns columns Β· depends on the arguments
`n_components := 2`
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Score on principal component 1 (components are ordered by variance explained).
pc_2 DOUBLE
Score on principal component 2 (components are ordered by variance explained).
`n_components := 3`
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Score on principal component 1 (components are ordered by variance explained).
pc_2 DOUBLE
Score on principal component 2 (components are ordered by variance explained).
pc_3 DOUBLE
Score on principal component 3 (components are ordered by variance explained).
Example

Score three samples on the two leading principal components straight from a long feature table β€” no distance matrix needed, unlike pcoa. Ordering by pc_1 shows which samples the dominant feature gradient separates.

SELECT sample_id, round(pc_1, 4) AS pc_1, round(pc_2, 4) AS pc_2
FROM skbio.stats.pca((SELECT * FROM (VALUES ('s1','a',4),('s1','b',2),('s2','a',1),('s2','b',9),('s3','a',0),('s3','b',5)) AS t(sample_id, feature_id, value)), n_components := 2)
ORDER BY pc_1;
Link
pcoa (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, n_components := BIGINT) 1 example

Principal Coordinates Analysis of a distance matrix (per-sample coordinates)

Positional arguments
data TABLE
A long distance matrix: (id_1, id_2, distance).
Named arguments
distance := VARCHAR
Distance column (defaults to the third column). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
n_components := BIGINT
Number of principal coordinate axes to return. Β· default 3
Returns columns
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Coordinate on principal axis 1 (axes are ordered by variance explained).
pc_2 DOUBLE
Coordinate on principal axis 2 (axes are ordered by variance explained).
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Coordinate on principal axis 1 (axes are ordered by variance explained).
pc_2 DOUBLE
Coordinate on principal axis 2 (axes are ordered by variance explained).
pc_3 DOUBLE
Coordinate on principal axis 3 (axes are ordered by variance explained).
Returns columns Β· depends on the arguments
`n_components := 2`
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Coordinate on principal axis 1 (axes are ordered by variance explained).
pc_2 DOUBLE
Coordinate on principal axis 2 (axes are ordered by variance explained).
`n_components := 3`
sample_id VARCHAR
Sample id.
pc_1 DOUBLE
Coordinate on principal axis 1 (axes are ordered by variance explained).
pc_2 DOUBLE
Coordinate on principal axis 2 (axes are ordered by variance explained).
pc_3 DOUBLE
Coordinate on principal axis 3 (axes are ordered by variance explained).
Example

Collapse a 3-sample distance matrix into two plottable coordinates and order the samples along the leading axis. Rounding keeps the output readable; sorting by pc_1 reads off the dominant gradient β€” which samples sit at the extremes of the largest source of variation.

SELECT sample_id, round(pc_1, 4) AS pc_1, round(pc_2, 4) AS pc_2
FROM skbio.stats.pcoa((SELECT * FROM (VALUES ('a','a',0.0),('a','b',0.5),('a','c',0.7),('b','a',0.5),('b','b',0.0),('b','c',0.6),('c','a',0.7),('c','b',0.6),('c','c',0.0)) AS d(id_1, id_2, distance)), n_components := 2)
ORDER BY pc_1;
Link
permanova (data TABLE, distance := VARCHAR, group := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, permutations := BIGINT) 1 example

PERMANOVA test: does a grouping explain between-sample distances?

Positional arguments
data TABLE
A long distance matrix with a group column: (id_1, id_2, distance, group).
Named arguments
distance := VARCHAR
Distance column (defaults to the third column). Β· default ""
group := VARCHAR
Group label of id_1 (defaults to the fourth column). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
permutations := BIGINT
Number of permutations for the p-value. Β· default 999
Returns columns
method VARCHAR
Test name.
test_statistic DOUBLE
The pseudo-F statistic.
p_value DOUBLE
Permutation p-value.
sample_size BIGINT
Number of samples.
number_of_groups BIGINT
Number of distinct groups.
permutations BIGINT
Number of permutations used.
Example

Test whether two groups of samples really are separated in community space, end to end: build the Bray-Curtis matrix, join each sample's group label onto id_1, and read off pseudo-F with its permutation p-value. The join is the pattern worth copying β€” a table function takes one input relation, so the grouping has to ride in as a fourth column rather than a second argument.

SELECT method, round(test_statistic, 4) AS pseudo_f, p_value,
  number_of_groups
FROM skbio.stats.permanova((SELECT b.id_1, b.id_2, b.distance, g.grp FROM skbio.diversity.beta_diversity((SELECT * FROM (VALUES ('s1','a',4),('s1','b',1),('s2','a',3),('s2','b',2),('s3','a',1),('s3','b',8),('s4','a',0),('s4','b',9)) AS t(sample_id, feature_id, count))) AS b JOIN (VALUES ('s1','x'),('s2','x'),('s3','y'),('s4','y')) AS g(sample, grp) ON b.id_1 = g.sample));
Link
power (data TABLE, feature := VARCHAR, power := DOUBLE, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

Compositional power transform of a long feature table

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
power := DOUBLE
Exponent applied to each part of the composition. Β· default 1.0
pseudocount := DOUBLE
Added to every value before the transform. Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature_id VARCHAR
Feature id.
value DOUBLE
Transformed value.
Example

Sharpen a composition by squaring every part and re-closing it: the dominant features gain share and the rare ones lose it, while the result still sums to 1. An exponent below 1 does the opposite (flattens), which is how compositional data is up- or down-weighted without leaving the simplex.

SELECT sample_id, feature_id, round(value, 4) AS value
FROM skbio.stats.power((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)), power := 2.0)
ORDER BY sample_id, feature_id;
Link
rclr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR) 1 example

rclr compositional transform of a long feature table

Positional arguments
data TABLE
One row per (sample_id, feature_id, value).
Named arguments
feature := VARCHAR
Feature-id column (defaults to the second column). Β· default ""
pseudocount := DOUBLE
Added to every value before the transform (to handle zeros). Β· default 0.0
sample := VARCHAR
Sample-id column (defaults to the first column). Β· default ""
value := VARCHAR
Value column (defaults to the third column). Β· default ""
Returns columns
sample_id VARCHAR
Sample id.
feature_id VARCHAR
Feature id.
rclr DOUBLE
Transformed value.
Example

Take log-ratios of a feature table without inventing a pseudocount: rclr excludes zeros from each sample's geometric mean instead of offsetting them. Reach for this rather than clr whenever the table is sparse, as microbiome count tables almost always are.

SELECT sample_id, feature_id, round(rclr, 4) AS rclr
FROM skbio.stats.rclr((SELECT * FROM (VALUES ('s1','a',1),('s1','b',2),('s1','c',3),('s2','a',4),('s2','b',5),('s2','c',6)) AS t(sample_id, feature_id, value)))
ORDER BY sample_id, feature_id;
Link
tree 10 functions

Build phylogenetic trees from distances and inspect Newick strings.

Schema examples (1)
Example

Tips of a Newick tree

SELECT skbio.tree.tip_count('((a:2,b:3):3,d:4,c:4);');
Scalar functions
cophenetic_distance (newick1 VARCHAR, newick2 VARCHAR) 1 example

Distance between two Newick trees based on tip-to-tip distances

Arguments
newick1 VARCHAR
First Newick tree
newick2 VARCHAR
Second Newick tree
ReturnsDOUBLE
Example

Compare two trees by the tip-to-tip distances they imply, rather than by their splits. It answers the question that actually matters downstream β€” do these trees place the taxa at the same distances from each other? β€” and so reacts to the long branches in the second tree that robinson_foulds ignores.

SELECT skbio.tree.cophenetic_distance('((a:1,b:1):1,(c:1,d:1):1);', '((a:1,c:1):5,(b:1,d:1):5);') AS cophenetic_distance;
Link
robinson_foulds (newick1 VARCHAR, newick2 VARCHAR) 1 example

Robinson-Foulds topological distance between two Newick trees

Arguments
newick1 VARCHAR
First Newick tree
newick2 VARCHAR
Second Newick tree
ReturnsDOUBLE
Example

Ask whether two trees group the same taxa together, ignoring branch lengths entirely: these two disagree on whether a pairs with b or with c, so the distance is non-zero. This is the standard way to check whether two reconstruction methods, or two bootstrap replicates, found the same shape.

SELECT skbio.tree.robinson_foulds('((a,b),(c,d));', '((a,c),(b,d));') AS rf_distance;
Link
tip_count (newick VARCHAR) 1 example

Number of tips (leaves) in a Newick tree

Arguments
newick VARCHAR
A Newick tree
ReturnsBIGINT
Example

Size a tree without leaving SQL β€” the quickest sanity check that a builder kept every taxon, and the denominator for anything you normalise per tip. Point it at a column of Newick strings to profile a whole table of trees.

SELECT skbio.tree.tip_count('((a:2,b:3):3,d:4,c:4);') AS tips;
Link
total_branch_length (newick VARCHAR) 1 example

Total branch length (sum of all branch lengths) of a Newick tree

Arguments
newick VARCHAR
A Newick tree
ReturnsDOUBLE
Example

Measure how much evolutionary change a tree encodes in total. Over a tree pruned to one sample's features this is exactly Faith's PD, which makes it the way to compute phylogenetic diversity when you already hold the subtree rather than a feature table.

SELECT skbio.tree.total_branch_length('((a:2,b:3):3,d:4,c:4);') AS branch_length;
Link
tree_height (newick VARCHAR) 1 example

Height of a Newick tree (maximum root-to-tip branch-length distance)

Arguments
newick VARCHAR
A Newick tree
ReturnsDOUBLE
Example

Read the deepest root-to-tip distance, i.e. how far back the tree reaches. On an ultrametric tree (anything from upgma) every tip sits at this height, so comparing it with a tip's own depth is a quick test of ultrametricity.

SELECT skbio.tree.tree_height('((a:2,b:3):3,d:4,c:4);') AS height;
Link
weighted_robinson_foulds (newick1 VARCHAR, newick2 VARCHAR) 1 example

Weighted Robinson-Foulds distance (branch-length aware) between two Newick trees

Arguments
newick1 VARCHAR
First Newick tree
newick2 VARCHAR
Second Newick tree
ReturnsDOUBLE
Example

Compare two trees on topology *and* branch lengths, so a pair that groups taxa identically but stretches a branch still scores non-zero. Use this rather than robinson_foulds when the lengths carry meaning β€” divergence times, substitution rates β€” and not just the grouping.

SELECT skbio.tree.weighted_robinson_foulds('((a:1,b:1):1,(c:1,d:1):1);', '((a:1,c:1):1,(b:1,d:1):1);') AS wrf_distance;
Link
Table in-out functions
bme (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR) 1 example

Build a bme tree from a distance matrix (Newick output)

Positional arguments
data TABLE
A long distance matrix: (id_1, id_2, distance).
Named arguments
distance := VARCHAR
Distance column (defaults to the third column). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
Returns columns
newick VARCHAR
The tree in Newick format.
Example

Build the balanced-minimum-evolution tree (the criterion FastME optimises), which is usually more accurate than greedy ME at a similar cost. Compare its output against neighbor_joining with robinson_foulds to see whether the method choice changed the topology at all.

SELECT newick, skbio.tree.tip_count(newick) AS tips
FROM skbio.tree.bme((SELECT * FROM (VALUES ('a','b',5),('a','c',9),('a','d',9),('b','c',10),('b','d',10),('c','d',8)) AS d(id_1, id_2, distance)));
Link
gme (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR) 1 example

Build a gme tree from a distance matrix (Newick output)

Positional arguments
data TABLE
A long distance matrix: (id_1, id_2, distance).
Named arguments
distance := VARCHAR
Distance column (defaults to the third column). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
Returns columns
newick VARCHAR
The tree in Newick format.
Example

Build a minimum-evolution tree greedily, which is the one to reach for when the matrix is large enough that neighbour joining's cubic cost hurts. On a small matrix like this one it agrees with the others; the tip count confirms no taxa were dropped.

SELECT newick, skbio.tree.tip_count(newick) AS tips
FROM skbio.tree.gme((SELECT * FROM (VALUES ('a','b',5),('a','c',9),('a','d',9),('b','c',10),('b','d',10),('c','d',8)) AS d(id_1, id_2, distance)));
Link
neighbor_joining (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR) 1 example

Build a neighbor_joining tree from a distance matrix (Newick output)

Positional arguments
data TABLE
A long distance matrix: (id_1, id_2, distance).
Named arguments
distance := VARCHAR
Distance column (defaults to the third column). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
Returns columns
newick VARCHAR
The tree in Newick format.
Example

Turn a pairwise distance matrix into an actual tree, then check it round-tripped by counting its tips. Neighbour joining is the default choice when the distances come from real data and no molecular clock can be assumed; feed it a beta_diversity matrix to get a sample dendrogram straight out of SQL.

SELECT newick, skbio.tree.tip_count(newick) AS tips
FROM skbio.tree.neighbor_joining((SELECT * FROM (VALUES ('a','b',5),('a','c',9),('a','d',9),('b','c',10),('b','d',10),('c','d',8)) AS d(id_1, id_2, distance)));
Link
upgma (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR) 1 example

Build a upgma tree from a distance matrix (Newick output)

Positional arguments
data TABLE
A long distance matrix: (id_1, id_2, distance).
Named arguments
distance := VARCHAR
Distance column (defaults to the third column). Β· default ""
id_1 := VARCHAR
First-id column (defaults to the first column). Β· default ""
id_2 := VARCHAR
Second-id column (defaults to the second column). Β· default ""
Returns columns
newick VARCHAR
The tree in Newick format.
Example

Build a rooted, ultrametric tree β€” every tip ends up equidistant from the root, so tree_height is the same for all of them. Reach for UPGMA when you want a clustering dendrogram to cut at a threshold, and for neighbor_joining when you want a phylogeny.

SELECT newick, skbio.tree.tip_count(newick) AS tips
FROM skbio.tree.upgma((SELECT * FROM (VALUES ('a','b',5),('a','c',9),('a','d',9),('b','c',10),('b','d',10),('c','d',8)) AS d(id_1, id_2, distance)));
Link

Try these queries

GC content of a DNA sequence.

SELECT skbio.sequence.gc_content('ATGCGGATTACAGG') AS gc;

Uses gc_content

Reverse complement of a DNA sequence.

SELECT skbio.sequence.reverse_complement('ATGCGGATTACAGG') AS rc;

Uses reverse_complement

3-mer composition of two reads (long format).

SELECT *
FROM skbio.sequence.kmer_frequencies((SELECT * FROM (VALUES (1, 'ATGCGGATTACAGG'), (2, 'TTGCACGT')) AS reads(id, seq)), id := 'id', k := 3);

Uses kmer_frequencies

Optimal global alignment score between two DNA sequences.

SELECT skbio.alignment.align_score_nucleotide('ACTGGT', 'ACTGT') AS score;

Uses align_score_nucleotide

Faith's phylogenetic diversity per sample given a tree.

SELECT *
FROM skbio.diversity.faith_pd((SELECT * FROM (VALUES ('s1','f1',1),('s1','f2',1),('s2','f3',1),('s2','f4',1)) AS t(sample_id, feature_id, count)), tree := '((f1:0.1,f2:0.2):0.3,(f3:0.15,f4:0.25):0.35);');

Uses faith_pd

Shannon alpha diversity per sample over a long feature table.

SELECT sample_id, skbio.diversity.shannon(count) AS shannon
FROM (VALUES (1,'a',4),(1,'b',2),(1,'c',1),(2,'a',1),(2,'b',9)) AS t(sample_id, feature_id, count)
GROUP BY sample_id
ORDER BY sample_id;

Uses shannon

1 more example

Bray-Curtis distance matrix, then a 2-axis PCoA embedding.

SELECT *
FROM skbio.stats.pcoa((SELECT * FROM skbio.diversity.beta_diversity((SELECT * FROM (VALUES ('s1','a',4),('s1','b',1),('s2','a',3),('s2','b',2),('s3','a',0),('s3','b',9)) AS t(sample_id, feature_id, count)))), n_components := 2);

Uses pcoabeta_diversity

95 more examples in the Catalog, each listed under the table or function it uses.

Questions it can answer

Plain-English questions from the worker's agent test tasks. An AI agent with this catalog attached should answer each one with SQL.

  • Break the DNA read 'ATGCGGATTACAGG' down into its per-base counts. Return one row per distinct base with columns residue and count, ordered by residue.
  • Translate the DNA read 'ATGCGGATTACAGG' in all six reading frames. Return one row per frame with columns frame and protein, ordered by frame.

scikit-bio is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.