musabid 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
musabid-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MusaBiD developers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
musabid-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: musabid
3
+ Version: 0.1.0
4
+ Summary: MusaBiD: identify head-to-head (bidirectional-promoter) gene pairs in plant genomes, tuned for banana (Musa).
5
+ Author: MusaBiD developers
6
+ License: MIT
7
+ Keywords: banana,musa,bidirectional promoter,head-to-head,divergent genes,GFF3
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=7; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ # MusaBiD — Musa bidirectional-promoter gene pair finder
18
+
19
+ `musabid` (MusaBiD) identifies **head-to-head (divergent) gene pairs** — two
20
+ adjacent genes on opposite strands whose 5' ends face each other across a
21
+ shared intergenic region — the classic genomic arrangement behind
22
+ bidirectional promoters. It is tuned for banana (*Musa*) annotations (e.g.
23
+ the DH-Pahang reference) but works on any GFF3.
24
+
25
+ v0.1 is the annotation-level MVP: pair finding, filtering and reporting.
26
+ Epigenome scoring (DNase/ATAC, H3K4me3/H3K27ac/H3K9ac/H3K27me3), DAP-seq
27
+ TF evidence and RNA-seq co-expression weighting are planned for v0.2/v0.3
28
+ (see Roadmap).
29
+
30
+ ## Definition
31
+
32
+ ```
33
+ <-| A |------ intergenic region ------| B |->
34
+ TSS_A = A.end TSS_B = B.start
35
+
36
+ left gene A : '-' strand (5' end at its end coordinate)
37
+ right gene B: '+' strand (5' end at its start coordinate)
38
+ TSS distance = B.start - A.end
39
+ ```
40
+
41
+ Pairs are only formed between **adjacent** genes in the annotation (an
42
+ intervening gene — of any biotype — breaks adjacency). Convergent
43
+ (tail-to-tail), tandem and same-strand arrangements are ignored.
44
+
45
+ ## Install
46
+
47
+ Zero-dependency (Python >= 3.9), including FASTA extraction:
48
+
49
+ ```bash
50
+ pip install -e . # console command: musabid
51
+ # or run without installing:
52
+ # PYTHONPATH=src python -m musabid find ...
53
+ ```
54
+
55
+ Run the tests:
56
+
57
+ ```bash
58
+ pip install -e ".[dev]"
59
+ pytest -q
60
+ ```
61
+
62
+ ## Quick start
63
+
64
+ ```bash
65
+ musabid inspect -g examples/mini.gff3 # pre-flight summary (feature types, seqids, biotypes)
66
+ musabid find -g examples/mini.gff3 -o demo_out
67
+ ```
68
+
69
+ Or with a real banana annotation (e.g. the Banana Genome Hub GFF3, which
70
+ has no `gene` rows -- mRNA isoforms are collapsed to their Parent genes
71
+ automatically) plus genome FASTA:
72
+
73
+ ```bash
74
+ musabid inspect -g musa_acuminata_checked.gff3
75
+ musabid find \
76
+ -g musa_acuminata_checked.gff3 \
77
+ -f musa_acuminata_v2_pseudochromosome.fna \
78
+ -o musabid_out \
79
+ --seqids chr01,chr02,chr03,chr04,chr05,chr06,chr07,chr08,chr09,chr10,chr11
80
+ ```
81
+
82
+ Note: `-f` needs the whole-genome assembly FASTA (chromosome records
83
+ chr01..chr11), not the per-gene `*_gene.fna` file, because promoters lie
84
+ outside the gene-body sequences.
85
+
86
+ ## Options (`musabid find`)
87
+
88
+ | option | default | meaning |
89
+ |---|---|---|
90
+ | `-g/--gff3` | — (required) | input GFF3 annotation |
91
+ | `-o/--outdir` | `musabid_out` | output directory |
92
+ | `-f/--fasta` | none | optional genome FASTA → `promoters.fa` |
93
+ | `--flank` | 0 | extra bp beyond each TSS for FASTA extraction |
94
+ | `--min-tss-dist` | 1 | minimum TSS distance (1 = non-overlapping bodies) |
95
+ | `--max-tss-dist` | 2000 | maximum TSS distance for reported pairs |
96
+ | `--gene-type` | `gene` | GFF3 feature type used as gene model (falls back to mRNA/transcript) |
97
+ | `--no-collapse` | off | keep mRNA/transcript isoforms instead of merging to Parent genes |
98
+ | `--seqids` | all | comma-separated seqids to analyze (e.g. chr01..chr11 to skip organelles) |
99
+ | `--biotype` | none | comma list; both pair members must match |
100
+ | `--block-types` | `ncRNA,transposable_element,repeat_region` | feature types excluding a pair when overlapping its intergenic region; empty string disables |
101
+ | `--soft-block` | off | keep blocked pairs, flag them instead of excluding |
102
+
103
+ ## Outputs (in `--outdir`)
104
+
105
+ * `pairs.tsv` — kept pairs: ids, names, biotypes, coordinates, TSSs,
106
+ `tss_dist`, `intergenic_len`, `promoter_len`, `blocked_types`.
107
+ * `excluded.tsv` — rejected pairs with `excluded_reason`.
108
+ * `promoters.bed` — BED6 of the TSS-to-TSS region (both TSSs included).
109
+ * `promoters.fa` — promoter sequences (only with `-f`).
110
+ * `run_summary.txt` — machine-readable key=value run summary (input stats,
111
+ counts, distance bins, output paths).
112
+
113
+ The console prints the same summary in human-readable form, including the
114
+ distance distribution of **all** head-to-head pairs up to 5 kb (computed
115
+ independently of `--max-tss-dist`), useful as background for enrichment
116
+ analyses.
117
+
118
+ ## Banana-specific notes
119
+
120
+ * Triploid cultivars (AAA, e.g. Cavendish) are highly heterozygous. Use a
121
+ haploid-resolved annotation such as *M. acuminata* DH-Pahang when you need
122
+ clean TSS positions; for cultivar data, expect allelic duplicate models.
123
+ * The Banana Genome Hub checked GFF3 has no `gene` rows (only mRNA/exon/CDS)
124
+ and no biotype attribute. musabid falls back to mRNA and merges isoforms
125
+ sharing a Parent gene automatically (45,719 mRNAs -> 35,159 genes in the
126
+ 2026-07-18 checked annotation); `musabid inspect` reports these numbers so
127
+ you can confirm before pairing.
128
+ * Annotation quality dominates results. The 1 kb / 2 kb TSS-distance bins
129
+ reported by default match the common conventions for plant bidirectional-
130
+ promoter screens.
131
+
132
+ ## Roadmap
133
+
134
+ * v0.2 — epigenome evidence: DNase/ATAC bigWig coverage across the shared
135
+ region, H3K4me3/H3K27ac/H3K9ac/H3K27me3 chromatin-state classification,
136
+ per-pair evidence score.
137
+ * v0.3 — TF evidence (DAP-seq peaks + motifs), RNA-seq co-expression
138
+ weighting, HTML report per candidate pair.
139
+ * v1.0 — packaging, bioconda, benchmark golden set, online resource.
140
+
141
+ ## License
142
+
143
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,127 @@
1
+ # MusaBiD — Musa bidirectional-promoter gene pair finder
2
+
3
+ `musabid` (MusaBiD) identifies **head-to-head (divergent) gene pairs** — two
4
+ adjacent genes on opposite strands whose 5' ends face each other across a
5
+ shared intergenic region — the classic genomic arrangement behind
6
+ bidirectional promoters. It is tuned for banana (*Musa*) annotations (e.g.
7
+ the DH-Pahang reference) but works on any GFF3.
8
+
9
+ v0.1 is the annotation-level MVP: pair finding, filtering and reporting.
10
+ Epigenome scoring (DNase/ATAC, H3K4me3/H3K27ac/H3K9ac/H3K27me3), DAP-seq
11
+ TF evidence and RNA-seq co-expression weighting are planned for v0.2/v0.3
12
+ (see Roadmap).
13
+
14
+ ## Definition
15
+
16
+ ```
17
+ <-| A |------ intergenic region ------| B |->
18
+ TSS_A = A.end TSS_B = B.start
19
+
20
+ left gene A : '-' strand (5' end at its end coordinate)
21
+ right gene B: '+' strand (5' end at its start coordinate)
22
+ TSS distance = B.start - A.end
23
+ ```
24
+
25
+ Pairs are only formed between **adjacent** genes in the annotation (an
26
+ intervening gene — of any biotype — breaks adjacency). Convergent
27
+ (tail-to-tail), tandem and same-strand arrangements are ignored.
28
+
29
+ ## Install
30
+
31
+ Zero-dependency (Python >= 3.9), including FASTA extraction:
32
+
33
+ ```bash
34
+ pip install -e . # console command: musabid
35
+ # or run without installing:
36
+ # PYTHONPATH=src python -m musabid find ...
37
+ ```
38
+
39
+ Run the tests:
40
+
41
+ ```bash
42
+ pip install -e ".[dev]"
43
+ pytest -q
44
+ ```
45
+
46
+ ## Quick start
47
+
48
+ ```bash
49
+ musabid inspect -g examples/mini.gff3 # pre-flight summary (feature types, seqids, biotypes)
50
+ musabid find -g examples/mini.gff3 -o demo_out
51
+ ```
52
+
53
+ Or with a real banana annotation (e.g. the Banana Genome Hub GFF3, which
54
+ has no `gene` rows -- mRNA isoforms are collapsed to their Parent genes
55
+ automatically) plus genome FASTA:
56
+
57
+ ```bash
58
+ musabid inspect -g musa_acuminata_checked.gff3
59
+ musabid find \
60
+ -g musa_acuminata_checked.gff3 \
61
+ -f musa_acuminata_v2_pseudochromosome.fna \
62
+ -o musabid_out \
63
+ --seqids chr01,chr02,chr03,chr04,chr05,chr06,chr07,chr08,chr09,chr10,chr11
64
+ ```
65
+
66
+ Note: `-f` needs the whole-genome assembly FASTA (chromosome records
67
+ chr01..chr11), not the per-gene `*_gene.fna` file, because promoters lie
68
+ outside the gene-body sequences.
69
+
70
+ ## Options (`musabid find`)
71
+
72
+ | option | default | meaning |
73
+ |---|---|---|
74
+ | `-g/--gff3` | — (required) | input GFF3 annotation |
75
+ | `-o/--outdir` | `musabid_out` | output directory |
76
+ | `-f/--fasta` | none | optional genome FASTA → `promoters.fa` |
77
+ | `--flank` | 0 | extra bp beyond each TSS for FASTA extraction |
78
+ | `--min-tss-dist` | 1 | minimum TSS distance (1 = non-overlapping bodies) |
79
+ | `--max-tss-dist` | 2000 | maximum TSS distance for reported pairs |
80
+ | `--gene-type` | `gene` | GFF3 feature type used as gene model (falls back to mRNA/transcript) |
81
+ | `--no-collapse` | off | keep mRNA/transcript isoforms instead of merging to Parent genes |
82
+ | `--seqids` | all | comma-separated seqids to analyze (e.g. chr01..chr11 to skip organelles) |
83
+ | `--biotype` | none | comma list; both pair members must match |
84
+ | `--block-types` | `ncRNA,transposable_element,repeat_region` | feature types excluding a pair when overlapping its intergenic region; empty string disables |
85
+ | `--soft-block` | off | keep blocked pairs, flag them instead of excluding |
86
+
87
+ ## Outputs (in `--outdir`)
88
+
89
+ * `pairs.tsv` — kept pairs: ids, names, biotypes, coordinates, TSSs,
90
+ `tss_dist`, `intergenic_len`, `promoter_len`, `blocked_types`.
91
+ * `excluded.tsv` — rejected pairs with `excluded_reason`.
92
+ * `promoters.bed` — BED6 of the TSS-to-TSS region (both TSSs included).
93
+ * `promoters.fa` — promoter sequences (only with `-f`).
94
+ * `run_summary.txt` — machine-readable key=value run summary (input stats,
95
+ counts, distance bins, output paths).
96
+
97
+ The console prints the same summary in human-readable form, including the
98
+ distance distribution of **all** head-to-head pairs up to 5 kb (computed
99
+ independently of `--max-tss-dist`), useful as background for enrichment
100
+ analyses.
101
+
102
+ ## Banana-specific notes
103
+
104
+ * Triploid cultivars (AAA, e.g. Cavendish) are highly heterozygous. Use a
105
+ haploid-resolved annotation such as *M. acuminata* DH-Pahang when you need
106
+ clean TSS positions; for cultivar data, expect allelic duplicate models.
107
+ * The Banana Genome Hub checked GFF3 has no `gene` rows (only mRNA/exon/CDS)
108
+ and no biotype attribute. musabid falls back to mRNA and merges isoforms
109
+ sharing a Parent gene automatically (45,719 mRNAs -> 35,159 genes in the
110
+ 2026-07-18 checked annotation); `musabid inspect` reports these numbers so
111
+ you can confirm before pairing.
112
+ * Annotation quality dominates results. The 1 kb / 2 kb TSS-distance bins
113
+ reported by default match the common conventions for plant bidirectional-
114
+ promoter screens.
115
+
116
+ ## Roadmap
117
+
118
+ * v0.2 — epigenome evidence: DNase/ATAC bigWig coverage across the shared
119
+ region, H3K4me3/H3K27ac/H3K9ac/H3K27me3 chromatin-state classification,
120
+ per-pair evidence score.
121
+ * v0.3 — TF evidence (DAP-seq peaks + motifs), RNA-seq co-expression
122
+ weighting, HTML report per candidate pair.
123
+ * v1.0 — packaging, bioconda, benchmark golden set, online resource.
124
+
125
+ ## License
126
+
127
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "musabid"
7
+ version = "0.1.0"
8
+ description = "MusaBiD: identify head-to-head (bidirectional-promoter) gene pairs in plant genomes, tuned for banana (Musa)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "MusaBiD developers" }]
13
+ keywords = ["banana", "musa", "bidirectional promoter", "head-to-head", "divergent genes", "GFF3"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
17
+ ]
18
+ dependencies = []
19
+
20
+ [project.optional-dependencies]
21
+ dev = ["pytest>=7"]
22
+
23
+ [project.scripts]
24
+ musabid = "musabid.cli:main"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+
29
+ [tool.pytest.ini_options]
30
+ testpaths = ["tests"]
31
+ # No cache writes: the cache dir cannot be created in this sandbox.
32
+ addopts = "-p no:cacheprovider"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """musabid -- MusaBiD: bidirectional (head-to-head) gene pair finder for plant genomes."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,224 @@
1
+ """Command-line interface for musabid."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .extract import extract_promoters
12
+ from .gff import parse_gff
13
+ from .pairs import (
14
+ Pair,
15
+ annotate_blocks,
16
+ apply_biotype_filter,
17
+ find_head_to_head_pairs,
18
+ )
19
+ from .report import (
20
+ bin_counts,
21
+ write_excluded_tsv,
22
+ write_pairs_tsv,
23
+ write_promoters_bed,
24
+ write_run_summary,
25
+ )
26
+
27
+ # Distance distribution in the console summary is always computed over
28
+ # head-to-head pairs up to this TSS distance, independently of --max-tss-dist.
29
+ _SUMMARY_MAX_DIST = 5000
30
+
31
+ LOG = logging.getLogger("musabid")
32
+
33
+
34
+ def _split_csv(value: str) -> list:
35
+ return [item.strip() for item in value.split(",") if item.strip()]
36
+
37
+
38
+ def build_parser() -> argparse.ArgumentParser:
39
+ parser = argparse.ArgumentParser(
40
+ prog="musabid",
41
+ description=(
42
+ "MusaBiD - identify head-to-head (bidirectional-promoter) gene "
43
+ "pairs in a GFF3 annotation. Tuned for banana (Musa) but "
44
+ "annotation-generic."
45
+ ),
46
+ )
47
+ parser.add_argument("--version", action="version", version=f"musabid {__version__}")
48
+ sub = parser.add_subparsers(dest="command", required=True)
49
+
50
+ inspect = sub.add_parser("inspect", help="pre-flight summary of a GFF3 annotation")
51
+ inspect.add_argument("-g", "--gff3", required=True, help="input GFF3 annotation")
52
+ inspect.add_argument("--gene-type", default="gene",
53
+ help="preferred GFF3 feature type for gene models (default: gene)")
54
+
55
+ find = sub.add_parser("find", help="find head-to-head gene pairs in a GFF3")
56
+ find.add_argument("-g", "--gff3", required=True, help="input GFF3 annotation")
57
+ find.add_argument("-o", "--outdir", default="musabid_out", help="output directory (default: musabid_out)")
58
+ find.add_argument("-f", "--fasta", default=None, help="optional genome FASTA; extracts promoter sequences")
59
+ find.add_argument("--flank", type=int, default=0, help="extra bases beyond each TSS for FASTA extraction (default: 0)")
60
+ find.add_argument("--min-tss-dist", type=int, default=1, help="minimum TSS distance (default: 1, i.e. non-overlapping bodies)")
61
+ find.add_argument("--max-tss-dist", type=int, default=2000, help="maximum TSS distance for reported pairs (default: 2000)")
62
+ find.add_argument("--gene-type", default="gene", help="GFF3 feature type used as gene model (default: gene; falls back to mRNA/transcript)")
63
+ find.add_argument("--no-collapse", action="store_true",
64
+ help="do NOT merge mRNA/transcript isoforms sharing a Parent gene (default: merge)")
65
+ find.add_argument("--seqids", default=None,
66
+ help="comma-separated seqids to analyze (default: all, e.g. chr01,chr02,...,chr11 to skip organelles)")
67
+ find.add_argument("--biotype", default=None, help="comma-separated biotypes both pair members must carry (default: no filter)")
68
+ find.add_argument("--block-types", default="ncRNA,transposable_element,repeat_region",
69
+ help="comma-separated feature types that exclude a pair when overlapping its intergenic region; empty string disables (default: ncRNA,transposable_element,repeat_region)")
70
+ find.add_argument("--soft-block", action="store_true",
71
+ help="keep blocked pairs and mark them in pairs.tsv instead of excluding them")
72
+ find.add_argument("-v", "--verbose", action="store_true", help="debug logging to stderr")
73
+ return parser
74
+
75
+
76
+ def _inspect(args) -> int:
77
+ from .gff import inspect_gff
78
+
79
+ info = inspect_gff(args.gff3, gene_type=args.gene_type)
80
+ print(f"musabid inspect - {args.gff3}")
81
+ print(f"total feature lines : {info['total_features']}")
82
+ print("feature types : " + ", ".join(f"{k}={v}" for k, v in info["type_counts"].items()))
83
+ seqid_list = ", ".join(info["seqids"][:15]) + (" ..." if len(info["seqids"]) > 15 else "")
84
+ print(f"seqids ({info['seqid_count']}) : {seqid_list}")
85
+ fallback_note = " <-- no 'gene' rows; falling back to this type" if info["fallback_used"] else ""
86
+ print(f"gene-type used : {info['gene_type_used']}{fallback_note}")
87
+ print(f"gene rows : {info['gene_rows']}")
88
+ strands = info["strands"]
89
+ print(f"strand distribution : +={strands.get('+', 0)} -={strands.get('-', 0)} unstranded={strands.get('.', 0)}")
90
+ print("biotype values : " + (", ".join(f"{k}={v}" for k, v in info["biotypes"].items()) or "(none found)"))
91
+ if info["mrna_total"]:
92
+ print(f"mRNA rows : {info['mrna_total']}")
93
+ print(f"distinct Parent genes: {info['distinct_parents']}"
94
+ f" (multi-transcript genes: {info['multi_transcript_genes']})")
95
+ return 0
96
+
97
+
98
+ def _find(args) -> int:
99
+ outdir = Path(args.outdir)
100
+ outdir.mkdir(parents=True, exist_ok=True)
101
+
102
+ genes, features, stats = parse_gff(args.gff3, gene_type=args.gene_type,
103
+ collapse_mrna=not args.no_collapse)
104
+
105
+ seqid_filter = _split_csv(args.seqids) if args.seqids else []
106
+ if seqid_filter:
107
+ keep_seqids = set(seqid_filter)
108
+ genes = [g for g in genes if g.seqid in keep_seqids]
109
+ features = [f for f in features if f.seqid in keep_seqids]
110
+
111
+ # Distance distribution over a fixed wide window (see _SUMMARY_MAX_DIST).
112
+ all_pairs = find_head_to_head_pairs(genes, min_tss_dist=1, max_tss_dist=_SUMMARY_MAX_DIST)
113
+
114
+ # Reported pairs under the user's distance thresholds.
115
+ pairs = find_head_to_head_pairs(genes, args.min_tss_dist, args.max_tss_dist)
116
+
117
+ biotypes = _split_csv(args.biotype) if args.biotype else []
118
+ if biotypes:
119
+ all_pairs = apply_biotype_filter(all_pairs, biotypes)
120
+ pairs = apply_biotype_filter(pairs, biotypes)
121
+
122
+ block_types = _split_csv(args.block_types) if args.block_types else []
123
+ annotate_blocks(pairs, features, block_types)
124
+
125
+ excluded: list = []
126
+ kept: list = []
127
+ for pair in pairs:
128
+ if pair.blocked and not args.soft_block:
129
+ pair.excluded_reason = "blocked_by:" + ",".join(pair.blocked)
130
+ excluded.append(pair)
131
+ else:
132
+ kept.append(pair)
133
+
134
+ pairs_path = outdir / "pairs.tsv"
135
+ excluded_path = outdir / "excluded.tsv"
136
+ bed_path = outdir / "promoters.bed"
137
+ write_pairs_tsv(pairs_path, kept)
138
+ write_excluded_tsv(excluded_path, excluded)
139
+ write_promoters_bed(bed_path, kept)
140
+
141
+ fasta_path = None
142
+ if args.fasta:
143
+ fasta_path = outdir / "promoters.fa"
144
+ n_written = extract_promoters(args.fasta, kept, fasta_path, flank=args.flank)
145
+ LOG.info("extracted %d promoter sequences to %s", n_written, fasta_path)
146
+
147
+ bins = bin_counts(all_pairs, max_bin=_SUMMARY_MAX_DIST)
148
+
149
+ info = {
150
+ "musabid_version": __version__,
151
+ "input_gff": str(Path(args.gff3).resolve()),
152
+ "gene_type_used": stats.gene_type_used,
153
+ "total_features": stats.total_features,
154
+ "gene_rows": stats.gene_rows,
155
+ "genes_parsed": stats.genes_parsed,
156
+ "skipped_no_strand": stats.skipped_no_strand,
157
+ "duplicate_ids": stats.duplicate_ids,
158
+ "collapsed": stats.collapsed,
159
+ "multi_transcript_genes": stats.multi_transcript_genes,
160
+ "mixed_strand_genes": stats.mixed_strand_genes,
161
+ "seqid_filter": ",".join(seqid_filter) or "all",
162
+ "min_tss_dist": args.min_tss_dist,
163
+ "max_tss_dist": args.max_tss_dist,
164
+ "biotype_filter": ",".join(biotypes) or "none",
165
+ "block_types": ",".join(block_types) or "none",
166
+ "soft_block": args.soft_block,
167
+ "candidates": len(pairs),
168
+ "blocked_excluded": len(excluded),
169
+ "kept": len(kept),
170
+ "bin_counts": bins,
171
+ "outputs": {
172
+ "pairs": str(pairs_path),
173
+ "excluded": str(excluded_path),
174
+ "promoters_bed": str(bed_path),
175
+ "promoters_fasta": str(fasta_path) if fasta_path else "none",
176
+ },
177
+ }
178
+ write_run_summary(outdir / "run_summary.txt", info)
179
+
180
+ # Console summary
181
+ print(f"musabid {__version__} - head-to-head gene pair finder")
182
+ print(f"input GFF3 : {args.gff3}")
183
+ print(f"gene-type feature : {stats.gene_type_used} (rows={stats.gene_rows})")
184
+ collapse_note = ""
185
+ if stats.collapsed:
186
+ collapse_note = (f" [collapsed to genes: {stats.multi_transcript_genes} multi-transcript,"
187
+ f" {stats.mixed_strand_genes} mixed-strand]")
188
+ print(f"genes parsed : {stats.genes_parsed}"
189
+ f" (skipped no-strand={stats.skipped_no_strand}, duplicate ids={stats.duplicate_ids}){collapse_note}")
190
+ if seqid_filter:
191
+ print(f"seqid filter : {','.join(seqid_filter)} ({len(genes)} genes kept)")
192
+ if biotypes:
193
+ print(f"biotype filter : {','.join(biotypes)}")
194
+ print(f"TSS distance window : {args.min_tss_dist}..{args.max_tss_dist} bp")
195
+ print(f"candidate pairs : {len(pairs)}")
196
+ print(f" blocked/excluded : {len(excluded)} (feature types: {','.join(block_types) or 'none'})")
197
+ print(f" kept : {len(kept)}")
198
+ print("distance distribution (all head-to-head pairs, <= %d bp, pre-block):" % _SUMMARY_MAX_DIST)
199
+ for label in ("1-500 bp", "501-1000 bp", "1001-2000 bp", f"2001-{_SUMMARY_MAX_DIST} bp"):
200
+ print(f" {label:<14}: {bins[label]}")
201
+ print(f"outputs : {outdir}")
202
+ print(f" pairs.tsv, excluded.tsv, promoters.bed, run_summary.txt"
203
+ + (", promoters.fa" if fasta_path else ""))
204
+ return 0
205
+
206
+
207
+ def main(argv=None) -> int:
208
+ parser = build_parser()
209
+ args = parser.parse_args(argv)
210
+ logging.basicConfig(
211
+ level=logging.DEBUG if getattr(args, "verbose", False) else logging.INFO,
212
+ format="[%(levelname)s] %(message)s",
213
+ stream=sys.stderr,
214
+ )
215
+ if args.command == "find":
216
+ return _find(args)
217
+ if args.command == "inspect":
218
+ return _inspect(args)
219
+ parser.error(f"unknown command: {args.command}")
220
+ return 2
221
+
222
+
223
+ if __name__ == "__main__":
224
+ raise SystemExit(main())
@@ -0,0 +1,74 @@
1
+ """Extraction of promoter-region sequences from a genome FASTA.
2
+
3
+ Pure-Python single-pass implementation: records are streamed from the
4
+ FASTA file (memory stays low even for large plant genomes) and regions
5
+ for the pairs on the current record are sliced out on the fly. No
6
+ third-party dependencies.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from pathlib import Path
13
+ from typing import Dict, Iterable, List, Sequence
14
+
15
+ from .pairs import Pair
16
+
17
+ LOG = logging.getLogger("musabid")
18
+
19
+
20
+ def extract_promoters(
21
+ fasta_path: str,
22
+ pairs: Sequence[Pair],
23
+ out_path,
24
+ flank: int = 0,
25
+ ) -> int:
26
+ """Write one FASTA record per pair spanning [left.tss-flank, right.tss+flank].
27
+
28
+ Region coordinates are 1-based inclusive; they are clipped to the
29
+ chromosome bounds. Pairs whose seqid is absent from the FASTA are
30
+ skipped (logged). Returns the number of records written.
31
+ """
32
+ by_seqid: Dict[str, List[Pair]] = {}
33
+ for pair in pairs:
34
+ by_seqid.setdefault(pair.seqid, []).append(pair)
35
+
36
+ out = Path(out_path)
37
+ written = 0
38
+ missing = 0
39
+ found_seqids: set = set()
40
+
41
+ def flush_record(name: str, parts: List[bytes]) -> None:
42
+ nonlocal written
43
+ seq = b"".join(parts).replace(b"\r", b"").replace(b"\n", b"")
44
+ for pair in by_seqid.get(name, []):
45
+ start = max(0, pair.left.tss - 1 - flank) # 0-based half-open
46
+ end = min(len(seq), pair.right.tss + flank)
47
+ if end <= start:
48
+ LOG.warning("empty region for %s on %s; skipped", pair.label, name)
49
+ continue
50
+ s = seq[start:end].decode("ascii")
51
+ fh.write(f">{pair.label} {pair.seqid}:{start + 1}-{end}\n")
52
+ for i in range(0, len(s), 80):
53
+ fh.write(s[i:i + 80] + "\n")
54
+ written += 1
55
+
56
+ with open(fasta_path, "rb") as fh_src, out.open("w", encoding="utf-8") as fh:
57
+ name = None
58
+ parts: List[bytes] = []
59
+ for raw in fh_src:
60
+ if raw.startswith(b">"):
61
+ if name is not None:
62
+ flush_record(name, parts)
63
+ name = raw[1:].decode("ascii", "replace").strip().split()[0]
64
+ parts = []
65
+ found_seqids.add(name)
66
+ else:
67
+ parts.append(raw)
68
+ if name is not None:
69
+ flush_record(name, parts)
70
+
71
+ missing = sum(1 for seqid in by_seqid if seqid not in found_seqids)
72
+ if missing:
73
+ LOG.warning("%d pair seqid(s) not found in the FASTA (skipped)", missing)
74
+ return written