Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 195 additions & 0 deletions analysis/rhodotorula_mucilage/build_orthofinder_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
"""Build the OrthoFinder input folder for the two-tier subtraction: focal Rhodotorula plus BFD outgroups.

Plan: docs/superpowers/plans/2026-11-28-rhodotorula-mucilage-candidate-discovery.md (Step 2).

Inputs are the two signed lists (focal_signed.tsv from focal_set.py, outgroups_gate80.tsv from
outgroup_set.py). The folder holds one plain FASTA per genome, named <Genus_species_...>.proteins.fa,
plus manifest.tsv (file, tier, species, group, locus tag, protein count) for reading the results.

Checks, each fatal: every file resolves and is non-empty; every FASTA header starts with the genome's
locus-tag prefix (so a wrong file cannot slip in); no protein id appears twice, inside a file or across
files; no isoform suffix -T2 or higher (OrthoFinder wants one protein per gene).
BFD files are gzipped and are decompressed here, because OrthoFinder reads plain FASTA.

python3 analysis/rhodotorula_mucilage/build_orthofinder_input.py --focal focal_signed.tsv \
--outgroups outgroups_gate80.tsv --rodeo-pep RODEO/input/pep --bfd-pep BFD/input/pep \
--out-dir DIR [--max-outgroup-dup 10]
"""

import argparse
import csv
import gzip
import os
import re
import shutil
import sys

ISOFORM = re.compile(r"-T([2-9]|\d\d+)(\s|$)")


class InputError(Exception):
pass


def sanitize(text):
return re.sub(r"[^A-Za-z0-9._-]+", "_", text.strip()).strip("_")


def read_tsv(path):
with open(path, newline="", encoding="utf-8-sig") as handle:
return [
{k.strip(): (v or "").strip() for k, v in row.items()}
for row in csv.DictReader(handle, delimiter="\t")
]


def bfd_candidates(species, strain, locustag):
base = sanitize(species.replace(" ", "_"))
names = []
if strain:
names.append(f"{base}_{sanitize(strain.replace(' ', '_'))}")
names.append(base)
return [f"{n}.proteins.fa.gz" for n in names]


def open_text(path):
return gzip.open(path, "rt") if path.endswith(".gz") else open(path)


def scan_fasta(path):
"""Return (n_proteins, set of id prefixes before the first underscore, ids). Raises on bad content."""
ids = []
with open_text(path) as handle:
for line in handle:
if line.startswith(">"):
if ISOFORM.search(line.split()[0]):
raise InputError(f"{path}: isoform id {line.split()[0]}")
ids.append(line[1:].split()[0])
if not ids:
raise InputError(f"{path}: no sequences")
return ids


def resolve_bfd(pep_dir, species, strain, locustag):
"""The BFD file whose first header carries the locus tag; names with and without strain are tried."""
tried = []
for name in bfd_candidates(species, strain, locustag):
path = os.path.join(pep_dir, name)
tried.append(path)
if os.path.exists(path):
with open_text(path) as handle:
first = handle.readline()
if first.startswith(">" + locustag + "_"):
return path
raise InputError(f"no BFD proteome for {species} / {strain} / {locustag}; tried {tried}")


def plan(focal, outgroups, rodeo_pep, bfd_pep, max_outgroup_dup=None):
"""List of dicts: file, src, tier, species, group, locustag."""
items = []
for row in focal:
src = os.path.join(rodeo_pep, row["proteome"] + ".proteins.fa")
if not os.path.exists(src):
raise InputError(f"missing focal proteome {src}")
items.append(
{
"file": sanitize(row["proteome"]) + ".proteins.fa",
"src": src,
"tier": "focal",
"species": row["species"],
"group": row.get("pop", ""),
"locustag": None,
}
)
dropped = []
for row in outgroups:
if max_outgroup_dup is not None and float(row["busco_duplicated"]) > max_outgroup_dup:
dropped.append(row["SPECIES"])
continue
src = resolve_bfd(bfd_pep, row["SPECIES"], row["STRAIN"], row["LOCUSTAG"])
stem = sanitize(row["SPECIES"].replace(" ", "_")) + "_" + row["LOCUSTAG"]
items.append(
{
"file": stem + ".proteins.fa",
"src": src,
"tier": "outgroup",
"species": row["SPECIES"],
"group": (row.get("ORDER") or row.get("CLASS") or ""),
"locustag": row["LOCUSTAG"],
}
)
files = [i["file"] for i in items]
if len(set(files)) != len(files):
raise InputError("duplicate output file names")
return items, dropped


def build(items, out_dir):
os.makedirs(out_dir)
seen = {}
manifest = []
for item in items:
ids = scan_fasta(item["src"])
if item["locustag"] and not all(i.startswith(item["locustag"] + "_") for i in ids):
raise InputError(f"{item['src']}: ids outside locus tag {item['locustag']}")
if len(set(ids)) != len(ids):
raise InputError(f"{item['src']}: duplicate ids inside the file")
for i in ids:
if i in seen:
raise InputError(f"id {i} in {item['file']} and {seen[i]}")
seen[i] = item["file"]
dest = os.path.join(out_dir, item["file"])
with open_text(item["src"]) as src, open(dest, "w") as out:
shutil.copyfileobj(src, out)
manifest.append({**item, "n_proteins": len(ids)})
return manifest


def write_manifest(path, manifest):
with open(path, "w", newline="") as handle:
out = csv.writer(handle, delimiter="\t", lineterminator="\n")
out.writerow("file tier species group locustag n_proteins".split())
for m in manifest:
out.writerow(
[
m["file"],
m["tier"],
m["species"],
m["group"],
m["locustag"] or "",
m["n_proteins"],
]
)


def main(argv=None):
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--focal", required=True)
p.add_argument("--outgroups", required=True)
p.add_argument("--rodeo-pep", required=True)
p.add_argument("--bfd-pep", required=True)
p.add_argument("--out-dir", required=True)
p.add_argument("--max-outgroup-dup", type=float, default=None)
args = p.parse_args(argv)
if os.path.exists(args.out_dir):
print(f"FATAL: {args.out_dir} exists; nothing is overwritten", file=sys.stderr)
raise SystemExit(1)
items, dropped = plan(
read_tsv(args.focal),
read_tsv(args.outgroups),
args.rodeo_pep,
args.bfd_pep,
args.max_outgroup_dup,
)
manifest = build(items, args.out_dir)
write_manifest(os.path.join(args.out_dir + ".manifest.tsv"), manifest)
n_focal = sum(m["tier"] == "focal" for m in manifest)
print(
f"wrote {len(manifest)} proteomes ({n_focal} focal, {len(manifest) - n_focal} outgroup); "
f"dropped for duplication: {dropped}; proteins: {sum(m['n_proteins'] for m in manifest)}"
)
return 0


if __name__ == "__main__":
raise SystemExit(main())
30 changes: 30 additions & 0 deletions analysis/rhodotorula_mucilage/busco_hap.sbatch
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
#SBATCH --job-name=busco_hap
#SBATCH --partition=exfab
#SBATCH --cpus-per-task=8
#SBATCH --mem=16G
#SBATCH --time=02:00:00
#SBATCH --output=%x_%j.log
# BUSCO (fungi_odb12, protein mode) for the four Rodeo haplotype proteomes that have no summary.
# Summaries are named like the BFD/Rodeo ones so focal_set.py can read them with --busco-dir.
# Work happens in $SCRATCH (cleared at job end); only the summaries are kept.
set -euo pipefail
# `module load busco/6.1.0` runs `conda activate --stack`, which the cluster conda rejects inside a job,
# so the module's environment is put on PATH directly.
BUSCO_ENV=/opt/linux/rocky/8.x/x86_64/pkgs/busco/6.1.0/env
test -x "$BUSCO_ENV/bin/busco" || { echo "FATAL: no busco in $BUSCO_ENV"; exit 1; }
export PATH="$BUSCO_ENV/bin:$PATH"
PEP=/bigdata/stajichlab/shared/projects/Rhodotorula/Rhodotorula_Rodeo/input/pep
LIN=/srv/projects/db/BUSCO/v12/lineages/fungi_odb12
OUT=${OUT:?set OUT to the result directory}
test -d "$LIN" || { echo "FATAL: no lineage $LIN"; exit 1; }
mkdir -p "$OUT"
for name in Rhodotorula_mucilaginosa_DBVPG_3045_hap1 Rhodotorula_mucilaginosa_DBVPG_3855_hap1 \
Rhodotorula_mucilaginosa_TFCN_17-0-2E334-4_hap1 Rhodotorula_mucilaginosa_TFCN_17Y-278-1_hap1; do
fa=$PEP/$name.proteins.fa
test -s "$fa" || { echo "FATAL: missing $fa"; exit 1; }
busco -i "$fa" -m proteins -l "$LIN" --offline -c "$SLURM_CPUS_PER_TASK" -o "$name" --out_path "$SCRATCH" -f
s=$(ls "$SCRATCH/$name"/short_summary.specific.fungi_odb12.*.txt | head -1)
cp "$s" "$OUT/$name.BUSCO_summary.fungi_odb12.txt"
done
ls -l "$OUT"
Loading
Loading