File size: 3,565 Bytes
638ea38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe11dd9
 
 
 
638ea38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from functools import lru_cache
from pathlib import Path
import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
RAW = ROOT / "data" / "raw"
EXT = ROOT / "data" / "external"
RES = ROOT / "results"
RES.mkdir(exist_ok=True)

OX = {"h2o2", "paraquat", "4nqo"}
OS = {"sorbitol", "nacl"}
AGENTS = ["h2o2", "paraquat", "4nqo", "nacl", "sorbitol"]
MIN_NONMISSING = 350
SEED = 0
TERMS = {"oxidative": ("oxidative stress resistance",),
         "osmotic": ("hyperosmotic stress resistance", "osmotic stress resistance")}
SOURCE_PMIDS = {"18420932", "12140549"}


def agent(label):
    parts = label.split(":")
    return parts[1].strip().lower() if len(parts) > 1 else ""


@lru_cache(maxsize=None)
def _parse(name):
    with open(RAW / name) as fh:
        conds = fh.readline().rstrip("\n").split("\t")[1:]
        genes, rows = [], []
        for line in fh:
            f = line.rstrip("\n").split("\t")
            genes.append(f[0].split(":")[0])
            rows.append([np.nan if x in ("", "NA") else float(x) for x in f[1:]])
    return pd.DataFrame(rows, index=genes, columns=conds, dtype=float)


def read_matrix(name, min_nonmissing=0):
    Z = _parse(name)
    rank = pd.DataFrame({"n": Z.notna().sum(axis=1).values, "i": np.arange(len(Z))}, index=Z.index)
    keep = rank.sort_values(["n", "i"]).groupby(level=0).tail(1).i.sort_values().values
    Z = Z.iloc[keep]
    return Z[Z.notna().sum(axis=1) >= min_nonmissing].copy()


def axes(conds):
    ag = np.array([agent(c) for c in conds])
    ox = np.isin(ag, list(OX))
    os_ = np.isin(ag, list(OS))
    return ag, ox, os_, ~(ox | os_)


def hom(filtered=True, min_nonmissing=MIN_NONMISSING):
    Z = read_matrix("hom.z_result_nm.pub")
    if filtered:
        Z = Z[Z.notna().sum(1) >= min_nonmissing]
    return Z


def centre(Z, how="median"):
    if how == "median":
        m = Z.median(axis=1)
    elif how == "mean":
        m = Z.mean(axis=1)
    else:
        from scipy.stats import trim_mean
        m = Z.apply(lambda r: trim_mean(r.dropna(), 0.1), axis=1)
    return Z.sub(m, axis=0)


def effects(Zc, ox, os_):
    return Zc.loc[:, ox].mean(axis=1), Zc.loc[:, os_].mean(axis=1)


def agent_effects(Zc, ag):
    return pd.DataFrame({a: Zc.loc[:, ag == a].mean(axis=1) for a in AGENTS})


def abc():
    return pd.read_csv(RAW / "abc_transporters.csv")


@lru_cache(maxsize=None)
def phenotypes():
    rows = [l.rstrip("\n").split("\t") for l in open(RAW / "phenotype_data.tab", encoding="utf-8", errors="ignore")]
    df = pd.DataFrame([r[:10] for r in rows if len(r) >= 10],
                      columns=["orf", "type", "gene", "sgdid", "ref", "exptype", "mutant", "allele", "strain", "phenotype"])
    df["pmid"] = df.ref.str.extract(r"PMID:(\d+)", expand=False)
    return df


def sgd_labels(stress=None, term=None, exptypes=None, exclude_pmids=SOURCE_PMIDS):
    df = phenotypes()
    df = df[df.mutant == "null"]
    if exptypes is not None:
        df = df[df.exptype.isin(exptypes)]
    if exclude_pmids:
        df = df[~df.pmid.isin(exclude_pmids)]
    head = df.phenotype.str.rsplit(": ", n=1).str[0]
    tail = df.phenotype.str.rsplit(": ", n=1).str[-1]
    keep = head.isin(TERMS[stress]) if stress else head == term
    d = np.where(tail == "increased", 1, np.where(tail == "decreased", -1, 0))
    v = pd.Series(d[keep.values], index=df.orf[keep.values].values)
    v = v[v != 0].groupby(level=0).sum()
    return np.sign(v[v != 0]).astype(int)