-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClinicalTrialFunctions.py
1802 lines (1424 loc) · 72.5 KB
/
ClinicalTrialFunctions.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
# system
import os
from pathlib import Path
import glob
import re
from collections import OrderedDict
from collections import Counter
from datetime import datetime
import string
# data
import pandas as pd
import numpy as np
import json
import requests
import pgeocode
# math
from scipy.stats import mannwhitneyu
from scipy.stats import kruskal
from scipy.stats import spearmanr
import math
import scipy
import umap
# nlp
import spacy
import scispacy
from scispacy.linking import EntityLinker
from bertopic import BERTopic
#from scispacy.umls_linking import UmlsEntityLinker
#import spacy_streamlit
# plotting
import streamlit as st
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import ScalarFormatter
from statannot import add_stat_annotation
import plotly.express as px
import plotly.graph_objects as go
# manuscript only
######################################################
### DTx manuscript functions
def createSupplementalTopicTables(topics_per_class, topics=[0,1,2,3,4], topic_names=None):
"""
Formats BERTopic values for manuscript table
Params:
topics_per_class
Returns:
pd.DataFrame()
"""
# filter values
table_df=pd.DataFrame()
topics_per_class= topics_per_class[topics_per_class["Topic"].isin(topics)]
topics_per_class = topics_per_class.groupby(["Name", "Class", "Topic"]).first()
# add proportion components
table_df.index = topics_per_class.index
table_df["Proportion"] = [ "%s/%s (%.1f%%)"%(f,t,p*100) for f, t, p in zip(topics_per_class["Frequency"], topics_per_class["Total"], topics_per_class["Percent"])]
table_df["Components"] = topics_per_class["Words"]
# sort values
table_df["Percent"] = topics_per_class["Percent"]
table_df = table_df.reset_index()
#topics_per_class = topics_per_class.sort_values(["Name", "Percent"], ascending=False)
table_df= table_df.sort_values(["Name", "Percent"], ascending=[True, False])
del table_df["Percent"]
# formatting
if topic_names is not None:
table_df["Topic names"] = [topic_names[str(n)] for n in table_df["Topic"]]
del table_df["Topic"]
table_df.columns = ["Global topic representation", "MeSH Heading", "Proportion", "Components", "Topic names"]
table_df = table_df[["Topic names", "MeSH Heading", "Proportion", "Components"]]
else:
del table_df["Topic"]
table_df.columns = ["Topic names", "MeSH Heading", "Proportion", "Components"]
table_df = table_df[["Topic names", "MeSH Heading", "Proportion", "Components"]]
return table_df.set_index(["Topic names", "MeSH Heading"])
def printStudyMetrics(metrics_df, groupby="StudyType", study_type="Interventional",
values = "NumberLocations", metrics=["count", "median", "std"]):
"""
Prints metrics for values in a specified group
Params:
metrics_df
groupby (str): col to groupby
study_type (str): group to print metrics for
values (str): value column
metrics (list): type of metrics to print (must be list of 3 values)
Returns:
None
"""
int_count, int_mean, int_std = metrics_df.groupby(groupby)[[values]].agg(metrics).loc[study_type][values]
metrics_df = metrics_df[metrics_df[groupby]==study_type]
median = metrics_df[values].median()
iqr_25, iqr_75 = np.percentile(metrics_df[values], q=[25 , 75], interpolation="midpoint")
print("%s %s"%(study_type, values))
print("Count: %s"%int_count)
print("%s: %.2f "%(metrics[1], int_mean))
print("IQR (25%%), IQR (75%%): %.2f-%.2f"%(iqr_25, iqr_75))
print("Range: %.2f-%.2f"%(metrics_df[values].min(), metrics_df[values].max()))
#print("95%% CI: %.2f - %.2f"%((int_mean - 1.96*int_std), (int_mean + 1.96*int_std)))
print()
def printEnrollmentMetrics(enrollment_df, values=["Actual", "Anticipated"]):
"""
Prints count, mean/median, range information for each clinical trial
Params:
enrollment (list<int, float>): list of enrollment counts (or log counts)
"""
for x in enrollment_df["conditionMeshMainBranch"].unique():
curr_df = enrollment_df[enrollment_df["conditionMeshMainBranch"]==x]
if values is None:
print(x+", actual + anticipated")
enrollment = curr_df["EnrollmentCount"]
median = enrollment.median()
mean = enrollment.mean()
iqr_25, iqr_75 = np.percentile(enrollment, q=[25 , 75], interpolation="midpoint")
print("Count: %d "%len(enrollment))
print("Mean, median: %d, %d"%(enrollment.mean(), enrollment.median()))
print("IQR (25%%), IQR (75%%): %s - %s"%(iqr_25, iqr_75))
print("Range: %d - %d"%(enrollment.min(), enrollment.max()))
#print("95%% CI, mean: %.2f - %.2f"%((mean - 1.96*enrollment.std()), (mean + 1.96*enrollment.std())))
print()
else:
for a in values:
print(x+", "+a)
enrollment = curr_df[curr_df["EnrollmentType"] == a]["EnrollmentCount"]
median = enrollment.median()
mean = enrollment.mean()
iqr_25, iqr_75 = np.percentile(enrollment, q=[25 , 75], interpolation="midpoint")
print("Count: %d "%len(enrollment))
print("Mean, median: %d, %d"%(enrollment.mean(), enrollment.median()))
print("IQR (25%%), IQR (75%%): %s - %s"%(iqr_25, iqr_75))
print("Range: %d - %d"%(enrollment.min(), enrollment.max()))
#print("95%% CI, mean: %.2f - %.2f"%((mean - 1.96*enrollment.std()), (mean + 1.96*enrollment.std())))
print()
def printTopicValues(topics_per_class, topics=[0,1,2,3,4], sort_col="Percent",
freq_col="Frequency", total_col="Total", pct_col="Percent"):
"""
Formatted printing for topic values
Params:
topics_per_class (pd.DataFrame): frequency, total, percent values for each class topic
topics (list<int>): list of topics to print
sort_col (str): column to sort values for printing
freq_col (list<str>): list of values to print
"""
# filtering
if topics is not None:
topics_per_class = topics_per_class[topics_per_class["Topic"].isin(topics)]
# print percentages for each topic
for topic in topics_per_class["Topic"].unique():
curr_df = topics_per_class[topics_per_class["Topic"] == topic]
curr_df = curr_df.sort_values(sort_col, ascending=False)
curr_df = curr_df.set_index("Class")
print(curr_df["Name"].unique()[0])
for c in curr_df.index:
row = curr_df.loc[c]
print("\t%s: %s/%s (%.2f)"%(c, row[freq_col], row[total_col], row[pct_col]*100), row["Words"])
print()
def plotPopulationvsNumTrialLocations(state_df, min_label=25, height=8):
"""
Scatterplot of state population vs number of clinical trials
"""
state_df = state_df.dropna(subset=["state_code"])
state_df["clinicalTrials"] = state_df["clinicalTrials"].replace(np.nan, 0)
sns.set(font_scale = 2)
sns.set_style("white")
sns.set_context("talk")
lm = sns.lmplot(data = state_df, x = "July2021Estimate", y= "clinicalTrials", height=height)
ax = lm.axes[0,0]
print("State population vs # trial sites: ", spearmanr(state_df["clinicalTrials"], state_df["July2021Estimate"]))
labels = state_df.copy(deep=True)
labels["label"] = labels["state_code"]
labels = labels[labels["clinicalTrials"] > min_label]
ax = addLabels(ax, labels=labels, xValues="July2021Estimate", yValues="clinicalTrials",
plotType='scatter', size=16, color='black', correction=1.5)
ax.set_ylabel("Number of DTx trial locations")
ax.set_xlabel("State population (100k)")
return ax
def plotMissingness(missing_df, sort_values="BaselineGroup", max_values=0.7,
figsize=(12,18), row_colors = "StudyType", **kwargs):
"""
Plots heatmap of missingness, with values sorted by specified columns
"""
total = missing_df.shape[0]
curr_df = missing_df.copy(deep=True)
max_values = int(total*max_values)
min_col = None
# convert to missingness
for i in missing_df.columns:
curr_df[i] = [0 if x is None else 1 for x in curr_df[i]]
if sum(curr_df[i]) <= max_values:
min_col = i
min_value = sum(curr_df[i])
if sum(curr_df[i]) > max_values:
del curr_df[i]
curr_df = curr_df.sort_values(sort_values)
# plot
g = sns.clustermap(curr_df.T, figsize=figsize, dendrogram_ratio=0.1, cbar_pos=None, xticklabels=False, yticklabels=1)
g.ax_heatmap.set_yticklabels(g.ax_heatmap.get_ymajorticklabels(), fontsize = 14)
g.ax_row_dendrogram.set_visible(False)
g.ax_col_dendrogram.set_visible(False)
plt.yticks(ha='left',)
plt.tick_params(length=1)
return g
def plotTrialLocationsPerADI(state_df, rank_type="ADI_NATRANK", height=8):
"""
Plots number of locations per ADI
Params:
rank_type (str): "ADI_NATRANK" or "ADI_STATERNK," see University of Wisconsin ADI dataset for more info
"""
# get all clincal trial location values
state_df = state_df.explode(rank_type)
# group and plot values (national)
state_df = state_df.groupby(rank_type).count().reset_index()
state_df[rank_type] = state_df[rank_type].astype(int, errors="ignore")
lm = sns.lmplot(data = state_df, x = rank_type, y= "NCTId", height=height)
lm.set(ylim=(0, None))
ax = lm.axes[0,0]
ax.set_ylabel("Number of DTx trial locations")
print("# trial sites vs ADI: ", spearmanr(state_df["NCTId"], state_df[rank_type]))
return ax
def getLocationZipADI(state_df, states=["CA", "TX", "FL", "NY", "PA"]):
"""
Gets ADI for each clinical trial zip code
Can only do a few states because the ADI zip code mapping files are pretty big and can only be downloaded state by state
2019 ADI data pulled from here: https://www.neighborhoodatlas.medicine.wisc.edu/download
Last accessed: August 29, 2022
Params:
state_df (pd.DataFrame): clinical trial dataframe with LocationZip
states (list<str>): list of 2-letter codes for state of interest
Returns ADI values
"""
# load ADI values and map to zip
state_df = state_df.explode("LocationZip")
nat_dict = {}
state_dict = {}
color_dict = {}
for s in states:
curr_df = pd.read_csv("./dataInput/State_ADI_Data/%s_2019_ADI_9 Digit Zip Code_v3.1.txt"%s,
sep=",", index_col=0, dtype={'TYPE': 'str', "ADI_NATRANK":"str", 'ADI_STATERNK': 'str'})
#drop missing values
curr_df = curr_df[curr_df["ADI_NATRANK"]!="GQ"] #GQ = high group quarters population
curr_df = curr_df[curr_df["ADI_NATRANK"]!="PH"] #PH = low population/housing
curr_df = curr_df[curr_df["ADI_NATRANK"]!="GQ-PH"] #PH-GQ = both types of suppression criteria
curr_df = curr_df[curr_df["ADI_NATRANK"]!="PH-GQ"]
curr_df = curr_df[curr_df["ADI_NATRANK"]!="KVM"] #KVM = Key Missing Variables
# update values dicts
curr_df["zipclean"] = [z[1:6] for z in curr_df["ZIPID"]]
nat_dict.update(dict(zip(curr_df["zipclean"], curr_df["ADI_NATRANK"])))
state_dict.update(dict(zip(curr_df["zipclean"], curr_df["ADI_STATERNK"])))
# map ADI values to zip
state_df["ADI_NATRANK"] = state_df["LocationZip"].map(nat_dict)
state_df["ADI_STATERNK"] = state_df["LocationZip"].map(state_dict)
return state_df[["NCTId", "ADI_NATRANK", "ADI_STATERNK"]]
######################################################
### Helper functions
def addLabels(ax, labels, xValues, yValues, plotType='scatter', size=12, color='black', correction=0.2):
"""
Add labels to matplotlib plot
"""
for index in labels.index:
if plotType == 'scatter':
ax.text(labels[xValues][index]+np.random.uniform(-correction, correction), labels[yValues][index]
+np.random.uniform(-correction, correction),
labels['label'][index], horizontalalignment='left', size=size, color=color, weight=500)
else:
name = labels['label'][index]
ax.text(xValues.index(labels['type'][index]) + correction, labels[yValues][index] + correction,
name, horizontalalignment='left', size=size, color=color, weight=500)
return ax
def mannWhitneyLongDf(stats_df, values_col, labels_col, subset_col=None,
min_values=10, avg="median", correct=True, sig_only=True):
"""
Runs statistical test on long form data for two categories, returns median values
Params:
stats_df (pd.DataFrame): dataframe
values_col (str): column containing data to compare by mann whitney
labels_col (str): column containing groups to compare by mann whitney
subset_col (str, None): column contaning subsets to run statistical testing for
min_values (str): min values in each subset to run statistical testing for
avg (str): 'mean' or 'median'
correct (bool): bonferroni correction on number of subset groups
sig_only (bool): only return significant groups by mann whitney
(TODO) labelA, B (str): selection of groups within labels_col
Returns:
pd.DataFrame: pvalues for mann whitney results
"""
stats_dict = {}
# if subset_col not defined, use all values
if subset_col is None:
stats_df["subset_col"] = 1
subset_col = "subset_col"
# calculate average and mannwhitney between categories
for b in stats_df[subset_col].unique():
curr_df = stats_df[stats_df[subset_col] == b]
diff = 0
if len(curr_df) >= min_values:
groupA_label = curr_df[labels_col].unique()[0]
groupB_label = curr_df[labels_col].unique()[1]
groupA = curr_df[curr_df[labels_col] == groupA_label]
groupB = curr_df[curr_df[labels_col] == groupB_label]
if (len(groupB[values_col].dropna()) > 3) and (len(groupA[values_col].dropna()) > 3):
x = mannwhitneyu(groupA[values_col].dropna(), y=groupB[values_col].dropna(), )
groupA_avg = 0
groupB_avg = 0
if avg=="mean":
groupA_avg= groupA[values_col].mean()
groupB_avg= groupB[values_col].mean()
elif avg=="median":
groupA_avg= groupA[values_col].median()
groupB_avg= groupB[values_col].median()
stats_dict[b]=(x[1], groupA_avg, groupB_avg)
else:
print("Not enough values for stats on %s"%b)
pvals_df = pd.DataFrame.from_dict(stats_dict, orient="index")
pvals_df.columns = ["pval", groupA_label+" "+ str(avg), groupB_label+" "+ str(avg)]
if correct: # bonferroni
pvals_df["pval"] = pvals_df["pval"]*len(pvals_df)
if sig_only:
pvals_df = pvals_df[pvals_df["pval"]<0.05]
return pvals_df
### Sponsor & trial location cleaning
def collapseCollaboratorType(collab_class, multiple="group"):
"""
Get primary collabortor type for ClinicalTrials.gov data
Collapses duplicate values and groups values for multiple collaborator types
Params:
collab_class (list<list<str>>): list of collaborators for each clinical trial
multiple (str): how to deal with multiple values, "group", "common", or custom list order
Returns:
Primary collaborator type for each clinical trial
If multiple is "group," creates separate Multiple label
If multiple is "ignore," returns most common collaborator type
Can also specify custom order for groupings by setting mutiple to a list with
trials assigned to the first-occuring collaborator type prioritized in the list order.
"""
# if "common", get most common value
if multiple == "common": # get most common in each
return [max(set(c), key = c.count) if type(c)==list else "None" for c in collab_class]
# Otherwise, collapse collaborator and group/sort
collab_class = ["NONE" if c is None else "NONE" if type(c)==float else set(c) for c in collab_class]
if multiple == "group":
return ["NONE" if c=="NONE" else list(c)[0] if len(c) == 1 else "MULTIPLE" for c in collab_class]
elif type(multiple)==list:
for m in multiple:
collab_class = [c if type(c)==str
else m if m in c
else c for c in collab_class]
collab_class = [c if type(c)==str else "OTHER/UNKNOWN" for c in collab_class]
return collab_class
def getTrialLocations(zip_codes, country="us"):
"""
Get latitude and longitude values for all locations
Params:
zip_codes (list<int, list<int>>): zip code values from ClinicalTrials.gov LocationZip field
country (str): country to search for
Returns:
None, saves lat/long values to ./dataOutput/zip_lat_lng.csv
"""
# map values to lat/long using cached values & pgeocode
# https://pypi.org/project/pgeocode/
nomi = pgeocode.Nominatim(country)
# get all zip codes
all_zips = set(zip_codes.explode())
all_zips = [str(z) if type(z)!=str
else z[:5] if len(z)>5 and "-" in z
else z for z in all_zips]
# read cached values
zip_lat_lng = pd.read_csv("./dataOutput/zip_lat_lng.csv")
zip_lat_lng["postal_code"] = zip_lat_lng["postal_code"].astype(str)
zip_lat_lng = zip_lat_lng.dropna(subset=["latitude"])
# get non-cached values
cache_lat = dict(zip(zip_lat_lng["postal_code"], zip_lat_lng["latitude"]))
for z in all_zips:
if ((str(z) not in cache_lat.keys()) & (len(z)>0)):
z_lat_lng = nomi.query_postal_code(z)
zip_lat_lng = zip_lat_lng.append(z_lat_lng.transpose())
elif math.isnan(cache_lat[z]):
z_lat_lng = nomi.query_postal_code(z)
zip_lat_lng = zip_lat_lng.append(z_lat_lng.transpose())
zip_lat_lng = zip_lat_lng.dropna(subset=["latitude"])
zip_lat_lng = zip_lat_lng.drop_duplicates("postal_code")
zip_lat_lng = zip_lat_lng.set_index("postal_code", drop=True)
zip_lat_lng.to_csv("./dataOutput/zip_lat_lng.csv") # update with new values
def mapTrialLocations(loc_df, zip_file="./dataOutput/zip_lat_lng.csv"):
"""
Map latitude/longitude values for each clinical trial
Params:
loc_df (pd.DataFrame): contains "NCTId" and "LocationZip" values
zip_file (str, filepath): file containing pgeocode values for each zip code
Returns:
pd.DataFrame with lat/long and additional pgeocode values for each clinical trial
"""
zip_lat_lng = pd.read_csv(zip_file)
# map lat/long to studies
loc_df = loc_df.explode('LocationZip')
loc_df["LocationZipClean"] = [str(z) if type(z)!=str
else z[:5] if len(z)>5 and "-" in z
else z for z in loc_df["LocationZip"]]
loc_df = loc_df.merge(zip_lat_lng, left_on="LocationZipClean", right_on="postal_code", how="left")
# create lists
loc_df = loc_df.groupby('NCTId').agg(lambda x: list(x))
return loc_df
######################################################
### Condition data cleaning
def extractConditionMeshBranch(cond_list, **kwargs):
"""
Given list of clinical trial conditions, map each condition to a MeSH branch
Params:
cond_list (list, pd.Series): list of clinical trial condition values
//collapse (bool): if True, returns only most common MeSH branch for each value, otherwise returns full list
**kwargs: extractMeshEnts
Returns:
dict<str:list>: dictionary of condition:mapped MeSH branch
"""
all_ents = set(cond_list.sum())
ent_dict = {}
# get entities for all conditions
for a in all_ents:
ent_dict[a] = extractMeshEnts(a, **kwargs)
# map entities to cond_list
conditions = []
for c in cond_list:
curr_cond = []
for r in c:
if r in ent_dict.keys():
curr_cond.extend(ent_dict[r])
conditions.append(curr_cond)
return conditions
def extractMeshEnts(text, mesh_dict, _nlp, lemma=False, stopwords=None):
"""
Extract entities from text -> identify MeSH terms (using EntityLinkers) -> map to MeSH branches
Params:
text (str): string to extract MeSH Entities for
_nlp (scispacy model): Scispacy model with EntityLinker
mesh_dict (dict): dictionary of Mesh branch values
Returns:
list: list of mapped mesh branch values
"""
# Previously lowercase but turns out the Spacy EntityLinker is case sensitive
#text = text.lower().strip()
# preprocessing
if lemma ==True:
model = _nlp(text)
text = " ".join([word.lemma_ for word in model])
if stopwords is not None:
text = " ".join([t for t in text.split(" ") if t not in stopwords])
# map entities to Mesh terms
model = _nlp(text)
mesh_ids = [(m.text, m._.kb_ents[0][0]) if (len(m._.kb_ents)>0) else (m.text, "Unknown") for m in model.ents ]
# return MeSH branch for each value
mesh_branches = [(curr_ent[0], curr_ent[1], mesh_dict[curr_ent[1]]["branch_name"],
mesh_dict[curr_ent[1]]["main_branch"]) if curr_ent[1] in list(mesh_dict.keys())
else (curr_ent[0], curr_ent[1], "Unknown", "Unknown") for curr_ent in mesh_ids]
return list(mesh_branches)
def filterMeshBranches(mesh_ids, branches=["C", "F"], exclude=False):
"""
Limit Scispacy linked MeSH values to specific branches
Params:
mesh_ids (list): list of Mesh values mapped by Scispacy EntityLinker
branches (list<str>): branch values to limit to, default are disease branches "C" and "F"
"""
if exclude:
return [m for m in mesh_ids if len(m)>0 if all(b not in m[3] for b in branches)]
return [m for m in mesh_ids if len(m)>0 if any(b in m[3] for b in branches)]
def collapseMeshEnts(mesh_ids, prefer=["C", "F"]):
"""
Get most common MeSH branch from a list of Scispacy mapped Mesh values
Params:
mesh_ids (list): list of Mesh values mapped by Scispacy EntityLinker
prefer (list): Mesh branches to prioritize
"""
best = [m[2] for m in mesh_ids if any(p in m[3] for p in prefer)]
best = [m for m in best if "Unknown" not in m]
# take the most common preferred value
if len(best) > 2:
return max(set(best), key=best.count)
elif len(best) > 0:
return best[0]
# take the most common value
common = [m[2] for m in mesh_ids if len(m)>0]
common = [m for m in common if "Unknown" not in m]
if len(common) > 2:
return max(set(common), key=common.count)
elif len(common) > 0:
return common[0]
# return unknown only if all the values are unknown
return "Unknown"
######################################################
### Eligibility criteria cleaning
def extractInclusionExclusionCriteria(elig_df, **kwargs):
"""
Extract inclusion and exclusion criteria from EligibilityCriteria columns in clinicalTrials.gov data
Params:
plots_df (pd.DataFrame): contains ["NCTId", "EligibilityCriteria"]
nlp (spacy or stanza model): NER-enabled NLP model used to extract criteria
extractEnts (func): defines how NERs should be extracted, default uses scispacy EntityLinker module
**kwargs: passed to extractEnts
Returns:
pd.DataFrame containing parsed inclusion and exclusion criteria for each clinical trial
"""
### Extract inclusion and exclusion criteria
# extract inclusion criteria
elig_df = elig_df.set_index("NCTId", drop=True)
elig_df = elig_df['EligibilityCriteria'].str.split('Inclusion Criteria', expand=True)
elig_df = elig_df.stack()
elig_df = elig_df.reset_index()
elig_df = elig_df[elig_df[0] != ""]
# get exclusion criteria
elig_df[["InclusionCriteria", "ExclusionCriteria"]] = elig_df[0].str.split('Exclusion Criteria', expand=True, n=1)
elig_df = elig_df.sort_values("level_1")
elig_df = elig_df.replace(np.nan, "")
# collapse criteria by NCTId
inclusion_df = elig_df.groupby(['NCTId'])['InclusionCriteria'].apply(lambda x: ' '.join(x).strip()).reset_index()
exclusion_df = elig_df.groupby(['NCTId'])['ExclusionCriteria'].apply(lambda x: ' '.join(x).strip()).reset_index()
return inclusion_df.merge(exclusion_df, how="outer",left_on="NCTId", right_on="NCTId")
def extractIndividualEligibility(bert_df, criteria_col="ExclusionCriteria", stopwords=[]):
"""
Get each line from clincial trial eligibility criteria
Params:
bert_df (pd.DataFrame): clinical trials data with inclusion and exclusion criteria split
criteria_col (str): criteria column in bert_df
Returns:
"""
# explode criteria to individual lines
embed_col = criteria_col+"Embed"
bert_df[embed_col] = [n.split("\n") for n in bert_df[criteria_col]]
bert_df[embed_col] = [[k.strip() for k in c if len(k)>1] for c in bert_df[embed_col]]
bert_df = bert_df.explode([embed_col])
# clean text values
bert_df["%sClean"%embed_col] = cleanTextValues(bert_df[embed_col], regex='[^\sA-Za-z0-9 ><≤≥\.]+', stopwords=stopwords)
bert_df["%sClean"%embed_col] = [b.replace(" - ", "-") for b in bert_df["%sClean"%embed_col]]
bert_df = bert_df[bert_df["%sClean"%embed_col] != ""]
bert_df = bert_df.dropna(subset=["%sClean"%embed_col])
# lemma - the problem with this is it removes things like ios and is not great on the clinical text side
# tried NLTK stemming as well, but that removed a lot more suffixes that it wasn't supposed to
# bert_df["InclusionCriteriaEmbedClean"] = [" ".join([tok.lemma_ if len(tok.text)>3 else tok.text for tok in spacy_nlp(c)]) for c in bert_df["InclusionCriteriaEmbedClean"]]
return bert_df
#@st.experimental_singleton
def extractBERTopics(bert_df, _nlp=None, seed=None, nr_topics='auto', embeddings=None,
cache_embeddings=None, criteria_col = "ExclusionCriteriaEmbedClean",
class_col='conditionMeshMainBranch', **kwargs):
"""
Get topics using BERTopic run on spacy embeddings
https://arxiv.org/abs/2203.05794
Params:
bert_df (list<str>): clinical trials data with inclusion and exclusion criteria split
_nlp (None, spacy model): spacy model for embedding, ignored if custom embeddings are passed
stopwords (list): list of stopwords to remove
criteria_col (str): criteria column in criteria_df
cache_embeddings (str, pathlike): folder to save embeddings to for easier loading, should be in form "path/folder/"
class_col (str): column containing groups to plot top topics for
embeddings (np.ndarray): custom embeddings, supersedes nlp model
nr_topics (str, int): number of topics for BERTopic to select, use 'auto' for DBSCAN auto selection
"""
# set seed for reproducibility
if seed is not None: umap_model = umap.UMAP(random_state=seed, **kwargs)
# get docs and embeddings
docs = bert_df[criteria_col]
if embeddings is None:
embeddings = np.asarray([_nlp(c).vector for c in docs])
if cache_embeddings is not None:
embeddings.save(cache_embeddings+criteria_col+".npy")
# Train our topic model using our pre-trained sentence-transformers embeddings
model = BERTopic(nr_topics=nr_topics, umap_model=umap_model).fit(docs, embeddings)
bert_df["Topics"], bert_df["TopicProbs"] = model.transform(docs, embeddings, )
return model, bert_df
def updateBERTopicPerClassValues(model, bert_df, original_df, count_col="NCTId",
groupby="conditionMeshMainBranch", topic_values="Exclusion"):
"""
Update topics per class from BERTopic models with correct (not exploded) group values
Params:
model (BERTopic): BERTopic model fit on bert_df ["%sCriteriaEmbedClean"%topic_values] values
bert_df (pd.DataFrame): dataframe containing exploded Eligibility Criteria values
original_df (pd.DataFrame): dataframe containing non-exploded eligibility values
count_col (str): for counting purposes
groupby (str): column containing groups to count values for
topic_values (str): Inclusion or Exclusion
Returns:
pd.DataFrame: topics_per_class from model.topics_per_class updated with non-exploded values
"""
# get topics_per_class values (really only used to generate the dataframe columns)
topics_per_class = model.topics_per_class(bert_df["%sCriteriaEmbedClean"%topic_values],
topics=bert_df["Topics"], classes=bert_df[groupby])
# update with unique values (Calculate (# trials in each group with topic / total trials in each group)
# not (# elibility lines in each group mapped to topic / total elibility lines in each group))
topics_per_class_custom = original_df.explode("%sTopicNames"%topic_values).groupby(["%sTopicNames"%topic_values, groupby]).count()[[count_col]].reset_index()
topics_per_class_custom["Topic"] = [int(t.split("_")[0]) for t in topics_per_class_custom["%sTopicNames"%topic_values]]
# merge to topics_per_class
topics_per_class_custom = topics_per_class_custom.set_index(["Topic", groupby])
topics_per_class = topics_per_class.set_index(["Topic", "Class"])
topics_per_class["Frequency"] = topics_per_class.index.map(topics_per_class_custom[count_col])
# add totals
topics_per_class = topics_per_class.reset_index()
number_trials_per_mesh = dict(original_df.groupby([groupby]).count()[count_col])
topics_per_class["Total"] = topics_per_class["Class"].map(number_trials_per_mesh)
# add percentage
topics_per_class["Percent"] = topics_per_class["Frequency"] / topics_per_class["Total"]
return topics_per_class
### Outcomes cleaning
def cleanTimeValues(time_values):
"""
Clean ClinicalTrial.gov Outcome Timeframe values
Params:
time_values (pd.Series): clinical_df["PrimaryOutcomeTimeFrame"] values
Returns:
list: cleaned time_values
"""
# basic preprocessing
time_values = ["---".join(p) for p in time_values]
time_values = cleanTextValues(time_values, regex='[^\sA-Za-z0-9-, ><≤≥\.()]+')
# basic time values
for v in ["week", "day", "month", "year", "hour", "minute", "second"]:
time_values = [p.replace(v+"s", v) for p in time_values]
numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
for v in range(10):
time_values = [p.replace(numbers[v], str(v)) for p in time_values]
# clinical trial baseline values
trial_times = {"baseline":"day 0", "immediately prior":"day 0",
"before intervention":"day 0", "immediately before":"day 0"}
for v in trial_times.keys():
time_values = [p.replace(v, trial_times[v]) for p in time_values]
return [p.split("---") for p in time_values]
def extractTimeframeValues(time_values):
"""
Regex based time frame extraction for ClinicalTrial.gov data based on most common patterns
Recommended that you run cleanTimeValues first for clean timeframe text data
Params:
time_values (pd.Series): PrimaryOutcomeTimeFrame CT.gov values
Returns:
list: extracted values (standardized to months) for each CT entry
"""
# params
extracted_time = []
s = "day|month|year|hour|minute|week|second"
# extract all time values from outcome timeframe
for trial_time in time_values:
trial_values = []
#((?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|(nov|dec)(?:ember)?)\D?(\d{1,2}\D?)?\D?((19[7-9]\d|20\d{2})|\d{2}
#p = re.compile('(?P<timeframe>%s) \d+ to (?P<value>\d+) (?!%s)'%(s,s)) #"day XX to XX" or "XX and XX "
for curr_time in trial_time:
curr_values = []
#"X-month" or "X month"
p = re.compile('(?P<value>\d+)[\s\-]*(?P<timeframe>%s)'%s)
for c in p.findall(curr_time):
curr_values.extend([(c[1], c[0])])
#"(X) month"
p = re.compile('(?P<value>\(\d+\))[\s\-]*(?P<timeframe>%s)'%s)
for c in p.findall(curr_time):
curr_values.extend([(c[1], c[0].strip('\(\)'))])
#"X-X minutes"
p = re.compile('(?P<value1>\d+)\-+(?P<value2>\d+)[\s\-]*(?P<timeframe>%s)'%s)
for c in p.findall(curr_time):
curr_values.extend([(c[2], c[0])])
curr_values.extend([(c[2], c[1])])
#"year X"
p = re.compile('(?P<timeframe>%s)[\s\-](?P<value>\d+)'%s)
curr_values.extend(p.findall(curr_time))
#"day XX, XX, XX" or "day XX, XX, and XX" or "day XX, XX and XX"
p = re.compile('(?P<timeframe>%s)\s(?P<value>\d+(?:\,\s\d+)+,?\s?(?:and)?\s?\d*(?:%s)?)'%(s,s))
for list_time in p.findall(curr_time):
if not any(d in list_time[1] for d in "day|month|year|hour|minute|week|second".split("|")):
c = list_time[0]
list_time = list_time[1].replace(", and", ",")
list_time = list_time.replace("and", ",")
for l in list_time.split(","):
l = l.strip()
curr_values.extend([(c, l)])
trial_values.append(list(set(curr_values)))
extracted_time.append(trial_values)
return extracted_time
def convertTimeframe(value, start="day", end="month", round_dec=6):
"""
Converts values from one timeframe to another
Supported timeframes are "day", "month", "year", "minute", "second", "hour", "week"
Params:
value (int, float): value to convert
start (str): original timeframe
end (str): timeframe to convert to
round_dec (int, None): number of decimal spaces to round to
Return:
float: converted time value
"""
timeframes = {"day":1, "month":float(1/30), "year":float(1/365),
"minute":24*60, "second":24*60*60, "hour":24, "week":float(1/7)}
if round_dec is not None:
return round(value * (float(timeframes[end])/float(timeframes[start])), round_dec)
else:
return (value * (float(timeframes[end])/float(timeframes[start])))
def convertOutcomeTimeframeValues(time_values, convert_to="day"):
"""
Converts clinical trial outcome timeframe values
Timeframe values should be extracted using extractTimeframeValues
Params:
time_values (pd.Series): CT.gov time values to convert
convert_to (str): Supported formats are "day", "month", "year", "minute", "second", "hour", "week"
Returns:
list: converted time values
"""
converted = []
for times in time_values:
curr_times = []
for curr_t in times:
curr_t = [convertTimeframe(value=float(t[1]), start=t[0], end=convert_to) for t in curr_t]
curr_times.append(curr_t)
converted.append(curr_times)
return converted
def extractLongestTimeframePerOutcome(outcome_time):
"""
Extracts longest timeframe for *each outcome* in a clinical trial
Assumes standardized timeframes
Params:
outcome_time (list): CT.gov timeframe values for a single outcome
Returns:
float, float: longest time value for each clinical trial
"""
max_time = max(outcome_time)
return max_time, outcome_time.index(max_time)
def extractOverallLongestTimeframe(ct_timeframes):
"""
Extracts overall longest timeframe in a clinical trial
Assumes standardized timeframes
Params:
outcome_time (list): CT.gov timeframe values for a single outcome
Returns:
list, list: longest time value for each outcome and overall for clinical trial
"""
overall = []
per_outcome = []
for curr_timeframe in ct_timeframes:
# get max for each outcome
outcome_longest = [max(t) if len(t)>0 else np.nan for t in curr_timeframe]
per_outcome.append(outcome_longest)
# get overall longest
overall.append(max(outcome_longest))
return per_outcome, overall
######################################################
### General data cleaning - non NLP related cleaning
def convertToDatetime(dates):
"""
Format datetime to %Y-%m-%d from ClinicalTrials.gov
Params:
dates (list<str>): Datetime values
"""
dates = [s if type(s)!=str
else np.nan if s ==""
else datetime.strptime(s, '%Y-%m-%d') if "-" in s
else datetime.strptime(s, '%B %d, %Y') if "," in s
else datetime.strptime(formatDate(s), '%m/%d/%y') if "/" in s
else datetime.strptime(s, '%B %Y') for s in dates]
return [d if type(d)!=str else d.strftime('%Y-%m-%d') for d in dates]
def extractDictValuesFromList(dict_list, key):
"""
Given a list of dictionary values, extract out values for a specific key
Params:
dict_list (list<dict>): list of dictionaries to extract values from
key_value (str): dictionary key to extract values of
Returns:
list<values> from specified key
Example:
multi_list = [{"A":1, "B":4}, {"A":2, "B":5}, {"A":3, "B":6}]
extractDictValuesFromList(multi_list, key_value="A")
>> [1,2,3]
"""
return [c if type(c)==float else [x[key] if key in x.keys() else "NA" for x in list(c)] if c is not None else c for c in dict_list]
def formatDate(d, values='d/m/y', sep="/", ret_values='d/m/y'):
"""
Formats date values to be zero-padded and converted to expected format
Params:
d (str): datetime formatted string
values (str): format of d
sep (str): separator for d
ret_values (str): format to convert d into
Returns:
Zero-padded date string
"""
d = d.split(sep)
d = ["0"+curr_d if len(curr_d)==1 else curr_d for curr_d in d]
values_dict = dict(zip(values.split(sep), d))
for k in values_dict.keys():
ret_values = ret_values.replace(k, values_dict[k])
return ret_values
def cleanTextValues(text_field, regex='[^\sA-Za-z0-9- ><≤≥\.]+',
stopwords=[], concat=None):
"""
Basic text cleaning (stripping special characters, stopword removal, etc) from clinical trials field
Params:
elig_criteria (list, pd.Series): eligibility criteria from clinical trials data
regex (str): regex values to capture
stopwords (list): list of stopwords