-
Notifications
You must be signed in to change notification settings - Fork 0
/
Biologics_Humira_HS-PSO_Program_SAS_dependent.py
1779 lines (1669 loc) · 94.4 KB
/
Biologics_Humira_HS-PSO_Program_SAS_dependent.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 os
import sys
import pandas
import numpy
import datetime
from multiprocessing import cpu_count, Pool
import win32api, win32process, win32con
'''
# 1: Read SAS file to VAR type
def ReadSAStoVAR(sasfilename):
sasvar=SAS7BDAT(sasfilename+".sas7bdat");
return sasvar;
# 2: Write VAR type to TXT file (Obsolete)
def WriteVARtoTXT(sasvar):
texter=open("VARtoTXT.txt", "w+");
for row in sasvar:
for word in row:
if len(str(word)) > 7 and len(str(word)) < 16:
texter.write("%s\t\t\t" % word);
elif len(str(word)) >= 16 and len(str(word)) < 24 :
texter.write("%s\t\t" % word);
elif len(str(word)) >= 24:
texter.write("%s\t" % word);
else:
texter.write("%s\t\t\t\t" % word);
texter.write("\n");
texter.close();
# 3: Write SAS file to TXT file (Obsolete)
def WriteSAStoTXT(sasfilename):
texter=open("SAStoTXT.txt", "w+");
with SAS7BDAT(sasfilename+".sas7bdat") as f:
for row in f:
for word in row:
if len(str(word)) > 7 and len(str(word)) < 16:
texter.write("%s\t\t\t" % word);
elif len(str(word)) >= 16 and len(str(word)) < 24 :
texter.write("%s\t\t" % word);
elif len(str(word)) >= 24:
texter.write("%s\t" % word);
else:
texter.write("%s\t\t\t\t" % word);
texter.write("\n");
texter.close();'''
# 4: Divide Transaction Rows by Units (Verified)
def DivideRowsbyUnits(sasframe): #The Units column doesn't update but the rows replicate.
tempframe=sasframe;
for index, row in sasframe.iterrows(): #Problem Encountered (Solved): Original Dataframe's Unit column's first element becomes 1.
if int(sasframe['Units'].loc[index]) > 1:
units=int(sasframe['Units'][index]);
units-=1;
copyframe=tempframe.loc[[index]];
copyframe['Units']=1; #Number of 'SettingWithCopyWarning's received.
for i in range(int(units)):
tempframe=pandas.concat([tempframe, copyframe]);
tempframe['Units'].loc[[index]]=1;
print("Multi unit encountered");
return tempframe;
# 5: Convert SAS Date to Python Date
def DateSAStoPython(sasdate):
sasdate=int(sasdate);
leapyears=sasdate/1461;
remyears=(sasdate%1461)/365;
remdays=(sasdate%1461)%365;
year=1960+4*int(leapyears)+int(remyears);
if int(remyears)==3: #Leap Year
if remdays <= 182:
if remdays <= 91:
if remdays <= 31: #January
month=1;
date=remdays;
elif remdays > 31 and remdays <= 60: #February
month=2;
date=remdays-31;
else: #March
month=3;
date=remdays-60;
else:
if remdays <= 121: #April
month=4;
date=remdays-91;
elif remdays > 121 and remdays <= 152: #May
month=5;
date=remdays-121;
else: #June
month=6;
date=remdays-152;
else:
if remdays <= 274:
if remdays <= 213: #July
month=7;
date=remdays-182;
elif remdays > 213 and remdays <= 244: #August
month=8;
date=remdays-213;
else: #September
month=9;
date=remdays-244;
else:
if remdays <= 305: #October
month=10;
date=remdays-274;
elif remdays > 305 and remdays <= 335: #November
month=11;
date=remdays-305;
else: #December
month=12;
date=remdays-335;
else: #Normal Year
if remdays <= 181:
if remdays <= 90:
if remdays <= 31: #January
month=1;
date=remdays;
elif remdays > 31 and remdays <= 59: #February
month=2;
date=remdays-31;
else: #March
month=3;
date=remdays-59;
else:
if remdays <= 120: #April
month=4;
date=remdays-90;
elif remdays > 120 and remdays <= 151: #May
month=5;
date=remdays-120;
else: #June
month=6;
date=remdays-151;
else:
if remdays <= 273:
if remdays <= 212: #July
month=7;
date=remdays-181;
elif remdays > 212 and remdays <= 243: #August
month=8;
date=remdays-212;
else: #September
month=9;
date=remdays-243;
else:
if remdays <= 304: #October
month=10;
date=remdays-273;
elif remdays > 304 and remdays <= 334: #November
month=11;
date=remdays-304;
else: #December
month=12;
date=remdays-334;
pydate=datetime.date(year, month, date);
print(str(year)+" year and "+str(month)+" month and "+str(date)+" day.");
return pydate;
# 6: Convert Python Date to SAS Date
def DatePythontoSAS(pydate):
date=pydate.day;
month=pydate.month;
year=pydate.year;
monthdays=[31,28,31,30,31,30,31,31,30,31,30,31];
leapmonthdays=[31,29,31,30,31,30,31,31,30,31,30,31];
daysofmonths=0;
if int(year)%4!=0:
for i in range(int(month)-1):
daysofmonths+=monthdays[i];
else:
for i in range(int(month)-1):
daysofmonths+=leapmonthdays[i];
sasdate=(int(year)-1960)*365+int((int(year-1)-1960)/4)+int(daysofmonths)+int(date);
return sasdate;
# 7: Input and Parse Python Date
def ReadandParseDateinPython():
date_entry=input('Enter the date in YYYY-MM-DD format:');
year,month,day=map(int, date_entry.split('-'));
pydate=datetime.date(year,month,day);
return pydate;
# 8: Check No. of patients in a Dataframe by 'P_ID':
def NumofPatients(dataframe):
dfgroup=dataframe.groupby('P_ID');
i=0;
for patient_id, patient_stats in dfgroup:
i+=1;
return i;
# 9: Check for Patient No. in the dataframe:
def IsPatientNumin(dataframe, patient_id):
answer=False;
for p_id in dataframe['P_ID']:
if int(p_id) == int(patient_id):
answer=True;
return answer;
# 10: Isolate Patient data from a dataframe
def RetrievePatientfrom(dataframe, p_id):
dfgroup=dataframe.groupby('P_ID');
for patient_id, patient_stats in dfgroup:
if patient_id == p_id:
patientframe=patient_stats;
return patientframe;
# 11: Get patient IDs from a data frame
def RetrievePatientIDsfrom(dataframe):
patientframe={
'P_ID':[],
}
pframe=pandas.DataFrame(patientframe);
dfgroup=dataframe.groupby('P_ID');
for patient_id, patient_stats in dfgroup:
pframe=pframe.append({'P_ID':patient_id}, ignore_index=True);
return pframe;
# 12: Multiprocessing Pack Numbering
#def PackNumbering(packframe, patient_stats):
# 13: Multiprocessing Therapy Duration
#def AssignRXDuration(rx):
def AssignPatientLevelSpec(threadframe):
HighPriority();
emptyframe2=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', 'TransactionDate', 'FCC', 'Units', 'ShortCode','P_ID', 'TransactionMonth', 'atc', 'prod', 'pack', 'str_unit','str_meas', 'gene', 'DoctorSpeciality', 'CU', 'PSIZE', 'numdax', 'DoctorClass', 'PatientLevelClass']);
emptyframe=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', 'TransactionDate', 'FCC', 'Units', 'ShortCode','P_ID', 'TransactionMonth', 'atc', 'prod', 'pack', 'str_unit','str_meas', 'gene', 'DoctorSpeciality', 'CU', 'PSIZE', 'numdax', 'DoctorClass']);
rframe=dframe=uframe=emptyframe2;
oframe=emptyframe;
patientframe={
'PatientNum':[],
'PatientDocClass':[]
}
pframe=pandas.DataFrame(patientframe);
excelconst=pandas.read_excel('Biologics_Humira_HS-PSO_Program_Settings.xlsx', sheet_name='SpecialityBiologics');
tfgroup=threadframe.groupby('P_ID');
for patient_id, patient_stats in tfgroup:
rpositive=dpositive=False; #@gpositive var removed
for molecule in patient_stats['combomol']:
for const in excelconst['Rheumato_Molecules']:
if molecule==const:
rpositive=True;
for const in excelconst['Dermato_Molecules']:
if molecule==const:
dpositive=True;
'''for const in excelconst['Gastro_Molecules']: #not_implemented
if molecule==const:
gpositive=True;'''
if rpositive==True and dpositive==False:
pframe=pframe.append({'PatientNum':patient_id,'PatientDocClass':'Rheumato'}, ignore_index=True);
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Rheumato';
rframe=pandas.concat([rframe, tempframe]);
elif rpositive==False and dpositive==True:
pframe=pframe.append({'PatientNum':patient_id,'PatientDocClass':'Dermato'}, ignore_index=True);
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Dermato';
dframe=pandas.concat([dframe, tempframe]);
elif rpositive==True and dpositive==True:
pframe=pframe.append({'PatientNum':patient_id,'PatientDocClass':'Unknown'}, ignore_index=True);
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Unknown';
uframe=pandas.concat([uframe, tempframe]);
else:
pframe=pframe.append({'PatientNum':patient_id,'PatientDocClass':'Others'}, ignore_index=True);
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
#tempframe['PatientLevelClass']='Others';
oframe=pandas.concat([oframe, tempframe]);
print("Patient No."+str(patient_id)+" processed.");
threadframelist=[pframe, rframe, dframe, uframe, oframe];
return threadframelist;
def AssignPatientLevelSpectoExceptions(threadframe):
HighPriority();
emptyframe2=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', 'TransactionDate', 'FCC', 'Units', 'ShortCode','P_ID', 'TransactionMonth', 'atc', 'prod', 'pack', 'str_unit','str_meas', 'gene', 'DoctorSpeciality', 'CU', 'PSIZE', 'numdax', 'DoctorClass', 'PatientLevelClass']);
gframe=eframe=rframe=dframe=emptyframe2;
tfgroup=threadframe.groupby('P_ID');
for patient_id, patient_stats in tfgroup:
g=r=d=irr=0;
for spec in patient_stats['DoctorClass']:
if spec == 'Gastro':
g+=1;
elif spec == 'Rheumato':
r+=1;
elif spec == 'Dermato':
d+=1;
elif spec == 'Irrelevant':
irr+=1;
else:
continue;
if g > r and g > d and g >= irr:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Gastro';
gframe=pandas.concat([gframe, tempframe]);
elif r > g and r > d and r >= irr:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Rheumato';
rframe=pandas.concat([rframe, tempframe]);
elif d > g and d > r and d >= irr:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Dermato';
dframe=pandas.concat([dframe, tempframe]);
elif r==g and r > d and r >= irr:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Rheumato';
rframe=pandas.concat([rframe, tempframe]);
elif r==d and d > g and d >= irr:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Rheumato';
rframe=pandas.concat([rframe, tempframe]);
elif g==d and g > r and g >= irr:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Gastro';
gframe=pandas.concat([gframe, tempframe]);
elif r==g and g==d and d >= irr:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Rheumato';
rframe=pandas.concat([rframe, tempframe]);
elif irr==g and g > r and g > d:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Gastro';
gframe=pandas.concat([gframe, tempframe]);
elif irr==r and r > g and r > d:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Rheumato';
rframe=pandas.concat([rframe, tempframe]);
elif irr==d and d > r and d > g:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Dermato';
dframe=pandas.concat([dframe, tempframe]);
elif irr==g and g==r and r==d:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Rheumato';
rframe=pandas.concat([rframe, tempframe]);
else:
tempframe=patient_stats;
tempframe=tempframe.copy(); #bad_practice
tempframe['PatientLevelClass']='Error';
eframe=pandas.concat([eframe, tempframe]);
print("Exception Patient No."+str(patient_id)+" processed.");
threadframelist=[gframe, rframe, dframe, eframe];
return threadframelist;
def PackNumbering(threadframe):
HighPriority();
print("Multithreading starts...", flush=0);
i=0;
global packnumbermatrix;
for index, rx in threadframe.iterrows():
if i==0:
threadframe['PackNumber'].iloc[[i]]=1;
j=1;
else:
if threadframe['P_ID'].iloc[[i-1]].item() == threadframe['P_ID'].iloc[[i]].item() \
and threadframe['combomol'].iloc[[i-1]].item() == threadframe['combomol'].iloc[[i]].item():
j+=1;
elif threadframe['P_ID'].iloc[[i-1]].item() == threadframe['P_ID'].iloc[[i]].item() \
and threadframe['combomol'].iloc[[i-1]].item() != threadframe['combomol'].iloc[[i]].item():
j=1;
else:
j=1;
threadframe['PackNumber'].iloc[[i]]=j;
print(str(i+1)+" RXs indexed.",flush=True);
i+=1;
return threadframe;
print("...end of Multithreading", flush=0);
def PartitionDataFramebyPatientIDs(refframe):
rflength=len(refframe);
midindex=int(rflength/2);
lastpatient=False;
while not lastpatient:
if refframe['P_ID'].iloc[[midindex+1]].item() == refframe['P_ID'].iloc[[midindex]].item() \
and midindex + 2 < rflength:
midindex+=1;
else:
lastpatient=True;
print("Partition done.")
partframe1=refframe[:midindex+1];
partframe2=refframe[midindex+1:];
partslist=[partframe1, partframe2];
return partslist;
def PartitionDataFramebyCores(refframe, parts):
if parts==1:
partslist=[refframe];
print("No partioning as only 1 core.");
return partslist;
elif parts==2:
partslist=PartitionDataFramebyPatientIDs(refframe);
print("Double partition done");
return partslist;
elif parts==4:
partslist=PartitionDataFramebyPatientIDs(refframe);
partframe1=partslist[0];
partframe2=partslist[1];
partslist1=PartitionDataFramebyPatientIDs(partframe1);
partslist2=PartitionDataFramebyPatientIDs(partframe2);
partslist=partslist1+partslist2;
print("Quadruple partition done");
return partslist;
else:
partslist=PartitionDataFramebyPatientIDs(refframe);
partframe1=partslist[0];
partframe2=partslist[1];
partslist1=PartitionDataFramebyPatientIDs(partframe1);
partslist2=PartitionDataFramebyPatientIDs(partframe2);
partframe1=partslist1[0];
partframe2=partslist1[1];
partframe3=partslist2[0];
partframe4=partslist2[1];
partslist1=PartitionDataFramebyPatientIDs(partframe1);
partslist2=PartitionDataFramebyPatientIDs(partframe2);
partslist3=PartitionDataFramebyPatientIDs(partframe3);
partslist4=PartitionDataFramebyPatientIDs(partframe4);
partslist=partslist1+partslist2+partslist3+partslist4;
print("Octuple partition done");
return partslist;
def HighPriority():
""" Set the priority of the process to high (Source:Stackexchange) """
try:
sys.getwindowsversion();
except AttributeError:
isWindows = False;
else:
isWindows = True;
if isWindows:
# Based on:
# "Recipe 496767: Set Process Priority In Windows" on ActiveState
# http://code.activestate.com/recipes/496767/
pid = win32api.GetCurrentProcessId();
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid);
win32process.SetPriorityClass(handle, win32process.NORMAL_PRIORITY_CLASS);
else:
os.nice(10);
if __name__=='__main__':
# --------------------------------PHASE I-------------------------------------
print("Importing Biologics SAS dataset...");
filelocs=pandas.read_excel("Biologics_Humira_HS-PSO_Program_Settings.xlsx", sheet_name='FileLocations');
importedsasfile=filelocs['Address'][0];
sasframe=pandas.read_sas(importedsasfile, format='sas7bdat', encoding='iso-8859-1');
sasframe['DoctorClass']=sasframe['DoctorSpeciality'];
sasframe['DoctorClass'].replace(['31','32','47'],['Dermato','Gastro','Rheumato'], inplace=True);
for num in range(sasframe['DoctorClass'].size):
if sasframe['DoctorClass'][num]=='':
sasframe['DoctorClass'].at[num]='Irrelevant';
elif sasframe['DoctorClass'][num]!='Rheumato' and sasframe['DoctorClass'][num]!='Gastro' and sasframe['DoctorClass'][num]!='Dermato':
sasframe['DoctorClass'].at[num]='Irrelevant';
print(sasframe);
sasframe=DivideRowsbyUnits(sasframe);
# ---------------------------------PHASE II-----------------------------------
#sasframe['P_LevelClass']='';
emptyframe2=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', 'TransactionDate', 'FCC', 'Units', 'ShortCode','P_ID', 'TransactionMonth', 'atc', 'prod', 'pack', 'str_unit','str_meas', 'gene', 'DoctorSpeciality', 'CU', 'PSIZE', 'numdax', 'DoctorClass', 'PatientLevelClass']);
emptyframe=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', 'TransactionDate', 'FCC', 'Units', 'ShortCode','P_ID', 'TransactionMonth', 'atc', 'prod', 'pack', 'str_unit','str_meas', 'gene', 'DoctorSpeciality', 'CU', 'PSIZE', 'numdax', 'DoctorClass']);
rframe=dframe=uframe=emptyframe2;
oframe=emptyframe;
patientframe={
'PatientNum':[],
'PatientDocClass':[]
}
pframe=pandas.DataFrame(patientframe);
if cpu_count() < 2:
partitions=1;
elif cpu_count() < 4:
partitions=2;
elif cpu_count() < 8:
partitions=4;
else:
partitions=8;
sasframe=sasframe.sort_values(by=['P_ID', 'numdax', 'combomol'], ascending=[True, True, True]);
print("Dataframe sorted by Patient ID, Transaction date and Molecule.");
sasframe['PatientLevelClass']='';
sasflength=len(sasframe);
processedpartitionframelist=[];
partitionframelist=PartitionDataFramebyCores(sasframe, partitions);
pool=Pool();
processedpartitionframelist.append(pool.map(AssignPatientLevelSpec, partitionframelist));
pool.close();
pool.join();
for i in range(partitions):
pframe=pandas.concat([pframe, processedpartitionframelist[0][i][0]]);
rframe=pandas.concat([rframe, processedpartitionframelist[0][i][1]]);
dframe=pandas.concat([dframe, processedpartitionframelist[0][i][2]]);
uframe=pandas.concat([uframe, processedpartitionframelist[0][i][3]]);
oframe=pandas.concat([oframe, processedpartitionframelist[0][i][4]]);
print("Phase II: Part I execution ended at"+str(datetime.datetime.now().time()));
# ------------------------PHASE II: Exception Handling------------------------
emptyframe2=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', 'TransactionDate', 'FCC', 'Units', 'ShortCode','P_ID', 'TransactionMonth', 'atc', 'prod', 'pack', 'str_unit','str_meas', 'gene', 'DoctorSpeciality', 'CU', 'PSIZE', 'numdax', 'DoctorClass', 'PatientLevelClass']);
gframe=eframe=emptyframe2;
oframe=oframe.sort_values(by=['P_ID', 'numdax', 'combomol'], ascending=[True, True, True]);
print("Dataframe sorted by Patient ID, Transaction date and Molecule.");
oflength=len(oframe);
processedpartitionframelist=[]
partitionframelist=PartitionDataFramebyCores(oframe, partitions);
pool=Pool();
processedpartitionframelist.append(pool.map(AssignPatientLevelSpectoExceptions, partitionframelist));
pool.close();
pool.join();
for i in range(partitions):
gframe=pandas.concat([gframe, processedpartitionframelist[0][i][0]]);
rframe=pandas.concat([rframe, processedpartitionframelist[0][i][1]]);
dframe=pandas.concat([dframe, processedpartitionframelist[0][i][2]]);
eframe=pandas.concat([eframe, processedpartitionframelist[0][i][3]]);
print("Phase II: Part II execution ended at"+str(datetime.datetime.now().time()));
# ----------------- PHASE III: i. Flag Product Transactions ------------------
emptyframe3=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', \
'TransactionDate', 'FCC', 'Units', \
'ShortCode','P_ID', 'TransactionMonth', \
'atc', 'prod', 'pack', 'str_unit', \
'str_meas', 'gene', 'DoctorSpeciality', \
'CU', 'PSIZE', 'numdax', 'DoctorClass', \
'PatientLevelClass', 'ProdTransaction']);
npframe=emptyframe3;
dfgroup=dframe.groupby('P_ID');
for patient_id, patient_stats in dfgroup:
tempframe=patient_stats;
tempframe=tempframe.sort_values(by=['numdax', 'combomol'], ascending=[True, True]);
tempframe['prevnumdax']=tempframe['numdax'].shift(1);
tempframe['prevnumdax'].iloc[[0]]=0;
tempframe['interval']=tempframe.apply(lambda rx: rx['numdax']-rx['prevnumdax'], axis=1);
tempframe['ProdTransaction']=tempframe['interval'].apply(lambda rx: 'New' if rx >= 540 else '');
'''
for index, rx in tempframe.iterrows():
if int(rx['interval']) >= 540:
rx['ProdTransaction']=='New';
tempframe['firstnumdax']=rx['numdax'];
else:
rx['ProdTransaction']=='';
'''
tempframe.drop(['prevnumdax', 'interval'], axis=1);
npframe=pandas.concat([npframe, tempframe]);
print('Patient No.'+str(patient_id)+'\'s transactions flagged.');
'''
i=0;
newi=0;
for sasdate in tempframe['numdax']:
currprod=tempframe['combomol'].iloc[[i]];
if i==0:
tempframe['ProdTransaction'].iloc[[i]]='New';
prevprod=currprod;
prevdate=sasdate;
else:
if int(prevdate + 540) > int(sasdate):
if prevprod.item() == currprod.item():
tempframe['ProdTransaction'].iloc[[i]]='Repeat';
else:
tempframe['ProdTransaction'].iloc[[i]]='Switch';
else:
tempframe['ProdTransaction'].iloc[[i]]='New';
prevprod=currprod;
prevdate=sasdate;
i+=1;
npframe=pandas.concat([npframe, tempframe]);
print('Patient No.'+str(patient_id)+'\'s transactions flagged.');
'''
# ----------------- PHASE III: ii. Filter New Humira Patients ----------------
npfgroup=npframe.groupby('P_ID');
newhumirafilterframe=nonhumirafilterframe=emptyframe3;
for patient_id, patient_stats in npfgroup:
humirauser=False;
tempframe=patient_stats;
i=0;
for molecule in tempframe['combomol']:
if 'ADALIMUMAB' in str(molecule) \
and tempframe['ProdTransaction'].iloc[[i]].item()=='New':
humirauser=True;
i+=1;
i=0;
for molecule in tempframe['combomol']:
if "SER.PREREMPL 20MG ENF 2 .2ML" in tempframe['pack'].iloc[[i]].item() \
or "SOL.INJ. 40MG ENF 2 .8ML" in tempframe['pack'].iloc[[i]].item() \
or "TECFIDERA" in tempframe['prod'].iloc[[i]].item() \
or "MABTHERA" in tempframe['prod'].iloc[[i]].item():
humirauser=False;
i+=1;
if humirauser:
print('New Humira user found.');
newhumirafilterframe=pandas.concat([newhumirafilterframe, tempframe]);
else:
nonhumirafilterframe=pandas.concat([nonhumirafilterframe, tempframe]);
# ------------------ PHASE III: iii. HS/PsO Indication Split -----------------
newhumirafilterframe['Flag_Till_Now']=numpy.nan;
emptyframe6=pandas.DataFrame(columns=['combomol', 'DDMS_PHA', \
'TransactionDate', 'FCC', 'Units', \
'ShortCode','P_ID', 'TransactionMonth', \
'atc', 'prod', 'pack', 'str_unit', \
'str_meas', 'gene', 'DoctorSpeciality', \
'CU', 'PSIZE', 'numdax', 'DoctorClass', \
'PatientLevelClass', 'ProdTransaction', \
'Flag_Till_Now']);
# ----------------- PHASE III: iii. a.) September 2016 Update ----------------
hsp1frame=oldhpframe=emptyframe6;
nhffgroup=newhumirafilterframe.groupby('P_ID');
for patient_id, patient_stats in nhffgroup:
newonhumirapostsept2016=False;
tempframe=patient_stats;
i=0;
for buydate in tempframe['TransactionDate']:
if tempframe['combomol'].iloc[[i]].item()=='ADALIMUMAB' \
and tempframe['ProdTransaction'].iloc[[i]].item()=='New' \
and int(buydate) >= 20160901:
newonhumirapostsept2016=True;
elif tempframe['combomol'].iloc[[i]].item()=='ADALIMUMAB' \
and tempframe['ProdTransaction'].iloc[[i]].item()=='New' \
and int(buydate) < 20160901:
tempframe['ProdTransaction'].iloc[[i]].item()=='Old'
i+=1;
if newonhumirapostsept2016==True:
hsp1frame=pandas.concat([hsp1frame, tempframe]);
else:
oldhpframe=pandas.concat([oldhpframe, tempframe]);
# ------------- PHASE III: iii. b) Anti-TNF to PsO Classification ------------
print("Initializing Anti-TNF to PSO classification.");
hsp2frame=pso1frame=emptyframe6;
hsp1fgroup=hsp1frame.groupby('P_ID');
for patient_id, patient_stats in hsp1fgroup:
onlyhumira=True;
tempframe=patient_stats;
i=0;
for molecule in tempframe['combomol']:
if 'ADALIMUMAB' not in str(molecule):
onlyhumira=False;
i+=1;
if onlyhumira:
print("HS probable patient No."+str(patient_id)+" detected.");
hsp2frame=pandas.concat([hsp2frame, tempframe]);
else:
print("PsO Patient No."+str(patient_id)+" detected.");
pso1frame=pandas.concat([pso1frame, tempframe]);
print("Concluding Anti-TNF to PSO classification.");
# --------------- PHASE III: iii. c.) 1st Month Injections Basis -------------
print("Initializing Monthly injection based classification.");
hsp3frame=pso2frame=hs1frame=emptyframe6;
hsp2fgroup=hsp2frame.groupby('P_ID');
for patient_id, patient_stats in hsp2fgroup:
sumofunits=0;
tempframe=patient_stats;
tempframe=tempframe.sort_values(by=['numdax'], ascending=True);
i=0;
for buydate in tempframe['numdax']:
if tempframe['ProdTransaction'].iloc[[i]].item() == 'New':
firstdate=buydate;
#break;
i+=1;
i=0;
for buydate in tempframe['numdax']:
if 0 <= int(buydate - firstdate) <= 30:
#sumofunits+=int(tempframe['Units'].iloc[[i]].item());
sumofunits+=int(int(tempframe['PSIZE'].iloc[[i]].item())*int(tempframe['str_unit'].iloc[[i]].item())*int(tempframe['Units'].iloc[[i]].item()))/80;
i+=1;
if int(sumofunits) >= 3:
print("HS patient No."+str(patient_id)+" detected.");
hs1frame=pandas.concat([hs1frame, tempframe]);
elif int(sumofunits) == 2:
print("HS probable patient No."+str(patient_id)+" detected.");
hsp3frame=pandas.concat([hsp3frame, tempframe]);
else:
print("PsO patient No."+str(patient_id)+" detected.");
pso2frame=pandas.concat([pso2frame, tempframe]);
print("Concluding Monthly injection based classification.");
# --------------------- PHASE III: iii. d.) Server Access --------------------
#created hsp3masterframe including comedications for patients in hs3frame and sort by P_ID and TransactionDate/numdax
patproframe=RetrievePatientIDsfrom(hsp1frame);
patproframe.to_excel("PatientProfilePID.xlsx", sheet_name='Patient ID', index=False);
print("Exporting the patients to import master data.");
exportpatientframe=RetrievePatientIDsfrom(hsp3frame);
exportpatientframe.to_excel("ComedicationID.xlsx", sheet_name="Patient ID", index=False);
print("Exporting the patients to import patient profile data.");
'''
hsp3masterframe['Batch_ID']=numpy.nan;
hsp3masterframe['Sequence']=numpy.nan;
hsp3masterframe['BasketNumber']=numpy.nan;
hsp3masterframe['RX_ID']=numpy.nan;
hsp3masterframe['TransactionType']=numpy.nan;
hsp3masterframe['P_Gender']=numpy.nan;
hsp3masterframe['P_Loyalty']=numpy.nan;
hsp3masterframe['DCI_VOS']=numpy.nan;
'''
input("Please place the master SAS dataset (name=master1) and patient profile SAS dataset (name=patprofil) in the program's folder and press ENTER to continue.");
print("Importing Master comedication dataset.");
#importedsasfile2=input("Enter the filename of the Master SAS dataset to be imported(without ext.):")
importedsasfile2=filelocs['Address'][1];
penultimateframe=pandas.read_sas(importedsasfile2, format='sas7bdat', encoding='iso-8859-1');
penultimateframe.reset_index(drop=True);
if 'COMBOMOL' in penultimateframe.columns:
penultimateframe['combomol']=penultimateframe['COMBOMOL'];
if 'PROD' in penultimateframe.columns:
penultimateframe['prod']=penultimateframe['PROD'];
if 'PSIZE' in penultimateframe.columns:
penultimateframe['psize']=penultimateframe['PSIZE'];
if 'PACK' in penultimateframe.columns:
penultimateframe['pack']=penultimateframe['PACK'];
pufgroup=penultimateframe.groupby('P_ID');
masterframe=penultimateframe[0:0];
for patient_id_10, patient_stats_10 in pufgroup:
exception=False;
tempframe=patient_stats_10;
i=0;
for molecule in tempframe['combomol']:
if "SER.PREREMPL 20MG ENF 2 .2ML" in str(tempframe['pack'].iloc[[i]].item()) \
or "SOL.INJ. 40MG ENF 2 .8ML" in str(tempframe['pack'].iloc[[i]].item()) \
or "TECFIDERA" in str(tempframe['prod'].iloc[[i]].item()) \
or "MABTHERA" in str(tempframe['prod'].iloc[[i]].item()):
exception=True;
i+=1;
if exception:
continue;
else:
masterframe=pandas.concat([masterframe, tempframe]);
for index, row in masterframe.iterrows():
if str(masterframe['combomol'].loc[index])=='ADALIMUMAB':
masterframe=masterframe.drop(index=[index]);
masterframe2=masterframe[0:0];
masterfgroup=masterframe.groupby('P_ID');
for patient_id_ex in exportpatientframe['P_ID']:
for patient_id_master, tempframe_master in masterfgroup:
if patient_id_ex == patient_id_master:
masterframe2=pandas.concat([masterframe2, tempframe_master]);
hsp3masterframe=pandas.concat([masterframe2, hsp3frame], sort=True);
patproframe=RetrievePatientIDsfrom(hsp1frame);
patproframe.to_excel("PatProFrame.xlsx", sheet_name='PatProfil', index=False);
'''
hsp3masterframe=pandas.merge(hsp3frame, masterframe, \
how='outer', \
left_on=['combomol', 'DDMS_PHA', \
'TransactionDate', 'FCC', 'Units', \
'ShortCode', 'P_ID', 'prod', 'pack', \
'PSIZE'], \
right_on=['combomol', 'DDMS_PHA', \
'TransactionDate', 'FCC', 'Units', \
'ShortCode', 'P_ID', 'prod', 'pack', \
'psize']);
mfgroup=masterframe.groupby('P_ID');
hsp3fgroup=hsp3frame.groupby('P_ID');
for patient_id_1, patient_stats_1 in hsp3fgroup:
for patient_id_2, patient_stats_2 in mfgroup:
if patient_id_1 == patient_id_2:
tempframe=patient_stats_2;
hsp3masterframe=pandas.concat([hsp3masterframe, tempframe]);
else:
continue;
print("Combined Master comedication dataset with the original.");
'''
# - PHASE III: iii. e.) Antibiotic:Tetracycline & Rifampicin + Clindampicine -
print("Initializing Antibiotic check on comedication.");
emptyframe7=pandas.DataFrame(columns=['Batch_ID', 'Sequence', 'BasketNumber', \
'RX_ID', 'TransactionType', 'P_Gender', \
'P_Loyalty', 'DCI_VOS', 'combomol', \
'DDMS_PHA', 'TransactionDate', 'FCC', \
'Units', 'ShortCode','P_ID', \
'TransactionMonth', 'atc', 'prod', \
'pack', 'str_unit','str_meas', 'gene', \
'DoctorSpeciality', 'CU', 'PSIZE', \
'psize', 'numdax', 'DoctorClass', \
'PatientLevelClass', 'ProdTransaction', \
'Flag_Till_Now']);
hsp4frame=hs2frame=emptyframe7;
hsp3mfgroup=hsp3masterframe.groupby('P_ID');
for patient_id, patient_stats in hsp3mfgroup:
antibiotic1=antibiotic2=pre_clindamycin=pre_rifampicin=False;
combidate=-1;
tempframe=patient_stats;
tempframe=tempframe.sort_values(by=['TransactionDate'], ascending=True);
i=0;
for molecule in tempframe['combomol']:
if 'ADALIMUMAB' in str(molecule) \
and tempframe['ProdTransaction'].iloc[[i]].item() == 'New':
firstdate=tempframe['TransactionDate'].iloc[[i]].item();
i+=1;
i=0;
for buydate in tempframe['TransactionDate']:
if 'TETRACYCLINE' in str(tempframe['prod'].iloc[[i]].item()) \
or 'TETRACYCLINE' in str(tempframe['combomol'].iloc[[i]].item()) \
or 'LYMECYCLINE' in str(tempframe['prod'].iloc[[i]].item()) \
or 'LYMECYCLINE' in str(tempframe['combomol'].iloc[[i]].item()) \
or 'MINOCYCLINE' in str(tempframe['prod'].iloc[[i]].item()) \
or 'MINOCYCLINE' in str(tempframe['combomol'].iloc[[i]].item()) \
or 'DOXYCYCLINE' in str(tempframe['prod'].iloc[[i]].item()) \
or 'DOXYCYCLINE' in str(tempframe['combomol'].iloc[[i]].item()):
if True: #buydate < firstdate:
antibiotic1=True;
#if 'RIFAMPICIN' in str(tempframe['combomol'].iloc[[i]].item()) \
#and buydate < firstdate:
if 'RIFAMPICIN' in str(tempframe['combomol'].iloc[[i]].item()):
transpydate=datetime.date(int(buydate/10000), \
int((buydate%10000)/100), \
int(buydate%100));
sasdate=DatePythontoSAS(transpydate);
rxd=tempframe['psize'].iloc[[i]].item()*tempframe['Units'].iloc[[i]].item();
if pre_clindamycin and combidate > sasdate:
antibiotic2=True;
break;
elif pre_rifampicin and combidate > sasdate:
combidate=combidate+rxd;
else:
combidate=sasdate+rxd;
pre_rifampicin=True;
pre_clindamycin=False;
#if 'CLINDAMYCIN' in str(tempframe['combomol'].iloc[[i]].item()) \
#and buydate < firstdate:
if 'CLINDAMYCIN' in str(tempframe['combomol'].iloc[[i]].item()):
transpydate=datetime.date(int(buydate/10000), \
int((buydate%10000)/100), \
int(buydate%100));
sasdate=DatePythontoSAS(transpydate);
rxd=tempframe['psize'].iloc[[i]].item()*tempframe['Units'].iloc[[i]].item();
if pre_clindamycin and combidate > sasdate:
combidate=combidate+rxd;
elif pre_rifampicin and combidate > sasdate:
antibiotic2=True;
break;
else:
combidate=sasdate+rxd;
pre_clindamycin=True;
pre_rifampicin=False;
i+=1;
if antibiotic1 == True:
print("HS patient No."+str(patient_id)+" with Tetracyclins detected.");
hs2frame=pandas.concat([hs2frame, tempframe]);
elif antibiotic2 == True:
print("HS patient No."+str(patient_id)+" with CLINDAMYCIN + RIFAMPICIN detected.");
hs2frame=pandas.concat([hs2frame, tempframe]);
else:
print("HS probable patient No."+str(patient_id)+" detected.");
hsp4frame=pandas.concat([hsp4frame, tempframe]);
print("Concluding Antibiotic check on comedication.");
# -------------- PHASE III: iii. f.) Methotrexate & Cyclosporine -------------
print("Initiializing Methotrexate & Cyclosporine check on comedication.");
hsp5frame=pso3frame=emptyframe7;
hsp4fgroup=hsp4frame.groupby('P_ID');
for patient_id, patient_stats in hsp4fgroup:
psopositive=False;
tempframe=patient_stats;
tempframe=tempframe.sort_values(by=['TransactionDate'], ascending=True);
i=0;
for molecule in tempframe['combomol']:
if 'ADALIMUMAB' in str(molecule) \
and tempframe['ProdTransaction'].iloc[[i]].item() == 'New':
firstdate=tempframe['TransactionDate'].iloc[[i]].item();
i+=1;
i=0;
for buydate in tempframe['TransactionDate']:
#if 'METHOTREXATE' in str(tempframe['combomol'].iloc[[i]].item()) \
#and buydate < firstdate:
if 'METHOTREXATE' in str(tempframe['combomol'].iloc[[i]].item()):
psopositive=True;
#if 'CICLOSPORIN' in str(tempframe['combomol'].iloc[[i]].item()) \
#and buydate < firstdate:
if 'CICLOSPORIN' in str(tempframe['combomol'].iloc[[i]].item()):
psopositive=True;
i+=1;
if psopositive:
print("PsO patient No."+str(patient_id)+" detected.");
pso3frame=pandas.concat([pso3frame, tempframe]);
else:
print("HS probable patient No."+str(patient_id)+" detected.");
hsp5frame=pandas.concat([hsp5frame, tempframe]);
print("Concluding Methotrexate & Cyclosporine check on comedication.");
# ---------------------- PHASE III: iii. g.) Isobetadine --------------------
print("Initializing Iso-betadine check on comedication.");
hsp6frame=hs3frame=emptyframe7;
hsp5fgroup=hsp5frame.groupby('P_ID');
for patient_id, patient_stats in hsp5fgroup:
hspositive=False;
tempframe=patient_stats;
tempframe=tempframe.sort_values(by=['TransactionDate'], ascending=True);
i=0;
for molecule in tempframe['combomol']:
if 'ADALIMUMAB' in str(molecule) \
and tempframe['ProdTransaction'].iloc[[i]].item() == 'New':
firstdate=tempframe['TransactionDate'].iloc[[i]].item();
i+=1;
i=0;
for buydate in tempframe['TransactionDate']:
if 'ISO-BETADINE' in str(tempframe['combomol'].iloc[[i]].item()) \
or 'ISO-BETADINE' in str(tempframe['prod'].iloc[[i]].item()):
if buydate >= firstdate:
hspositive=True;
i+=1;
if hspositive:
print("HS patient No."+str(patient_id)+" detected.");
hs3frame=pandas.concat([hs3frame, tempframe]);
else:
print("HS probable patient No."+str(patient_id)+" detected.");
hsp6frame=pandas.concat([hsp6frame, tempframe]);
print("Concluding Iso-betadiene check on comedication.");
# ----------------- PHASE III: iii. h.) Psoriasis Only Drugs -----------------
print("Initializing Psoriasis-only drug check on comedication.");
hsp7frame=pso4frame=emptyframe7;
hsp6fgroup=hsp6frame.groupby('P_ID');
psoonlydrugs=pandas.read_excel('Biologics_Humira_HS-PSO_Program_Settings.xlsx', \
sheet_name='PsoriasisOnlyDrugs');
for patient_id, patient_stats in hsp6fgroup:
tempframe=patient_stats;
psopositive=False;
for molecule in tempframe['combomol']:
for drug in psoonlydrugs['PsoriasisOnlyDrugs']:
if str(drug) in str(molecule):
psopositive=True;
for product in tempframe['prod']:
for drug in psoonlydrugs['PsoriasisOnlyDrugs']:
if str(drug) in str(product):
psopositive=True;
if psopositive:
print("PsO patient No."+str(patient_id)+" detected.");
pso4frame=pandas.concat([pso4frame, tempframe]);
else:
print("HS probable patient No."+str(patient_id)+" detected.");
hsp7frame=pandas.concat([hsp7frame, tempframe]);
print("Concluding Psoriasis-only drug check on comedication.");
# ---------------- PHASE III: iii. i.) 3 month Injection Basis ---------------
print("Initializing Tri-monthly injection based classification.");
hsp8_1frame=hsp8_2frame=newhspframe=newpsoframe=newhsframe=emptyframe7;
hsp1fgroup=hsp1frame.groupby('P_ID');
for patient_id, patient_stats in hsp1fgroup:
plus3months=False;
tempframe=patient_stats;
tempframe=tempframe.sort_values(by=['TransactionDate'], ascending=True);
i=0;
for molecule in tempframe['combomol']:
if 'ADALIMUMAB' in str(molecule) \
and tempframe['ProdTransaction'].iloc[[i]].item() == 'New':
firstdate=tempframe['TransactionDate'].iloc[[i]].item();
transdate=firstdate;
transpydate=datetime.date(int(transdate/10000), \
int((transdate%10000)/100), \
int(transdate%100));
firstsasdate=DatePythontoSAS(transpydate);
#break;
i+=1;
i=0;
for buydate in tempframe['TransactionDate']:
itransdate=buydate;
itranspydate=datetime.date(int(itransdate/10000), \