| import os |
| import gzip |
| import json |
| import requests |
| import numpy as np |
| import pandas as pd |
| from Bio import SeqIO |
| from Bio.Seq import Seq |
| from scipy.stats import mannwhitneyu, poisson |
| from statsmodels.stats.multitest import multipletests |
|
|
| DATA_DIR = "data" |
| RESULTS_DIR = "results" |
| K = 11 |
| PROMOTER_LENGTH = 1000 |
| DOWNSTREAM_LENGTH = 500 |
|
|
| os.makedirs(DATA_DIR, exist_ok=True) |
| os.makedirs(RESULTS_DIR, exist_ok=True) |
|
|
| ABC_TRANSPORTERS = { |
| "PDR5": {"type": "Drug efflux", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "SNQ2": {"type": "Drug efflux", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "YOR1": {"type": "Drug efflux", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR10": {"type": "Drug efflux", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR11": {"type": "Sterol transport", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR12": {"type": "Weak acid efflux", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR15": {"type": "Drug efflux", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR1": {"type": "Transcription factor", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR3": {"type": "Transcription factor", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "YCF1": {"type": "Vacuolar transport", "essential": False, "stress": True, "subfamily": "MRP"}, |
| "YBT1": {"type": "Bile acid transport", "essential": False, "stress": False, "subfamily": "Other"}, |
| "VMR1": {"type": "Vacuolar transport", "essential": False, "stress": False, "subfamily": "MRP"}, |
| "ATM1": {"type": "Mitochondrial Fe-S", "essential": True, "stress": False, "subfamily": "ATM"}, |
| "MDL1": {"type": "Mitochondrial peptide", "essential": False, "stress": False, "subfamily": "MDL"}, |
| "MDL2": {"type": "Mitochondrial peptide", "essential": False, "stress": False, "subfamily": "MDL"}, |
| "YEF3": {"type": "Translation elongation","essential": True, "stress": False, "subfamily": "Other"}, |
| "GCN20": {"type": "Translation initiation","essential": False, "stress": False, "subfamily": "Other"}, |
| "ARB1": {"type": "Ribosome biogenesis", "essential": True, "stress": False, "subfamily": "Other"}, |
| "RLI1": {"type": "Ribosome biogenesis", "essential": True, "stress": False, "subfamily": "RLI"}, |
| "BPT1": {"type": "Bile pigment transport","essential": False, "stress": False, "subfamily": "Other"}, |
| "PDR16": {"type": "Phospholipid transport","essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR17": {"type": "Transcription factor", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "PDR18": {"type": "Drug efflux", "essential": False, "stress": True, "subfamily": "PDR"}, |
| "HMT1": {"type": "Heavy metal tolerance", "essential": False, "stress": True, "subfamily": "Other"}, |
| "NMD5": {"type": "Protein import", "essential": False, "stress": False, "subfamily": "Other"}, |
| "STE6": {"type": "a-factor export", "essential": False, "stress": False, "subfamily": "STE"}, |
| } |
|
|
| GFF_URL = ( |
| "https://ftp.ensembl.org/pub/release-110/gff3/saccharomyces_cerevisiae/" |
| "Saccharomyces_cerevisiae.R64-1-1.110.gff3.gz" |
| ) |
|
|
|
|
| def load_nullomers(path): |
| with open(path) as f: |
| return set(line.strip() for line in f if line.strip()) |
|
|
|
|
| def download_gff(gff_gz): |
| if not os.path.exists(gff_gz): |
| r = requests.get(GFF_URL, timeout=180) |
| if r.status_code != 200: |
| raise RuntimeError(f"GFF download failed: HTTP {r.status_code}") |
| with open(gff_gz, "wb") as f: |
| f.write(r.content) |
|
|
|
|
| def parse_gff(gff_gz): |
| coords = {} |
| with gzip.open(gff_gz, "rt") as f: |
| for line in f: |
| if line.startswith("#") or not line.strip(): |
| continue |
| fields = line.strip().split("\t") |
| if len(fields) < 9 or fields[2] != "gene": |
| continue |
| attrs = {} |
| for attr in fields[8].split(";"): |
| if "=" in attr: |
| k, v = attr.split("=", 1) |
| attrs[k] = v |
| name = attrs.get("Name", "") |
| if name: |
| coords[name] = { |
| "chrom": fields[0], |
| "start": int(fields[3]), |
| "end": int(fields[4]), |
| "strand": fields[6], |
| } |
| return coords |
|
|
|
|
| def load_genome_dict(genome_file): |
| records = list(SeqIO.parse(genome_file, "fasta")) |
| return {r.id: str(r.seq).upper() for r in records} |
|
|
|
|
| def extract_sequences(gene_name, coords, genome_dict, promoter_len, downstream_len): |
| c = coords[gene_name] |
| chrom_seq = genome_dict.get(c["chrom"], "") |
| if not chrom_seq: |
| return None |
| start, end, strand = c["start"], c["end"], c["strand"] |
| gene_seq = chrom_seq[start - 1:end] |
| if strand == "+": |
| prom_seq = chrom_seq[max(0, start - promoter_len - 1):start - 1] |
| down_seq = chrom_seq[end:end + downstream_len] |
| else: |
| prom_seq = str(Seq(chrom_seq[end:min(len(chrom_seq), end + promoter_len)]).reverse_complement()) |
| down_seq = str(Seq(chrom_seq[max(0, start - downstream_len - 1):start - 1]).reverse_complement()) |
| gene_seq = str(Seq(gene_seq).reverse_complement()) |
| return {"gene": gene_seq, "promoter": prom_seq, "downstream": down_seq} |
|
|
|
|
| def find_nems(sequence, nullomer_set, k=11): |
| nems = [] |
| seq = str(sequence).upper() |
| bases = ["A", "C", "G", "T"] |
| for pos in range(len(seq)): |
| orig = seq[pos] |
| for new in bases: |
| if new == orig: |
| continue |
| check_start = max(0, pos - k + 1) |
| check_end = min(len(seq) - k, pos) |
| for ks in range(check_start, check_end + 1): |
| kmer = seq[ks:ks + k] |
| if ks <= pos < ks + k: |
| mp = pos - ks |
| mutated = kmer[:mp] + new + kmer[mp + 1:] |
| if mutated in nullomer_set: |
| nems.append({ |
| "position": pos, |
| "original": orig, |
| "mutant": new, |
| "mutation": f"{orig}{pos+1}{new}", |
| "nullomer": mutated, |
| }) |
| return nems |
|
|
|
|
| def permutation_test(group1, group2, n_perm=10000, seed=42): |
| rng = np.random.default_rng(seed) |
| obs = np.mean(group1) - np.mean(group2) |
| combined = np.concatenate([group1, group2]) |
| n1 = len(group1) |
| diffs = [] |
| for _ in range(n_perm): |
| rng.shuffle(combined) |
| diffs.append(np.mean(combined[:n1]) - np.mean(combined[n1:])) |
| p = np.mean(np.abs(diffs) >= np.abs(obs)) |
| return float(obs), float(p), diffs |
|
|
|
|
| def main(): |
| nullomers_path = os.path.join(RESULTS_DIR, f"nullomers_k{K}.txt") |
| if not os.path.exists(nullomers_path): |
| raise FileNotFoundError(f"{nullomers_path} not found. Run 01_nullomer_identification.py first.") |
| nullomers = load_nullomers(nullomers_path) |
|
|
| gff_gz = os.path.join(DATA_DIR, "yeast.gff3.gz") |
| download_gff(gff_gz) |
| gene_coords = parse_gff(gff_gz) |
|
|
| genome_file = os.path.join(DATA_DIR, "yeast_genome.fsa") |
| if not os.path.exists(genome_file): |
| raise FileNotFoundError("Genome not found. Run 01_nullomer_identification.py first.") |
| genome_dict = load_genome_dict(genome_file) |
|
|
| abc_sequences = {} |
| for gene in ABC_TRANSPORTERS: |
| if gene in gene_coords: |
| seqs = extract_sequences(gene, gene_coords, genome_dict, PROMOTER_LENGTH, DOWNSTREAM_LENGTH) |
| if seqs: |
| abc_sequences[gene] = seqs |
|
|
| nem_results = {} |
| for gene, seqs in abc_sequences.items(): |
| nem_results[gene] = { |
| "gene": find_nems(seqs["gene"], nullomers, K), |
| "promoter": find_nems(seqs["promoter"], nullomers, K), |
| "downstream": find_nems(seqs["downstream"], nullomers, K), |
| } |
|
|
| rows = [] |
| for gene in nem_results: |
| info = ABC_TRANSPORTERS[gene] |
| for region in ["gene", "promoter", "downstream"]: |
| count = len(nem_results[gene][region]) |
| length = len(abc_sequences[gene][region]) |
| rows.append({ |
| "gene": gene, "region": region, |
| "nem_count": count, "seq_length": length, |
| "nem_density_per_kb": (count / length) * 1000 if length > 0 else 0, |
| "type": info["type"], "essential": info["essential"], |
| "stress": info["stress"], "subfamily": info["subfamily"], |
| }) |
| nem_df = pd.DataFrame(rows) |
| nem_df.to_csv(os.path.join(RESULTS_DIR, "nem_comprehensive_summary.csv"), index=False) |
|
|
| nullomer_rate = len(nullomers) / (4 ** K) |
| enrich_rows = [] |
| for gene in abc_sequences: |
| info = ABC_TRANSPORTERS[gene] |
| for region in ["gene", "promoter", "downstream"]: |
| length = len(abc_sequences[gene][region]) |
| observed = len(nem_results[gene][region]) |
| expected = length * 3 * K * nullomer_rate |
| ratio = observed / expected if expected > 0 else 0 |
| p = 1 - poisson.cdf(observed - 1, expected) |
| enrich_rows.append({ |
| "gene": gene, "region": region, |
| "observed_nems": observed, "expected_nems": expected, |
| "enrichment_ratio": ratio, "p_value": p, |
| "seq_length": length, "type": info["type"], |
| "essential": info["essential"], "stress": info["stress"], |
| }) |
| enrich_df = pd.DataFrame(enrich_rows) |
| enrich_df["p_adjusted"] = multipletests(enrich_df["p_value"], method="bonferroni")[1] |
| enrich_df["significant"] = enrich_df["p_adjusted"] < 0.05 |
| enrich_df.to_csv(os.path.join(RESULTS_DIR, "nem_enrichment_analysis.csv"), index=False) |
|
|
| stress_density, nonstress_density = [], [] |
| for gene in abc_sequences: |
| info = ABC_TRANSPORTERS[gene] |
| total_len = len(abc_sequences[gene]["gene"]) + len(abc_sequences[gene]["promoter"]) |
| total_nems = len(nem_results[gene]["gene"]) + len(nem_results[gene]["promoter"]) |
| density = (total_nems / total_len) * 1000 if total_len > 0 else 0 |
| (stress_density if info["stress"] else nonstress_density).append(density) |
|
|
| u_stat, p_mw = mannwhitneyu(stress_density, nonstress_density, alternative="two-sided") |
| obs_diff, p_perm, _ = permutation_test(np.array(stress_density), np.array(nonstress_density)) |
| pooled_std = np.sqrt((np.std(stress_density) ** 2 + np.std(nonstress_density) ** 2) / 2) |
| cohens_d = obs_diff / pooled_std if pooled_std > 0 else 0 |
|
|
| perm_out = { |
| "stress_mean": round(float(np.mean(stress_density)), 2), |
| "stress_std": round(float(np.std(stress_density)), 2), |
| "nonstress_mean": round(float(np.mean(nonstress_density)), 2), |
| "nonstress_std": round(float(np.std(nonstress_density)), 2), |
| "observed_diff_nems_per_kb": round(obs_diff, 2), |
| "mannwhitney_u": float(u_stat), |
| "mannwhitney_p": float(p_mw), |
| "permutation_p": p_perm, |
| "cohens_d": round(float(cohens_d), 3), |
| "n_stress": len(stress_density), |
| "n_nonstress": len(nonstress_density), |
| } |
| with open(os.path.join(RESULTS_DIR, "stress_permutation_test.json"), "w") as f: |
| json.dump(perm_out, f, indent=2) |
|
|
| total_nems = nem_df["nem_count"].sum() |
| print(f"Total NEMs: {total_nems:,} stress p={p_mw:.4f} perm p={p_perm:.4f} d={cohens_d:.3f}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|