Metadata-Version: 2.4
Name: seedmatch
Version: 0.1.0
Requires-Dist: numpy>=2.0
Requires-Dist: pandas>=2.2
Requires-Dist: scipy>=1.14
Requires-Dist: matplotlib>=3.8 ; extra == 'plot'
Provides-Extra: plot
License-File: LICENSE
Summary: Agent-sandbox-ready Python port of SeedMatchR: seed matches of an siRNA guide strand and their effect on differential expression.
License-Expression: MIT
Requires-Python: >=3.12
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/inflexa-ai/seedmatch/releases
Project-URL: Homepage, https://github.com/inflexa-ai/seedmatch
Project-URL: Issues, https://github.com/inflexa-ai/seedmatch/issues

# seedmatch

[![Test](https://github.com/inflexa-ai/seedmatch/actions/workflows/test.yml/badge.svg)](https://github.com/inflexa-ai/seedmatch/actions/workflows/test.yml)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/inflexa-ai/seedmatch/badge)](https://scorecard.dev/viewer/?uri=github.com/inflexa-ai/seedmatch)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/inflexa-ai/seedmatch/blob/main/LICENSE)

seedmatch is a Python port of the R package [SeedMatchR](https://github.com/tacazares/SeedMatchR), ready for AI agent sandboxes. It finds the seed matches of an siRNA guide strand in transcript sequences. It then joins the matches with the results of a differential expression (DE) analysis. Thus you can see which genes with a seed match go down.

The output is the same as the output of SeedMatchR on the core paths. R golden files in `tests/golden/` keep this true. The installed package holds these documents, and `importlib.resources.files("seedmatch").joinpath(name).read_text()` reads each one without network:

- [`guide.md`](https://github.com/inflexa-ai/seedmatch/blob/main/src/seedmatch/guide.md): the options, the limits, and the edge cases of each function.
- [`r-map.md`](https://github.com/inflexa-ai/seedmatch/blob/main/src/seedmatch/r-map.md): the Python name of each R function, and the changes of the arguments.
- [`divergences.md`](https://github.com/inflexa-ai/seedmatch/blob/main/src/seedmatch/divergences.md): each change of behavior from R, with its ID `D-NNN`.

## Installation

Python 3.12 or later is necessary. Install seedmatch from PyPI:

```bash
uv pip install seedmatch
```

To draw the figures of `seedmatch.plot`, install the extra `plot`:

```bash
uv pip install "seedmatch[plot]"
```

PyPI has a wheel for Linux x86_64 and Linux aarch64 (glibc 2.28 or later), and for macOS arm64. On a different platform, the install builds the Rust extension from the sdist. To install the code of `main`, use `uv pip install git+https://github.com/inflexa-ai/seedmatch.git`. A build from the source needs [rustup](https://rustup.rs) and a C linker. [`CONTRIBUTING.md`](https://github.com/inflexa-ai/seedmatch/blob/main/CONTRIBUTING.md) gives the setup of the build.

## A part of an agentic toolchain for bioinformatics

Inflexa, Inc. builds an agentic toolchain for bioinformatics. The toolchain ports existing tools to languages and architectures that an agent sandbox can run. An example of such a sandbox is the sandbox of [Inflexa](https://github.com/inflexa-ai/inflexa). seedmatch is a tool of this toolchain.

A sandbox such as the Inflexa sandbox has no network egress, and an agent corrects its calls from the error messages. Thus seedmatch obeys these rules:

- **No network in the core.** The core modules never use the network. Each function reads its input from a path or an object that you give. The separate module `seedmatch.fetch` downloads the resources (see [Resources](#resources)).
- **No R and no system library.** The package is Python on numpy, pandas, and scipy, with a compiled extension for the search kernels. It does not use R or a system library. The extra `plot` adds matplotlib.
- **Errors that an agent can use.** Each `InputError` names the bad value and the expected value. Thus an agent can correct the call. Each error class that seedmatch defines is a `SeedMatchError`, and `InputError` is also a `ValueError`. If a file does not exist, the function raises `FileNotFoundError`.

## Example

```python
from seedmatch import (
    Guide,
    SearchOptions,
    Seed,
    annotate_seed_counts,
    count_matches,
    filter_de,
    find_matches,
    read_deseq2_table,
    read_fasta,
    seed_match_report,
)

# The ID of each FASTA record is the gene ID of its sequence.
sequences = read_fasta("transcripts.fa")

# The guide strand, 5' to 3'. The target is the DNA site that the seed pairs with.
guide = Guide("UUAUAGAGCAAGAACACUGUUUU")
target = guide.target(Seed.MER7M8)

# The number of matches in each sequence, and the 1-based range of each match.
counts = count_matches(target, sequences)
ranges = find_matches(target, sequences, SearchOptions(max_mismatch=1))

# A DESeq2 table with 8 columns, filtered as filter_res does it in R.
de = filter_de(read_deseq2_table("deseq2_results.tsv"))

# Add the column "mer7m8": the count of the seed matches of each gene.
de = annotate_seed_counts(de, sequences, target)

# The SeedMatchReport of R: the genes of each match class, and the off-targets among them.
report = seed_match_report(de, sequences, guide)
summary = report.report
matches = report.matches
```

`ecdf_test` compares the `log2FoldChange` values of two gene sets. This example compares the genes with a seed match to the genes without a match. With the default KS test, a small p-value shows that the genes with a seed match go down.

```python
from seedmatch import ecdf_test

# The genes with a seed match, and the genes without a match.
seed_genes = de.loc[de["mer7m8"] >= 1, "gene_id"]
background = de.loc[de["mer7m8"] == 0, "gene_id"]

# The KS test of R. The default alternative is GREATER, as in R.
ecdf_result = ecdf_test(de, target=seed_genes, background=background)
print(ecdf_result.statistic, ecdf_result.p_value)
```

To get the sequences from an annotation, open a `Reference`. A `Reference` joins an EnsDb file and a genome file of the same build.

```python
from seedmatch import FeatureType, Reference, count_matches

with Reference.from_paths(ensdb="ensdb.sqlite", genome="genome.2bit") as ref:
    # The 3' UTR of each canonical protein-coding transcript.
    # The ID of a sequence is its transcript ID.
    utr3 = ref.sequences(FeatureType.UTR3)

# The number of seed matches in each 3' UTR, with the target of the example above.
utr3_counts = count_matches(target, utr3)
```

## Other analyses

Each example uses the objects of the examples above. [`guide.md`](https://github.com/inflexa-ai/seedmatch/blob/main/src/seedmatch/guide.md) gives the options and the edge cases of each function.

`kmer_counts` counts the k-mers of each sequence, and `kmer_gene_counts` gives the number of genes that have each k-mer.

```python
from seedmatch import kmer_counts, kmer_gene_counts

# The 7-mers of the sequences. The default k is 7, the default of R.
kmers = kmer_counts(sequences)

# The number of genes with each 7-mer, as a Series. The index is the 7-mer.
genes_with_kmer = kmer_gene_counts(kmers)

# The number of genes that have the 7-mer of the target.
print(genes_with_kmer[target.sequence])
```

`alignment_text` shows how the guide pairs with the sequence at one match.

```python
from seedmatch import alignment_text

# The three lines: the guide, the pairs, and the sequence. The default seed is Seed.MER7M8.
alignment = alignment_text(find_matches(target, sequences).iloc[0], guide, sequences)
print(alignment)
```

`match_distances` gives the distance between each pair of matches in one sequence.

```python
from seedmatch import match_distances

# One row for each pair of matches in a sequence. A sequence with one match has no row (D-011).
distances = match_distances(find_matches(guide.target(Seed.MER6), sequences))
print(distances.head())
```

`e_values` gives the e-value of the seed count of each gene against a null of shuffled guides from `e_value_null`.

```python
from seedmatch import e_value_null, e_values

# The null: the seed count of each gene for each of 100 shuffles of the guide.
null = e_value_null(guide, sequences, rng=1, n_random=100)

# The e-value of the column "mer7m8". A small e-value shows a count that shuffles rarely reach.
scored = e_values(de, null, column="mer7m8")
print(scored[["gene_id", "mer7m8", "e_value"]].head())
```

`benchmark_predictions` scores the seed counts against a gold standard of genes that go down.

```python
from seedmatch import benchmark_predictions

# The scores are the seed counts of the column "mer7m8". The cutoffs are the R defaults: 0.15 and 0.
benchmark = benchmark_predictions(de)
print(benchmark.pr.auc_integral, benchmark.roc.auc)
```

`read_mirdb` reads the miRDB table of predicted miRNA targets. This example keeps the rows of the rat, which has the species code `rno`.

```python
from seedmatch import read_mirdb

# The columns: mirdb_id, target_refseq_id, target_score, species, and mirna_name.
rat_targets = read_mirdb("miRDB_v6.0_prediction_result.txt.gz", species="rno")
print(rat_targets.head())
```

`wobble_bulge_matches` finds the sites that have G:U pairs or a bulge in the seed region.

```python
from seedmatch import annotate_wobble_bulge_counts, wobble_bulge_matches

# One row for each distinct start of a site, with the place and the size of its bulge.
wobble_matches = wobble_bulge_matches(guide, sequences)
print(wobble_matches.head())

# The column "overall_matches": for each gene, the largest number of rows of one of its sequences (D-003).
wobble_de = annotate_wobble_bulge_counts(de, sequences, guide)
print(wobble_de[["gene_id", "overall_matches"]].head())
```

`compensatory_sites` finds the sites with a seed match and a second region of the guide that pairs with the sequence before the match.

```python
from seedmatch import compensatory_sites, ecdf_test

# One row for each pair of a seed match and a region of one sequence.
sites = compensatory_sites(guide, sequences)
print(sites.head())

# As in the R vignette: the genes with a site against the other genes of the DE table.
site_genes = sites["gene_id"].unique()
other_genes = de.loc[~de["gene_id"].isin(site_genes), "gene_id"]
site_result = ecdf_test(de, target=site_genes, background=other_genes)
print(site_result.p_value)
```

`read_trrust` reads the TRRUST table of regulators and their targets. `trrust_scores` gives each gene of the table a repression score and an activation score.

```python
from seedmatch import read_trrust, trrust_scores

# The columns: source, target, edge_type, and evidence.
trrust = read_trrust("trrust_rawdata.human.tsv")

# TRRUST names a gene by its symbol, not by its Ensembl gene ID.
# Replace the symbols of the example with the symbols of your seed genes.
trrust_result = trrust_scores(trrust, ["TFA", "GC", "TFC"])
print(trrust_result.head())
```

`read_string_links` reads the STRING protein links. `string_gene_network` maps the proteins to genes, and `string_scores` gives each gene of the network a score.

```python
import pandas as pd

from seedmatch import Reference, read_string_links, string_gene_network, string_scores

# The links with a score of 400 or more, and then the links above the 95th percentile of these scores.
links = read_string_links("10116.protein.links.v12.5.txt.gz")

# The EnsDb of the same species and build gives the gene of each protein.
with Reference.from_paths(ensdb="ensdb.sqlite", genome="genome.2bit") as ref:
    network = string_gene_network(links.links, ref)

# The seed count of each 3' UTR, with the gene ID of the UTR. A gene with more than one row keeps the highest count (D-062).
utr3_de = pd.DataFrame({"gene_id": utr3.gene_ids, "mer7m8": utr3_counts})
string_result = string_scores(network.edges, utr3_de, column="mer7m8")
print(string_result.head())
```

## Plots and the HTML report

The functions of `seedmatch.plot` work only with the extra `plot`. A plot function returns a `matplotlib.figure.Figure`, and `report_html` returns the report table as HTML.

```python
from pathlib import Path

from seedmatch import report_html
from seedmatch.plot import (
    plot_alignment,
    plot_benchmark,
    plot_ecdf,
    plot_kmer_histogram,
    plot_ranges,
    plot_wasserstein,
)

# The ECDF of the two gene sets of the ecdf_test example, with the result of the test.
ecdf_figure = plot_ecdf(de, {"Background": background, "mer7m8": seed_genes}, ecdf_result)
ecdf_figure.savefig("ecdf.png", dpi=300)

# The density, the ECDF, and the ECDF difference of the Wasserstein areas.
wasserstein_figure = plot_wasserstein(
    de.loc[de["mer7m8"] >= 1, "log2FoldChange"], de.loc[de["mer7m8"] == 0, "log2FoldChange"]
)

# The number of genes with each 7-mer, with a line at the target.
kmer_figure = plot_kmer_histogram(genes_with_kmer, target.sequence)

# The alignment text of the example above.
alignment_figure = plot_alignment(alignment)

# One bar for each match range of the first example.
ranges_figure = plot_ranges(ranges)

# The PR curve and the ROC curve of the benchmark example.
benchmark_figure = plot_benchmark(benchmark)

# The SeedMatchReport table as HTML.
Path("report.html").write_text(report_html(report, guide), encoding="utf-8")
```

## Resources

The sandbox of an agent has no network access. Thus a machine with network access runs `seedmatch-fetch`, and the sandbox reads the files from a path. The registry in `seedmatch.resources` pins the URL, the size, and the SHA-256 digest of each file.

```bash
# The 2bit file and the EnsDb file of one genome build.
seedmatch-fetch reference rnor7 refs/rnor7

# The DESeq2 tables of the siRNA example (GEO series GSE184929).
seedmatch-fetch example sirna data/sirna

# The miRDB v6.0 predictions.
seedmatch-fetch mirdb data/mirdb

# The TRRUST table of human or mouse.
seedmatch-fetch trrust human data/trrust

# The STRING protein links of one NCBI taxon.
seedmatch-fetch string 10116 data/string

# One line for each file: the group, the key, the file name, the size in bytes, and the description.
seedmatch-fetch list
```

[`guide.md`](https://github.com/inflexa-ai/seedmatch/blob/main/src/seedmatch/guide.md) gives the output and the exit status of the command, and the Python API of the registry.

## Differences from SeedMatchR

seedmatch corrects the defects of SeedMatchR that it finds. These changes are the most important for a user:

- The ranges of a search obey the same rules as the counts. In R, `vmatchPattern2` uses the indel algorithm also when `with.indels` is `FALSE`, if the pattern is longer than `max.mismatch`. Thus the ranges and the counts do not agree (D-001).
- A result for a gene uses all the sequences of the gene. R uses the first sequence for the seed count, and it counts each sequence in the report (D-003).
- `full_search_ranges` gives a result for each input. R stops if each search finds a match, or if no search finds a match (D-022).
- `wobble=True` with `fixed_pattern=True` raises `InputError`, because a fixed pattern matches the wobble letter R only to the letter R (D-026).
- A sequence from an annotation keeps its transcript ID and its gene ID. In R, `load_annotations` gives the name `NA` to each sequence of a gene union (D-002), and `tx.names` is `NULL` (D-009).
- `ecdf_test` drops the rows without a fold change for each test. R drops them for the KS and Wilcoxon tests only, and it stops for DTS and Wasserstein (D-036). `ecdf_test` raises `InputError` for an `alternative` with DTS or Wasserstein, but R ignores it without a message (D-035).
- `kmer_gene_counts` counts the genes with a k-mer. The histogram of R counts the sequences, but its label says genes (D-042).
- `benchmark_predictions` applies the `padj` cutoff. In R, `padj <= padj` compares the column with itself, thus each row with a `padj` passes. R also gives the labels to the ROC curve as the scores of the negative class (D-006).
- `alignment_text` shows the full guide, from g1 to the last base. In R, the guide line of `plotAlignment` has no g1, and the function stops for the default positions (D-045).
- The wobble and bulge search runs. In R, each call of `run_wobble_bulges_pipeline` stops with an error. The port counts each distinct start of a site one time, and a bulge is a run of extra target bases (D-005).
- The 3' compensatory search runs. R returns 0 rows for each input. Without the early return, its code stops at the first site. The port gives each pair of a seed match and a region (D-004).
- `trrust_scores` takes the messages of a gene from its regulators. R takes them from the targets of the gene (D-007).
- `plot_ecdf` gives a figure for each p-value, and its legend counts the values of each line. R stops for a p-value of 0.01, and its legend counts the gene lists (D-063, D-064).
- An input that R accepts in silence, but that gives a wrong result, raises `InputError`. The message gives the bad value. Examples are a gap letter in a sequence (D-017), a DESeq2 table with the wrong columns (D-021), and a NaN cutoff (D-024).

## Performance

seedmatch is faster than SeedMatchR, and its process uses less memory. The table gives the values of `seed_match_report` with the default options, on the canonical 3' UTRs of the rat genome build `rnor7`. This input has 18,614 sequences and 17,913,962 bases. The machine is an Apple M2 Max with 12 CPUs. Each run makes three calls in one process, and a cell gives the range of two runs. SeedMatchR uses one thread.

| Measure | seedmatch, all CPUs | seedmatch, 1 thread | SeedMatchR |
|---|---|---|---|
| Time of one call | 0.18 to 0.20 s | 1.19 to 1.22 s | 9.32 to 9.63 s |
| Speedup over SeedMatchR | 47× to 54× | 7.6× to 8.1× | 1× |
| Peak resident memory of the process | 137 to 140 MiB | 135 to 136 MiB | 432 to 443 MiB |

[`docs/performance.md`](https://github.com/inflexa-ai/seedmatch/blob/main/docs/performance.md) gives the versions, the commands that measure these values, and the time of each search of `full_search`.

## Development

[`CONTRIBUTING.md`](https://github.com/inflexa-ai/seedmatch/blob/main/CONTRIBUTING.md) gives the setup, the checks, and the rules for a contribution. To report a security problem, obey [`SECURITY.md`](https://github.com/inflexa-ai/seedmatch/blob/main/SECURITY.md).

## License

seedmatch uses the MIT License, the same license as SeedMatchR. See [`LICENSE`](https://github.com/inflexa-ai/seedmatch/blob/main/LICENSE).

