scikit-bio
scikit-bio β sequence analysis, alignment, community diversity, ordination and phylogenetics
- Connector software
- Free and open source
- Service credentials
- Not needed
- Query Farm hosting
- Available Β· $10/month organization minimum
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);
| 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.
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;
INSTALL vgi FROM community;
LOAD vgi;
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'
);
Attach the signed image
Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.
ATTACH 'skbio' AS skbio (
TYPE vgi,
LOCATION 'oci://ghcr.io/query-farm/vgi-scikit-bio:0.4.1'
);
3. Run a query
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);
Run the connector on a server you manage. You operate the service and choose who can connect.
1. Deploy the connector on your server
Follow the connectorβs deployment instructions. Use its supported HTTP transport, or launch it remotely over SSH. The connection guide explains both options.
2. Install the vgi extension
Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.
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;
INSTALL vgi FROM community;
LOAD vgi;
3. Attach the connector
For an HTTP deployment, replace the example URL with your endpoint. Add the authentication options your deployment requires. For SSH, use the SSH connection instructions.
ATTACH 'skbio' AS skbio
(TYPE vgi, LOCATION 'https://your-connector.example.com');
4. Run a query
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);
Query Farm operates scikit-bio for your team. Hosting has a $10 monthly minimum per organization; usage counts toward it. From $2.97 per instance-month ($10 monthly minimum).
1. Create your hosted connector
Open the console, choose your organization and deployment size, and add any service credentials there.
2. Install the vgi extension
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;
INSTALL vgi FROM community;
LOAD vgi;
3. Attach your deployment
Copy the ATTACH statement from your deployment in the console and run it in DuckDB or Haybarn. Use skbio as the catalog alias for the query below.
4. Run a query
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);
Technical details
- Verified connector release
- v0.4.1
- Engine
- 2.0.1
- VGI protocol
- 3.4.0
- Verified on
- December 1, 2026
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'
);
Attach the signed image
Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.
ATTACH 'skbio' AS skbio (
TYPE vgi,
LOCATION 'oci://ghcr.io/query-farm/vgi-scikit-bio:0.4.1'
);
Overview
scikit-bio for SQL: sequence analysis, community diversity, ordination, and phylogenetics in DuckDB
Exposes scikit-bio to DuckDB/SQL as VGI functions:
- Sequence β GC content, reverse complement, translation (incl. six-frame), composition, validation, sequence distances
- Alignment β global/local pairwise alignment (scores and aligned strings)
- Diversity β the full alpha-diversity metric family (aggregates), beta-diversity matrices, phylogenetic Faith's PD & UniFrac, and rarefaction
- Stats β PCA/CA/PCoA ordination, PERMANOVA / ANOSIM / Mantel tests, CLR/ILR/ALR transforms, ANCOM & Dirichlet-multinomial differential abundance
- Tree β neighbour joining / UPGMA / minimum evolution, Newick inspection, and tree comparison
Catalog
Everything skbio exposes once attached β read straight from the worker's
released build.
alignment 4 functions
Pairwise sequence alignment: scores and aligned strings.
Schema 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;
align_score_nucleotide (seq1 VARCHAR, seq2 VARCHAR)
Optimal global alignment score between two DNA sequences
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;
align_score_protein (seq1 VARCHAR, seq2 VARCHAR)
Optimal global alignment score between two protein sequences
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;
pairwise_align_nucleotide (data TABLE, id := VARCHAR, mode := VARCHAR, seq1 := VARCHAR, seq2 := VARCHAR)
Pairwise align two DNA columns; emit aligned strings and score
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;
pairwise_align_protein (data TABLE, id := VARCHAR, mode := VARCHAR, seq1 := VARCHAR, seq2 := VARCHAR)
Pairwise align two protein columns; emit aligned strings and score
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;
diversity 36 functions
Community-ecology diversity from a long (sample, feature, count) table.
Schema 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;
ace (abundance DOUBLE)
ace alpha-diversity metric over one sample's feature counts
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;
berger_parker_d (abundance DOUBLE)
berger_parker_d alpha-diversity metric over one sample's feature counts
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;
brillouin_d (abundance DOUBLE)
brillouin_d alpha-diversity metric over one sample's feature counts
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;
chao1 (abundance DOUBLE)
chao1 alpha-diversity metric over one sample's feature counts
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;
chao1_ci (abundance DOUBLE)
chao1_ci alpha-diversity metric over one sample's feature counts
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;
dominance (abundance DOUBLE)
dominance alpha-diversity metric over one sample's feature counts
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;
doubles (abundance DOUBLE)
doubles alpha-diversity metric over one sample's feature counts
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;
enspie (abundance DOUBLE)
enspie alpha-diversity metric over one sample's feature counts
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;
esty_ci (abundance DOUBLE)
esty_ci alpha-diversity metric over one sample's feature counts
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;
fisher_alpha (abundance DOUBLE)
fisher_alpha alpha-diversity metric over one sample's feature counts
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;
gini_index (abundance DOUBLE)
gini_index alpha-diversity metric over one sample's feature counts
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;
goods_coverage (abundance DOUBLE)
goods_coverage alpha-diversity metric over one sample's feature counts
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;
heip_evenness (abundance DOUBLE)
heip_evenness alpha-diversity metric over one sample's feature counts
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;
hill (abundance DOUBLE, q DOUBLE)
hill alpha-diversity metric over one sample's feature counts
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;
inv_simpson (abundance DOUBLE)
inv_simpson alpha-diversity metric over one sample's feature counts
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;
kempton_taylor_q (abundance DOUBLE)
kempton_taylor_q alpha-diversity metric over one sample's feature counts
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;
margalef (abundance DOUBLE)
margalef alpha-diversity metric over one sample's feature counts
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;
mcintosh_d (abundance DOUBLE)
mcintosh_d alpha-diversity metric over one sample's feature counts
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;
mcintosh_e (abundance DOUBLE)
mcintosh_e alpha-diversity metric over one sample's feature counts
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;
menhinick (abundance DOUBLE)
menhinick alpha-diversity metric over one sample's feature counts
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;
observed_features (abundance DOUBLE)
observed_features alpha-diversity metric over one sample's feature counts
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;
osd (abundance DOUBLE)
osd alpha-diversity metric over one sample's feature counts
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;
pielou_evenness (abundance DOUBLE)
pielou_evenness alpha-diversity metric over one sample's feature counts
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;
renyi (abundance DOUBLE, q DOUBLE)
renyi alpha-diversity metric over one sample's feature counts
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;
robbins (abundance DOUBLE)
robbins alpha-diversity metric over one sample's feature counts
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;
shannon (abundance DOUBLE)
shannon alpha-diversity metric over one sample's feature counts
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;
simpson (abundance DOUBLE)
simpson alpha-diversity metric over one sample's feature counts
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;
simpson_d (abundance DOUBLE)
simpson_d alpha-diversity metric over one sample's feature counts
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;
simpson_e (abundance DOUBLE)
simpson_e alpha-diversity metric over one sample's feature counts
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;
singles (abundance DOUBLE)
singles alpha-diversity metric over one sample's feature counts
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;
strong (abundance DOUBLE)
strong alpha-diversity metric over one sample's feature counts
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;
tsallis (abundance DOUBLE, q DOUBLE)
tsallis alpha-diversity metric over one sample's feature counts
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;
beta_diversity (data TABLE, count := VARCHAR, feature := VARCHAR, metric := VARCHAR, sample := VARCHAR)
Between-sample distance matrix from a long feature table (long output)
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;
faith_pd (data TABLE, count := VARCHAR, feature := VARCHAR, sample := VARCHAR, tree := VARCHAR)
Faith's phylogenetic diversity per sample (needs a tree)
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;
subsample_counts (data TABLE, count := VARCHAR, depth := BIGINT, feature := VARCHAR, sample := VARCHAR, seed := BIGINT, with_replacement := BOOLEAN)
Rarefy each sample's feature counts to a fixed depth (long output)
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;
unifrac (data TABLE, count := VARCHAR, feature := VARCHAR, sample := VARCHAR, tree := VARCHAR, weighted := BOOLEAN)
UniFrac phylogenetic distance matrix between samples (needs a tree)
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;
sequence 20 functions
Analyze DNA, RNA, and protein sequences held in VARCHAR columns.
Schema 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;
complement (seq VARCHAR)
Complement of a DNA sequence (same 5'->3' order)
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;
count_subsequence (seq VARCHAR, subsequence VARCHAR)
Count occurrences of a subsequence within a sequence
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;
degap (seq VARCHAR)
Remove gap characters from a sequence
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;
gc_content (seq VARCHAR)
GC content of a DNA sequence as a fraction in [0, 1]
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;
gc_frequency (seq VARCHAR)
Number of G/C bases in a DNA sequence
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;
hamming_distance (seq1 VARCHAR, seq2 VARCHAR)
Hamming distance (fraction of differing positions) between two sequences
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;
has_degenerates (seq VARCHAR)
True if the DNA sequence contains degenerate (ambiguity) codes
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;
has_gaps (seq VARCHAR)
True if the sequence contains gap characters
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;
is_reverse_complement (seq1 VARCHAR, seq2 VARCHAR)
True if the second DNA sequence is the reverse complement of the first
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;
is_valid_dna (seq VARCHAR)
True if the string is a valid IUPAC DNA sequence
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;
is_valid_protein (seq VARCHAR)
True if the string is a valid IUPAC protein sequence
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;
match_count (seq1 VARCHAR, seq2 VARCHAR)
Number of agreeing positions between two equal-length sequences
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;
mismatch_count (seq1 VARCHAR, seq2 VARCHAR)
Number of differing positions between two equal-length sequences
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;
reverse_complement (seq VARCHAR)
Reverse complement of a DNA sequence
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;
reverse_transcribe (seq VARCHAR)
Reverse transcribe an RNA sequence to DNA (U -> T)
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;
transcribe (seq VARCHAR)
Transcribe a DNA sequence to RNA (T -> U)
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;
translate (seq VARCHAR)
Translate a DNA sequence to protein (standard genetic code)
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;
kmer_frequencies (data TABLE, id := VARCHAR, k := BIGINT, sequence := VARCHAR)
Count overlapping k-mers per sequence (long format)
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;
residue_frequencies (data TABLE, id := VARCHAR, sequence := VARCHAR)
Count single residues (bases or amino acids) per sequence (long format)
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;
translate_six_frames (data TABLE, id := VARCHAR, sequence := VARCHAR)
Translate each DNA sequence in all six reading frames (long format)
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;
stats 20 functions
Ordination, distance-matrix hypothesis tests, and compositional transforms.
Schema examples (1)
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;
alr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, ref_idx := BIGINT, sample := VARCHAR, value := VARCHAR)
Additive log-ratio (ALR) transform of a long feature table (D-1 components)
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;
alr_inv (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, ref_idx := BIGINT, sample := VARCHAR, value := VARCHAR)
alr_inv: inverse compositional transform back to proportions
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;
ancom (data TABLE, feature := VARCHAR, group := VARCHAR, sample := VARCHAR, value := VARCHAR)
ANCOM differential-abundance test per feature between groups
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;
anosim (data TABLE, distance := VARCHAR, group := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, permutations := BIGINT)
ANOSIM test: are within-group distances smaller than between-group?
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));
ca (data TABLE, feature := VARCHAR, n_components := BIGINT, sample := VARCHAR, value := VARCHAR)
Correspondence Analysis of a long feature (count) table (per-sample scores)
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;
centralize (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
centralize compositional transform of a long feature table
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;
closure (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
closure compositional transform of a long feature table
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;
clr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
Centred log-ratio (CLR) transform of a long feature table
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;
clr_inv (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
clr_inv: inverse compositional transform back to proportions
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;
dirmult_ttest (data TABLE, feature := VARCHAR, group := VARCHAR, sample := VARCHAR, value := VARCHAR)
Dirichlet-multinomial t-test for differential abundance per feature
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;
ilr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
Isometric log-ratio (ILR) transform of a long feature table (D-1 components)
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;
ilr_inv (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
ilr_inv: inverse compositional transform back to proportions
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;
mantel (data TABLE, distance_x := VARCHAR, distance_y := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, method := VARCHAR, permutations := BIGINT)
Mantel test: correlation between two distance matrices
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)));
multi_replace (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
multi_replace compositional transform of a long feature table
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;
pairwise_vlr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
Pairwise variance of log-ratios between features (long matrix)
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;
pca (data TABLE, feature := VARCHAR, n_components := BIGINT, sample := VARCHAR, value := VARCHAR)
Principal Components Analysis of a long feature table (per-sample scores)
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;
pcoa (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, n_components := BIGINT)
Principal Coordinates Analysis of a distance matrix (per-sample coordinates)
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;
permanova (data TABLE, distance := VARCHAR, group := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR, permutations := BIGINT)
PERMANOVA test: does a grouping explain between-sample distances?
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));
power (data TABLE, feature := VARCHAR, power := DOUBLE, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
Compositional power transform of a long feature table
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;
rclr (data TABLE, feature := VARCHAR, pseudocount := DOUBLE, sample := VARCHAR, value := VARCHAR)
rclr compositional transform of a long feature table
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;
tree 10 functions
Build phylogenetic trees from distances and inspect Newick strings.
Schema examples (1)
Tips of a Newick tree
SELECT skbio.tree.tip_count('((a:2,b:3):3,d:4,c:4);');
cophenetic_distance (newick1 VARCHAR, newick2 VARCHAR)
Distance between two Newick trees based on tip-to-tip distances
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;
robinson_foulds (newick1 VARCHAR, newick2 VARCHAR)
Robinson-Foulds topological distance between two Newick trees
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;
tip_count (newick VARCHAR)
Number of tips (leaves) in a Newick tree
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;
total_branch_length (newick VARCHAR)
Total branch length (sum of all branch lengths) of a Newick tree
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;
tree_height (newick VARCHAR)
Height of a Newick tree (maximum root-to-tip branch-length distance)
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;
weighted_robinson_foulds (newick1 VARCHAR, newick2 VARCHAR)
Weighted Robinson-Foulds distance (branch-length aware) between two Newick trees
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;
bme (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR)
Build a bme tree from a distance matrix (Newick output)
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)));
gme (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR)
Build a gme tree from a distance matrix (Newick output)
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)));
neighbor_joining (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR)
Build a neighbor_joining tree from a distance matrix (Newick output)
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)));
upgma (data TABLE, distance := VARCHAR, id_1 := VARCHAR, id_2 := VARCHAR)
Build a upgma tree from a distance matrix (Newick output)
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)));
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;
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 Hide 1 more
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.
Related workers
Chem
Science & health
Compute molecular descriptors, fingerprints, similarity, substructure matches and InChI keys from SMILES strings
Periodic table
Science & health
The periodic table, isotopes and chemical formula molar masses as offline DuckDB SQL
FHIR
Science & health
Query HL7 FHIR R4 REST servers from SQL: patients, observations, generic search, reads by id, and server capabilities