-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_EM.py
More file actions
134 lines (121 loc) · 8.83 KB
/
Copy pathmain_EM.py
File metadata and controls
134 lines (121 loc) · 8.83 KB
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
import os
import json
import argparse
import warnings
import numpy as np
import pandas as pd
from preparation import getFeatureScore, getEdgeScore
from expectation import expectation
from maximization import maximization, mergeBackup
from evaluation import plotScore, evaluation, plotSizes, plotEpoch
# python main_EM.py --input fuzzyValueDirectory(s) --metadata metadata --template templateDirectory --reference referenceEdges --config config \
# --optimize_goal [context-specific / marker] --output outputDirectory
parser = argparse.ArgumentParser ()
parser.add_argument ("--input", nargs = "+", type = str, required = True, help = "Directory / directories for feature / regulator and target fuzzy values")
parser.add_argument ("--metadata", type = str, required = True, help = "Metadata containing initial contexts as well as regulator and target sample mapping (TSV)")
parser.add_argument ("--template", type = str, required = True, help = "Directory for template vectors / matrices (CSV)")
parser.add_argument ("--reference", type = str, required = False, help = "Table of reference edges, pointing from regulator to target (TSV)")
parser.add_argument ("--config", type = str, required = True, help = "Config file for detailed parameters (JSON)")
parser.add_argument ("--optimize_goal", type = str, required = True, choices = ["context-specific", "marker"], help = "Whether to deliver context-specific or marker optimization")
parser.add_argument ("--output", type = str, required = True, help = "Output directory for optimized feature / network and sample assignment")
args = parser.parse_args ()
metadata = pd.read_csv (args.metadata, index_col = None, sep = "\t")
if metadata.columns[0] == "Unnamed: 0":
metadata = metadata.rename (columns = {"Unnamed: 0": "index"})
templateDict = {file[:-4]: pd.read_csv (os.path.join (args.template, file), header = None, index_col = None, sep = ",").to_numpy ()
for file in sorted (os.listdir (args.template))}
allTemplates = sorted (templateDict.keys ())
with open (args.config) as f:
config = json.load (f)
mode = config["mode"]; allowExchange = config.get ("exchange_between_contexts", False)
colSep = config.get ("metadata_context_column_separator", "*")
cutoffItem = {"minimal_score_for_support": config["minimal_score_for_support"],
"minimal_percent_for_support": config["minimal_percent_for_support"],
"maximal_percent_for_not_support": config.get ("maximal_percent_for_not_support", np.inf)}
cutoffBackup = {"minimal_score_for_support": config["minimal_score_for_support"],
"minimal_percent_for_support": 1.2 * min (0.75, max (0.5, config["minimal_percent_for_support"])),
"maximal_percent_for_not_support": config.get ("maximal_percent_for_not_support", np.inf)}
cutoffSample = {"minimal_score_for_support": config["minimal_score_for_support"],
"minimal_percent_for_support": 0.25,
"maximal_percent_for_not_support": np.inf}
maxIter = config.get ("maximal_iterations", np.inf)
barplotCmap = config.get ("barplot_colors", dict ())
context = pd.DataFrame ({"sample": metadata[config.get ("metadata_index_column", "index")].values,
"context": metadata[config.get ("metadata_context_columns", ["context"])].agg (colSep.join, axis = 1).values,
"template": "unassigned"})
context.insert (0, "index", range (context.shape[0]))
allContexts = sorted (set (context["context"])); sampleList = list (context["sample"])
if mode == "feature":
scoreMtx, itemList = getFeatureScore (args.input[0], sampleList, templateDict, allTemplates, config)
elif mode == "edge":
try:
refEdges = pd.read_csv (args.reference, index_col = None, sep = "\t")
refEdges = pd.DataFrame ({"regulator": refEdges[config.get ("reference_regulator_column", "regulator")].values,
"target": refEdges[config.get ("reference_target_column", "target")].values}).drop_duplicates ()
except FileNotFoundError:
warnings.warn ("No reference edges available, using all combinatory edges instead.")
refEdges = pd.DataFrame ()
sampleMapping = pd.DataFrame ({"regulator": metadata[config.get ("metadata_regulator_column", "regulator")].values,
"target": metadata[config.get ("metadata_target_column", "target")].values})
scoreMtx, itemList, refEdges = getEdgeScore (args.input[0], args.input[1], refEdges, sampleMapping, templateDict, allTemplates, config)
else:
raise ValueError ("Expectation-maximization algorithm only implemented for feautre-wise (\"feature\") or edge-wise (\"edge\") optimization.")
print (f"scoring matrix completed: dimension {scoreMtx.shape}")
sampleLabeling = context.groupby ("context")["index"].agg (list).to_dict (); backup = dict ()
history = context.rename (columns = {"context": "context_0"}).drop ("index", axis = 1); history["template_0"] = "unassigned"
markerAssignment = (args.optimize_goal == "marker")
numIter = 1; percents = list ()
print (f"expected output: {args.optimize_goal} {mode}s")
os.makedirs (args.output, exist_ok = True)
os.makedirs (os.path.join (args.output, "evaluation_plots"), exist_ok = True)
os.makedirs (os.path.join (args.output, f"{mode}_scores"), exist_ok = True)
while numIter <= maxIter:
print (f"----- iteration {numIter} -----")
assignment, itemLabeling, allContexts = maximization (itemList, mode, sampleLabeling, scoreMtx, cutoffItem, allContexts, allTemplates,
markerAssignment = markerAssignment)
if bool (backup):
tmp, _, _ = maximization (itemList, mode, backup, scoreMtx, cutoffBackup, sorted (backup.keys ()), allTemplates,
markerAssignment = markerAssignment)
assignment, itemLabeling, allContexts, backup = mergeBackup (mode, assignment, tmp, backup)
plotScore (scoreMtx, assignment, context, backup, allContexts, allTemplates, mode,
os.path.join (args.output, "evaluation_plots", f"score_iteration_{numIter}.png"))
context, backup, sampleLabeling, allContexts = expectation (sampleList, itemLabeling, scoreMtx, cutoffSample, allContexts, allTemplates,
history, allowExchange = allowExchange)
history, pctChanged, sameAssignment = evaluation (context, backup, history, numIter); percents.append (pctChanged)
print ("edge assignment:"); print (assignment.value_counts ("context").sort_index ().to_dict ())
print (f"sample assignment ({len (sampleList) - context.shape[0]} unassigned):")
print (context.value_counts ("context").sort_index ().to_dict ())
print ("backup sample assignment:"); print ({key: len (backup[key]) for key in sorted (backup.keys ())})
print (f"percent changed: {pctChanged:.2%}")
if sameAssignment:
break
numIter += 1
history = history.drop ("template", axis = 1).set_index ("sample").rename_axis (None, axis = 0)
if bool (backup):
backup = pd.concat ([pd.DataFrame ({"index": backup[cont], "sample": [sampleList[x] for x in backup[cont]], "context": cont})
for cont in backup],
axis = 0, ignore_index = True).sort_values ("index").reset_index (drop = True)
else:
backup = pd.DataFrame (columns = ["index", "sample", "context"], dtype = str)
if assignment.empty or context.empty:
scores = {temp: pd.concat ([pd.DataFrame (columns = [mode, "context", "template"], dtype = str),
pd.DataFrame (columns = allTemplates, dtype = float)],
axis = 1)
for temp in allTemplates}
else:
plotSizes (assignment, context, allContexts, allTemplates, mode, barplotCmap, args.output)
plotEpoch (percents, args.output)
scores = {temp: pd.DataFrame (index = itemList, columns = allContexts, dtype = float) for temp in allTemplates}
for idx in range (len (allTemplates)):
temp = allTemplates[idx]
for cont in allContexts:
idxList = context.loc[context["context"] == cont, "index"]
tmp = pd.Series (0 if len (idxList) == 0 else scoreMtx[idx, :, idxList].mean (axis = 0), index = itemList).round (3)
scores[temp][cont] = tmp[sorted (set (assignment[mode]))]
scores[temp][cont] = 0 if len (idxList) == 0 else scoreMtx[idx, :, idxList].mean (axis = 0).round (3)
assignment.to_csv (os.path.join (args.output, f"{mode}_assignment.tsv"), index = None, sep = "\t")
context.to_csv (os.path.join (args.output, "optimized_context_assignment.tsv"), index = None, sep = "\t")
history.to_csv (os.path.join (args.output, "context_assignment_history.tsv"), sep = "\t")
backup.to_csv (os.path.join (args.output, "context_backup.tsv"), index = None, sep = "\t")
for temp in allTemplates:
scores[temp].to_csv (os.path.join (args.output, f"{mode}_scores", f"scores_{temp}.tsv"), sep = "\t")