-
Notifications
You must be signed in to change notification settings - Fork 0
/
mgs.py
282 lines (255 loc) · 8.25 KB
/
mgs.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import json
import urllib.request
from collections import Counter
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import date
from enum import Enum
from typing import NewType, Optional
from collections import defaultdict
import os
import csv
from pydantic import BaseModel
from pathogen_properties import TaxID
BIOPROJECTS_DIR = "bioprojects"
# Check if we're in the p2ra-manuscript folder
if not os.path.basename(os.getcwd()) == "p2ra-manuscript":
# If not, assume we are in a child directory
BIOPROJECTS_DIR = os.path.join("..", "bioprojects")
else:
BIOPROJECTS_DIR = "bioprojects"
BioProject = NewType("BioProject", str)
Sample = NewType("Sample", str)
target_bioprojects = {
"crits_christoph": [BioProject("CC-PRJNA661613")],
"rothman": [BioProject("Rothman-PRJNA729801")],
"spurbeck": [BioProject("Spurbeck-PRJNA924011")],
"brinch": [
BioProject("Brinch-PRJEB13832"),
BioProject("Brinch-PRJEB34633"),
],
}
class Enrichment(Enum):
VIRAL = "viral"
PANEL = "panel"
class SampleAttributes(BaseModel):
country: str
state: Optional[str] = None
county: Optional[str] = None
location: Optional[str] = None
fine_location: Optional[str] = None
# Fixme: Not all the dates are real dates
date: date | str
reads: Optional[int] = None
enrichment: Optional[Enrichment] = None
method: Optional[str] = None
def european_to_iso(date):
dd, mm, yyyy = date.split("/")
return "%s-%s-%s" % (yyyy, mm, dd)
def parse_metadata(record, paper):
if paper == "rothman":
(
sample,
library,
date,
location,
enrichment,
sample_alias,
dataset,
bioproject,
) = record
wtp = sample_alias.split("_")[0]
if wtp == "JW":
# Rothman confirmed over email that JW = JWPCP.
wtp = "JWPCP"
return sample, SampleAttributes(
country="United States",
date=date,
state="California",
location="Los Angeles",
county={
# Hyperion
"HTP": "Los Angeles County",
# San Jose Creek
"SJ": "Los Angeles County",
# Joint Water Pollution Control Plant
"JWPCP": "Los Angeles County",
# Orange County
"OC": "Orange County",
# Point Loma
"PL": "San Diego County",
# South Bay
"SB": "San Diego County",
# North City
"NC": "San Diego County",
# Escondido Hale Avenue Resource Recovery Facility
"ESC": "San Diego County",
}[wtp],
fine_location=wtp,
enrichment="panel" if enrichment == "1" else "viral",
)
elif paper == "crits_christoph":
(
library,
sample,
location,
date,
method,
enrichment,
sample_alias,
dataset,
bioproject,
) = record
return sample, SampleAttributes(
date=european_to_iso(date),
country="United States",
state="California",
location="San Francisco",
county={
"Berkeley": "Alameda County",
"Marin": "Marin County",
"Oakland": "Alameda County",
"SF": "San Francisco County",
}[location],
fine_location=location,
method=method,
enrichment="panel" if enrichment == "enriched" else "viral",
)
elif paper == "spurbeck":
(
library,
sample,
group,
date,
instrument_model,
sample_alias,
bioproject,
dataset,
) = record
return sample, SampleAttributes(
date=european_to_iso(date),
country="United States",
state="Ohio",
location="Ohio",
# https://github.com/naobservatory/mgs-pipeline/issues/9
county={
"A": "Summit County",
"B": "Trumbull County",
"C": "Lucas County",
"D": "Lawrence County",
"E": "Sandusky County",
"F": "Franklin County",
"G": "Licking County",
"H": "Franklin County",
"I": "Greene County",
"J": "Montgomery County",
}[group],
fine_location=group,
enrichment="viral",
method={
"A": "AB",
"B": "AB",
"C": "C",
"D": "D",
"E": "EFGH",
"F": "EFGH",
"G": "EFGH",
"H": "EFGH",
"I": "IJ",
"J": "IJ",
}[group],
)
elif paper == "brinch":
library, sample, location, date = record
return sample, SampleAttributes(
date=date,
country="Denmark",
location="Copenhagen",
fine_location=location,
)
else:
assert False
SampleCounts = dict[TaxID, dict[Sample, int]]
metadata_bioprojects = {}
metadata_samples = {}
sample_counts = defaultdict(Counter) # taxid -> sample -> clade count
for paper, bioprojects in target_bioprojects.items():
for bioproject in bioprojects:
samples = []
with open(
os.path.join(BIOPROJECTS_DIR, bioproject, "sample-metadata.csv")
) as inf:
for i, record in enumerate(csv.reader(inf)):
if i == 0:
continue
sample, sample_attributes = parse_metadata(record, paper)
samples.append(sample)
metadata_samples[sample] = sample_attributes
metadata_bioprojects[bioproject] = samples
with open(
os.path.join(BIOPROJECTS_DIR, bioproject, "hv_clade_counts.tsv")
) as inf:
for i, row in enumerate(inf):
if i == 0:
continue
(
taxid,
name,
rank,
parent_taxid,
sample,
n_reads_direct,
n_reads_clade,
) = row.rstrip("\n").split("\t")
taxid = int(taxid)
n_reads_clade = int(n_reads_clade)
if n_reads_clade:
sample_counts[taxid][sample] = n_reads_clade
with open(
os.path.join(BIOPROJECTS_DIR, bioproject, "qc_basic_stats.tsv")
) as inf:
for i, row in enumerate(inf):
row = row.rstrip("\n").split("\t")
if i == 0:
cols = row
continue
metadata_samples[row[cols.index("sample")]].reads = int(
row[cols.index("n_read_pairs")]
)
@dataclass
class MGSData:
bioprojects: dict[BioProject, list[Sample]]
sample_attrs: dict[Sample, SampleAttributes]
read_counts: SampleCounts
@staticmethod
def from_repo():
return MGSData(
bioprojects=metadata_bioprojects,
sample_attrs=metadata_samples,
read_counts=sample_counts,
)
def sample_attributes(
self, bioproject: BioProject, enrichment: Optional[Enrichment] = None
) -> dict[Sample, SampleAttributes]:
samples = {
s: self.sample_attrs[s] for s in self.bioprojects[bioproject]
}
if enrichment:
return {
s: attrs
for s, attrs in samples.items()
if attrs.enrichment == enrichment
}
else:
return samples
def total_reads(self, bioproject: BioProject) -> dict[Sample, int]:
return {
s: self.sample_attrs[s].reads for s in self.bioprojects[bioproject]
}
def viral_reads(
self, bioproject: BioProject, taxids: Iterable[TaxID]
) -> dict[Sample, int]:
return {
s: sum(self.read_counts[taxid][s] for taxid in taxids)
for s in self.bioprojects[bioproject]
}