-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathppmi_merger.py
More file actions
executable file
·2387 lines (2132 loc) · 127 KB
/
ppmi_merger.py
File metadata and controls
executable file
·2387 lines (2132 loc) · 127 KB
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
#!/usr/bin/env python
# coding: utf-8
__doc__ = """
ppmi_merger.py
A script to merge tables (CSV files) of interest from the
Parkinson's Progression Markers Initiative dataset, available from
the Laboratory Of NeuroImaging (LONI) Imaging Data Archive (IDA)
at the University of Southern California:
http://ida.loni.usc.edu
Script developed by Neil P Oxtoby as part of his NetMON research project.
Funded by a grant from the Biomarkers Across Neurodegenerative Disease
(BAND) program sponsored by
The Michael J Fox Foundation for Parkinson's Research,
Alzheimer's Association,
Alzheimer's Research UK, and
Weston Brain Institute.
Instructions:
0. Download all of the PPMI CSV files into a single folder:
`PPMI_csv_path` (define yourself below)
1. If including MRI results (e.g., FreeSurfer), then download the
LONI IDA CSV corresponding to your Image Collection.
Define in variable near start of this script
2. Search for sections labelled FIXME and replace/comment-out as appropriate
Set some variable names
"""
__author__ = "Neil P Oxtoby"
__copyright__ = "Copyright 2015-2020, Neil P Oxtoby"
__credits__ = ["Neil Oxtoby", "Coffee", "Biomarkers Across Neurodegenerative Diseases"]
__license__ = "TBC"
__version__ = "1.0"
__maintainer__ = "Neil Oxtoby"
__email__ = "neil@neiloxtoby.com"
__status__ = "Pretty much done"
__python_version__ = "3.5.2"
import os
#******** FIX ME **********
data_path = os.path.join('path','to','PPMI','Data')
# data_path = '/Users/noxtoby/Documents/Research/Personal/20200206-POPS_PD_Subtypes/data/PPMI'
data_path = '/Users/noxtoby/Documents/research-data/PPMI/downloads'
PPMI_csv_path = os.path.join(data_path,'2021-07-24')
PPMI_csv_path = os.path.join(PPMI_csv_path,'csv')
#****** END FIX ME ********
#* Your image collection, e.g., T1-anatomical
wd = data_path #os.path.join(data_path,'imaging')
# ppmi_t1_ida_csv = os.path.join(wd,"PPMI-NonGenetic-T1_bl_4_14_2020.csv")
ppmi_t1_ida_csv = os.path.join(wd,"ppmi-t1-dti-20210714_7_14_2021.csv")
#* Corresponding CSV from the IDA search => gives visit codes
ppmi_t1_ida_search_csv = ppmi_t1_ida_csv.replace('.csv','_idaSearch.csv') #os.path.join(wd,"PPMI-T1-Orig-3T_5_10_2019_idaSearch.csv")
#* Processed image data
# ppmi_t1_gif3_csv = ppmi_t1_ida_csv.replace('.csv','_gif3.csv') #os.path.join(data_path,"PPMI-T1-Anatomical_GIF3Vols.csv")
# ppmi_t1_freesurfer_csv = ppmi_t1_ida_csv.replace('.csv','_freesurfer6p0p0.csv') #os.path.join(data_path,"PPMI-T1-Anatomical_freesurfer6p0p0.csv")
ppmi_t1_gif3_csv = '/Users/noxtoby/Documents/research-data/PPMI/processed/ppmi_gif3_volumes_202107.csv'
ppmi_t1_freesurfer_csv = '/Users/noxtoby/Documents/research-data/PPMI/processed/ppmi_freesurfer7p1p1_aparcstats2table.csv'
ppmi_t1_biomarkers_csv = '/Users/noxtoby/Documents/research-data/PPMI/processed/ppmi_t1_biomarkers.csv'
include_t1_biomarkers = True
# ## Notes on PPMI
# - Page name (PAG_NAME) is table's key in the Data Dictionary (where PAG_NAME is present)
# - Be aware of variable coding
# - e.g., Gender can be
# - text (Female/Male), or
# - numeric (Female = 0,1; Male = 2). Note that 0 is female of child-bearing potential.
# - Diagnosis in lab data tables is sometimes APPRDX in clinical data tables
#
# Useful files:
# - **Data Dictionary**
# - `Data_Dictionary.csv`
# - CRF (Case Report Forms) - don't list the variable names
# - `PPMI-CRF-All-in-One-AM13.pdf`
# - **Code List**: DECODE is explanation of score (CODE)
# - `Code_List.csv`
# - PPMI derived variable definitions and score calculations
# - `Derived_Variable_Definitions_and_Score_Calculations.csv`
#
# Enrolled subjects: in both `SCREEN` and `RANDOM`, plus nonempty `ENROLLDT` in `RANDOM`
#
# APPRDX (numbers as of early 2018):
# - 1 PD (n=423) - recent diagnosis of PD (<2 yrs) who are not taking PD medications
# - 2 HC (n=196) - without PD, >30 yrs old, no first-degree blood relative with PD
# - 3 SWEDD (n=64) - PD subjects whose DaTscan does not show evidence of a dopaminergic deficit
# - 4 Prodromal (n=65) - at-risk cohort (without PD), diagnosed of hyposmia or REM sleep behavior disorder (RBD)
# - 5(6) Genetic Cohort PD (unaffected) - with (without) PD, having a genetic mutation in LRRK2, GBA, or SNCA
# - 7(8) Genetic Registry PD (unaffected) - with (without) PD, having either:
# - a genetic mutation in LRRK2, GBA, or SNCA or
# - a first-degree relative with a LRRK2, GBA, or SNCA mutation
#
# Note that `CLINDX`\[PRIMDIAG\] = (1) Idiopathic PD; (2) Alzheimer's disease; (3) Chromosome-17 frontotemporal dementia; (4) Corticobasal degeneration; (5) Dementia with Lewy bodies; (6) Dopa-responsive dystonia; (7) Essential tremor; (8) Hemiparkinson/hemiatrophy syndrome; (9) Juv. autosomal recessive parkinsonism; (10) Motor neuron disease with parkinsonism; (11) Multiple system atrophy; (12) Neuroleptic-induced parkinsonism; (13) Normal pressure hydrocephalus; (14) Progressive supranuclear palsy; (15) Psychogenic illness; (16) Vascular parkinsonism; (17) No PD nor other neurological disorder; (18) Spinocerebellar Ataxia (SCA); (19) Other neurological disorder(s)
#
# Visit dates are scattered. Here's some info on visits:
# - ST is a Symptomatic Therapy visit where therapy started. Sometimes this unscheduled visit replaces a planned visit (see notes in `SIGNATURE` Signature_Form.csv)
# - From `CODE_LIST`:
# - Uxx are unscheduled visits (UT1 include T1/T2 + DaTscan followup);
# - AVx are unscheduled telephone AV-133;
# - PW is premature withdrawal;
# - Txx telephone contact;
# - V01-04: Months 3/6/9/12;
# - V05-V12: six-monthly 18 to 60;
# - V13-V15: months 72,84,96;
# - V16-V20: annually months 108 to 156;
# - SCBL: screening/baseline combined;
# - RS1: rescreen;
# - Xxx: Transfer event
#
# See http://www.ppmi-info.org/wp-content/uploads/2015/12/PPMI-data-access-final.mp4 for presentation with example of extracting alpha-synuclein data. Also from this presentation: beware ST visits (where symptomatic therapy started), not present in DATSCAN SBR because it's "been accounted for" (whatever that means).
# ### === Dependencies, Functions ===
import sys,glob
from datetime import datetime
import pandas as pd
import numpy as np
from scipy import stats
#* Only if you want to plot anything
from matplotlib import pyplot as plt
# get_ipython().run_line_magic('matplotlib', 'inline')
plt.style.use('ggplot')
from matplotlib import rcParams # For changing default figure size
#*** Custom Functions
## Remove duplicates by taking the most recent RUNDATE
def remove_duplicates(df, ID='PATNO', keyColumns=['PATNO', 'EVENT_ID', 'TYPE', 'TESTNAME'], dateColumn='RUNDATE'):
"""
Idea: Sort database by entries expected to be identical for repeated tests,
keeping only the latest result
"""
# Sort the data frame
df_sorted = df.sort_values(keyColumns + [dateColumn], ascending = False)
df_len = len(df_sorted)
# Key columns for identifying retests:
df_sorted_keyCols = df_sorted[keyColumns].copy()
# Step through the sorted list, line by line.
# If the columns match up, only keep the newest (latest) result.
# rowsRetained stores the rows to be kept (in the sorted data frame).
rows_retained = []
rows_removed = []
last_entry = []
for row in range(0, df_len):
entry = df_sorted_keyCols.iloc[row].tolist()
if (entry != last_entry):
rows_retained.append(row)
else:
rows_removed.append(row)
last_entry = entry
# Eliminate the duplicate/obsolete rows
df_sorted = df_sorted.take(rows_retained, axis = 0)
# Sort the database again, in a more user-friendly ascending format, and return:
return df_sorted.sort_values(keyColumns + [dateColumn], ascending = True), rows_removed, rows_retained
#***
#* Convert super-tall (e.g., biomarkers stacked in same column)
#* to semi-wide (biomarkers split, but still multiple rows per subject) format
def unstack_df(df_tall,idCols_Subject_Visit,tallCol_Name_Value):
id_ = idCols_Subject_Visit[0]
vis_ = idCols_Subject_Visit[1]
tall_name = tallCol_Name_Value[0]
tall_value = tallCol_Name_Value[1]
v = df_tall[id_].values
if type(v[0])==str:
id_is_str = True
else:
id_is_str = False
df_tall_pivot = df_tall.copy()
df_tall_pivot.loc[:,'ID'] = df_tall_pivot[id_].map(str) + '_' + df_tall_pivot[vis_].map(str)
df_tall_pivot = df_tall_pivot.pivot_table(index='ID',columns=tall_name,values=tall_value,aggfunc='first')
df_tall_pivot = pd.DataFrame(df_tall_pivot.to_records())
if id_is_str:
df_tall_pivot.loc[:,id_] = df_tall_pivot['ID'].map(lambda x: x.split('_')[0])
else:
df_tall_pivot.loc[:,id_] = df_tall_pivot['ID'].map(lambda x: int(x.split('_')[0]))
df_tall_pivot.loc[:,vis_] = df_tall_pivot['ID'].map(lambda x: x.split('_')[1])
df_tall_pivot.drop('ID',axis=1,inplace=True)
# Move id and visit to be the first columns
cols = df_tall_pivot.columns.isin([id_,vis_])
df_tall_pivot = df_tall_pivot[df_tall_pivot.columns[cols].append(df_tall_pivot.columns[~cols])]
return df_tall_pivot
#***
#*** Courtesy of Markus Konrad:
# https://mkonrad.net/2016/04/16/cross-join--cartesian-product-between-pandas-dataframes.html
def df_crossjoin(df1, df2, **kwargs):
"""
Make a cross join (cartesian product) between two dataframes by using a constant temporary key.
Also sets a MultiIndex which is the cartesian product of the indices of the input dataframes.
See: https://github.com/pydata/pandas/issues/5401
:param df1 dataframe 1
:param df1 dataframe 2
:param kwargs keyword arguments that will be passed to pd.merge()
:return cross join of df1 and df2
"""
df1.loc[:,'_tmpkey'] = 1
df2.loc[:,'_tmpkey'] = 1
res = pd.merge(df1, df2, on='_tmpkey', **kwargs).drop('_tmpkey', axis=1)
res.index = pd.MultiIndex.from_product((df1.index, df2.index))
df1.drop('_tmpkey', axis=1, inplace=True)
df2.drop('_tmpkey', axis=1, inplace=True)
return res
#***
daysInAYear = 365.25
# ## === Manually load PPMI tables (CSV files) into pandas DataFrames ===
# Read tables using pandas.read_csv( )
# - Drop uninteresting columns (`update_stamp`, `REC_ID`, etc.)
# - Ensure `PATNO` is a string
runDate = datetime.today().isoformat().replace('-','')[0:8]
#* Output files
PPMIMERGE_csv = os.path.normpath(os.path.join(PPMI_csv_path,'PPMIMERGE_%s.csv' % str(runDate)))
BIOLAB_csv = os.path.normpath(os.path.join(data_path,'Current_Biospecimen_Analysis_Results_with_Elapsed_Times.csv'))
#* Identify all the CSV files
PPMI_tables = glob.glob(os.path.join(PPMI_csv_path,'*.csv'))
#* Load data tables
PPMI_df = []
PPMI_df_names = []
# Naming scheme: CSV filename with certain characters removed
for k in range(0,len(PPMI_tables)):
PPMI_df.append(pd.read_csv(PPMI_tables[k],low_memory=False))
nom = os.path.basename(PPMI_tables[k])
nom = nom.replace('.csv','').replace('-','_').replace('+','_').replace(',','') # remove hyphen, plus, comma
if any('PATNO' == PPMI_df[k].columns):
PPMI_df[k]['PATNO'] = PPMI_df[k]['PATNO'].astype(str)
if any('SUBJECT_NUMBER' == PPMI_df[k].columns):
PPMI_df[k]['PATNO'] = PPMI_df[k]['SUBJECT_NUMBER'].astype(str)
PPMI_df_names.append(nom)
#print('{0}\n - {1}'.format(PPMI_df_names[-1],PPMI_df[k].columns.values))
#* For decoding visit codes
Keys = ['PATNO','EVENT_ID']
Code_List_n = np.where([1 if n=="Code_List" else 0 for n in PPMI_df_names])[0][0]
df_Code_List = PPMI_df[Code_List_n]
EVENT_ID_CODE = df_Code_List['CODE'][df_Code_List.CDL_NAME=='EVENT_ID']
EVENT_ID_DECODE = df_Code_List['DECODE'][df_Code_List.CDL_NAME=='EVENT_ID']
EVENT_ID_CODEs, I1 = np.unique(EVENT_ID_CODE, return_index=True)
EVENT_ID_DECODEs = EVENT_ID_DECODE.iloc[I1].values
df_EVENT_ID = pd.DataFrame(data={'CODE':EVENT_ID_CODEs, 'DECODE':EVENT_ID_DECODEs})
# ***
# ## Data preparation: tidying, renaming columns for consistency, adding dates, etc.
#
# Keys for joining most tables: `['PATNO','EVENT_ID']`
#
# **Beware**: joins will fail if keys are of different types (str and int, for example).
# ### Tasks
# 1. Identify enrolled subjects - add demographics and some covariates:
# - `RANDOM` + `SCREEN`: gender, ethnicity (`HISPLAT`), race (Amer/Asian/Afro/Pacific/White/NotSpecified), enrolment diagnosis
# - `FAMHXPD`: family history of PD (converted to numbers of 1st-/2nd-degree relatives with PD)
# - `MUTRSLT`: genetic category (GENECAT = 1,2,3: LRRK2,GBA,SNCA)
# - `MUTTEST`: duration of PD at enrollment (PDDURYRS)
# - `SOCIOECO`: dominant hand (`HANDED` = 1,2,3: I guess R,L,ambidextrous)
# 2. Tables that need dates (`INFODT`):
# 1. `BIOANALYS` - get from `LAB` (`Laboratory_Procedures_with_Elapsed_Times.csv`)
# 1. Also needs some columns renaming: `CLINICAL_EVENT` to `EVENT_ID`
# 2. Also needs to be pivoted: `TESTNAME` entries become columns, populated by `TESTVALUE`
# 3. All tables:
# - Calculate years since baseline: convert INFODT fields to DATENUM
# - Rename date column: add suffix (`PAG_NAME` if it exists)
# - Harmonise variable encoding and naming, e.g., APPRDX in clinical tables is DIAGNOSIS in lab tables
# 4. Create PPMIMERGE blank table from Subjects`x`Visits
# 5. Merge DataFrames of interest using pandas.DataFrame.merge( )
# - CSF: Alpha-synuclein, Hemoglobin, pTau, tTau, ABeta 1-42, Abeta 42; ApoE genotype
# - `BIOANALYS` (my pivot-table version)
# - Demographics: Age at clinical visit, Years_bl, Medication (`PDMEDUSE`)
# - Diagnostics - `CLINDX`\[INFODT, PRIMDIAG, DCRTREM, DCRIGID, DCBRADY\] or `PRIMDXPD`\[PRIMDIAG\]; potentially add other DX and features (DXFxxxxx and/or `PDFEAT`)
# - Vital signs - `VITAL`\[WGTKG, HTCM, TEMPC, SYSSUP, DIASUP, HRSUP, SYSSTND, DIASTND, HRSTND\]: weight, height, temp, blood pressure, heart rate
# - Neurological
# - `PECN` (Cranial nerves) \[CN1RSP,CN2RSP,CN346RSP,CN5RSP,CN7RSP,CN8RSP,CN910RSP,CN11RSP,CN12RSP\]
# - `PENEURO` (General neurological: muscle strength, etc.) \[MSRARSP, MSRACM, MSLARSP, MSLACM, MSRLRSP, MSRLCM, MSLLRSP, MSLLCM, COFNRRSP, COFNRCM, COFNLRSP, COFNLCM, COHSRRSP, COHSRCM, COHSLRSP, COHSLCM, SENRARSP, SENRACM, SENLARSP, SENLACM, SENRLRSP, SENRLCM, SENLLRSP, SENLLCM, RFLRARSP, RFLRACM, RFLLARSP, RFLLACM, RFLRLRSP, RFLRLCM, RFLLLRSP, RFLLLCM, PLRRRSP, PLRRCM, PLRLRSP, PLRLCM\]
# - Neuropsych
# - `MOCA`\[MCATOT\]
# - `SFT`\[DVS_SFTANIM, DVT_SFTANIM, VLTANIM, VLTVEG, VLTFRUIT\] (total 3: sum 1-3)
# - `LNSPD`\[LNS_TOTRAW, DVS_LNS\] (total 21: sum 1-7.a+b+c)
# - `HVLT`\[DVT_TOTAL_RECALL, DVT_DELAYED_RECALL, DVT_RETENTION, DVT_RECOG_DISC_INDEX\] (can split: immediate recall; delayed recall; delayed recognition)
# - `LINEORNT`\[JLO_TOTRAW, JLO_TOTCALC, AGE_ASSESS_JLO, DVS_JLO_MSSA, DVS_JLO_MSSAE\] (odd numbered questions at first visit; even at second)
# - `SDM`\[SDMTOTAL, DVSD_SDM, DVT_SDM\]
# - Neurobehaviour:
# - `GDSSHORT`\[GDSSATIS, GDSDROPD, GDSEMPTY, GDSBORED, GDSGSPIR, GDSAFRAD, GDSHAPPY, GDSHLPLS, GDSHOME, GDSMEMRY, GDSALIVE, GDSWRTLS, GDSENRGY, GDSHOPLS, GDSBETER\] (depression: 0-4 normal, 5-7 mild, 8-11 moderate, 12-15 severe)
# - Convert to single depression score: sum(GDSSATIS, GDSGSPIR, GDSHAPPY, GDSALIVE, GDSENRGY == 0) + sum(GDSDROPD, GDSEMPTY, GDSBORED, GDSAFRAD, GDSHLPLS, GDSHOME, GDSMEMRY, GDSWRTLS, GDSHOPLS, GDSBETER == 1)
# - Test is only considered valid if 12 or more answers are provided
# - `STAI`\[STAIAD[1-40]\] (anxiety)
# - Convert to a single score somehow (not sure how, as it's not in `Data_Acquisition_and_Usage_20140609.pdf`)
# - `QUIPCS`\[TMGAMBLE, CNTRLGMB, TMSEX, CNTRLSEX, TMBUY, CNTRLBUY, TMEAT, CNTRLEAT, TMTORACT, TMTMTACT, TMTRWD, TMDISMED, CNTRLDSM\] (impulsive-compulsive disorders)
# - Total score: sum of all
# - `EPWORTH`\[ESS[1-8]\] Total is sum of 8 Qs, each worth 0-3 (sleepiness scale: biomarker cutpoint is normal <=9, sleepy >=10)
# - (Not sure how to total the score, so I've omitted this. Perhaps convert to binary DX of RBD.) `REMSLEEP`\[\] (sleep behaviour disorder questionnaire)
# - Total: sum(1-9) + ?
# - Maybe also add `REMBHVDS`\[REMONSDT, REMONEST, RBDDXDT, RBDDXEST\] (date of RBD onset, date estimated?, date of RBD DX, date estimated?)
# - Motor-symptoms: new UPDRS
# - `NUPDRS1`[NP1COG, NP1HALL, NP1DPRS, NP1ANXS, NP1APAT, NP1DDS] - sum total
# - `NUPDRS1p`[NP1SLPN, NP1SLPD, NP1PAIN, NP1URIN, NP1CNST, NP1LTHD, NP1FATG] - sum total
# - `NUPDRS2p`[NP2SPCH, NP2SALV, NP2SWAL, NP2EAT, NP2DRES, NP2HYGN, NP2HWRT, NP2HOBB, NP2TURN, NP2TRMR, NP2RISE, NP2WALK, NP2FREZ] - sum total
# - (prior to medication) `NUPDRS3`[NP3SPCH, NP3FACXP, NP3RIGN, NP3RIGRU, NP3RIGLU, PN3RIGRL, NP3RIGLL, NP3FTAPR, NP3FTAPL, NP3HMOVR, NP3HMOVL, NP3PRSPR, NP3PRSPL, NP3TTAPR, NP3TTAPL, NP3LGAGR, NP3LGAGL, NP3RISNG, NP3GAIT, NP3FRZGT, NP3PSTBL, NP3POSTR, NP3BRADY, NP3PTRMR, NP3PTRML, NP3KTRMR, NP3KTRML, NP3RTARU, NP3RTALU, NP3RTARL, NP3RTALL, NP3RTALJ, NP3RTCON] - sum total; Also `NUPDRS3`[NHY] is Hoehn and Yahr stage
# - (post-medication) `PAG_NAME` = `NUPDRS3A` => additionally ANNUAL_TIME_BTW_DOSE_NUPDRS,PD_MED_USE
# - `NUPDRS4`[NP4WDYSK, NP4DYSKI, NP4OFF, NP4FLCTI, NP4FLCTX, NP4DYSTN] - sum total
# - Non-motor:
# - Olfactory `UPSIT`[UPSITBK[1-4]] - sum total
# - Autonomic `SCOPAAUT`[SCAUx]
# - Six subscales (23A and 26 do not contribute to the score)
# - Gastrointestinal: sum 1-7
# - Urinary: sum 8-13 (beware coding 9 for "uses a catheter", which scores as 3 "often")
# - Cardiovascular: sum 14-16
# - Thermoregulatory: sum 17,18,20-21
# - Pupillomotor: 19
# - Sexual: 22+23 (male) or 24+25 (female) (beware 9 coding for not-applicable - scores 0)
# - Total out of 23
# - Imaging:
# - `DATSCAN`[CAUDATE_R, CAUDATE_L, PUTAMEN_R, PUTAMEN_L] (occipital:striatal binding ratio, SBR in L&R caudate and putamen)
# - AV133 (`AVIMAG`, `ind_av133_sbr`[RCAUD-S, RPUTANT-S, RPUTPOST-S, LCAUD-S, LPUTANT-S, LPUTPOST-S], `ind_av133_metadata`[scan_quality_rating_pet, 12_scan_quality_rating_mr])
# - `MRI` volumes/atrophy
# - `DTIROI` - FA and Eigenvalues (I think): see [PPMI_DTI_ROI_Methods_20160915.pdf](/Users/noxtoby/Documents/Research/UCLPOND/Projects/201803-PPMI-EBM/Data/CSV/PPMI_DTI_ROI_Methods_20160915.pdf), the six ROIs are manually-drawn ones in the L&R SN, and two reference regions in the L&R cerebral peduncle
# ### Data Preparation step 1: Identify enrolled subjects and demographics
#*** Enrolled subjects: in both SCREEN and RANDOM, plus non-null ENROLLDT in RANDOM table ***
df_RANDOM = PPMI_df[np.where([1 if n=="Randomization_table" else 0 for n in PPMI_df_names])[0][0]].copy()
df_RANDOM_enrolled = df_RANDOM.loc[df_RANDOM.ENROLLDT.notnull(),:]
df_SCREEN = PPMI_df[np.where([1 if n=="Screening___Demographics" else 0 for n in PPMI_df_names])[0][0]].copy()
# Inner join: RANDOM and SCREEN. Get APPRDX and race/ethnicity from SCREEN
df_RANDOM_enrolled = pd.merge(df_RANDOM_enrolled[['PATNO','BIRTHDT','GENDER','ENROLLDT','CONSNTDT']],
df_SCREEN[['PATNO','APPRDX','CURRENT_APPRDX',
'HISPLAT','RAINDALS','RAASIAN','RABLACK','RAHAWOPI','RAWHITE','RANOS']].sort_values('PATNO',axis=0),
on='PATNO',suffixes=['_Random','_Screen'])
df_RANDOM_enrolled.rename(index=str, columns={'APPRDX':'APPRDX_SCREEN'})
#* HANDED,EDUCYRS from SOCIOECO
df_SOCIOECO = PPMI_df[np.where([1 if n=="Socio_Economics" else 0 for n in PPMI_df_names])[0][0]].copy()
df_RANDOM_enrolled = pd.merge(df_RANDOM_enrolled,
df_SOCIOECO[['PATNO','HANDED','EDUCYRS']].sort_values('PATNO',axis=0),
on='PATNO',suffixes=['_Random','_SocioEco'])
PATNO = df_RANDOM_enrolled.PATNO
# df_RANDOM_enrolled
# ### Data Preparation step 2: Tables that need dates
# #### 2.1 `BIOANALYS`
# 1. Change `CLINICAL_EVENT` to `EVENT_ID`
# 2. Add `INFODT` from `Laboratory_Procedures_with_Elapsed_Times`
# 3. Cleanup: prefer reprocessed Bioanalyses (remove old ones)
# - (PPMI_CSF_baseline_analysis_Assay_variability_April_2014.pdf says to keep 2013 rather than 2011, but there are others that get reprocessed)
# 4. Convert `TESTVALUE` to numeric using a map: replaces text entries such as 'below detection limit' with the detection limit
# 5. Convert long format to semi-wide: one column per `TESTNAME`, populated by `TESTVALUE`
Bio_n = np.where([1 if n=="Current_Biospecimen_Analysis_Results" else 0 for n in PPMI_df_names])[0][0]
df_BIO = PPMI_df[Bio_n].copy()
df_BIO['PI_INSTITUTION'] = df_BIO['PI_INSTITUTION'].str.replace("’","") #* Annoying weirdly-encoded apostrophe
df_BIO.PATNO = df_BIO['PATNO'].astype(str)
#*** 1. Translate CLINICAL_EVENT to EVENT_ID: FIXME: May need to add future visit codes as the study continues
event_list = ['SC', 'BL', 'SCBL',
'V01', 'V02', 'V03', 'V04', 'V05', 'V06', 'V07', 'V08', 'V09', 'V10',
'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20',
'PW', 'ST',
'U01', 'U02', 'U03', 'U04', 'U05', 'U06', 'UT1', 'UT2', 'UT3', 'UT4']
#** EVENT_ID descriptions
event_desc = []
for k in range(len(event_list)):
event_desc.append(df_EVENT_ID.DECODE[df_EVENT_ID.CODE == event_list[k]].values[0])
event_dict = dict(zip(event_list, event_desc))
#** Discard all rows with non-recognized keys
df_BIO_ = df_BIO[(df_BIO['CLINICAL_EVENT'].isin(event_list))]
#** Rename the column
df_BIO_ = df_BIO_.rename(columns = {'CLINICAL_EVENT' : 'EVENT_ID'})
#** Translate (if they have a translation)
df_BIO_['EVENT_DESC'] = df_BIO_['EVENT_ID'].apply(lambda x : event_dict[x])
#*** 2. Add INFODT from Laboratory_Procedures_with_Elapsed_Times
# (seems not required for EVENT_ID =='SC' because these were the
# DNA test results; these dates do exist - in the VITAL table).
Lab_n = np.where([1 if n=="Laboratory_Procedures_with_Elapsed_Times" else 0 for n in PPMI_df_names])[0][0]
df_LAB = PPMI_df[Lab_n].copy()
df_LAB = df_LAB.drop(['REC_ID','F_STATUS','PAG_NAME','ORIG_ENTRY','LAST_UPDATE','QUERY','SITE_APRV'],axis=1)
#* Merge Bio to Lab
df_BIOLAB = df_BIO_.merge(df_LAB[Keys+['INFODT','PDMEDYN']],how='left',on=Keys,suffixes=('_BIO','_LAB'))
#*** 3. Remove earlier Bioanalyses that were reprocessed, and also remove rows: DNA, RNA
df_BIOLAB = df_BIOLAB.drop(['PI_INSTITUTION','PI_NAME','PROJECTID','update_stamp'],axis=1) # remove some columns for convenience
df_BIOLAB.loc[:,'TYPE'] = df_BIOLAB['TYPE'].str.replace('Cerebrospinal Fluid','CSF') # Recode to CSF
#* Remove DNA, RNA rows (except APOE genotype)
remove_DNA_bool = False
if remove_DNA_bool:
df_BIOLAB_ = df_BIOLAB.loc[(~df_BIOLAB.TYPE.isin(['DNA','RNA'])) | (df_BIOLAB.TESTNAME.map(lambda x: x.lower()) == 'apoe genotype') ,'TESTNAME'].unique()
else:
df_BIOLAB_ = df_BIOLAB.copy()
#* Genetics mapper: see Table 1 in PPMI_Methods_PD_Variants_Table.pdf
rsid = [
'rs114138760','rs421016','rs76763715','rs75548401','rs2230288','rs104886460','rs387906315',
'rs823118','rs4653767','rs10797576','rs34043159','rs6430538','rs353116','rs1955337','rs4073221',
'rs12497850','rs143918452','rs1803274','rs12637471','rs34884217','rs34311866','rs11724635',
'rs6812193','rs356181','rs3910105','rs104893877','rs104893875','rs104893878','rs4444903','rs121434567','rs78738012',
'rs2694528','rs9468199','rs8192591','rs115462410','rs199347','rs1293298','rs591323','rs2280104','rs13294100',
'rs10906923','rs118117788','rs329648','rs76904798','rs33939927','rs33939927','rs33949390','rs35801418',
'rs34637584','rs34778348','rs11060180','rs11158026','rs8005172','rs2414739','rs11343','rs14235','rs4784227',
'rs11868035','rs17649553','rs12456492','rs55785911','rs737866','rs174674','rs5993883','rs740603','rs165656',
'rs6269','rs4633','rs2239393','rs4818','rs4680','rs165599'
]
chr = [
'chr1','chr1','chr1','chr1','chr1','chr1','chr1',
'chr1','chr1','chr1','chr2','chr2','chr2','chr2','chr3',
'chr3','chr3','chr3','chr3','chr4','chr4','chr4',
'chr4','chr4','chr4','chr4','chr4','chr4','chr4','chr4','chr4',
'chr5','chr6','chr6','chr6','chr7','chr8','chr8','chr8','chr9',
'chr10','chr10','chr11','chr12','chr12','chr12','chr12','chr12',
'chr12','chr12','chr12','chr14','chr14','chr15','chr16','chr16','chr16',
'chr17','chr17','chr18','chr20','chr22','chr22','chr22','chr22','chr22',
'chr22','chr22','chr22','chr22','chr22','chr22'
]
bp_hg38 = [
'154925709','155235252','155235843','155236246','155236376','155240629','155240660',
'205754444','226728377','232528865','101796654','134782397','165277122','168272635','18235996',
'48711556','52782824','165773492','183044649','950422','958159','15735478',
'76277833','89704988','89761420','89828149','89828170','89835580','109912954','110004540','113439216',
'60978096','27713436','32218019','32698883','23254127','11854934','16839582','22668467','17579692',
'15527599','119950976','133895472','40220632','40310434','40310434','40320043','40321114',
'40340400','40363526','122819039','54882151','88006268','61701935','19268142','31110472','52565276',
'17811787','45917282','43093415','3172857','19942586','19946502','19950115','19957654','19961340',
'19962429','19962712','19962905','19963684','19963748','19969258'
]
variant_or_gene = [
'PMVK','GBA_L444P','GBA_N370S','GBA_T408M','GBA_E365K','GBA_IVS2+1','GBA_84GG',
'NUCKS1','ITPKB','SIPA1L2','IL1R2/MAP4K4','ACMSD/TMEM163','SCN3A/SCN2A','STK39','SATB1',
'NCKIPSD/CDC71/IP6K2','ITIH1','BuChE','MCCC1','TMEM175','TMEM175','BST1',
'FAM47E/STBD1','SNCA','SNCA','SNCA_A53T','SNCA_E46K','SNCA_A30P','EGF','EGF','ANK2/CAMK2D',
'ELOVL7/NDUFAF2','ZNF184','NOTCH4_G1739S','HLA_DBQ1','GPNMP','CTSB','MICU3/FGF20','BIN3','SH3GL2',
'FAM171A1/ITGA8','MIR4682','MIR4697','LRRK2','LRRK2_R1441G','LRRK2_R1441C','LRRK2_R1628P/H','LRRK2_Y1699C',
'LRRK2_G2019S','LRRK2_G2385R','OGFOD2/CCDC62','GCH1','GALC/GPR65','VPS13C','COQ7/SYT17','ZNF646/KAT8/BCKDK','TOX3/CASC16',
'SREBF1','MAPT','SYT4/RIT2','DDRGK1','COMT','COMT','COMT','COMT','COMT',
'COMT','COMT','COMT','COMT','COMT','COMT'
]
simplified_gene = [
'PMVK','GBA','GBA','GBA','GBA','GBA','GBA',
'NUCKS1','ITPKB','SIPA1L2','IL1R2/MAP4K4','ACMSD/TMEM163','SCN3A/SCN2A','STK39','SATB1',
'NCKIPSD/CDC71/IP6K2','ITIH1','BuChE','MCCC1','TMEM175','TMEM175','BST1',
'FAM47E/STBD1','SNCA','SNCA','SNCA','SNCA','SNCA','EGF','EGF','ANK2/CAMK2D',
'ELOVL7/NDUFAF2','ZNF184','NOTCH4_G1739S','HLA_DBQ1','GPNMP','CTSB','MICU3/FGF20','BIN3','SH3GL2',
'FAM171A1/ITGA8','MIR4682','MIR4697','LRRK2','LRRK2','LRRK2','LRRK2','LRRK2',
'LRRK2','LRRK2','OGFOD2/CCDC62','GCH1','GALC/GPR65','VPS13C','COQ7/SYT17','ZNF646/KAT8/BCKDK','TOX3/CASC16',
'SREBF1','MAPT','SYT4/RIT2','DDRGK1','COMT','COMT','COMT','COMT','COMT',
'COMT','COMT','COMT','COMT','COMT','COMT'
]
df_PPMI_Methods_PD_Variants_Table = pd.DataFrame({'rsid':rsid,'chr':chr,'bp_hg38':bp_hg38,'Variant Name/Implicated Gene(s)':variant_or_gene,'Simplified Gene':simplified_gene})
df_PPMI_Methods_PD_Variants_Table.to_csv(os.path.join(data_path,'PPMI_Methods_PD_Variants_Table.csv'))
ppmi_genetics_mapper = dict(zip(rsid,simplified_gene))
keyColumns = Keys + ['TYPE','TESTNAME']
dateColumn = 'INFODT' #'RUNDATE'
# df_BIOLAB_2, rowsRemoved, rowsRetained = remove_duplicates( df_BIOLAB_, ID='PATNO', keyColumns=keyColumns, dateColumn=dateColumn)
df_BIOLAB_sorted = df_BIOLAB_.sort_values(by=keyColumns+[dateColumn],ascending=True)
df_BIOLAB_unique = df_BIOLAB_sorted.drop_duplicates(subset=keyColumns,keep='last').copy()
dna_rna_rowz = (df_BIOLAB_unique.TYPE.isin(['DNA','RNA'])).values
#*** 4. Convert non-comprehensive subset of TESTVALUE to numeric (removes 'below detection limit', etc.)
TESTVALUE_dict = {
# CSF Hemoglobin
'below detection limit':20, 'below':20, '>20':20, '<20':20, 'above':12500,
'>12500 ng/ml':12500,'>12500ng/ml':12500,
# pTau
'<8':8,
# Abeta 1-42
'<200':200, '>1700':1700,
# tTau
'<80':80,
# IL-6
'<1.5': 1.5,
# Dopamine
'<LOD':0,
# 3,4-Dihydroxyphenylalanine (DOPA)
'>ULOQ': '', # 19.3
# 3-Methoxytyrosine
'>ULOQ': '', # 300
# NfL
'>1997': 1997,
# others
'insufficientvolume': '',
#'5907 +/- 39': 5907, '3595+/-50': 3595,'2160 +/- 50': 2160, '3024 +/-10':3024,
# ApoE Genotype
'e2/e2':'22', 'e2/e4':'24', 'e3/e2':'32', 'e3/e3':'33', 'e4/e3':'43', 'e4/e4':'44'}
df_BIOLAB_unique.loc[~dna_rna_rowz,["TESTVALUE"]].replace(to_replace=TESTVALUE_dict,inplace=True)
#* Convert to float, unless it's DNA/RNA
numerics = pd.to_numeric(df_BIOLAB_unique["TESTVALUE"],errors='coerce')
for k in df_BIOLAB_unique.index[~dna_rna_rowz]:
df_BIOLAB_unique.at[k,"TESTVALUE"] = numerics.at[k]
# df_BIOLAB_unique["TESTVALUE"][~dna_rna_rowz].astype(str).map(lambda x: x.replace(' ','').split('+/-')[0].replace('<','').replace('>','').replace('insufficientvolume',''))
#* New visit key for unstacking: EVENT_ID + INFODT + on/off meds
s = '*'
df_BIOLAB_unique['key'] = df_BIOLAB_unique['EVENT_ID'].map(str) +s+ df_BIOLAB_unique['INFODT'].map(str) +s+ df_BIOLAB_unique['PDMEDYN'].map(str)
#*** 5. Convert long to semi-wide format: pivot on TESTNAME,TESTVALUE
df_BIOLAB_SemiWide = unstack_df(df_BIOLAB_unique,idCols_Subject_Visit=['PATNO','key'],tallCol_Name_Value=['TESTNAME','TESTVALUE'])
df_BIOLAB_SemiWide['EVENT_ID'] = df_BIOLAB_SemiWide['key'].map(lambda x: x.split(s)[0])
df_BIOLAB_SemiWide['INFODT'] = df_BIOLAB_SemiWide['key'].map(lambda x: x.split(s)[1])
df_BIOLAB_SemiWide['PDMEDYN'] = df_BIOLAB_SemiWide['key'].map(lambda x: x.split(s)[2])
#* Combine two APOE columns
apoe_col = 'APOE GENOTYPE'
apoe = df_BIOLAB_SemiWide[apoe_col]
apoe[apoe.isnull()] = df_BIOLAB_SemiWide['ApoE Genotype'][apoe.isnull()].values
df_BIOLAB_SemiWide.loc[:,apoe_col] = apoe.values
df_BIOLAB_SemiWide.drop(columns=['ApoE Genotype'],inplace=True)
print('Filling in missing genetic data for:')
#* Backfill/Forwardfill selected columns (APOE/GBA/MAPT)
# From PPMI_Methods_PD_Variants_Table.pdf (see also ppmi_genetics_mapper above)
# - MAPT: rs17649553
# - GBA: rs421016, rs76763715, rs75548401, rs2230288, rs104886460, rs387906315
# - APOE:
fillna_selected_biolab_columns = ['rs17649553','rs421016','rs76763715','rs75548401','rs2230288','rs104886460','rs387906315',apoe_col]
fillna_selected_biolab_columns_gene = ['MAPT','GBA variant','GBA variant','GBA variant','GBA variant','GBA variant','GBA variant','ApoE']
for c,g in zip(fillna_selected_biolab_columns,fillna_selected_biolab_columns_gene):
print('\t %s (%s)' % (c,g))
# print('Missing values in rs17649553 (prefill): %i' % df_BIOLAB_SemiWide['rs17649553'].isnull().sum())
for patno_k in df_BIOLAB_SemiWide.PATNO.unique():
rowz = (df_BIOLAB_SemiWide.PATNO == patno_k).values
print('.', end='', flush=True)
for gene_k in fillna_selected_biolab_columns:
colz = df_BIOLAB_SemiWide.columns[df_BIOLAB_SemiWide.columns.str.contains(gene_k)]
for col_k in colz:
if not df_BIOLAB_SemiWide.loc[rowz,col_k].isnull().all():
df_BIOLAB_SemiWide.loc[rowz,[col_k]] = df_BIOLAB_SemiWide.loc[rowz,[col_k]].fillna(method='bfill', axis=0)
df_BIOLAB_SemiWide.loc[rowz,[col_k]] = df_BIOLAB_SemiWide.loc[rowz,[col_k]].fillna(method='ffill', axis=0)
# print('Missing values in rs17649553 (postfill): %i' % df_BIOLAB_SemiWide['rs17649553'].isnull().sum())
df_BIOLAB_SemiWide.drop('key',axis=1,inplace=True)
#* Rename selected rsid columns to include gene info
fillna_selected_biolab_columns_newname = []
for gene_k,g in zip(fillna_selected_biolab_columns,fillna_selected_biolab_columns_gene):
colz = df_BIOLAB_SemiWide.columns[df_BIOLAB_SemiWide.columns.str.contains(gene_k)]
for col_k in colz:
n = col_k + ' ('+g+')'
if col_k==apoe_col:
#* Don't rename APOE column
fillna_selected_biolab_columns_newname.append(col_k)
else:
df_BIOLAB_SemiWide.rename(columns = {col_k:n}, inplace = True)
fillna_selected_biolab_columns_newname.append(n)
#* Reorder columns
first_cols = ['PATNO','EVENT_ID','INFODT','PDMEDYN']+fillna_selected_biolab_columns_newname
cols = df_BIOLAB_SemiWide.columns.isin(first_cols)
df_BIOLAB_SemiWide = df_BIOLAB_SemiWide[first_cols + df_BIOLAB_SemiWide.columns[~cols].tolist()]
#* Write new BIOLAB to CSV
df_BIOLAB_SemiWide.to_csv(BIOLAB_csv,index=False)
# ### Data Preparation step 3: Prepare tables of interest
# - 3.1 Calculate total scores and subscores for various assessments
#
# When merging later, rename `INFODT` columns: add suffix (e.g., `PAG_NAME` where it exists)
#*** Add LEDD: see PPMI_Methods_LESS_LevodopaEquivalent_Daily_Dose_20160608.pdf
def calculate_ledd_CONMED(df_CONMED):
"""
FIXME: Work In Progress
For PD medications except COMT inhibitors, the column LEDD will show the value
of the Levodopa equivalent dose for that medication.
For COMT inhibitors, the column LEDD will read
“LD x 0.33” (for Entacapone) or
“LD x 0.5” (for Tolcapone).
To find the LEDD for COMT inhibitors, first find the total dose of Levodopa only,
and then multiply the Levodopa dose by either 0.33 or 0.5 as instructed.
To find the total LEDD at a specific time point:
- add all values of the column LEDD for the PD medications taken at that time point.
Anticholinergics and other PD medications that are not included in the calculation
of the total LEDD will have a missing value for the LEDD column.
"""
df_cm = df_CONMED[['PATNO','EVENT_ID','LEDD','STARTDT','STOPDT']].copy()
not_missing = ~df_cm[['LEDD','STARTDT','STOPDT']].isnull().all(axis=1)
df_cm = df_cm.loc[not_missing].copy().sort_values(by='PATNO').reset_index(drop=True)
#* LEDD for each medication
ledd = df_cm.LEDD.values
#*
ledd_COMT
#* LEDD is for all but COMT inhibitors, which show '0.3 x LD'
df_cm = df_cm['PATNO','EVENT_ID','LEDD']
df_temp = pd.merge(df,df_cm,on=['PATNO','EVENT_ID'],how='left')
return df_temp
def calculate_scores_MOCA(df_MOCA):
"""
Calculates MOCA subscores by summing the relevant questions:
MOCA_Visuospatial = MCAALTTM + MCACUBE + MCACLCKC + MCACLCKN + MCACLCKH
MOCA_Naming = MCALION + MCARHINO + MCACAMEL
MOCA_Attention = MCAFDS + MCABDS + MCAVIGIL + MCASER7
MOCA_Language = MCASNTNC + MCAVF
MOCA_DelayedRecall = MCAREC1 + MCAREC2 + MCAREC3 + MCAREC4 + MCAREC5
MOCA_Orientation = MCADATE + MCAMONTH + MCAYR + MCADAY + MCAPLACE + MCACITY
MOCA_Letter_Fluency = MCAVFNUM
Returns a list of added column names
"""
cols_visuospatial = ['MCAALTTM','MCACUBE','MCACLCKC','MCACLCKN','MCACLCKH']
cols_naming = ['MCALION','MCARHINO','MCACAMEL']
cols_attention = ['MCAFDS','MCABDS','MCAVIGIL','MCASER7']
cols_language = ['MCASNTNC','MCAVF']
cols_recall = ['MCAREC1','MCAREC2','MCAREC3','MCAREC4','MCAREC5']
cols_orientation = ['MCADATE','MCAMONTH','MCAYR','MCADAY','MCAPLACE','MCACITY']
cols_letter_fluency = ['MCAVFNUM']
df_MOCA['MOCA_Visuospatial'] = df_MOCA[cols_visuospatial].sum(axis=1)
df_MOCA['MOCA_Naming'] = df_MOCA[cols_naming].sum(axis=1)
df_MOCA['MOCA_Attention'] = df_MOCA[cols_attention].sum(axis=1)
df_MOCA['MOCA_Language'] = df_MOCA[cols_language].sum(axis=1)
df_MOCA['MOCA_DelayedRecall'] = df_MOCA[cols_recall].sum(axis=1)
df_MOCA['MOCA_Orientation'] = df_MOCA[cols_orientation].sum(axis=1)
df_MOCA['MOCA_Letter_Fluency'] = df_MOCA[cols_letter_fluency].values
return ['MOCA_Visuospatial','MOCA_Naming','MOCA_Attention','MOCA_Language','MOCA_DelayedRecall','MOCA_Orientation','MOCA_Letter_Fluency']
#* Could add explicit text for COGSTATE column:
# 3 - Dementia (PDD)
# 2 - Mild Cognitive Impairment (PD-MCI)
# 1 - Normal Cognition (PD-NC)
def calculate_scores_GDSSHORT(df_GDSSHORT):
"""
Calculates a single depression score:
GDS_TOT = sum(GDSSATIS, GDSGSPIR, GDSHAPPY, GDSALIVE, GDSENRGY == 0)
+ sum(GDSDROPD, GDSEMPTY, GDSBORED, GDSAFRAD, GDSHLPLS, GDSHOME, GDSMEMRY, GDSWRTLS, GDSHOPLS, GDSBETER == 1)
The GDS is valid only if 12 or more answers are provided.
For invalid tests, this function returns GDS_TOT = NA
Returns a list of added column names
"""
# Negative depression - depression indicated by 0 for these questions
negative_questions = [ 'GDSSATIS', 'GDSGSPIR', 'GDSHAPPY', 'GDSALIVE', 'GDSENRGY' ]
# Positive depression - depression indicated by 1 for these questions
positive_questions = [ 'GDSDROPD', 'GDSEMPTY', 'GDSBORED', 'GDSAFRAD', 'GDSHLPLS', 'GDSHOME', 'GDSMEMRY', 'GDSWRTLS', 'GDSHOPLS', 'GDSBETER' ]
df_GDSSHORT['GDS_TOT'] = (0 == df_GDSSHORT[negative_questions]).sum(axis=1) + (1 == df_GDSSHORT[positive_questions]).sum(axis=1)
# Check for at least 12 non-missing answers, otherwise NaN
na_rows = (np.logical_not(np.isnan(df_GDSSHORT[negative_questions + positive_questions])).sum(axis=1) < 12)
df_GDSSHORT.loc[na_rows.values,'GDS_TOT'] = np.nan
return ['GDS_TOT']
def calculate_scores_SCOPAAUT(df_SCOPAAUT):
"""
Calculates SCPOPA-AUT subscores and total by summing the relevant questions:
Gastrointestinal: sum 1-7
Urinary: sum 8-13 (beware coding 9 for "uses a catheter", which scores as 3=="often")
Cardiovascular: sum 14-16
Thermoregulatory: sum 17,18,20-21
Pupillomotor: 19
Sexual: 22+23 (male) or 24+25 (female) (beware 9 coding for not-applicable - scores 0)
Total: out of 23 (23A and 26 do not contribute to the score)
Returns a list of added column names
"""
# First check for 9 and change to 3 (urinary) or 0 (sexual)
urinary_columns = df_SCOPAAUT[[ 'SCAU8', 'SCAU9', 'SCAU10', 'SCAU11', 'SCAU12', 'SCAU13' ]].copy().replace([9],[3])
sexual_columns = df_SCOPAAUT[[ 'SCAU22', 'SCAU23', 'SCAU24', 'SCAU25']].copy().replace([9],[0])
# Sum total for each SCOPA-AUT subscale
df_SCOPAAUT.loc[:,'SCOPAAUT_gastrointestinal'] = df_SCOPAAUT[[ 'SCAU1', 'SCAU2', 'SCAU3', 'SCAU4', 'SCAU5', 'SCAU6', 'SCAU7' ]].sum(axis=1)
df_SCOPAAUT.loc[:,'SCOPAAUT_urinary'] = urinary_columns.sum(axis=1)
df_SCOPAAUT.loc[:,'SCOPAAUT_cardiovascular'] = df_SCOPAAUT[[ 'SCAU14', 'SCAU15', 'SCAU16' ]].sum(axis=1)
df_SCOPAAUT.loc[:,'SCOPAAUT_thermoregulatory'] = df_SCOPAAUT[[ 'SCAU17', 'SCAU18', 'SCAU20', 'SCAU21' ]].sum(axis=1)
df_SCOPAAUT.loc[:,'SCOPAAUT_pupillomotor'] = df_SCOPAAUT[[ 'SCAU19' ]].sum(axis=1)
df_SCOPAAUT.loc[:,'SCOPAAUT_sexual'] = sexual_columns.sum(axis=1)
df_SCOPAAUT.loc[:,'SCOPAAUT_TOT'] = df_SCOPAAUT[['SCOPAAUT_gastrointestinal',
'SCOPAAUT_urinary',
'SCOPAAUT_cardiovascular',
'SCOPAAUT_thermoregulatory',
'SCOPAAUT_pupillomotor',
'SCOPAAUT_sexual']].sum(axis=1)
return ['SCOPAAUT_gastrointestinal','SCOPAAUT_urinary','SCOPAAUT_cardiovascular','SCOPAAUT_thermoregulatory','SCOPAAUT_pupillomotor','SCOPAAUT_sexual','SCOPAAUT_TOT']
def calculate_scores_STAI(df_STAI):
"""
Calculates STAI subscores (state and trait) and total by summing the relevant questions:
Each question is scored between 1-4, so we simply sum the "affirmative" questions,
and invert the scale
State anxiety:
Positive anxiety (3,4,6,7,9,12,13,14,17,18)
Negative anxiety (1,2,5,8,10,11,15,16,19,20)
Trait anxiety:
Positive anxiety (22,24,25,28,29,31,32,35,37,38,40)
Negative anxiety (21,23,26,27,30,33,34,36,39)
Returns a list of added column names
"""
state_cols_positive = ['STAIAD3', 'STAIAD4', 'STAIAD6', 'STAIAD7', 'STAIAD9', 'STAIAD12', 'STAIAD13', 'STAIAD14', 'STAIAD17', 'STAIAD18']
state_cols_negative = ['STAIAD1', 'STAIAD2', 'STAIAD5', 'STAIAD8', 'STAIAD10', 'STAIAD11', 'STAIAD15', 'STAIAD16', 'STAIAD19', 'STAIAD20']
trait_cols_positive = ['STAIAD22', 'STAIAD24', 'STAIAD25', 'STAIAD28', 'STAIAD29', 'STAIAD31', 'STAIAD32', 'STAIAD35', 'STAIAD37', 'STAIAD38', 'STAIAD40']
trait_cols_negative = ['STAIAD21', 'STAIAD23', 'STAIAD26', 'STAIAD27', 'STAIAD30', 'STAIAD33', 'STAIAD34', 'STAIAD36', 'STAIAD39']
df_STAI['STAI_TOT_State'] = df_STAI[state_cols_positive].sum(axis=1) + (5-df_STAI[state_cols_negative]).sum(axis=1)
df_STAI['STAI_TOT_Trait'] = df_STAI[trait_cols_positive].sum(axis=1) + (5-df_STAI[trait_cols_negative]).sum(axis=1)
df_STAI['STAI_TOT'] = df_STAI[['STAI_TOT_State','STAI_TOT_Trait']].sum(axis=1)
return ['STAI_TOT_State','STAI_TOT_Trait','STAI_TOT']
def calculate_scores_QUIPCS(df_QUIPCS):
"""
Calculates total scores for QUIPCS:
Raw total:
QUIPCS_TOT = sum()
Suggested calculation in Derived_Variable_Definitions_and_Score_Calculations.csv:
QUIP_Number = any(cols_A==1) + any(cols_B==1) + any(cols_C==1) + any(cols_D==1) + sum(cols_E==1)
Returns a list of added column names
"""
# Impulsive-Compulsive behaviour: Gambling, Sex, Shopping, Eating, Other, Medication
cols_A = ['TMGAMBLE','CNTRLGMB']
cols_B = ['TMSEX','CNTRLSEX']
cols_C = ['TMBUY','CNTRLBUY']
cols_D = ['TMEAT','CNTRLEAT']
cols_E = ['TMTORACT','TMTMTACT','TMTRWD']
cols_F = ['TMDISMED','CNTRLDSM']
df_QUIPCS['QUIPCS_TOT'] = df_QUIPCS[cols_A].sum(axis=1)
#* Calculation from Derived_Variable_Definitions_and_Score_Calculations.csv
df_QUIPCS['QUIP_Number'] = 1*df_QUIPCS[cols_A].any(axis=1) + 1*df_QUIPCS[cols_B].any(axis=1) + 1*df_QUIPCS[cols_C].any(axis=1) + 1*df_QUIPCS[cols_D].any(axis=1) + df_QUIPCS[cols_E].sum(axis=1)
return ['QUIPCS_TOT','QUIP_Number']
def calculate_scores_EPWORTH(df_EPWORTH):
"""
Calculates total score for EPWORTH:
ESS_TOT = sum()
Returns a list of added column names
"""
cols = ['ESS1','ESS2','ESS3','ESS4','ESS5','ESS6','ESS7','ESS8']
df_EPWORTH['ESS_TOT'] = df_EPWORTH[cols].sum(axis=1)
df_EPWORTH['ESS_Sleepy'] = df_EPWORTH['ESS_TOT'] >= 10
return ['ESS_TOT','ESS_Sleepy']
def calculate_scores_REMSLEEP(df_REMSLEEP):
"""
Calculates total score for REMSLEEP, according to
Derived_Variable_Definitions_and_Score_Calculations.csv:
1 point each for "Yes" to the following variables:
DRMVIVID, DRMAGRAC, DRMNOCTB, SLPLMBMV, SLPINJUR, DRMVERBL, DRMFIGHT, DRMUMV, DRMOBJFL, MVAWAKEN, DRMREMEM, SLPDSTRB
Add a further 1 point if any of these are "Yes":
STROKE, HETRA, PARKISM, RLS, NARCLPSY, DEPRS, EPILEPSY, BRNINFM, CNSOTH
- If any of the previous variables are missing, then RBD score is missing.
- Subjects with score >=5 are RBD Positive. Subjects with score <5 are RBD Negative.
Returns a list of added column names
"""
cols_sum = ['DRMVIVID','DRMAGRAC','DRMNOCTB','SLPLMBMV','SLPINJUR','DRMVERBL',
'DRMFIGHT','DRMUMV','DRMOBJFL','MVAWAKEN','DRMREMEM','SLPDSTRB']
cols_neuro = ['STROKE','HETRA','PARKISM','RLS','NARCLPSY','DEPRS','EPILEPSY','BRNINFM']
df_REMSLEEP['RBD_TOT'] = df_REMSLEEP[cols_sum].sum(axis=1) + 1*(df_REMSLEEP[cols_neuro].any(axis=1))
# Missing values cause the total score to be missing
m = np.isnan(df_REMSLEEP[cols_sum + cols_neuro]).any(axis=1)
df_REMSLEEP.loc[m.values,'RBD_TOT'] = np.nan
return ['RBD_TOT']
def calculate_scores_UPSIT(df_UPSIT):
"""
Calculates total score for UPSIT:
UPSIT_TOT = sum()
Also sets the total to NaN where any individual score is missing.
Could also look into the COMM column to understand other low scores
that might've been entered as zero, rather than missing.
Returns a list of added column names
"""
UPSIT_cols = ['UPSITBK1','UPSITBK2','UPSITBK3','UPSITBK4']
df_UPSIT['UPSIT_TOT'] = df_UPSIT[UPSIT_cols].sum(axis=1)
#* Potentially corrupted data due to missing/expired smell test booklets
rows_equal_to_zero = (df_UPSIT[UPSIT_cols]==0).any(axis=1)
rows_missing = np.isnan(df_UPSIT[UPSIT_cols]).any(axis=1)
#df_UPSIT.set_value(rows_equal_to_zero | rows_missing,'UPSIT_TOT',np.nan)
df_UPSIT.loc[rows_missing.values,'UPSIT_TOT'] = np.nan
return ['UPSIT_TOT']
def calculate_scores_NUPDRS1(df_NUPDRS1):
"""
Calculates total score for part 1 of the UPDRS
NP1_TOT = sum()
Returns a list of added column names
"""
cols = ['NP1COG','NP1HALL','NP1DPRS','NP1ANXS','NP1APAT','NP1DDS']
df_NUPDRS1['NP1_TOT'] = df_NUPDRS1[cols].sum(axis=1)
return ['NP1_TOT']
def calculate_scores_NUPDRS1p(df_NUPDRS1p):
"""
Calculates total score for part 1p of the UPDRS
NP1p_TOT = sum()
Returns a list of added column names
"""
cols = ['NP1SLPN','NP1SLPD','NP1PAIN','NP1URIN','NP1CNST','NP1LTHD','NP1FATG']
df_NUPDRS1p['NP1p_TOT'] = df_NUPDRS1p[cols].sum(axis=1)
return ['NP1p_TOT']
def calculate_scores_NUPDRS2p(df_NUPDRS2p):
"""
Calculates total score for part 2 of the UPDRS
NP2_TOT = sum()
Returns a list of added column names
"""
cols = ['NP2SPCH','NP2SALV','NP2SWAL','NP2EAT',
'NP2DRES','NP2HYGN','NP2HWRT','NP2HOBB','NP2TURN',
'NP2TRMR','NP2RISE','NP2WALK','NP2FREZ']
df_NUPDRS2p['NP2_TOT'] = df_NUPDRS2p[cols].sum(axis=1)
return ['NP2_TOT']
def calculate_scores_NUPDRS3(df_NUPDRS3):
"""
Calculates total score for part 3 of the UPDRS
NP3_TOT = sum()
Returns a list of added column names
Note the typo in the column named PN3RIGRL (as of March 2018).
"""
cols = ['NP3SPCH','NP3FACXP','NP3RIGN','NP3RIGRU','NP3RIGLU',
'PN3RIGRL',
'NP3RIGLL','NP3FTAPR','NP3FTAPL','NP3HMOVR','NP3HMOVL','NP3PRSPR','NP3PRSPL',
'NP3TTAPR','NP3TTAPL','NP3LGAGR','NP3LGAGL','NP3RISNG','NP3GAIT','NP3FRZGT',
'NP3PSTBL','NP3POSTR','NP3BRADY','NP3PTRMR','NP3PTRML','NP3KTRMR','NP3KTRML',
'NP3RTARU','NP3RTALU','NP3RTARL','NP3RTALL','NP3RTALJ','NP3RTCON']
df_NUPDRS3['NP3_TOT'] = df_NUPDRS3[cols].sum(axis=1)
return ['NP3_TOT']
def calculate_scores_NUPDRS4(df_NUPDRS4):
"""
Calculates total score for part 4 of the UPDRS
NP4_TOT = sum()
Returns a list of added column names
"""
cols = ['NP4WDYSK','NP4DYSKI','NP4OFF','NP4FLCTI','NP4FLCTX','NP4DYSTN']
df_NUPDRS4['NP4_TOT'] = df_NUPDRS4[cols].sum(axis=1)
return ['NP4_TOT']
def calculate_scores_NUPDRS_TOT(df_NUPDRS1,df_NUPDRS1p,df_NUPDRS2p,df_NUPDRS3_or_3A,df_NUPDRS4):
"""
Calculates total score UPDRS, pre/post dose:
NP1_TOT + NP1p_TOT + NP2_TOT + NP3_TOT
Returns the total score
"""
UPDRS_TOT = df_NUPDRS1['NP1_TOT'] + df_NUPDRS1p['NP1p_TOT'] + df_NUPDRS2p['NP2_TOT'] + df_NUPDRS3_or_3A['NP3_TOT']
# UPDRS_TOT = UPDRS_TOT + df_NUPDRS4['NP4_TOT']
return UPDRS_TOT
def calculate_scores_PENEURO(df_PENEURO):
"""
Calculates subscores and total score for PENEURO:
PENEURO_R = sum(test results on RHS)
PENEURO_L = sum(test results on LHS)
PENEURO_TOT = PENEURO_R + PENEURO_L
Returns a list of added column names
"""
# Muscle strength: R and L
cols_MSR = ['MSRARSP','MSRLRSP']
cols_MSL = ['MSLARSP','MSLLRSP']
cols_MS = cols_MSR + cols_MSL
# Coordination: R and L
cols_COR = ['COFNRRSP','COHSRRSP']
cols_COL = ['COFNLRSP','COHSLRSP']
cols_CO = cols_COR + cols_COL
# Sensory: R and L
cols_SER = ['SENRARSP','SENRLRSP']
cols_SEL = ['SENLARSP','SENLLRSP']
cols_SE = cols_SER + cols_SEL
# Reflex: R and L
cols_RFR = ['RFLRARSP','RFLRLRSP']
cols_RFL = ['RFLLARSP','RFLLLRSP']
cols_RF = cols_RFR + cols_RFL
# Plantar: R and L
cols_PR = ['PLRRRSP']
cols_PL = ['PLRLRSP']
cols_P = cols_PR + cols_PL
cols_R = cols_MSR + cols_COR + cols_SER + cols_RFR + cols_PR
cols_L = cols_MSL + cols_COL + cols_SEL + cols_RFL + cols_PL
df_PENEURO['PENEURO_R'] = df_PENEURO[cols_R].sum(axis=1)
df_PENEURO['PENEURO_L'] = df_PENEURO[cols_L].sum(axis=1)
df_PENEURO['PENEURO_TOT'] = df_PENEURO[cols_R + cols_L].sum(axis=1)
return ['PENEURO_R','PENEURO_L','PENEURO_TOT']
def calculate_scores_PECN(df_PECN):
"""
Calculates total score for PECN:
CN_TOT = sum(cols)
Returns a list of added column names
"""
#
cols = ['CN1RSP','CN2RSP','CN346RSP','CN5RSP','CN7RSP','CN8RSP','CN910RSP','CN11RSP','CN12RSP']
df_PECN['CN_TOT'] = df_PECN[cols].sum(axis=1)
return ['CN_TOT']
#*** 3.0 Tables of interest
#* Created earlier by this script: BIOLAB
#* Suggest adding MRI volumes (perhaps using GIF, or FreeSurfer, for example)
#* PPMI raw tables
tables_of_interest = {
'PDMEDUSE':'Use_of_PD_Medication',
#'CONMED':'Concomitant_Medications',
'CLINDX':'Clinical_Diagnosis_and_Management',
'COGCATG':'Cognitive_Categorization',
'PDFEAT':'PD_Features',
'VITAL':'Vital_Signs',
'PECN':'Neurological_Exam___Cranial_Nerves',
'PENEURO':'General_Neurological_Exam',
'MOCA':'Montreal_Cognitive_Assessment__MoCA_',
'SFT':'Semantic_Fluency',
'LNSPD':'Letter___Number_Sequencing__PD_',
'HVLT':'Hopkins_Verbal_Learning_Test',
'LINEORNT':'Benton_Judgment_of_Line_Orientation',
'SDM':'Symbol_Digit_Modalities',
'GDSSHORT':'Geriatric_Depression_Scale__Short_',
'STAI':'State_Trait_Anxiety_Inventory',
'QUIPCS':'QUIP_Current_Short',
'EPWORTH':'Epworth_Sleepiness_Scale',
'REMSLEEP':'REM_Sleep_Disorder_Questionnaire',
'NUPDRS1':'MDS_UPDRS_Part_I',
'NUPDRS1p':'MDS_UPDRS_Part_I__Patient_Questionnaire',
'NUPDRS2p':'MDS_UPDRS_Part_II__Patient_Questionnaire',
'NUPDRS3':'MDS_UPDRS_Part_III', #'NUPDRS3':'MDS_UPDRS_Part_III__Post_Dose_',
'NUPDRS4':'MDS_UPDRS_Part_IV',
'UPSIT':'University_of_Pennsylvania_Smell_ID_Test',
'SCOPAAUT':'SCOPA_AUT',
'DATSCAN':'DaTscan_Imaging',
'DATSCAN_RESULTS':'DATScan_Analysis',
#'DATSCAN_visual':'DaTSCAN_SPECT_Visual_Interpretation_Assessment',
'AVIMAG_meta':'AV_133_Image_Metadata',
'AVIMAG_RESULTS':'AV_133_SBR_Results',
'DTIROI':'DTI_Regions_of_Interest',
'MRI':'Magnetic_Resonance_Imaging'
}
valz = list(tables_of_interest.values())
keyz = list(tables_of_interest.keys())
columns_of_interest = {
'PDMEDUSE':['PDMEDYN','ONLDOPA','ONDOPAG','ONOTHER'], #
#'CONMED':['LEDD'],
'CLINDX':['INFODT', 'PRIMDIAG', 'DCRTREM', 'DCRIGID', 'DCBRADY'],
'COGCATG':['COGDECLN','COGSTATE'],
'PDFEAT':['PDDXDT','PDDXEST','DXTREMOR','DXRIGID','DXBRADY','DOMSIDE'],
'VITAL':['WGTKG', 'HTCM', 'TEMPC', 'SYSSUP', 'DIASUP', 'HRSUP', 'SYSSTND', 'DIASTND', 'HRSTND'],
'PECN':['CN1RSP','CN2RSP','CN346RSP','CN5RSP','CN7RSP','CN8RSP','CN910RSP','CN11RSP','CN12RSP'],
# Updated July 2021
# 'PENEURO':['MSRARSP','MSRACM','MSLARSP','MSLACM','MSRLRSP','MSRLCM','MSLLRSP','MSLLCM',
# 'COFNRRSP','COFNRCM','COFNLRSP','COFNLCM','COHSRRSP','COHSRCM','COHSLRSP','COHSLCM',
# 'SENRARSP','SENRACM','SENLARSP','SENLACM','SENRLRSP','SENRLCM','SENLLRSP','SENLLCM',