-
Notifications
You must be signed in to change notification settings - Fork 0
/
Her2Unstruct.py
1410 lines (1331 loc) · 73 KB
/
Her2Unstruct.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 pandas as pd
# For regex
import re
from MetaMapForLots import metamapstringoutput
# Display everything
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 150)
# Now beginning the sorting out!
pathReports = pd.read_csv("/Users/bholmes/Desktop/LatestNLP/MSMDRO_Narratives/March2020HFHS.csv", low_memory=False)
# Use this to truncate huge files for quicker testing
#pathReports = pd.read_csv("/Users/bholmes/Desktop/LatestNLP/MSMDRO_Narratives/TruncatedJan2020.csv", low_memory=False)
#truncated = pathReports.iloc[5000000:]
#truncated.to_csv("~/Desktop/LatestNLP/MSMDRO_Narratives/TruncatedJan2020.csv", index=False)
#print("LOADED!")
#input()
# The lists for the file
firstNameList = []
middleNameList = []
lastNameList = []
mrnList = []
dobList = []
accessionList = []
testTextList = []
fullTextList = []
testTypeList = []
testTechList = []
sampleLocationList = []
pathologistList = []
dateOrderedList = []
dateReportedList = []
icdCodeList = []
patientIdList = []
reportIdList = []
# These will hold the metamap 4-tuple. We'll move column mapping to another function!
biomarkerResultList = []
conceptResultList = []
numericResultList = []
qualifierResultList = []
storedLen = 0
# Wrongway tests are those ones that aren't even path reports - distinguised by not having 'patient name' as a field.
# Aberrent tests are those that don't follow expected patterns. We're expecting formatting that we're not finding.
# Failed tests are ones that break either the NLP or this script entirely. The original run (of the 350k tests) will have 0 of these. Keep new ones for analysis!
# Extra tests are those that still have the biomarker in question in the report text by the end.
aberrentTests = []
aberrentReasons = []
wrongwayTests = []
wrongwayReasons = []
extraTests = []
failedTests = []
failedReasons = []
# To avoid typing this out every time for every test, we'll define a method here.
def standardAppends(fname, mname, lname, mrnf, dobf, acc, ttype, sloc, path, dorder, dreport, ttext, ftext, ficd, frid, fpid):
firstNameList.append(fname)
middleNameList.append(mname)
lastNameList.append(lname)
mrnList.append(mrnf)
dobList.append(dobf)
accessionList.append(acc)
testTypeList.append(ttype)
sampleLocationList.append(sloc)
pathologistList.append(path)
dateOrderedList.append(dorder)
dateReportedList.append(dreport)
testTextList.append(ttext)
fullTextList.append(ftext)
icdCodeList.append(ficd)
reportIdList.append(frid)
patientIdList.append(fpid)
# These values are specific per test. We don't want to persist one sample location between samples. So reset!
def resetDerived():
global pathologist
global orderedDate
global reportedDate
global sampleLocation
pathologist = ''
orderedDate = ''
reportedDate = ''
sampleLocation = ''
# Also to avoid re-printing this for each test
def printResults():
print("THE RESULTS")
print(firstName)
print(lastName)
print(accession)
print(lower)
print(fullTest)
print(results)
print(lot)
print(orderedDate)
print(reportedDate)
print(sampleLocation)
print(testType)
print(testTech)
print(pathologist)
for x in range(0, len(pathReports['description'])):
#for x in range(0, 10000):
# try:
if x % 100 == 0:
print(x, ' of ', len(pathReports['description']))
patientId = pathReports['patientid'][x]
reportId = pathReports['id'][x]
# if reportId != '25be56ef-b1a0-4181-8382-3cec8f718d26':
# continue
lower = str(pathReports['description'][x]).lower()
lower = re.sub(' +', ' ', lower)
splitReport = lower.split('\n')
# These reports are truncated and don't contain info - NONE have 'her 2' or 'her2' or 'her-2'
if 'patient name:' not in lower:
wrongwayTests.append(lower)
wrongwayReasons.append('no Patient')
continue
# We'll pull out the MRN
try:
mrnIndex = lower.index("rec.:")
except Exception as e:
# There's only one kind without a rec.:, and it's a regadenoson pharmacological stress myocardial perfusion study
wrongwayTests.append(lower)
wrongwayReasons.append('no MRN')
continue
MRN = lower[mrnIndex + 5:mrnIndex + 14].strip()
# And the ICD codes - we'll also delete anything that's like a: b:
try:
icdIndex = lower.index('icd code(s):') + len('icd code(s):')
icdPart = lower[icdIndex:].replace('\n', ' ')
icdPart = icdPart[:icdPart.index('billing fee')]
except:
icdPart = ''
icdCode = icdPart.strip()
icdLists = re.findall('\s[a-z]\:\s', icdCode)
for icd in icdLists:
icdCode = icdCode.replace(icd, ' ')
icdCode = ', '.join(list(dict.fromkeys(icdCode.split())))
# And the name
nameIndex = lower.index('name:')
endName = lower.index('accession')
nameBit = lower[nameIndex + 5: endName]
firstName = nameBit.split(',')[1].strip()
lastName = nameBit.split(',', )[0].strip()
middleName = ''
if len(firstName.split()) > 1:
middleName = firstName.split()[1]
firstName = firstName.split()[0]
# And the accession
accession = lower[endName + len('accession #:'):mrnIndex - 5].strip()
# And the DOB
dobindex = lower.index('dob:')
enddod = lower.index('(age')
dob = lower[dobindex + 4:enddod].strip()
index = [idx for idx, s in enumerate(splitReport) if 'patient name:' in s][0]
indexTT = index - 1
testType = splitReport[indexTT]
# Pull out test type
while testType == '' or 'amended' in testType.lower() or testType.lower().replace('-', '') == '':
indexTT = indexTT - 1
testType = splitReport[indexTT].strip()
if testType.endswith('.'):
testType = testType[:-1]
testTypeOrig = testType
if 'her2' in lower or 'her-2' in lower or 'her 2' in lower:
# We want to remove all 'test description's, because they can contain the strings of the biomarkers we're looking for, and they don't matter!
# Pull these out later if you want the test descriptions!
while 'test description:' in lower:
firstInstance = re.search(r"test description:", lower)
testDescription = lower[firstInstance.start():]
paragraphBreak = re.search('\n\n', testDescription)
testDesString = lower[firstInstance.start():firstInstance.start() + paragraphBreak.start()]
lower = '\n'.join(lower.split(testDesString))
# Alright, now we're gonna get them.
barlower = lower.replace('\n', '|').replace('her-2', 'her2').replace('over expression', 'overexpression')
spacelower = lower
lower = lower.replace('\n', '|').replace('her-2', 'her2').replace('over expression', 'overexpression')
# I'm shifting this from an 'if' to a 'while', so that if there's any errors, we only delete the one section in question, instead of the whole test.
while 'her2/ neu protein assay (ihc)' in lower:
resetDerived()
print("her2/ new protein assay")
print(lower)
#input()
testStarts = []
testEnds = []
testType = 'her2/neu protein assay (ihc)'
testTech = 'ihc'
opener = lower.index('her2/ neu protein assay (ihc)')
fullTest = lower[opener:]
if 'pathologist|' in fullTest:
fullTestEnd = fullTest.index('pathologist|')
fullTest = fullTest[:fullTestEnd + len('pathologist')]
else:
aberrentTests.append(fullTest)
aberrentReasons.append('no pathologist')
lower = lower[:opener] + lower[opener+len('her2/neu protein assay (ihc)'):]
continue
testStarts.append(opener)
testEnds.append(opener + fullTestEnd)
if 'date ordered:' in fullTest:
orderedDate = re.search('date ordered: ', fullTest)
orderedDateEnd = re.search('date reported: ', fullTest)
orderedDate = fullTest[orderedDate.start() + len("date ordered: "): orderedDateEnd.start()].strip()
reportedDate = re.search('date reported: ', fullTest)
try:
reportedDateEnd = re.search('\|', fullTest[reportedDate.start():])
except Exception as e:
aberrentTests.append(fullTest)
aberrentReasons.append('dates missing')
lower = lower[:opener] + lower[opener + len('her2/neu protein assay (ihc)'):]
continue
try:
reportedDate = fullTest[reportedDate.start() + len("date reported: "): reportedDate.start() + reportedDateEnd.start()].strip()
except Exception as e:
aberrentTests.append(fullTest)
aberrentReasons.append('dates missing')
lower = lower[:opener] + lower[opener + len('her2/neu protein assay (ihc)'):]
continue
if 'pending' in reportedDate:
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, sampleText, lower, icdCode, reportId,
patientId)
biomarkerResultList.append('her2')
conceptResultList.append('')
numericResultList.append('')
qualifierResultList.append('pending')
lower = lower[:opener] + lower[opener + len('her2/neu protein assay (ihc)'):]
continue
pathologist = re.search('out\*\*\*\|', fullTest)
pathologist = fullTest[pathologist.start() + len('out***|'):].strip()
else:
orderedDate = ''
reportedDate = ''
# Now let's find all the samples:
samples = re.finditer('\|[a-z]\.\s', fullTest)
for sample in samples:
sampleText = fullTest[sample.end():]
try:
sampleEnd = sampleText.index(': ')
except Exception as e:
continue
# We'll pull out the location of the sample here
sampleLocation = sampleText[:sampleEnd]
sampleText = sampleText[sampleEnd + 2:]
# Now we separate the two types!
if 'ki-67' in sampleText:
sampleTextStart = sampleText.index('mib1')
sampleTextEnd = sampleText.index('|||')
sampleText = sampleText[sampleTextStart:sampleTextEnd]
sampleText = sampleText.replace('|', ' ')
else:
try:
sampleTextStart = sampleText.index('interpretation: ')
except Exception as e:
sampleTextStart = 0
try:
sampleTextEnd = sampleText.index('results: ')
except Exception as e:
if 'protein.' in sampleText:
sampleTextEnd = sampleText.index('protein.') + len('protein.')
else:
aberrentTests.append('sampleText')
aberrentReasons.append('no results')
continue
sampleText = sampleText[sampleTextStart:sampleTextEnd]
sampleText = sampleText.replace('|', ' ')
linesOfTest = sampleText.split('|')
for lot in linesOfTest:
lot = lot + "\n"
if lot == '' or len(lot.strip()) == 0:
continue
file = '/Users/bholmes/Desktop/DeleteMeSoon/orus/MetaMapInput/sampleInput'
with open(file, 'w') as filetowrite:
filetowrite.write(lot)
results = metamapstringoutput()
# Turn this on to print results
#printResults()
#input()
# Turn this on to look at the whole test
# print(spacelower)
# #input()
for index, row in results.iterrows():
bioResult = ', '.join(row['Biomarker'])
conResult = ', '.join(row['Concept'])
numResult = ', '.join(row['Numeric'])
qualResult = ', '.join(row['Qualifier'])
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, lot, lower, icdCode, reportId,
patientId)
biomarkerResultList.append(bioResult)
conceptResultList.append(conResult)
numericResultList.append(numResult)
qualifierResultList.append(qualResult)
# Now we're going to snip all those tests out of the overall report!
sampleLocation = ''
testStarts.reverse()
testEnds.reverse()
for h in range(0, len(testStarts)):
lower = lower[:testStarts[h]] + lower[testEnds[h]:]
while 'her2/ neu gene amplification (fish) assay' in lower:
resetDerived()
print("her2/ neu gene amplification (fish) assay")
print(lower)
#input()
testStarts = []
testEnds = []
testType = 'her2/neu gene amplification (fish) assay'
testTech = 'fish'
opener = lower.index('her2/ neu gene amplification (fish) assay')
testStart = opener
fullTest = lower[testStart:]
if 'pathologist|' in fullTest:
fullTestEnd = fullTest.index('pathologist|')
else:
aberrentTests.append(fullTest)
aberrentReasons.append('no pathologist')
lower = lower[:opener] + lower[opener + len('her2/ neu gene amplification (fish) assay'):]
continue
testStarts.append(testStart)
testEnds.append(testStart + fullTestEnd)
fullTest = fullTest[:fullTestEnd + len('pathologist')]
if 'date ordered:' in fullTest:
if 'date reported:' in fullTest:
orderedDate = re.search('date ordered:', fullTest)
reportedDateText = 'date reported:'
orderedDateEnd = re.search('date reported:', fullTest)
reportedDate = re.search('date reported:', fullTest)
elif 'status:' in fullTest:
orderedDate = re.search('date ordered:', fullTest)
reportedDateText = 'status:'
orderedDateEnd = re.search('status:', fullTest)
reportedDate = re.search('status:', fullTest)
reportedDateEnd = re.search('\|', fullTest[reportedDate.start():])
try:
orderedDate = fullTest[orderedDate.start() + len('date ordered:'): orderedDateEnd.start()].strip()
reportedDate = fullTest[reportedDate.end(): reportedDate.start() + reportedDateEnd.start()].strip()
while orderedDate.endswith('|'):
orderedDate = orderedDate[:-1]
while reportedDate.endswith(':') or reportedDate.endswith('|'):
reportedDate = reportedDate[:-1]
except:
aberrentTests.append(fullTest)
aberrentReasons.append('no date')
lower = lower.replace('her2/neu gene amplification (fish) assay', '')
continue
if 'pending' in reportedDate:
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, sampleText, lower, icdCode, reportId,
patientId)
biomarkerResultList.append('her2')
conceptResultList.append('')
numericResultList.append('')
qualifierResultList.append('pending')
lower = lower[:opener] + lower[opener + len('her2/ neu gene amplification (fish) assay'):]
continue
pathologist = re.search('out\*\*\*\|', fullTest)
pathologist = fullTest[pathologist.start() + len('out***|'):].strip()
else:
orderedDate = ''
reportedDate = ''
# Now let's find all the samples:
samples = re.finditer('\|[a-z]:\s', fullTest)
for sample in samples:
sampleText = fullTest[sample.end():]
try:
sampleEnd = sampleText.index('|nuc')
except Exception as e:
continue
# We'll pull out the location of the sample here
sampleLocation = sampleText[:sampleEnd]
sampleText = sampleText[sampleEnd + 2:]
# Now we separate the two types!
if 'the results' not in sampleText:
sampleTextStart = sampleText.index('nuc')
try:
sampleTextEnd = sampleText.index('a her2 to')
except Exception as e:
sampleTextEnd = sampleText.index('her2 to chromosome')
sampleText = sampleText[sampleTextStart:sampleTextEnd].replace('results-comments', '')
sampleText = sampleText.replace('per asco/cap guidelines, the average her2', '')
sampleText = sampleText.replace('signal falls in the equivocal range (>4 and <6).', '')
sampleText = sampleText.replace('the number of her2', '')
sampleText = sampleText.replace('signals per cell is >4 and <6 signals.', '')
if 'see comment' in sampleText:
firstBit = sampleText[:sampleText.index('see comment')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
elif 'comment:' in sampleText:
firstBit = sampleText[:sampleText.index('comment:')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
else:
if 'nuc' not in sampleText:
print("NO NUC")
#input()
continue
sampleTextStart = sampleText.index('nuc')
sampleTextEnd = sampleText.index('the results')
sampleText1 = sampleText[sampleTextStart:sampleTextEnd].replace('results-comments', '')
sampleTextStart2 = sampleText.index('the ratio of')
sampleTextEnd2 = sampleText.index('a her2 to')
sampleText2 = sampleText[sampleTextStart2:sampleTextEnd2].replace('results-comments', '').strip()
sampleText = sampleText1 + ' ' + sampleText2
sampleText = sampleText.replace('per asco/cap guidelines, the average her2', '')
sampleText = sampleText.replace('signal falls in the equivocal range (>4 and <6).', '')
sampleText = sampleText.replace('the number of her2', '')
sampleText = sampleText.replace('signals per cell is >4 and <6 signals.', '')
if 'see comment' in sampleText:
firstBit = sampleText[:sampleText.index('see comment')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
elif 'comment:' in sampleText:
firstBit = sampleText[:sampleText.index('comment:')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
sampleText = sampleText.replace('|', ' . ')
sampleText = sampleText.replace(' . chromosome 17', ' . . chromosome 17')
sampleText = sampleText.replace(' . aneuploidy of', ' . . aneuploidy of')
linesOfTest = sampleText.split('|')
for lot in linesOfTest:
lot = lot + "\n"
if lot == '' or len(lot.strip()) == 0:
continue
file = '/Users/bholmes/Desktop/DeleteMeSoon/orus/MetaMapInput/sampleInput'
with open(file, 'w') as filetowrite:
filetowrite.write(lot)
results = metamapstringoutput()
# Turn this on to print results
# printResults()
# #input()
# Turn this on to look at the whole test
# print(spacelower)
# #input()
ratioGenes = []
signalRatio = ''
for index, row in results.iterrows():
bioResult = ', '.join(row['Biomarker'])
conResult = ', '.join(row['Concept'])
numResult = ', '.join(row['Numeric'])
qualResult = ', '.join(row['Qualifier'])
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, lot, lower, icdCode, reportId,
patientId)
biomarkerResultList.append(bioResult)
conceptResultList.append(conResult)
numericResultList.append(numResult)
qualifierResultList.append(qualResult)
# Now we're going to snip all those tests out of the overall report!
sampleLocation = ''
testStarts.reverse()
testEnds.reverse()
for r in range(0, len(testStarts)):
lower = lower[:testStarts[r]] + lower[testEnds[r]:]
while 'her2/ neu (sish) gene amplification assay' in lower:
resetDerived()
print("her2/ neu gene amplification (sish) assay")
print(lower)
#input()
testStarts = []
testEnds = []
testType = 'her2/ neu (sish) gene amplification assay'
testTech = 'sish'
opener = lower.index('her2/ neu (sish) gene amplification assay')
testStart = opener
fullTest = lower[testStart:]
if 'pathologist|' in fullTest:
fullTestEnd = re.search('pathologist\|', fullTest)
testStarts.append(testStart)
testEnds.append(testStart + fullTestEnd.start())
else:
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, sampleText, lower, icdCode, reportId,
patientId)
biomarkerResultList.append('her2')
conceptResultList.append('')
numericResultList.append('')
qualifierResultList.append('pending')
###
# TEMP
###
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, sampleText, lower, icdCode, reportId,
patientId)
biomarkerResultList.append('her2')
conceptResultList.append('')
numericResultList.append('')
qualifierResultList.append('pending')
lower = lower[:opener] + lower[opener + len('her2/ neu (sish) gene amplification assay'):]
continue
fullTest = fullTest[:fullTestEnd.start() + len('pathologist')]
if 'date ordered:' in fullTest:
if 'date reported:' in fullTest:
orderedDate = re.search('date ordered:', fullTest)
reportedDateText = 'date reported:'
orderedDateEnd = re.search('date reported:', fullTest)
reportedDate = re.search('date reported:', fullTest)
elif 'status:' in fullTest:
orderedDate = re.search('date ordered:', fullTest)
reportedDateText = 'status:'
orderedDateEnd = re.search('status:', fullTest)
reportedDate = re.search('status:', fullTest)
reportedDateEnd = re.search('\|', fullTest[reportedDate.start():])
try:
orderedDate = fullTest[orderedDate.start() + len('date ordered:'): orderedDateEnd.start()].strip()
reportedDate = fullTest[reportedDate.end(): reportedDate.start() + reportedDateEnd.start()].strip()
while orderedDate.endswith('|'):
orderedDate = orderedDate[:-1]
while reportedDate.endswith(':') or reportedDate.endswith('|'):
reportedDate = reportedDate[:-1]
except:
aberrentTests.append(fullTest)
aberrentReasons.append('no date')
lower = lower[:opener] + lower[opener + len('her2/ neu (sish) gene amplification assay'):]
continue
if 'pending' in reportedDate:
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, sampleText, lower, icdCode, reportId,
patientId)
biomarkerResultList.append('her2')
conceptResultList.append('')
numericResultList.append('')
qualifierResultList.append('pending')
lower = lower[:opener] + lower[opener + len('her2/ neu (sish) gene amplification assay'):]
continue
pathologist = re.search('out\*\*\*\|', fullTest)
pathologist = fullTest[pathologist.start() + len('out***|'):].strip()
else:
orderedDate = ''
reportedDate = ''
# Now let's find all the samples:
samples = re.finditer('\|[a-z]:\s', fullTest)
for sample in samples:
sampleText = fullTest[sample.end():]
try:
sampleEnd = sampleText.index(')|')
except Exception as e:
continue
# We'll pull out the location of the sample here
sampleLocation = sampleText[:sampleEnd] + ')'
sampleText = sampleText[sampleEnd + 2:]
# Now we separate the two types!
if 'the results' not in sampleText:
if 'nuc' not in sampleText:
aberrentTests.append(sampleText)
aberrentReasons.append('no nuc')
continue
sampleTextStart = sampleText.index('nuc')
try:
sampleTextEnd = sampleText.index('a her2 to')
except Exception as e:
try:
sampleTextEnd = sampleText.index('her2 to chromosome')
except Exception as e:
sampleTextEnd = sampleText.index('results-comments')
sampleText = sampleText[sampleTextStart:sampleTextEnd].replace('results-comments', '')
sampleText = sampleText.replace('per asco/cap guidelines, the average her2', '')
sampleText = sampleText.replace('signal falls in the equivocal range (>4 and <6).', '')
sampleText = sampleText.replace('the number of her2', '')
sampleText = sampleText.replace('signals per cell is >4 and <6 signals.', '')
if 'see comment' in sampleText:
firstBit = sampleText[:sampleText.index('see comment')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
elif 'comment:' in sampleText:
firstBit = sampleText[:sampleText.index('comment:')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
else:
if 'nuc' not in sampleText:
aberrentTests.append(sampleText)
aberrentReasons.append('no nuc')
continue
sampleTextStart = sampleText.index('nuc')
sampleTextEnd = sampleText.index('the results')
sampleText1 = sampleText[sampleTextStart:sampleTextEnd].replace('results-comments', '')
sampleTextStart2 = sampleText.index('the ratio of')
sampleTextEnd2 = sampleText.index('a her2 to')
sampleText2 = sampleText[sampleTextStart2:sampleTextEnd2].replace('results-comments', '').strip()
sampleText = sampleText1 + ' ' + sampleText2
sampleText = sampleText.replace('per asco/cap guidelines, the average her2', '')
sampleText = sampleText.replace('signal falls in the equivocal range (>4 and <6).', '')
sampleText = sampleText.replace('the number of her2', '')
sampleText = sampleText.replace('signals per cell is >4 and <6 signals.', '')
if 'see comment' in sampleText:
firstBit = sampleText[:sampleText.index('see comment')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
elif 'comment:' in sampleText:
firstBit = sampleText[:sampleText.index('comment:')]
secondBit = sampleText[sampleText.index('her2 duplication'):]
sampleText = firstBit + ' ' + secondBit
sampleText = sampleText.replace('|', ' . ')
sampleText = sampleText.replace(' . chromosome 17', ' . . chromosome 17')
sampleText = sampleText.replace(' . aneuploidy of', ' . . aneuploidy of')
linesOfTest = sampleText.split('|')
for lot in linesOfTest:
lot = lot + "\n"
if lot == '' or len(lot.strip()) == 0:
continue
file = '/Users/bholmes/Desktop/DeleteMeSoon/orus/MetaMapInput/sampleInput'
with open(file, 'w') as filetowrite:
filetowrite.write(lot)
results = metamapstringoutput()
# Turn this on to print results
# printResults()
# #input()
# Turn this on to look at the whole test
# print(spacelower)
# #input()
ratioGenes = []
signalRatio = ''
for index, row in results.iterrows():
bioResult = ', '.join(row['Biomarker'])
conResult = ', '.join(row['Concept'])
numResult = ', '.join(row['Numeric'])
qualResult = ', '.join(row['Qualifier'])
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, lot, lower, icdCode, reportId,
patientId)
biomarkerResultList.append(bioResult)
conceptResultList.append(conResult)
numericResultList.append(numResult)
qualifierResultList.append(qualResult)
# Now we're going to snip all those tests out of the overall report!
sampleLocation = ''
testStarts.reverse()
testEnds.reverse()
if len(testStarts) == len(testEnds):
for r in range(0, len(testStarts)):
lower = lower[:testStarts[r]] + lower[testEnds[r]:]
while 'gastroesophageal biopsy her2/neu summary' in lower:
resetDerived()
#input()
testStarts = []
testEnds = []
testType = 'gastroesophageal biopsy her2/neu summary'
testTech = 'ihc'
testStart = lower.index('gastroesophageal biopsy her2/neu summary')
# We're pulling out the full segment here so we can get the pathologist and dates
# I'm assuming that the sample is the one that contains this summary in it!
samples = re.finditer(' [a-z]:\s', lower)
sampleSize = sum(1 for _ in re.finditer(' [a-z]:\s', lower))
if sampleSize > 0:
sampStart = 0
# We want the latest sample that's before the start of our test
for sam in samples:
if sampStart < sam.end() < testStart:
sampStart = sam.end()
sampleLocation = lower[sampStart:]
sampleLocation = sampleLocation[:sampleLocation.index('|')]
fullTest = lower[testStart - 100:]
else:
# If we can't find any samples, we'll just go from the start of the test
fullTest = lower
sampStart = lower.index('gastroesophageal biopsy her2/neu summary') + len('gastroesophageal biopsy her2/neu summary')
fullTestEnd = re.search('pathologist\|', fullTest)
testStarts.append(testStart)
testEnds.append(testStart + fullTestEnd.start())
fullTest = fullTest[:fullTestEnd.start() + len('pathologist')]
if 'date ordered:' in fullTest:
orderedDate = re.search('date ordered: ', fullTest)
orderedDateEnd = re.search('date reported: ', fullTest)
orderedDate = fullTest[orderedDate.start() + len("date ordered: "): orderedDateEnd.start()].strip()
reportedDate = re.search('date reported: ', fullTest)
reportedDateEnd = re.search('\|', fullTest[reportedDate.start():])
reportedDate = fullTest[reportedDate.start() + len("date reported: "): reportedDate.start() + reportedDateEnd.start()].strip()
else:
orderedDate = ''
reportedDate = ''
# We'll also pull out the name of the pathologist
signOut = re.search('out\*?', fullTest)
signOutEnd = re.search('pathologist', fullTest[signOut.start():])
pathologist = fullTest[signOut.start() + len('out***|'):].strip()
# Just a little normalization
testPart = lower[testStart:]
testEnd = re.search('\)', testPart)
testEnd = testEnd.start()
testPart = testPart[len('gastroesophageal biopsy her2/neu summary '):testEnd + 1]
testPart = testPart.strip()
testPart = testPart.replace('|interpretation:', 'interpretation: her2').replace('greater than ', '>').replace('less than', '<')
testPart = testPart.replace('|', ' ')
linesOfTest = testPart.split('|')
for lot in linesOfTest:
lot = lot + "\n"
if lot == '' or len(lot.strip()) == 0:
continue
file = '/Users/bholmes/Desktop/DeleteMeSoon/orus/MetaMapInput/sampleInput'
with open(file, 'w') as filetowrite:
filetowrite.write(lot)
results = metamapstringoutput()
# Turn this on to print results
# printResults()
# #input()
# Turn this on to look at the whole test
# print(spacelower)
# #input()
for index, row in results.iterrows():
bioResult = ', '.join(row['Biomarker'])
conResult = ', '.join(row['Concept'])
numResult = ', '.join(row['Numeric'])
qualResult = ', '.join(row['Qualifier'])
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, lot, lower, icdCode, reportId,
patientId)
biomarkerResultList.append(bioResult)
conceptResultList.append(conResult)
numericResultList.append(numResult)
qualifierResultList.append(qualResult)
bioResult = ''
conResult = ''
numResult = ''
qualResult = ''
# Now we're going to snip all those tests out of the overall report!
testStarts.reverse()
testEnds.reverse()
for w in range(0, len(testStarts)):
lower = lower[:testStarts[w]] + lower[testEnds[w]:]
while 'her2 (results' in lower:
resetDerived()
print("her2 (results")
print(lower)
#input()
testStarts = []
testEnds = []
# Get the next ':'
testPart = lower.index('her2 (results')
testPart = lower[testPart:]
while testPart.index('|') < testPart.index(':'):
ind = testPart.index('|')
testPart = testPart[:ind] + ' ' + testPart[ind + 1:]
testPart = testPart[:testPart.index('|')]
testStarts.append(lower.index('her2 (results'))
testEnds.append(lower.index('her2 (results') + len(testPart))
testType = testTypeOrig
testTech = ''
testStart = re.search('her2 \(results', lower)
# We're pulling out the full segment here so we can get the pathologist and dates
testStart = testStart.start()
# I'm assuming that the sample is the one that contains this summary in it!
samples = re.finditer(' [a-z]:\s', lower)
sampStart = 0
# We want the latest sample that's before the start of our test
for sam in samples:
if sam.end() > sampStart and sam.end() < testStart:
sampStart = sam.end()
sampleLocation = lower[sampStart:]
sampleLocation = sampleLocation[:sampleLocation.index('|')]
testPart = 'her2 ' + testPart[testPart.index(':') + 1:]
linesOfTest = testPart.split('|')
for lot in linesOfTest:
lot = lot + "\n"
if lot == '' or len(lot.strip()) == 0:
continue
file = '/Users/bholmes/Desktop/DeleteMeSoon/orus/MetaMapInput/sampleInput'
with open(file, 'w') as filetowrite:
filetowrite.write(lot)
results = metamapstringoutput()
# Turn this on to print results
# printResults()
# #input()
# Turn this on to look at the whole test
# print(spacelower)
# #input()
for index, row in results.iterrows():
bioResult = ', '.join(row['Biomarker'])
conResult = ', '.join(row['Concept'])
numResult = ', '.join(row['Numeric'])
qualResult = ', '.join(row['Qualifier'])
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, lot, lower, icdCode, reportId,
patientId)
biomarkerResultList.append(bioResult)
conceptResultList.append(conResult)
numericResultList.append(numResult)
qualifierResultList.append(qualResult)
# Now we're going to snip all those tests out of the overall report!
# Now remove that title from the report!
lower = lower[:lower.index('her2 (results')] + lower[lower.index('her2 (results')+len('her2 (results'):]
while 'submitted her2 immunostain' in lower:
resetDerived()
print("submitted her2 immunostain")
print(lower)
#input()
testStarts = []
testEnds = []
# Get the next ':'
testPart = lower.index('submitted her2 immunostain')
testPart = lower[testPart:]
testPart = testPart[:testPart.index('staff pathologist') + len('staff pathologist')]
pathologist = re.search('out\*\*\*\|', fullTest)
pathologist = fullTest[pathologist.start() + len('out***|'):].strip()
testType = testTypeOrig
testStarts.append(lower.index('submitted her2 immunostain'))
testEnds.append(lower.index('submitted her2 immunostain') + + len(testPart))
testTech = ''
testStart = re.search('submitted her2 immunostain', lower)
# We're pulling out the full segment here so we can get the pathologist and dates
testStart = testStart.start()
# I'm assuming that the sample is the one that contains this summary in it!
samples = re.finditer(' [a-z]:\s', lower)
sampStart = 0
# We want the latest sample that's before the start of our test
for sam in samples:
if sam.end() > sampStart and sam.end() < testStart:
sampStart = sam.end()
sampleLocation = lower[sampStart:]
sampleLocation = sampleLocation[:sampleLocation.index('|')]
testPart = testPart[:testPart.index('|')]
linesOfTest = testPart.split('|')
for lot in linesOfTest:
lot = lot + "\n"
if lot == '' or len(lot.strip()) == 0:
continue
file = '/Users/bholmes/Desktop/DeleteMeSoon/orus/MetaMapInput/sampleInput'
with open(file, 'w') as filetowrite:
filetowrite.write(lot)
results = metamapstringoutput()
# Turn this on to print results
# printResults()
# #input()
# Turn this on to look at the whole test
# print(spacelower)
# #input()
for index, row in results.iterrows():
bioResult = ', '.join(row['Biomarker'])
conResult = ', '.join(row['Concept'])
numResult = ', '.join(row['Numeric'])
qualResult = ', '.join(row['Qualifier'])
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, lot, lower, icdCode, reportId,
patientId)
biomarkerResultList.append(bioResult)
conceptResultList.append(conResult)
numericResultList.append(numResult)
qualifierResultList.append(qualResult)
# Now we're going to snip all those tests out of the overall report!
# Now remove that title from the report!
lower = lower[:lower.index('submitted her2 immunostain')] + lower[lower.index('submitted her2 immunostain')+len('submitted her2 immunostain'):]
while 'in situ hybridization (fish or cish) for her2' in lower:
resetDerived()
print("in situ hybridization (fish or cish)")
print(lower)
#input()
testStarts = []
testEnds = []
# Get the next ':'
testPart = lower.index('in situ hybridization (fish or cish) for her2') + len('in situ hybridization (fish or cish) for her2')
testPart = lower[testPart:]
testPart = testPart[:testPart.index('(')]
pathologist = ''
testType = testTypeOrig
testStarts.append(lower.index('in situ hybridization (fish or cish) for her2'))
testEnds.append(lower.index('in situ hybridization (fish or cish) for her2') + len('in situ hybridization (fish or cish) for her2') + len(testPart))
testTech = 'fish or cish'
testStart = re.search('in situ hybridization \(fish or cish\) for her2', lower)
# We're pulling out the full segment here so we can get the pathologist and dates
testStart = testStart.start()
# I'm assuming that the sample is the one that contains this summary in it!
samples = re.finditer(' [a-z]:\s', lower)
sampStart = 0
# We want the latest sample that's before the start of our test
for sam in samples:
if sam.end() > sampStart and sam.end() < testStart:
sampStart = sam.end()
sampleLocation = lower[sampStart:]
sampleLocation = sampleLocation[:sampleLocation.index('|')]
testPart = 'her2' + testPart
testPart = testPart.replace('amplified', 'amplification')
linesOfTest = testPart.split('|')
for index, row in results.iterrows():
bioResult = ', '.join(row['Biomarker'])
conResult = ', '.join(row['Concept'])
numResult = ', '.join(row['Numeric'])
qualResult = ', '.join(row['Qualifier'])
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, lot, lower, icdCode, reportId,
patientId)
biomarkerResultList.append(bioResult)
conceptResultList.append(conResult)
numericResultList.append(numResult)
qualifierResultList.append(qualResult)
# Now we're going to snip all those tests out of the overall report!
# Now remove that title from the report!
lower = lower[:lower.index('in situ hybridization (fish or cish) for her2')] + lower[lower.index('in situ hybridization (fish or cish) for her2')+len('in situ hybridization (fish or cish) for her2'):]
while 'her2/neu is negative (' in lower or 'her2/neu is positive (' in lower or 'her2/neu is equivocal (' in lower:
resetDerived()
print("HER2 IS A THING PAREN")
testStarts = []
testEnds = []
testPart = lower.index('her2/neu is')
testStarts.append(testPart)
testPart = lower[testPart:]
if 'staff pathologist' not in testPart:
testPart = testPart[:testPart.index('||') + len('||')]
else:
testPart = testPart[:testPart.index('staff pathologist') + len('staff pathologist')]
testEnds.append(lower.index('her2/neu is') + len(testPart))
fullTest = testPart
sampleText = testPart
pathologist = re.search('out\*\*\*\|', testPart)
if not pathologist:
pathologist = ''
else:
pathologist = testPart[pathologist.start() + len('out***|'):].strip()
pathologist = pathologist.split('|')
realPathologist = ''
for p in pathologist:
if 'pathologist' in p:
pathologist2 = p
pathologist = p
testPart = testPart[testPart.index('is ') + len('is '):testPart.index('(')]
sampleLocation = ''
testType = 'Clinical History'
testTech = ''
orderedDate = ''
reportedDate = ''
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, sampleText, lower, icdCode, reportId,
patientId)
biomarkerResultList.append('her2')
conceptResultList.append('presence')
numericResultList.append('')
qualifierResultList.append(testPart)
###
# TEMP
###
standardAppends(firstName, middleName, lastName, MRN, dob, accession, testType, sampleLocation, pathologist, orderedDate, reportedDate, sampleText, lower, icdCode, reportId,
patientId)
biomarkerResultList.append('her2')
conceptResultList.append('presence')
numericResultList.append('')
qualifierResultList.append(testPart)
# Now we're going to snip all those tests out of the overall report!
testStarts.reverse()
testEnds.reverse()
for d in range(0, len(testStarts)):
lower = lower[:testStarts[d]] + lower[testEnds[d]:]
while 'her2/neu is negative ' in lower or 'her2/neu is positive ' in lower or 'her2/neu is equivocal ' in lower:
resetDerived()
print("HER2 IS A THING NO PAREN")
print(lower)
#input()
testStarts = []
testEnds = []
testPart = lower.index('her2/neu is')
testStarts.append(testPart)
testPart = lower[testPart:]
testPart = testPart[:testPart.index('staff pathologist') + len('staff pathologist')]
testEnds.append(lower.index('her2/neu is') + len(testPart))
fullTest = testPart
if 'out***' in testPart:
pathologist = re.search('out\*\*\*\|', testPart)
pathologist = testPart[pathologist.start() + len('out***|'):].strip()
else:
testSplit = testPart.split('|')
for ts in testSplit:
if 'staff pathologist' in ts:
pathologist = ts
testPart = testPart[testPart.index('is ') + len('is '):testPart.index('|')]
sampleLocation = ''
testType = testTypeOrig
testTech = ''
orderedDate = ''
reportedDate = ''