-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnoveltyCorrelation.py
441 lines (404 loc) · 16.2 KB
/
noveltyCorrelation.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#!/usr/bin/env python
__author__ = "Maria J. Falaguera"
__date__ = "10 May 2024"
# generate gcloud machine
"""
noveltyCorrelation.py: Analyse the co-ocurrance of novelty peaks across resources of the same type.
"""
# sumbit job to gcloud machine
"""
gcloud dataproc jobs submit pyspark noveltyCorrelation.py --cluster=cf-timeseries2 --project=open-targets-eu-dev --region="europe-west1"
"""
import sys
import itertools
from functools import reduce
import numpy as np
from pyspark.sql import functions as F
from pyspark.sql import SparkSession, Window, DataFrame
from scipy import stats
import pandas as pd
correlationNovelty_file = (
"gs://ot-team/cfalaguera/correlationNovelty/correlationNovelty"
)
spark = SparkSession.builder.getOrCreate()
prioritizedTherapeuticArea = [
"MONDO_0045024", # "cell proliferation disorder",
"EFO_0005741", # "infectious disease",
"OTAR_0000014", # "pregnancy or perinatal disease",
"EFO_0005932", # "animal disease",
"MONDO_0024458", # "disease of visual system",
"EFO_0000319", # "cardiovascular disease",
"EFO_0009605", # "pancreas disease",
"EFO_0010282", # "gastrointestinal disease",
"OTAR_0000017", # "reproductive system or breast disease",
"EFO_0010285", # "integumentary system disease",
"EFO_0001379", # "endocrine system disease",
"OTAR_0000010", # "respiratory or thoracic disease",
"EFO_0009690", # "urinary system disease",
"OTAR_0000006", # "musculoskeletal or connective tissue disease",
"MONDO_0021205", # "disease of ear",
"EFO_0000540", # "immune system disease",
"EFO_0005803", # "hematologic disease",
"EFO_0000618", # "nervous system disease",
"MONDO_0002025", # "psychiatric disorder",
"MONDO_0024297", # "nutritional or metabolic disease",
"OTAR_0000018", # "genetic, familial or congenital disease",
"OTAR_0000009", # "injury, poisoning or other complication",
"EFO_0000651", # "phenotype",
"EFO_0001444", # "measurement",
"GO_0008150", # "biological process"
]
excludeTherapeuticArea = [
"GO_0008150", # biological process
"EFO_0001444", # measurement
"EFO_0002571", # medical procedure
]
def getTherapeuticAreaForDisease():
"""
Map diseases to their prioritized therapeutic area.
Returns:
pyspark dataframe with the following columns:
- diseaseId
- therapeuticArea
- therapeuticAreaName
"""
# get TAs ranked by priority
therapeuticAreas = spark.createDataFrame(
data=[
[therapeuticArea, ranking]
for ranking, therapeuticArea in enumerate(
# otPlatform.prioritizedTherapeuticArea
prioritizedTherapeuticArea
)
],
schema=["therapeuticArea", "ranking"],
)
# select top TA for each disease
partition = Window.partitionBy("diseaseId").orderBy(F.col("ranking"))
diseases = spark.read.parquet(
"gs://open-targets-data-releases/23.06/output/etl/parquet/diseases"
).persist()
diseases = (
# get diseases mapped to multiple TAs
diseases.select(
F.col("id").alias("diseaseId"),
F.explode_outer("therapeuticAreas").alias("therapeuticArea"),
)
# add TA ranking
.join(therapeuticAreas, "therapeuticArea", "left")
# fill with 1000 those TA not included in the ranking (to avoid losing them)
.fillna(1000, subset=["ranking"])
# select top ranking TA for each disease
.withColumn("row", F.row_number().over(partition))
.filter(F.col("row") == 1)
.drop("row", "ranking")
# add TA name
.join(
diseases.select(
F.col("id").alias("therapeuticArea"),
F.col("name").alias("therapeuticAreaName"),
),
"therapeuticArea",
"left",
)
)
return diseases
# pairs
if 1:
for evidenceLink in (
"direct",
# "indirect"
):
print(evidenceLink)
if evidenceLink == "direct":
associations = "gs://ot-team/cfalaguera/novelty/23.06/associationByDatasourceDirectOverYears"
elif evidenceLink == "indirect":
associations = "gs://ot-team/cfalaguera/novelty/23.06/associationByDatasourceIndirectOverYears"
results2 = {}
for dataset in ["Shuffled", ""]:
print(dataset)
data = (
spark.read.parquet(associations + dataset)
.select("diseaseId", "targetId", "datasourceId", "year", "novelty")
.filter(F.col("year").isNotNull() & (F.col("novelty") > 0))
# only protein_coding targets
.join(
spark.read.parquet(
"gs://open-targets-data-releases/23.06/output/etl/parquet/targets"
)
.filter(F.col("biotype") == "protein_coding")
.select(F.col("id").alias("targetId")),
"targetId",
"inner",
)
# exclude TA
.join(
getTherapeuticAreaForDisease().select(
"diseaseId", "therapeuticArea", "therapeuticAreaName"
),
"diseaseId",
"left",
)
.filter(~F.col("therapeuticArea").isin(excludeTherapeuticArea))
.filter(~F.col("diseaseId").isin(prioritizedTherapeuticArea))
# filter clinvar in 2013 (noisy)
# .filter(
# (F.col("datasourceId") != "eva")
# | ((F.col("datasourceId") == "eva") & (F.col("year") > 2015))
# )
# max. novelty by datasource
.withColumn(
"maxNovelty",
F.max("novelty").over(
Window.partitionBy("diseaseId", "targetId", "datasourceId")
),
)
.filter(F.col("novelty") == F.col("maxNovelty"))
.groupby("diseaseId", "targetId", "datasourceId", "maxNovelty")
.agg(F.min("year").alias("year"))
).persist()
datasources = (
data.select("datasourceId").distinct().toPandas().datasourceId.tolist()
)
results = []
for datasourceIdA, datasourceIdB in itertools.product(
datasources,
repeat=2,
):
results.append(
data.filter(F.col("datasourceId") == datasourceIdA)
.select(
"diseaseId",
"targetId",
F.col("datasourceId").alias("datasourceIdA"),
F.col("maxNovelty").alias("maxNoveltyA"),
F.col("year").alias("yearA"),
)
.join(
data.filter(F.col("datasourceId") == datasourceIdB).select(
"diseaseId",
"targetId",
F.col("datasourceId").alias("datasourceIdB"),
F.col("maxNovelty").alias("maxNoveltyB"),
F.col("year").alias("yearB"),
),
["diseaseId", "targetId"],
"inner",
)
)
results = reduce(DataFrame.unionByName, results).repartition(
400, "datasourceIdA"
)
results2[dataset] = results
(
results2[""]
.select(
F.col("yearA").alias("realYearA"),
F.col("yearB").alias("realYearB"),
F.col("maxNoveltyA").alias("realMaxNoveltyA"),
F.col("maxNoveltyB").alias("realMaxNoveltyB"),
"diseaseId",
"targetId",
"datasourceIdA",
"datasourceIdB",
)
.join(
results2["Shuffled"].select(
F.col("yearA").alias("shuffledYearA"),
F.col("yearB").alias("shuffledYearB"),
F.col("maxNoveltyA").alias("shuffledMaxNoveltyA"),
F.col("maxNoveltyB").alias("shuffledMaxNoveltyB"),
"diseaseId",
"targetId",
"datasourceIdA",
"datasourceIdB",
),
["diseaseId", "targetId", "datasourceIdA", "datasourceIdB"],
"left",
)
.withColumn("realYearA-realYearB", F.col("realYearA") - F.col("realYearB"))
.withColumn(
"shuffledYearA-shuffledYearB",
F.col("shuffledYearA") - F.col("shuffledYearB"),
)
).write.parquet(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/pairs".format(
evidenceLink
)
)
# statistics
if 1:
for evidenceLink in [
"direct",
# "indirect",
]:
data = spark.read.parquet(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/pairs".format(
evidenceLink
)
).filter(
~F.col("datasourceIdA").isin(
["crispr_screen", "crispr", "gene_burden", "slapenrich", "sysbio"]
)
& ~F.col("datasourceIdB").isin(
["crispr_screen", "crispr", "slapenrich", "sysbio", "gene_burden"]
)
)
results_regression_r2_real = []
results_regression_pval_real = []
results_ttest_t_real = []
results_ttest_pval_real = []
results_regression_r2_random = []
results_regression_pval_random = []
for datasourceIdA in (
data.select("datasourceIdA").distinct().toPandas().datasourceIdA
):
for datasourceIdB in (
data.select("datasourceIdB").distinct().toPandas().datasourceIdB
):
print(datasourceIdA, datasourceIdB)
values = data.filter(
(F.col("datasourceIdA") == datasourceIdA)
& (F.col("datasourceIdB") == datasourceIdB)
)
# linear regression for real pairs
x = values.select("realYearA").toPandas().realYearA.values
y = values.select("realYearB").toPandas().realYearB.values
if (len(x) > 1) and (len(y) > 1):
rvalue, pvalue = stats.pearsonr(x, y)
else:
rvalue, pvalue = np.nan, np.nan
results_regression_r2_real.append(
{
"datasourceIdA": datasourceIdA,
"datasourceIdB": datasourceIdB,
"r_real": rvalue,
}
)
results_regression_pval_real.append(
{
"datasourceIdA": datasourceIdA,
"datasourceIdB": datasourceIdB,
"p_real": pvalue,
}
)
# t-test for real pairs
x = (
values.filter(F.col("realYearA-realYearB").isNotNull())
.select("realYearA-realYearB")
.toPandas()["realYearA-realYearB"]
.values
)
y = (
values.filter(F.col("shuffledYearA-shuffledYearB").isNotNull())
.select("shuffledYearA-shuffledYearB")
.toPandas()["shuffledYearA-shuffledYearB"]
.values
)
test = stats.ttest_ind(x, y)
statistic, pvalue = test.statistic, test.pvalue
results_ttest_t_real.append(
{
"datasourceIdA": datasourceIdA,
"datasourceIdB": datasourceIdB,
"t_real": statistic,
}
)
results_ttest_pval_real.append(
{
"datasourceIdA": datasourceIdA,
"datasourceIdB": datasourceIdB,
"p_real": pvalue,
}
)
# linear regression for random pairs
x = (
values.filter(~F.col("shuffledYearA").isNull())
.select("shuffledYearA")
.toPandas()
.shuffledYearA.values
)
y = (
values.filter(~F.col("shuffledYearB").isNull())
.select("shuffledYearB")
.toPandas()
.shuffledYearB.values
)
if (len(x) > 1) and (len(y) > 1):
rvalue, pvalue = stats.pearsonr(x, y)
else:
rvalue, pvalue = np.nan, np.nan
results_regression_r2_random.append(
{
"datasourceIdA": datasourceIdA,
"datasourceIdB": datasourceIdB,
"r_random": rvalue,
}
)
results_regression_pval_random.append(
{
"datasourceIdA": datasourceIdA,
"datasourceIdB": datasourceIdB,
"p_random": pvalue,
}
)
results_regression_r2_real = pd.DataFrame(results_regression_r2_real)
results_regression_r2_real = results_regression_r2_real.pivot(
index="datasourceIdA", columns="datasourceIdB", values="r_real"
).fillna(0)
results_regression_pval_real = pd.DataFrame(results_regression_pval_real)
results_regression_pval_real = results_regression_pval_real.pivot(
index="datasourceIdA", columns="datasourceIdB", values="p_real"
).fillna(0)
results_ttest_t_real = pd.DataFrame(results_ttest_t_real)
results_ttest_t_real = results_ttest_t_real.pivot(
index="datasourceIdA", columns="datasourceIdB", values="t_real"
).fillna(0)
results_ttest_pval_real = pd.DataFrame(results_ttest_pval_real)
results_ttest_pval_real = results_ttest_pval_real.pivot(
index="datasourceIdA", columns="datasourceIdB", values="p_real"
).fillna(0)
results_regression_r2_random = pd.DataFrame(results_regression_r2_random)
results_regression_r2_random = results_regression_r2_random.pivot(
index="datasourceIdA", columns="datasourceIdB", values="r_random"
).fillna(0)
results_regression_pval_random = pd.DataFrame(results_regression_pval_random)
results_regression_pval_random = results_regression_pval_random.pivot(
index="datasourceIdA", columns="datasourceIdB", values="p_random"
).fillna(0)
results_regression_r2_real.to_csv(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/regression_r_real.csv".format(
evidenceLink
),
sep="\t",
)
results_regression_pval_real.to_csv(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/regression_p_real.tsv".format(
evidenceLink
),
sep="\t",
)
results_ttest_t_real.to_csv(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/ttest_t_real.tsv".format(
evidenceLink
),
sep="\t",
)
results_ttest_pval_real.to_csv(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/ttest_p_real.tsv".format(
evidenceLink
),
sep="\t",
)
results_regression_r2_random.to_csv(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/regression_r_random.tsv".format(
evidenceLink
),
sep="\t",
)
results_regression_pval_random.to_csv(
"gs://ot-team/cfalaguera/noveltyCorrelation/evidenceLink={}/regression_p_random.tsv".format(
evidenceLink
),
sep="\t",
)