File size: 6,881 Bytes
94b0695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import os
import numpy as np
import pandas as pd
from itertools import product as iproduct
from Bio.Seq import Seq
from scipy.stats import spearmanr, mannwhitneyu

RESULTS_DIR = "results"

STRESS_ELEMENTS = {
    "PDRE": {
        "consensus": "TCCGCGGA",
        "variants": ["TCCGCGGA", "TCCGYGGA", "TCCACGGA", "TCCGTGGA"],
        "factors": "Pdr1/Pdr3",
    },
    "STRE": {
        "consensus": "AGGGG",
        "variants": ["AGGGG", "CCCCT", "AGGGA", "TCCCT"],
        "factors": "Msn2/Msn4",
    },
    "HSE": {
        "consensus": "nGAAn",
        "variants": ["AGAAA", "TGAAT", "CGAAA", "GGAAT", "AGAAT", "TGAAA"],
        "factors": "Hsf1",
    },
    "AP1": {
        "consensus": "TGASTCA",
        "variants": ["TGACTCA", "TGAGTCA", "TTAGTCA", "TTACTAA", "TGACTAA"],
        "factors": "Yap1",
    },
}

IUPAC = {
    "R": ["A", "G"], "Y": ["C", "T"], "S": ["G", "C"],
    "W": ["A", "T"], "K": ["G", "T"], "M": ["A", "C"],
    "B": ["C", "G", "T"], "D": ["A", "G", "T"],
    "H": ["A", "C", "T"], "V": ["A", "C", "G"],
    "N": ["A", "C", "G", "T"],
}

DRUG_EFFLUX_TYPES = {"Drug efflux", "Weak acid efflux"}


def expand_iupac(motif):
    positions = [IUPAC.get(c, [c]) for c in motif.upper()]
    return ["".join(combo) for combo in iproduct(*positions)]


def find_motif(sequence, motif):
    positions = []
    seq = sequence.upper()
    for expanded in expand_iupac(motif):
        ml = len(expanded)
        for i in range(len(seq) - ml + 1):
            if seq[i:i + ml] == expanded:
                positions.append({"position": i, "strand": "+", "sequence": expanded})
        rc = str(Seq(expanded).reverse_complement())
        for i in range(len(seq) - len(rc) + 1):
            if seq[i:i + len(rc)] == rc:
                positions.append({"position": i, "strand": "-", "sequence": rc})
    seen = set()
    unique = []
    for p in positions:
        key = (p["position"], p["strand"])
        if key not in seen:
            unique.append(p)
            seen.add(key)
    return unique


def scan_stress_elements(abc_sequences):
    results = {}
    for gene, seqs in abc_sequences.items():
        results[gene] = {}
        for etype, einfo in STRESS_ELEMENTS.items():
            all_pos = []
            for motif in [einfo["consensus"]] + einfo["variants"]:
                all_pos.extend(find_motif(seqs["promoter"], motif))
            seen = set()
            unique = []
            for p in all_pos:
                key = (p["position"], p["strand"])
                if key not in seen:
                    unique.append(p)
                    seen.add(key)
            results[gene][etype] = unique
    return results


def build_correlation_df(abc_sequences, nem_results, stress_results, abc_info):
    rows = []
    for gene in abc_sequences:
        info = abc_info[gene]
        prom_len = len(abc_sequences[gene]["promoter"])
        prom_nems = len(nem_results.get(gene, {}).get("promoter", []))
        nem_density = (prom_nems / prom_len) * 1000 if prom_len > 0 else 0
        counts = {etype: len(stress_results[gene][etype]) for etype in STRESS_ELEMENTS}
        rows.append({
            "gene": gene,
            "promoter_length": prom_len,
            "promoter_nems": prom_nems,
            "nem_density_per_kb": nem_density,
            "total_stress_elements": sum(counts.values()),
            **counts,
            "type": info["type"],
            "essential": info["essential"],
            "stress": info["stress"],
            "subfamily": info["subfamily"],
            "is_drug_efflux": info["type"] in DRUG_EFFLUX_TYPES,
        })
    return pd.DataFrame(rows)


def motif_disruption(abc_sequences, nem_results, stress_results):
    rows = []
    for gene in abc_sequences:
        prom_nems = nem_results.get(gene, {}).get("promoter", [])
        for nem in prom_nems:
            pos = nem["position"]
            for etype, einfo in STRESS_ELEMENTS.items():
                ml = len(einfo["consensus"])
                for elem in stress_results[gene][etype]:
                    estart = elem["position"]
                    if estart <= pos < estart + ml:
                        rows.append({
                            "gene": gene,
                            "nem_position": pos,
                            "nem_mutation": nem["mutation"],
                            "element_type": etype,
                            "motif_position": estart,
                            "motif_strand": elem["strand"],
                            "position_in_motif": pos - estart,
                        })
                        break
    return pd.DataFrame(rows)


def main():
    from importlib.util import spec_from_file_location, module_from_spec

    nem_csv = os.path.join(RESULTS_DIR, "nem_comprehensive_summary.csv")
    if not os.path.exists(nem_csv):
        raise FileNotFoundError(f"{nem_csv} not found. Run 02_nem_analysis.py first.")

    spec = spec_from_file_location("nem_mod", "02_nem_analysis.py")
    mod = module_from_spec(spec)
    spec.loader.exec_module(mod)

    nullomers = mod.load_nullomers(os.path.join(RESULTS_DIR, "nullomers_k11.txt"))
    gene_coords = mod.parse_gff(os.path.join("data", "yeast.gff3.gz"))
    genome_dict = mod.load_genome_dict(os.path.join("data", "yeast_genome.fsa"))
    abc_info = mod.ABC_TRANSPORTERS

    abc_sequences = {}
    for gene in abc_info:
        if gene in gene_coords:
            seqs = mod.extract_sequences(
                gene, gene_coords, genome_dict, mod.PROMOTER_LENGTH, mod.DOWNSTREAM_LENGTH
            )
            if seqs:
                abc_sequences[gene] = seqs

    nem_results = {}
    for gene in abc_sequences:
        nem_results[gene] = {
            "gene": mod.find_nems(abc_sequences[gene]["gene"], nullomers, mod.K),
            "promoter": mod.find_nems(abc_sequences[gene]["promoter"], nullomers, mod.K),
            "downstream": mod.find_nems(abc_sequences[gene]["downstream"], nullomers, mod.K),
        }

    stress_results = scan_stress_elements(abc_sequences)
    corr_df = build_correlation_df(abc_sequences, nem_results, stress_results, abc_info)
    corr_df.to_csv(os.path.join(RESULTS_DIR, "stress_element_nem_correlation.csv"), index=False)

    disrupt_df = motif_disruption(abc_sequences, nem_results, stress_results)
    if not disrupt_df.empty:
        disrupt_df.to_csv(os.path.join(RESULTS_DIR, "motif_disruption_by_nems.csv"), index=False)

    rho, p = spearmanr(corr_df["PDRE"], corr_df["nem_density_per_kb"])
    drug = corr_df[corr_df["is_drug_efflux"]]["nem_density_per_kb"].values
    other = corr_df[~corr_df["is_drug_efflux"]]["nem_density_per_kb"].values
    _, p_drug = mannwhitneyu(drug, other, alternative="two-sided")
    print(f"PDRE-NEM rho={rho:.3f} p={p:.2e}  drug efflux p={p_drug:.4f}  "
          f"disruptions={len(disrupt_df):,}")


if __name__ == "__main__":
    main()