-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_uuids_tsv.py
executable file
·176 lines (147 loc) · 5.77 KB
/
make_uuids_tsv.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
#!/usr/bin/env python3
import json
from argparse import ArgumentParser
import pandas as pd
import requests
import yaml
organ_types_yaml_file = "bin/organ_types.yaml"
def get_uuids(organ_name_mapping: dict, organ: str):
organ_code_mapping = {organ_name_mapping[key]: key for key in organ_name_mapping}
# Define the query payload based on organ
if organ is None:
query_payload = {
"from": 0,
"size": 10000,
"query": {
"bool": {
"must": [
{"match": {"dataset_type": "RNAseq [Salmon]"}},
{"match": {"data_access_level": "public"}}
]
}
}
}
else:
query_payload = {
"from": 0,
"size": 10000,
"query": {
"bool": {
"must": [
{"match": {"dataset_type": "RNAseq [Salmon]"}},
{"match": {"data_access_level": "public"}},
{"match": {"origin_samples.organ": organ_code_mapping[organ]}}
]
}
}
}
# Make the request
url = "https://search.api.hubmapconsortium.org/v3/search"
response = requests.post(url, json=query_payload)
print("Response status code: ", response.status_code)
# Handle a successful response
if response.status_code == 200:
return process_response(response)
# Handle 303 redirection
elif response.status_code == 303:
redirection_url = response.text.strip() # Get redirection URL from response body
print("Following redirection URL: ", redirection_url)
# Make a request to the redirection URL
redirection_response = requests.get(redirection_url)
if redirection_response.status_code == 200:
return process_response(redirection_response)
# Handle other error responses
else:
print(f"Error {response.status_code}: {response.text}")
return [], [], []
def process_response(response):
"""
Helper function to process the JSON response and extract UUIDs, HubMAP IDs, and donor metadata.
"""
data = response.json()
hits = data.get("hits", {}).get("hits", [])
uuids = []
hubmap_ids = []
donor_metadata_list = []
# Loop through each dataset (hit) and extract the relevant information
for hit in hits:
source = hit["_source"]
uuids.append(source["uuid"])
hubmap_ids.append(source["hubmap_id"])
# Attempt to extract donor metadata, if available
donor_metadata = source.get("donor", {}).get("metadata", {})
donor_metadata_list.append(extract_donor_metadata(donor_metadata))
return uuids, hubmap_ids, donor_metadata_list
def extract_donor_metadata(metadata):
"""
Extract donor metadata, including age, sex, height, weight, and other relevant information.
"""
donor_info = {
"age": None,
"sex": None,
"height": None,
"weight": None,
"bmi": None,
"cause_of_death": None,
"race": None
}
for item in metadata.get('organ_donor_data', []):
concept = item.get('grouping_concept_preferred_term')
value = item.get('data_value')
if concept == "Age":
donor_info["age"] = value
elif concept == "Sex":
donor_info["sex"] = item.get('preferred_term')
elif concept == "Height":
donor_info["height"] = value
elif concept == "Weight":
donor_info["weight"] = value
elif concept == "Body mass index":
donor_info["bmi"] = value
elif concept == "Cause of death":
donor_info["cause_of_death"] = item.get('preferred_term')
elif concept == "Race":
donor_info["race"] = item.get('preferred_term')
for item in metadata.get('living_donor_data', []):
concept = item.get('grouping_concept_preferred_term')
value = item.get('data_value')
if concept == "Age":
donor_info["age"] = value
elif concept == "Sex":
donor_info["sex"] = item.get('preferred_term')
elif concept == "Height":
donor_info["height"] = value
elif concept == "Weight":
donor_info["weight"] = value
elif concept == "Body mass index":
donor_info["bmi"] = value
elif concept == "Cause of death":
donor_info["cause_of_death"] = item.get('preferred_term')
elif concept == "Race":
donor_info["race"] = item.get('preferred_term')
return donor_info
def main(tissue_type: str):
organ_dict = yaml.load(open(organ_types_yaml_file), Loader=yaml.BaseLoader)
for key in organ_dict:
organ_dict[key] = organ_dict[key]["description"]
if tissue_type not in organ_dict.values():
print(f"Tissue {tissue_type} not found ")
tissue_type = None
uuids_list, hubmap_ids_list, donor_metadata = get_uuids(organ_dict, tissue_type)
uuids_df = pd.DataFrame()
uuids_df["uuid"] = pd.Series(uuids_list, dtype=str)
uuids_df["hubmap_id"] = pd.Series(hubmap_ids_list, dtype=str)
donor_metadata_df = pd.DataFrame(donor_metadata)
result_df = pd.concat([uuids_df, donor_metadata_df], axis=1)
key_for_tissue = [key for key, value in organ_dict.items() if value == tissue_type]
if key_for_tissue:
output_file_name = f"{key_for_tissue[0].lower()}.tsv"
else:
output_file_name = "rna.tsv"
print(result_df)
result_df.to_csv(output_file_name, sep="\t")
if __name__ == "__main__":
p = ArgumentParser()
p.add_argument("tissue_type", type=str, nargs="?", help="Type of tissue (optional)")
args = p.parse_args()
main(args.tissue_type)