-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinearmodels.py
260 lines (196 loc) · 7.88 KB
/
linearmodels.py
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import itertools
from pathlib import Path
import sys
# sys.path.insert(0, ".") # include path to xspecies module
import click
import numpy as np
import pandas as pd
import seaborn as sns
from xspecies.dataset import DatasetBuilder, Dataset
from xspecies.feature_analyzer_components import (BaseFilter,
BaseSplitter, BasePreprocessor)
from xspecies.models import LinearRegressionModel
from xspecies.feature_analyzer import FeatureAnalyzer
from utils_extract_results import execute_extract_results
# CLI Interface
@click.group()
@click.option('--type_input', '-t',
type=click.Choice(['genes', 'genesets'], case_sensitive=False))
@click.pass_context
def linearmodels(ctx, type_input):
ctx.ensure_object(dict)
ctx.obj['type_input'] = type_input
@linearmodels.command()
@click.argument('input',
type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.argument('output',
type=click.Path(exists=False, file_okay=False, dir_okay=True))
@click.pass_context
def analyze_models(ctx, input, output):
"""Fit and save model data for every organ, target variable and human inclusion selection."""
type_input = ctx.obj['type_input']
click.echo(f"Input dataset: {input}, Output directory: {output}, Input type: {type_input}")
param_dict = configure_analysis(input, output, type_input, command='analyze_models')
if type_input == 'genes':
log2_transform_features = True
elif type_input == 'genesets':
log2_transform_features = False
analysis_results = run_analysis(
analysis_dir=param_dict['output_path'],
name_template=param_dict['name_template'],
dataset=param_dict['dataset'],
organs=param_dict['organs'],
include_humans=param_dict['include_humans'],
targets=param_dict['targets'],
with_log2_features=log2_transform_features
)
@linearmodels.command()
@click.argument('input',
type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.argument('output',
type=click.Path(exists=False, file_okay=False, dir_okay=True))
@click.pass_context
def extract_results(ctx, input, output): # input output
"""Compile results from fitted model data obtained through analyze-models."""
type_input = ctx.obj['type_input']
click.echo(f"Input dataset: {input}, Output directory: {output}, Input type: {type_input}")
param_dict = configure_analysis(input, output, type_input, command='extract_results')
input_path = Path(input)
output_path = Path(output)
execute_extract_results(
input_dir=input_path,
results_dir=output_path,
alpha=param_dict['alpha'],
feature_type=type_input,
organs=param_dict['organs'],
include_humans=param_dict['include_humans'],
targets=param_dict['targets'],
name_template_callback=get_name_template
)
def configure_analysis(input_dir: str, output_dir: str, type_input: str,
command: str) -> dict:
assert command in {'analyze_models', 'extract_results'}
o_path = Path(output_dir)
if not o_path.is_dir():
o_path.mkdir()
template = get_name_template(type_input)
param_dict = {
'output_path': o_path,
'organs': ["Brain", "Heart", "Lung", "Liver", "Kidney"],
'include_humans': ['withHumans', 'withoutHumans'],
'targets': ['maxlifespan', 'mass', 'temperature',
'metabolicRate', 'gestation', 'mtGC'],
'name_template': template,
'alpha': 0.05
}
if command == 'analyze_models':
xspecies_ds = get_dataset(input_dir)
add_duplicate_cols(xspecies_ds)
param_dict.update({'dataset': xspecies_ds})
return param_dict
def get_name_template(type_input: str) -> str:
assert type_input in {'genes', 'genesets'}
if type_input == 'genes':
return "Xspecies_LinearRegression_Genes_{organ}_{include_human}_{target}"
else:
return "Xspecies_LinearRegression_Genesets_{organ}_{include_human}_{target}"
def get_dataset(input_dir):
path = Path(input_dir)
dataset_name = path.name
datasets_dir = path.parent
xspecies_ds = Dataset.load(dataset_name, datasets_dir)
return xspecies_ds
def add_duplicate_cols(ds: 'Dataset'):
# adds convenient column names
def add_duplicate_col(name_dup, colname):
ds.samples_meta[name_dup] = ds.samples_meta[colname]
add_duplicate_col('maxlifespan', 'Maximum longevity (yrs)')
add_duplicate_col('mass', 'Body mass (g)')
add_duplicate_col('temperature', 'Temperature (K)')
add_duplicate_col('metabolicRate', 'Metabolic rate (W)')
add_duplicate_col('gestation', 'Gestation/Incubation (days)')
def create_filter(organ: str,
include_humans: str):
FILTER_CONFIG = {
"samples": {
"tissue": ("=", organ),
"Class": ("=", "Mammalia")
},
}
samples_index_operation = {"organism": ("!=", "Homo_sapiens")}
if include_humans == 'withoutHumans':
FILTER_CONFIG["samples"].update(samples_index_operation)
return BaseFilter(FILTER_CONFIG)
def create_preprocessor(with_log2_features=True):
PREPROCESSOR_CONFIG = {
"samples_transforms": [("maxlifespan", "log2"),
("maxlifespan", "standardize")
],
}
if with_log2_features:
PREPROCESSOR_CONFIG["features_transforms"] = (
["log2", "standardize"]
)
else:
PREPROCESSOR_CONFIG["features_transforms"] = (
["standardize"]
)
return BasePreprocessor(PREPROCESSOR_CONFIG)
def model_per_organ_and_target(analysis_dir,
dataset: 'Dataset',
name: str,
formula: str,
organ: str,
include_humans: str,
target: str,
control_vars: list or None,
with_log2_features):
"""
Run analysis on a selection of organ, human inclusion and target variable.
"""
MODEL = LinearRegressionModel(formula)
FILTER = create_filter(organ, include_humans)
PREPROCESSOR = create_preprocessor(with_log2_features)
feature_analyzer = FeatureAnalyzer(
name=name, model=MODEL, filtor=FILTER,
preprocessor=PREPROCESSOR,
na_handler=None,
splitter=None) #TODO: No split
results = feature_analyzer.weight_features(
dataset, target=target, control_vars=control_vars)
results.save(analysis_dir)
return results
def run_analysis(analysis_dir,
name_template,
dataset,
organs,
include_humans,
targets,
with_log2_features):
"""
Iterate through model options, run each model on appropriate data
and save results.
"""
formula_template = 'Q("{feature}") ~ 1 + {{{target}}}'
results = {}
for (organ, include_human, target) in itertools.product(organs, include_humans, targets):
name = name_template.format(
organ=organ,
include_human=include_human,
target=target)
print(name)
if (analysis_dir / name).is_dir():
continue
formula = ("".join(formula_template.split(" ")[:-1])
+ " {}".format(target) )
results[name] = model_per_organ_and_target(
analysis_dir,
dataset,
name, formula, organ, include_human,
target=target,
control_vars=None,
with_log2_features=with_log2_features
)
return results
if __name__ == "__main__":
linearmodels(obj={})