Repository navigation
Expand file tree
/
Copy pathquery_api_script.py
More file actions
220 lines (187 loc) · 9.93 KB
/
Copy pathquery_api_script.py
File metadata and controls
220 lines (187 loc) · 9.93 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
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
import dataclasses
import json
import os
import click
import csv
from linkml_runtime.utils.schemaview import SchemaView
from linkml_runtime.dumpers import yaml_dumper, json_dumper, tsv_dumper
from ak_schema import *
from ak_schema_utils import *
ak_schema_view = SchemaView("ak-schema/project/linkml/ak_schema.yaml")
uberon = {}
with open('ak-ontology/src/ontology/exports/UberAnatomy.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
uberon[row['term_id']] = row['term_label']
print(f"Loaded UBERON ontology")
taxon = {}
with open('ak-ontology/src/ontology/exports/TaxonomicSpecies.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
taxon[row['term_id']] = row['term_label']
print(f"Loaded NCBI TAXON ontology")
with open('ak-ontology/src/ontology/exports/ONTIE_organisms.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
taxon[row['term_id']] = row['term_label']
print(f"Loaded ONTIE organisms ontology")
doid = {}
with open('ak-ontology/src/ontology/exports/Diseases.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
doid[row['term_id']] = row['term_label']
print(f"Loaded DOID ontology")
with open('ak-ontology/src/ontology/exports/ONTIE_Diseases.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
doid[row['term_id']] = row['term_label']
print(f"Loaded ONTIE diseases ontology")
pato = {}
with open('ak-ontology/src/ontology/exports/PhenotypeAndTraits.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
pato[row['term_id']] = row['term_label']
print(f"Loaded PATO ontology")
unit = {}
with open('ak-ontology/src/ontology/exports/Units.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
unit[row['term_id']] = row['term_label']
print(f"Loaded UO ontology")
obi = {}
with open('ak-ontology/src/ontology/exports/BiomedicalInvestigations.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
obi[row['term_id']] = row['term_label']
print(f"Loaded OBI ontology")
def create_object(output_path, path, load_type):
"""Construct query objects for AK API and save to JSONL."""
container = AIRRKnowledgeCommons()
load_ak_container(container, path, load_type)
print(f"LOADED AK CONTAINER WITH {load_type.upper()} DATA")
# TODO: missed in V3 but should be fixed in V4
if load_type == 'iedb':
pe = {}
# loop through life events and collect for each participant
for life_event_id in container["life_events"]:
life_event = container["life_events"][life_event_id]
participant_akc_id = life_event.participant
if pe.get(participant_akc_id) is None:
pe[participant_akc_id] = {}
if pe[participant_akc_id].get(life_event_id) is None:
pe[participant_akc_id][life_event_id] = container["life_events"][life_event_id]
for participant_akc_id in pe:
participant = container["participants"][participant_akc_id]
participant.life_events = []
for life_event_id in pe[participant_akc_id]:
participant.life_events.append(life_event_id)
with open(output_path, "w") as f:
for assay_id, assay in container["assays"].items():
experiment = QueryExperiment(akc_id=assay_id)
for field in dataclasses.fields(assay):
setattr(experiment, field.name, getattr(assay, field.name))
specimen = container["specimens"][assay["specimen"]]
specimen_collection = container["life_events"][specimen["life_event"]]
experiment.life_events[specimen_collection.akc_id] = specimen_collection
participant = container["participants"][specimen_collection["participant"]]
for life_event_id in participant.life_events:
experiment.life_events[life_event_id] = container["life_events"][life_event_id]
study_arm = container["study_arms"][participant["study_arm"]]
investigation = container["investigations"][study_arm["investigation"]]
if investigation.inclusion_exclusion_criteria is not None:
investigation.inclusion_exclusion_criteria = investigation.inclusion_exclusion_criteria.replace('\n','')
investigation.inclusion_exclusion_criteria = investigation.inclusion_exclusion_criteria.replace('"','')
investigation.inclusion_exclusion_criteria = investigation.inclusion_exclusion_criteria.replace('\\','')
if investigation.description is not None:
investigation.description = investigation.description.replace('\n','')
# look for genotype inference
if hasattr(assay, 'sequencing_files') and assay.sequencing_files:
for iomap in container['input_output_map']:
if iomap.has_specified_input == assay.sequencing_files:
dataset = container['datasets'].get(iomap.has_specified_output)
if dataset and DataItemTypeEnum('genotype') in dataset.data_item_types:
print("found genotype")
participant['genotype_set'] = json.loads(json_dumper.dumps(dataset))
#print(participant)
experiment.specimen = specimen
experiment.participant = participant
experiment.investigation = investigation
# remove relations
d = dataclasses.asdict(experiment)
#print(d)
del d['investigation']['participants']
del d['investigation']['assays']
del d['investigation']['simulations']
del d['investigation']['conclusions']
del d['specimen_processing']
# hack in ontology labels
if d.get('assay_type') is not None:
d['assay_type'] = { "term_id": d['assay_type'], "term_label": obi[d['assay_type']] }
if d['specimen']['tissue'] is not None:
if uberon.get(d['specimen']['tissue']):
d['specimen']['tissue'] = { 'term_id': d['specimen']['tissue'], 'term_label': uberon[d['specimen']['tissue']] }
elif obi.get(d['specimen']['tissue']):
d['specimen']['tissue'] = { 'term_id': d['specimen']['tissue'], 'term_label': obi[d['specimen']['tissue']] }
else:
print(f"unhandled tissue: {d['specimen']['tissue']}")
d['specimen']['tissue'] = { 'term_id': None, 'term_label': d['specimen']['tissue'] }
if d['participant']['species'] is not None:
d['participant']['species'] = { 'term_id': d['participant']['species'], 'term_label': taxon[d['participant']['species']] }
if d['participant']['sex'] is not None:
d['participant']['sex'] = { 'term_id': d['participant']['sex'], 'term_label': pato[d['participant']['sex']] }
if d['participant']['age_unit'] is not None:
d['participant']['age_unit'] = { 'term_id': d['participant']['age_unit'], 'term_label': unit[d['participant']['age_unit']] }
if d['investigation']['investigation_type'] is not None:
d['investigation']['investigation_type'] = { 'term_id': d['investigation']['investigation_type'], 'term_label': obi[d['investigation']['investigation_type']] }
for life_event_id in d['life_events']:
life_event = d['life_events'][life_event_id]
if life_event.get('life_event_type') is not None:
life_event['life_event_type'] = { 'term_id': life_event['life_event_type'], 'term_label': obi[life_event['life_event_type']] }
if life_event.get('disease') is not None:
life_event['disease'] = { 'term_id': life_event['disease'], 'term_label': doid[life_event['disease']] }
if life_event.get('exposure_material') is not None:
if taxon.get(life_event['exposure_material']) is not None:
life_event['exposure_material'] = { 'term_id': life_event['exposure_material'], 'term_label': taxon[life_event['exposure_material']] }
else:
print(f"unhandled exposure_material: {life_event['exposure_material']}")
life_event['exposure_material'] = { 'term_id': life_event['exposure_material'], 'term_label': "" }
f.write(json.dumps(d) + "\n")
@click.group()
def cli():
"""Query object generators."""
pass
# Set variables for ADC and VDJBASE
CONFIGS = {
"adc": {
"transform_dir": ADC_TRANSFORM_DATA,
"subdir": "adc_jsonl",
},
"vdjbase": {
"transform_dir": VDJBASE_TRANSFORM_DATA,
"subdir": "vdjbase_jsonl",
},
}
# Query ADC/VDJBASE
@cli.command(name="query")
@click.argument("source", type=click.Choice(["adc", "vdjbase"]))
@click.option("--cache-id", required=True)
def query(source, cache_id):
config = CONFIGS[source]
path = f"{config['transform_dir']}/{config['subdir']}/{cache_id}"
create_object(f"{path}/QueryAssay.jsonl", path, source)
print(f"Wrote query object data to {path}/QueryAssay.jsonl")
# Query IEDB. No cache_id needed
@cli.command(name="query-iedb")
def query_iedb():
path = f"{IEDB_TRANSFORM_DATA}/iedb_jsonl"
create_object(f"{path}/QueryAssay.jsonl", path, "iedb")
print(f"Wrote query object data to {path}/QueryAssay.jsonl")
# Query IRAD. No cache_id needed
@cli.command(name="query-irad")
def query_irad():
print("Implement data extraction first and then uncomment the code below.")
# path = f"{IRAD_TRANSFORM_DATA}/irad_jsonl"
# create_object(f"{path}/QueryAssay.jsonl", path, "irad")
# print(f"Wrote query object data to {path}/QueryAssay.jsonl")
if __name__ == "__main__":
cli()