-
Notifications
You must be signed in to change notification settings - Fork 0
/
analysis.py
3608 lines (3302 loc) · 131 KB
/
analysis.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import logging
import math
import re
import os
import sys
import tempfile
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Concatenate, Literal, ParamSpec, TypeVar
import fire
import numpy as np
import pandas as pd
import psutil
from xarray import Dataset
from dotenv import load_dotenv
from IPython.display import display
from lightgbm import LGBMClassifier
from pandas import DataFrame as PandasDataFrame
from pandas import Series as PandasSeries
from pandas.io.formats.style import Styler
from pyspark.sql import DataFrame as SparkDataFrame
from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F
from pyspark_gcs import get_gcs_enabled_config
from scipy.stats import wilcoxon
from scipy.stats.contingency import relative_risk
from scipy.stats import fisher_exact
from sklearn.base import BaseEstimator
from sklearn.compose import ColumnTransformer
from sklearn.discriminant_analysis import StandardScaler
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegressionCV, Ridge
from sklearn.pipeline import FunctionTransformer, Pipeline, make_pipeline
from sklearn.preprocessing import MinMaxScaler
import xrml
logger = logging.getLogger(__name__)
###############################################################################
# Configuration
###############################################################################
SEED = 0
FEATURES_PRIMARY_KEY = ["target_id", "disease_id", "year"]
MIN_EVIDENCE_YEAR = 1990
MAX_EVIDENCE_YEAR = 2024
DEFAULT_MAX_TRAINING_TRANSITION_YEAR = 2015
DEFAULT_CLINICAL_ADVANCEMENT_WINDOW = 2
DATASETS = {
"23.12": (
default_tables := {
"evidence": "evidence",
"targets": "targets",
"diseases": "diseases",
"targetPrioritisation": "targetPrioritisation",
"associationByOverallDirect": "associationByOverallDirect",
"associationByOverallIndirect": "associationByOverallIndirect",
}
),
"23.09": default_tables,
# Note: this typo in "Priorisation" is real for 23.06
"23.06": {**default_tables, **{"targetPrioritisation": "targetsPriorisation"}},
}
PRIMARY_TABLES = {
"relative_risk_p_values": {"caption": "P-values by model and limit"},
"relative_risk_averages_by_ta": {
"caption": "Average relative risk across therapeutic areas by model and limit"
},
}
@dataclass
class AnalysisConfig:
data_dir: str
open_targets_version: str
clinical_transition_phase: int
clinical_advancement_window: int
validate_modeling_features: bool
min_training_transition_year: int
max_training_transition_year: int
max_training_advancement_year: int
min_evaluation_transition_year: int
max_evaluation_advancement_year: int
max_evaluation_transition_year: int
def get_analysis_config(
data_dir: str,
open_targets_version: str,
max_training_transition_year: int,
clinical_advancement_window: int,
clinical_transition_phase: int = 2,
validate_modeling_features: bool = True,
) -> AnalysisConfig:
assert isinstance(data_dir, str)
assert isinstance(open_targets_version, str)
assert isinstance(max_training_transition_year, int)
assert isinstance(clinical_advancement_window, int)
assert isinstance(clinical_transition_phase, int)
assert isinstance(validate_modeling_features, bool)
return AnalysisConfig(
data_dir=data_dir,
open_targets_version=open_targets_version,
clinical_transition_phase=clinical_transition_phase,
clinical_advancement_window=clinical_advancement_window,
validate_modeling_features=validate_modeling_features,
min_training_transition_year=MIN_EVIDENCE_YEAR,
max_training_transition_year=max_training_transition_year,
max_training_advancement_year=max_training_transition_year
+ clinical_advancement_window,
min_evaluation_transition_year=max_training_transition_year + 1,
max_evaluation_advancement_year=MAX_EVIDENCE_YEAR,
max_evaluation_transition_year=MAX_EVIDENCE_YEAR - clinical_advancement_window,
)
###############################################################################
# Data
###############################################################################
def load_publication_years(spark: SparkSession) -> SparkDataFrame:
path = Path(tempfile.gettempdir()) / "pub_years.parquet"
if not path.exists():
# Load stable export from https://gist.github.com/eric-czech/44a9054e0d95b2fa9de3d37ba01a7527
url = "https://github.com/eric-czech/public-data/blob/74586e5aa694bc4f00b715e201d709617b639917/pubmed/pub_years.parquet?raw=true"
pd.read_parquet(url).to_parquet(path)
return spark.read.parquet(str(path))
def load_evidence(spark: SparkSession, version: str) -> SparkDataFrame:
return spark.read.parquet(get_gcs_path(version, "evidence"))
def load_association_scores(spark: SparkSession, version: str) -> SparkDataFrame:
return (
spark.read.parquet(get_gcs_path(version, "associationByOverallDirect"))
.select("targetId", "diseaseId", F.col("score").alias("directScore"))
.join(
spark.read.parquet(
get_gcs_path(version, "associationByOverallIndirect")
).select("targetId", "diseaseId", F.col("score").alias("indirectScore")),
on=["targetId", "diseaseId"],
how="outer",
)
.transform(to_snake_case)
)
def load_targets(
spark: SparkSession, version: str, include_prioritisation: bool = True
) -> SparkDataFrame:
targets = spark.read.parquet(get_gcs_path(version, "targets"))
if include_prioritisation:
targets = targets.join(
load_target_prioritisation(spark, version).withColumnRenamed(
"targetId", "id"
),
on="id",
how="left",
)
return targets
def load_target_prioritisation(spark: SparkSession, version: str) -> SparkDataFrame:
return spark.read.parquet(get_gcs_path(version, "targetPrioritisation"))
def load_diseases(spark: SparkSession, version: str) -> SparkDataFrame:
return spark.read.parquet(get_gcs_path(version, "diseases"))
def get_disease_id_to_name(identifiers: SparkDataFrame) -> PandasSeries:
return (
identifiers.filter(F.col("disease_id").isNotNull()) # type: ignore[attr-defined]
.select(
"disease_id",
F.coalesce("disease_name", F.col("disease_id")).alias("disease_name"),
)
.distinct()
.toPandas()
.set_index("disease_id")["disease_name"]
)
def get_target_id_to_symbol(identifiers: SparkDataFrame) -> PandasSeries:
return (
identifiers.filter(F.col("target_id").isNotNull()) # type: ignore[attr-defined]
.select(
"target_id",
F.coalesce("target_symbol", F.col("target_id")).alias("target_symbol"),
)
.distinct()
.toPandas()
.set_index("target_id")["target_symbol"]
)
def get_identifiers(
targets: SparkDataFrame, diseases: SparkDataFrame, evidence: SparkDataFrame
) -> SparkDataFrame:
return (
evidence.select(
"targetId",
"diseaseId",
)
.distinct()
.withColumn("inEvidence", F.lit(True))
.join(
targets.select(
F.col("id").alias("targetId"),
F.col("approvedSymbol").alias("targetSymbol"),
)
.distinct()
.withColumn("inTargets", F.lit(True)),
on="targetId",
how="outer",
)
.join(
diseases.select(
F.col("id").alias("diseaseId"), F.col("name").alias("diseaseName")
)
.distinct()
.withColumn("inDiseases", F.lit(True)),
on="diseaseId",
how="outer",
)
.transform(to_snake_case)
)
def get_target_features(targets: SparkDataFrame) -> SparkDataFrame:
return (
targets.select(
F.col("id").alias("targetId"),
"tissueSpecificity",
"tissueDistribution",
"geneticConstraint",
*(
[F.col("mouseKOScore").alias("mouseKoScore")]
if "mouseKOScore" in targets.columns
else []
),
)
.transform(to_snake_case)
.transform(
spark_lambda(
lambda df: df.select(
"target_id",
*[
F.col(c).alias(f"target__{c}")
for c in df.columns
if c != "target_id"
],
)
)
)
)
def get_target_tractability(targets: SparkDataFrame) -> SparkDataFrame:
return targets.select("id", F.explode("tractability").alias("tractability")).select(
F.col("id").alias("target_id"),
F.col("tractability.id").alias("tractability_id"),
F.col("tractability.value").alias("tractability_value"),
F.col("tractability.modality").alias("tractability_modality"),
)
def get_disease_therapeutic_areas(diseases: SparkDataFrame) -> SparkDataFrame:
return (
diseases.select(
F.col("id").alias("diseaseId"),
F.explode("therapeuticAreas").alias("therapeuticAreaId"),
)
.join(
diseases.filter(F.col("ontology.isTherapeuticArea")).select(
F.col("id").alias("therapeuticAreaId"),
F.col("name").alias("therapeuticAreaName"),
),
on="therapeuticAreaId",
how="inner",
)
.transform(
spark_lambda(
lambda df: df.unionByName(
df.select(
"diseaseId",
F.lit("ALL_0").alias("therapeuticAreaId"),
F.lit("all").alias("therapeuticAreaName"),
).distinct()
)
)
)
.select("diseaseId", "therapeuticAreaId", "therapeuticAreaName")
.transform(to_snake_case)
)
def get_clinical_evidence(evidence: SparkDataFrame) -> SparkDataFrame:
return (
evidence.filter(F.col("datasourceId") == "chembl")
.filter(F.col("clinicalPhase").isNotNull())
.select(
"targetId",
"diseaseId",
"studyStartDate",
"clinicalPhase",
)
)
def get_clinical_stages(clinical_evidence: SparkDataFrame) -> SparkDataFrame:
return (
clinical_evidence
# Ignore phase 0 trials
.filter(F.col("clinicalPhase") >= 1)
.withColumn("year", F.year("studyStartDate"))
# Implicitly ignore untemporalized approvals since they can't be used
.filter(F.col("year").isNotNull())
.transform(to_clamped_year)
.groupby("targetId", "diseaseId", "year")
.agg(
F.max("clinicalPhase").cast("int").alias("clinicalPhaseMaxReached"),
*[
F.max(F.when(F.col("clinicalPhase") == phase, F.lit(1))).alias(
f"clinicalPhase{phase}Reached"
)
for phase in [1, 2, 3, 4]
],
)
)
def augment_evidence(evidence: SparkDataFrame) -> SparkDataFrame:
return evidence.unionByName(
# Add a genetic evidence group corresponding to EVA associations with linked
# publications, which is effectively only OMIM submissions
evidence.filter(F.col("datatypeId") == "genetic_association")
.filter(F.col("datasourceId") == "eva")
.filter(F.col("literature").isNotNull() & (F.size(F.col("literature")) > 0))
.withColumn("datasourceId", F.lit("omim"))
).unionByName(
# Add an aggregate genetic evidence data source as a combination of sources
# that are curated, at least in part, to improve power for that kind of association;
# notable omissions from this are 'gene_burden' and 'ot_genetics_portal'
evidence.filter(F.col("datatypeId") == "genetic_association")
.filter(
F.col("datasourceId").isin(
[
"genomics_england",
"orphanet",
"gene2phenotype",
"uniprot_literature",
"uniprot_variants",
"clingen",
"eva",
]
)
)
.withColumn("datasourceId", F.lit("curated"))
)
def temporalize_evidence(
evidence: SparkDataFrame, pub_years: SparkDataFrame
) -> SparkDataFrame:
primary_key = ["datatypeId", "datasourceId", "targetId", "diseaseId"]
return (
(
evidence.filter(
F.col("literature").isNotNull() & (F.size(F.col("literature")) > 0)
)
.select(*primary_key, "score", F.explode("literature").alias("pmid"))
.withColumn("pmid", F.col("pmid").cast("long"))
.join(
pub_years.withColumnRenamed("pub_year", "year"), on="pmid", how="inner"
)
.drop("pmid")
)
.unionByName(
evidence.filter(F.col("publicationYear").isNotNull()).select(
*primary_key, "score", F.col("publicationYear").alias("year")
)
)
.transform(to_clamped_year)
.groupby(*primary_key, "year")
.agg(F.max("score").alias("score"))
.unionByName(
# Add time-independent max scores as well
evidence.groupby(*primary_key)
.agg(F.max("score").alias("score"))
.withColumn("year", F.lit(None).cast("int"))
)
)
def to_null_safe_year(df: SparkDataFrame) -> SparkDataFrame:
return df.withColumn("year", F.coalesce(F.col("year"), F.lit(-1)))
def from_null_safe_year(df: SparkDataFrame) -> SparkDataFrame:
return df.withColumn(
"year",
F.when(F.col("year") == -1, F.lit(None).cast("int")).otherwise(F.col("year")),
)
def to_clamped_year(df: SparkDataFrame) -> SparkDataFrame:
return df.withColumn(
"year",
F.when(F.col("year") < MIN_EVIDENCE_YEAR, F.lit(MIN_EVIDENCE_YEAR - 1))
.when(F.col("year") > MAX_EVIDENCE_YEAR, F.lit(MAX_EVIDENCE_YEAR + 1))
.otherwise(F.col("year")),
)
def get_evidence_features(
temporalized_evidence: SparkDataFrame, clinical_stages: SparkDataFrame
) -> tuple[SparkDataFrame, SparkDataFrame]:
phase_column = "target_disease__clinical__phase_max__reached"
features = (
clinical_stages.transform(to_snake_case)
.transform(
spark_lambda(
lambda df: df.select(
*[
F.col(c).alias(
"target_disease__"
+ re.sub("_(phase(\\d|_max))_", r"__\1__", c)
)
if c.startswith("clinical")
else F.col(c)
for c in df.columns
]
)
)
)
.transform(to_null_safe_year)
).join(
temporalized_evidence.withColumn(
"feature",
F.concat_ws(
"__",
F.lit("target_disease"),
F.col("datatypeId"),
F.col("datasourceId"),
),
)
.groupby("targetId", "diseaseId", "year")
.pivot("feature")
.agg(F.max("score"))
.transform(to_snake_case)
.transform(to_null_safe_year),
on=FEATURES_PRIMARY_KEY,
how="outer",
)
temporal_features = (
features.join(
features.filter(F.col(phase_column).isNotNull())
.select("target_id", "disease_id")
.distinct(),
on=["target_id", "disease_id"],
how="semi",
)
.transform(
spark_lambda(
lambda df: df.join(
df.groupby(["target_id", "year"])
.agg(
F.max(phase_column).alias(
"target__clinical__phase_max__reached"
)
)
.crossJoin(df.select("disease_id").drop_duplicates()),
on=FEATURES_PRIMARY_KEY,
how="outer",
).join(
df.groupby(["disease_id", "year"])
.agg(
F.max(phase_column).alias(
"disease__clinical__phase_max__reached"
)
)
.crossJoin(df.select("target_id").drop_duplicates()),
on=FEATURES_PRIMARY_KEY,
how="outer",
)
)
)
.transform(from_null_safe_year)
.transform(
spark_lambda(
lambda df: df.select(
*FEATURES_PRIMARY_KEY,
*[
F.max(F.col(c))
.over(
Window.partitionBy("target_id", "disease_id")
.orderBy(F.asc_nulls_last("year"))
.rowsBetween(Window.unboundedPreceding, 0)
)
.alias(c)
for c in df.columns
if c not in FEATURES_PRIMARY_KEY
],
)
)
)
)
static_features = (
features.withColumn("year", F.lit(None).cast("int"))
.transform(
spark_lambda(
lambda df: df.groupby(*FEATURES_PRIMARY_KEY).agg(
*[
F.max(F.col(c)).alias(c)
for c in df.columns
if c not in FEATURES_PRIMARY_KEY
]
)
)
)
.join(
temporal_features.groupby("target_id").agg(
F.max("target__clinical__phase_max__reached").alias(
"target__clinical__phase_max__reached"
)
),
on="target_id",
how="left",
)
.join(
temporal_features.groupby("disease_id").agg(
F.max("disease__clinical__phase_max__reached").alias(
"disease__clinical__phase_max__reached"
)
),
on="disease_id",
how="left",
)
.select(*temporal_features.columns)
)
return temporal_features, static_features
def get_aggregated_features(
features: SparkDataFrame, diseases: SparkDataFrame
) -> SparkDataFrame:
indirect_feature_names = [
c
for c in features.columns
if c.startswith("target_disease__") and "__clinical__" not in c
]
direct_feature_names = [
c
for c in features.columns
if c not in indirect_feature_names + FEATURES_PRIMARY_KEY
]
logger.info(
f"Aggregating indirect evidence for the following features: {indirect_feature_names}"
)
aggregated_features = (
(base_features := features.transform(to_null_safe_year))
.select(*FEATURES_PRIMARY_KEY, *direct_feature_names)
.join(
base_features.select(*FEATURES_PRIMARY_KEY, *indirect_feature_names)
.withColumnRenamed("disease_id", "disease_id_src")
.join(
diseases.select("id", "ancestors")
.withColumn(
"ancestors", F.array_union(F.array("id"), F.col("ancestors"))
)
.select(
F.col("id").alias("disease_id_dst"),
F.explode("ancestors").alias("disease_id_src"),
),
on="disease_id_src",
how="inner",
)
.withColumnRenamed("disease_id_dst", "disease_id")
.drop("disease_id_src")
.groupby("target_id", "disease_id", "year")
.agg(*[F.max(c).alias(c) for c in indirect_feature_names]),
on=FEATURES_PRIMARY_KEY,
how="inner",
)
.transform(from_null_safe_year)
.select(*features.columns)
)
return aggregated_features
def parquet_writer(
spark: SparkSession, output_dir: Path
) -> Callable[[SparkDataFrame, str], tuple[SparkDataFrame, Path]]:
def fn(df: SparkDataFrame, table: str) -> tuple[SparkDataFrame, Path]:
path = output_dir / f"{table}.parquet"
logger.info(f"Saving {table!r} to {path!r})")
df.printSchema()
df.write.parquet(str(path), mode="overwrite")
df = spark.read.parquet(str(path))
return df, path
return fn
def aggregate_features(output_path: str, version: str) -> None:
logger.info(f"Aggregating features for version {version!r} to {output_path!r}")
spark = get_spark()
output_dir = Path(output_path) / "features" / str(version)
write_parquet = parquet_writer(spark, output_dir)
features = spark.read.parquet(str(output_dir / "features.parquet"))
diseases = load_diseases(spark, version=version)
aggregated_features = get_aggregated_features(features=features, diseases=diseases)
aggregated_features, _ = write_parquet(aggregated_features, "aggregated_features")
assert aggregated_features.count() == features.count()
logger.info("Feature aggregation complete")
def get_feature_info(
feature_names: list[str], raise_on_uknown: bool = False
) -> PandasDataFrame:
result = []
for feature in feature_names:
entity = feature.split("__")[0]
if entity not in {"target", "disease", "target_disease"}:
if raise_on_uknown:
raise ValueError(f"Unknown entity: {entity}")
else:
continue
kind = "temporal"
if entity in {"target", "disease"} and "__clinical__" not in feature:
kind = "static"
elif entity == "target_disease" and feature.startswith(
"target_disease__genetic_association__"
):
kind = "static"
result.append({"feature": feature, "entity": entity, "kind": kind})
return pd.DataFrame(result)
def validate_features(features: SparkDataFrame, has_timeseries: bool = True) -> None:
feature_info = get_feature_info(
[c for c in features.columns if c not in FEATURES_PRIMARY_KEY]
)
feature_groups = (
feature_info.groupby(["entity", "kind"])["feature"]
.unique()
.apply(list)
.to_dict()
)
def _distinct_counts(
df: SparkDataFrame, columns: list[str], by: list[str]
) -> PandasSeries:
return (
df.groupby(*by) # type: ignore[attr-defined]
.agg(
*[
(
F.count_distinct(F.col(c))
+ F.max(F.col(c).isNull()).cast("int")
).alias(c)
for c in columns
]
)
.agg(*[F.max(c).alias(c) for c in columns])
.toPandas()
.iloc[0]
)
def _is_monotonic_increasing(
df: SparkDataFrame, columns: list[str], by: list[str]
) -> PandasSeries:
return (
df.select( # type: ignore[attr-defined]
*[
F.when(
F.col(c)
< F.lag(F.col(c), offset=1).over(
Window.partitionBy(*by).orderBy(F.asc_nulls_last("year"))
),
1,
)
.otherwise(0)
.alias(c)
for c in columns
]
)
.agg(*[(F.max(F.col(c)) <= 0).alias(c) for c in columns])
.toPandas()
.iloc[0]
)
def _validate_static_features(entity: str) -> None:
names = feature_groups.get((entity, "static"), [])
logger.info(f"Validating static features for entity {entity!r}: {names}")
if len(names) == 0:
return
counts = _distinct_counts(features, names, by=[f"{entity}_id"])
for feature in counts.index:
if (count := counts.loc[feature]) > 1:
raise ValueError(
f"Found {count} distinct values for static {entity} feature {feature!r}"
)
def _validate_temporal_features(entity: str) -> None:
names = feature_groups.get((entity, "temporal"), [])
logger.info(f"Validating temporal features for entity {entity!r}: {names}")
if len(names) == 0:
return
# Ensure that there is more than one unique value for the feature
# across years if it is supposed to differ in time
if has_timeseries:
counts = _distinct_counts(features, names, by=["year"])
for feature in counts.index:
if (count := counts.loc[feature]) <= 1:
raise ValueError(
f"Found only {count} distinct values across years for "
f"temporal {entity} feature {feature!r}"
)
# Ensure that all temporal features only increase or stay the same in time
by = [f"{entity}_id"]
if entity == "target_disease":
by = ["target_id", "disease_id"]
if has_timeseries:
is_monotonic = _is_monotonic_increasing(features, names, by=by)
if (~is_monotonic).any():
invalid = is_monotonic[~is_monotonic].index.tolist()
raise ValueError(
f"Found non-monotonic temporal features for entity {entity!r}: {invalid}"
)
# Ensure that there is only one value for a given (target|disease) + year
# combination for each feature; e.g. the same target + year combination should
# always have the same value regardless of the associated disease
if len(by) == 1:
counts = _distinct_counts(features, names, by=by + ["year"])
for feature in counts.index:
if (count := counts.loc[feature]) > 1:
raise ValueError(
f"Found {count} distinct values across years for temporal {entity} feature {feature!r}"
)
for entity in ["target", "disease"]:
_validate_static_features(entity)
for entity in ["target", "disease", "target_disease"]:
_validate_temporal_features(entity)
def export_features(output_path: str, version: str | float) -> None:
logger.info(f"Exporting features for version {version!r} to {output_path!r}")
spark = get_spark()
if isinstance(version, float):
version = str(version)
output_dir = Path(output_path) / "features" / version
if not output_dir.exists():
output_dir.mkdir(parents=True)
write_parquet = parquet_writer(spark, output_dir)
publication_years = load_publication_years(spark)
targets = load_targets(spark, version=version)
diseases = load_diseases(spark, version=version)
evidence = load_evidence(spark, version=version)
write_parquet(get_target_tractability(targets), "tractability")
write_parquet(get_disease_therapeutic_areas(diseases), "therapeutic_areas")
clinical_evidence = get_clinical_evidence(evidence)
clinical_stages = get_clinical_stages(clinical_evidence)
temporalized_evidence = temporalize_evidence(
augment_evidence(evidence), publication_years
)
clinical_stages, _ = write_parquet(clinical_stages, "clinical_stages")
temporalized_evidence, _ = write_parquet(
temporalized_evidence, "temporalized_evidence"
)
identifiers = get_identifiers(targets, diseases, temporalized_evidence)
identifiers, _ = write_parquet(identifiers, "identifiers")
temporal_features, static_features = get_evidence_features(
temporalized_evidence, clinical_stages
)
temporal_features, temporal_features_path = write_parquet(
temporal_features.join(
get_target_features(targets), on="target_id", how="left"
),
"temporal_features",
)
static_features, static_features_path = write_parquet(
static_features.join(get_target_features(targets), on="target_id", how="left"),
"static_features",
)
def _validate_features(df: SparkDataFrame, path: Path) -> None:
logger.info(f"Validating features at {str(path)!r}")
try:
validate_features(df)
except:
logger.error(f"Feature validation failed; review at {str(path)!r}")
raise
_validate_features(temporal_features, temporal_features_path)
_validate_features(static_features, static_features_path)
logger.info("Feature export complete")
###############################################################################
# Summaries
###############################################################################
def get_feature_advancement_statistics(
features: SparkDataFrame,
initial_phases: list[int],
min_transition_year: int,
max_transition_year: int,
) -> SparkDataFrame:
return (
features.filter(F.col("year").isNotNull())
.withColumn(
"target_disease__clinical__early_phase__reached",
F.greatest(
F.lit(0),
*[
F.coalesce(
f"target_disease__clinical__phase{phase}__reached", F.lit(0)
)
for phase in initial_phases
],
),
)
.transform(
spark_lambda(
lambda df: (
df.groupby("target_id", "disease_id").agg(
F.min(
F.when(
F.col("target_disease__clinical__early_phase__reached")
> 0,
F.col("year"),
)
).alias("phase__reached__first_year"),
F.min(
F.when(
(
F.col(
"target_disease__clinical__phase_max__reached"
)
> max(initial_phases)
)
& (
F.col(
"target_disease__clinical__early_phase__reached"
)
> 0
),
F.col("year"),
)
).alias("phase__surpassed__first_year"),
F.array(
*[
F.struct(
F.min(F.when(F.col(c) > 0, F.col("year"))).alias(
"first_year"
),
F.lit("__".join(c.split("__")[1:3])).alias("name"),
)
for c in df.columns
if c.startswith("target_disease__")
and "__clinical__" not in c
]
).alias("features"),
)
)
)
)
.filter(
F.col("phase__reached__first_year").between(
min_transition_year, max_transition_year
)
)
.select("*", F.explode("features").alias("feature"))
.drop("features")
.select(
"*",
F.col("feature.name").alias("feature_name"),
F.col("feature.first_year").alias("feature_first_year"),
)
.drop("feature")
.withColumn(
"emerged",
F.when(
F.col("feature_first_year").isNull()
| F.col("phase__reached__first_year").isNull(),
F.lit("none"),
)
.when(
F.col("feature_first_year") < F.col("phase__reached__first_year"),
F.lit("before"),
)
.when(
F.col("feature_first_year") >= F.col("phase__reached__first_year"),
F.lit("after"),
),
)
.withColumn(
"progress",
F.when(F.col("phase__reached__first_year").isNull(), F.lit("none"))
.when(F.col("phase__surpassed__first_year").isNull(), F.lit("stalled"))
.when(
F.col("phase__surpassed__first_year")
>= F.col("phase__reached__first_year"),
F.lit("advanced"),
),
)
.withColumn("pair", F.struct(F.col("target_id"), F.col("disease_id")))
.groupby(
"feature_name",
"emerged",
"progress",
)
.agg(F.count_distinct("pair").alias("n_pairs"))
)
def get_feature_statistics(
features: PandasDataFrame, therapeutic_areas: PandasDataFrame
) -> PandasDataFrame:
all_features = features.filter(regex="^target_disease__").columns.tolist()
evidence_features = features.filter(
regex="^target_disease__(?!time__|clinical__|outcome__)"
).columns.tolist()
non_evidence_features = list(set(all_features) - set(evidence_features))
logger.info(
"Target-disease features partitioned into:\n"
f"evidence features={evidence_features}\n"
f"non-evidence features={non_evidence_features}"
)
feature_statistics = (
features.assign(
pair=lambda df: df.apply(
lambda r: (r["target_id"], r["disease_id"]), axis=1
)
)
.assign(
has_target_disease_evidence=lambda df: (
(df[evidence_features] > 0).any(axis=1)
)
)
.merge(
therapeutic_areas,
on="disease_id",
how="left",
)
.pipe(assert_condition, lambda df: df["therapeutic_area_id"].notnull().all())
.pipe(
assert_condition,
lambda df: not df[
["therapeutic_area_name", "split", "target_id", "disease_id"]
]
.duplicated()
.any(),
)
.groupby(["therapeutic_area_name", "split"])
.agg(
n_targets=("target_id", "nunique"),
n_diseases=("disease_id", "nunique"),
n_pairs=("pair", "nunique"),
min_year=("transition_year", "min"),
max_year=("transition_year", "max"),
balance=("target_disease__outcome__advanced", "mean"),
n_pairs_with_evidence=("has_target_disease_evidence", "sum"),
fraction_pairs_with_evidence=("has_target_disease_evidence", "mean"),
)
.rename_axis("statistic", axis="columns")
)
return feature_statistics
def get_feature_presence(features: PandasDataFrame) -> PandasDataFrame:
def get_feature_group_label(fg: str) -> str:
entity, group = fg.split("__")
if entity == "target_disease":
entity = "pair"
if "phase_2" in group:
group = "prior phase 2+ trials"
elif group == "outcome":
group = "advanced beyond phase 2"