forked from MingzheHu-Duke/deid2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deid.pl
5414 lines (4556 loc) · 187 KB
/
deid.pl
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/perl
#**************************************************************************************************************
#file: deid.pl Original author: M. Douglass 2004
#Last revised: Apr 2009 DeID 1.1
#
#
#_______________________________________________________________________________
#
#deid.pl: De-identification algorithm -- scrubs PHI from free-text medical records
#(e.g. Discharge Summaries and Nursing Notes)
#
#Copyright (C) 2004-2007 Margaret Douglas and Ishna Neamatullah
#
#This code is free software; you can redistribute it and/or modify it under
#the terms of the GNU Library General Public License as published by the Free
#Software Foundation; either version 2 of the License, or (at your option) any
#later version.
#
#This library is distributed in the hope that it will be useful, but WITHOUT ANY
#WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
#PARTICULAR PURPOSE. See the GNU Library General Public License for more
#details.
#
#You should have received a copy of the GNU Library General Public License along
#with this code; if not, write to the Free Software Foundation, Inc., 59
#Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#You may contact the author by e-mail or postal mail
#(MIT Room E25-505, Cambridge, MA 02139 USA). For updates to this software,
#please visit PhysioNet (http://www.physionet.org/).
#_______________________________________________________________________________
#
# De-identification Algorithm: Scrubs PHI from free-text medical records
#(e.g. Discharge Summaries and Nursing Notes)
# Original version written by:
# Margaret Douglass (douglass AT alum DOT mit DOT edu)
# William Long (wjl AT mit DOT edu)
# Modified by:
# Ishna Neamatullah (ishna AT alum DOT mit DOT edu) in Sept 5, 2006
# Last modified by:
# Li-wei Lehman (lilehman AT alum DOT mit DOT edu) in April, 2009
#
# Command to run the software:
# perl deid.pl <filename> <config_filename>
#
# Input arguments:
# filename (without extension, where extension must be .text): file to be de-identified
# config_filename: configuration file
#
# Required library file: stat.pm
#
# Output files:
# filename.res: de-identified file
# filename.phi: file containing all PHI locations, used in calculating performance statistics
# filename.info: file containing information useful for debugging
# code performance statistics printed on screen if Gold Standard available for nursing notes (details in README)
#**************************************************************************************************************
#use Stat;
# Declaring some variables for algorithm run configuration
# Variables to switch on/off filter functions
$allfilters = "";
$ssnfilter = "";
$urlfilter = "";
$emailfilter = "";
$telfilter = "";
$unitfilter = "";
$agefilter = "";
$locfilter = "";
$datefilter = "";
$namefilter = "";
$us_state_filter = "";
$ds_specific_filter = ""; #filter for discharge summmary specific patterns
$gs_specific_filter = ""; #filter for gold std specific patterns
my $offset; # positive date shift in number of days
my $comparison = ""; # 1=comparison with gold standard, 0=no comparison with gold standard
# Variables to switch on/off dictionaries/lists
$alllists = "";
$pid_patientname_list = "";
$pid_dateshift_list = "";
$country_list = "";
$company_list = "";
$ethnicity_list = "";
$hospital_list = "";
$doctor_list = "";
$location_list = "";
$local_list = "";
$state_list = "";
use Time::Local;
my ($mday,$mon,$year) = (localtime(time))[3,4,5];
my $shortyear = substr($year,1,4);
my $longyear = '20'.$shortyear;
# Nursing note date as retrieved from the header
my $nn_year;
# Sets whether a de-identified version should be output: 0 = no new version of text output, 1 = fully de-identified version of text output
# Note: Generally keep output_deid_text = 1
$output_deid_text = 1;
#Default date used to de-identify the Gold Std if no default date is specified in the
#config file. You can change the default date by setting the "Default date" variable to
#some other dates (in MM/DD/YYYY format).
$DEFAULT_DATE = "01/01/2000";
#The "Two Digit Year Threshold" is used to determine whether
#to interpret the year as a year in the 1900's or 2000's.
#Must be a 1- or 2-digit number.
#Two digit years > Threshold are interepreted as in the 1900's
#Two digit years <= Threshold are interpreted as in the 2000's
$TWO_DIGIT_YEAR_THRESHOLD = 30;#change this default by setting "Two Digit Year Threshold" in config file.
# "Valid Year Low" and "Valid Year High" (must be 4-digit numbers) are
# used in certain date pattern checking routines to determine if a
# four digit number that appear in a potential
# date pattern is a year or not -- it is a valid year if it is
# in the range of [Valid Year Low, Valid Year High].
$VALID_YEAR_LOW = 1900;
$VALID_YEAR_HIGH = 2030;
my @known_phi;
my @known_first_name;
my @known_last_name;
# Hash that stores PHI information from de-identification
# KEY = (patient number), VALUE = array with each element = (%HASH with KEY = start-end, VALUE = array of types of PHI for the note number/index of the array)
%all_phi;
my %ID;
# Declares some global variables
%lhash = ();
@typename = ();
$ntype = 1;
@extend = ('phrases');
##########################################################################################
# Sets paths to lists and dictionaries in working directory that will be used in this algorithm
$date_shift_file = "shift.txt"; # contains mapping of PID to date offset
$countries_file = "lists/countries_unambig.txt";
$ethnicities_unambig_file = "lists/ethnicities_unambig.txt";
$companies_file = "lists/company_names_unambig.txt";
$companies_ambig_file = "lists/company_names_ambig.txt";
$common_words_file = "dict/common_words.txt";
$medical_words_file = "dict/sno_edited.txt";
$very_common_words_file = "dict/commonest_words.txt";
$female_unambig_file = "lists/female_names_unambig.txt";
$female_ambig_file = "lists/female_names_ambig.txt";
$female_popular_file = "lists/female_names_popular.txt";
$male_unambig_file = "lists/male_names_unambig.txt";
$male_ambig_file = "lists/male_names_ambig.txt";
$male_popular_file = "lists/male_names_popular.txt";
$last_unambig_file = "lists/last_names_unambig.txt";
$last_ambig_file = "lists/last_names_ambig.txt";
$last_popular_file = "lists/last_names_popular.txt";
#$last_name_prefixes_file = "lists/last_name_prefixes.txt";
$doctor_first_unambig_file = "lists/doctor_first_names.txt";
$doctor_last_unambig_file = "lists/doctor_last_names.txt";
$prefixes_unambig_file = "lists/prefixes_unambig.txt";
$locations_unambig_file = "lists/locations_unambig.txt";
$locations_ambig_file = "lists/locations_ambig.txt";
$local_places_ambig_file = "lists/local_places_ambig.txt";
$local_places_unambig_file = "lists/local_places_unambig.txt";
$hospital_file = "lists/stripped_hospitals.txt";
$last_name_prefix_file = "lists/last_name_prefixes.txt";
$patient_file = "lists/pid_patientname.txt"; # contains mapping of PID to patient name
$us_states_file = "lists/us_states.txt";
$us_states_abbre_file = "lists/us_states_abbre.txt";
$more_us_states_abbre_file = "lists/more_us_state_abbreviations.txt";
$us_area_code_file = "lists/us_area_code.txt";
$medical_phrases_file = "dict/medical_phrases.txt";
$unambig_common_words_file = "dict/notes_common.txt";
############################################################################################################
# Declares some arrays of context words that can be used to identify PHI
# Days of the month
@days = ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
# Titles that precede last names (ignore .'s)
@titles = ("MISTER", "DOCTOR", "DOCTORS", "MISS", "PROF", "PROFESSOR", "REV", "RABBI", "NURSE", "MD", "PRINCESS", "PRINCE", "DEACON", "DEACONESS", "CAREGIVER", "PRACTITIONER", "MR", "MS");
@strict_titles = ("Dr", "DRS", "Mrs"); #treat words after these strict_titles as PHI
%titles = ();
foreach $title (@titles){
$titles{$title} = 1;
}
# Name indicators that precede or follow names
@name_indicators = ("problem","problem:", "proxy", "daughter","daughters", "dtr", "son", "brother","sister", "mother", "mom", "father", "dad", "wife", "husband", "neice", "nephew", "spouse", "partner", "cousin", "aunt", "uncle", "granddaughter", "grandson", "grandmother", "grandmom", "grandfather", "granddad", "relative", "friend", "neighbor", "visitor", "family member", "lawyer", "priest", "rabbi", "coworker", "co-worker", "boyfriend", "girlfriend", "name is", "named", "rrt", "significant other", "jr", "caregiver", "proxys", "friends", "sons", "brothers", "sisters", "sister-in-law", "brother-in-law", "mother-in-law", "father-in-law", "son-in-law", "daughter-in-law", "dtr-in-law", "surname will be", "name will be", "name at discharge will be", "name at discharge is");
# Phrases that precede locations
@location_indicators = ("lives in", "resident of", "lived in", "lives at", "comes from", "called from", "visited from", "arrived from", "returned to");
@employment_indicators_pre = ("employee of", "employed by", "employed at", "CEO of", "manager at", "manager for", "manager of", "works at", "business");
# Hospital indicators that follow hospital names
@hospital_indicators = ("Hospital", "General Hospital", "Gen Hospital", "gen hosp", "hosp", "Medical Center", "Med Center", "Med Ctr", "Rehab", "Clinic", "Rehabilitation", "Campus", "health center", "cancer center", "development center", "community health center", "health and rehabilitation", "Medical", "transferred to", "transferred from", "transfered to", "transfered from");
# Location indicators that follow locations
@loc_indicators_suff = ("city", "town", "beach", "valley","county", "harbor", "ville", "creek", "springs", "mountain", "island", "lake", "lakes", "shore", "garden", "haven", "village", "grove", "hills", "hill", "shire", "cove", "coast", "alley", "street", "terrace", "boulevard", "parkway", "highway", "university", "college", "tower");
# Location indicators that are most likely preceded by locations
@loc_ind_suff_c = ("town", "ville", "harbor", "tower");
# Location indicators that precede locations
#@loc_indicators_pre = ("cape", "fort", "lake", "mount", "santa", "los", "great","east","west","north","south");
@loc_indicators_pre = ("cape", "fort", "lake", "mount", "santa", "los", "east","west","north","south");
@apt_indicators = ("apt", "suite"); #only check these after the street address is found
@street_add_suff = ("park", "drive", "street", "road", "lane", "boulevard", "blvd", "avenue", "highway", "circle","ave", "place", "rd", "st");
#Strict street address suffix: case-sensitive match on the following,
#and will be marked as PHI regardless of ambiguity (common words)
@strict_street_add_suff = ("Park", "Drive", "Street", "Road", "Lane", "Boulevard", "Blvd", "Avenue", "Highway","Ave",,"Rd", "PARK", "DRIVE", "STREET", "ROAD", "LANE", "BOULEVARD", "BLVD", "AVENUE", "HIGHWAY","AVE", "RD");
# Age indicators that follow ages
@age_indicators_suff = ("year old", "y\. o\.", "y\.o\.", "yo", "y", "years old", "year-old", "-year-old", "years-old", "-years-old", "years of age", "yrs of age");
# Age indicators that precede ages
@age_indicators_pre = ("age", "he is", "she is", "patient is");
# Digits, used in identifying ages
@digits = ("one","two","three","four","five","six","seven","eight","nine", "");
# Different variations of the 12 months
@months = ("January", "Jan", "February", "Feb", "March", "Mar", "April", "Apr", "May", "June", "Jun", "July", "Jul", "August", "Aug", "September", "Sept", "Sep", "October", "Oct", "November", "Nov", "December", "Dec");
######################################################################################
# If the correct number of input argument is provided, sets the input and output filenames.
if ($#ARGV == 1) {
$data_file = "$ARGV[0].text"; # data_file: input file
$output_file = "$ARGV[0].phi"; # output_file: file containing PHI locations
$debug_file = "$ARGV[0].info"; # debug_file: file used for debugging, contains PHI and non-PHI locations
$deid_text_file = "$ARGV[0].res"; # deid_text_file: de-identified text file
$gs_file = "$ARGV[0].deid"; # gs_file: Gold Standard of the input file
print "\n*******************************************************************************************************************\n";
print "De-Identification Algorithm: Identifies Protected Health Information (PHI) in Discharge Summaries and Nursing Notes";
print "\n*******************************************************************************************************************\n";
$config_file = $ARGV[1];
open CF, $config_file or die "Cannot open $config_file";
while ($cfline = <CF>) {
chomp $cfline;
if ($cfline =~ /\A[\#]+/){
next;
}
if ($cfline =~ /\bGold\s+standard\s+comparison\s*\=\s*([0-9])/ig) {
$comparison = ($1);
}
#Date default expects MM/DD/YYYY
if ($cfline =~ /\bDate\s+default\s*\=\s*(\d\d)\/(\d\d)\/(\d\d\d\d)/ig) {
my $mm = $1; $dd = $2; $yyyy = $3;
$DEFAULT_DATE = "$mm/$dd/$yyyy";
#print "Default date is $DEFAULT_DATE\n";
}
#The "Two Digit Year Threshold" is used to determine whether
#to interpret the year as a year in the 1900's or 2000's
if ($cfline =~ /\bTwo\s+Digit\s+Year\s+Threshold\s*=\s*(\d{1,2})/ig) {
$TWO_DIGIT_YEAR_THRESHOLD = "$1";
#print "Two Digit Year Threshold is $TWO_DIGIT_YEAR_THRESHOLD\n";
}
if ($cfline =~ /\bDate\s+offset\s*\=\s*([0-9]+)/ig) {
$offset = ($1);
#print "Date offset is $1\n";
}
if ($cfline =~ /\bSSN\s+filter\s*\=\s*([a-z])/ig) {
$ssnfilter = ($1);
}
if ($cfline =~ /\bURL\s+filter\s*\=\s*([a-z])/ig) {
$urlfilter = ($1);
}
if ($cfline =~ /\bEmail\s+filter\s*\=\s*([a-z])/ig) {
$emailfilter = ($1);
}
if ($cfline =~ /\bTelephone\s+filter\s*\=\s*([a-z])/ig) {
$telfilter = ($1);
}
if ($cfline =~ /\bUnit\s+number\s+filter\s*\=\s*([a-z])/ig) {
$unitfilter = ($1);
}
if ($cfline =~ /\bAge\s+filter\s*\=\s*([a-z])/ig) {
$agefilter = ($1);
}
if ($cfline =~ /\bLocation\s+filter\s*\=\s*([a-z])/ig) {
$locfilter = ($1);
}
if ($cfline =~ /\bDate\s+filter\s*\=\s*([a-z])/ig) {
$datefilter = ($1);
}
if ($cfline =~ /\bName\s+filter\s*\=\s*([a-z])/ig) {
$namefilter = ($1);
}
if ($cfline =~ /\bState\s+filter\s*\=\s*([a-z])/ig) {
$us_state_filter = ($1);
}
if ($cfline =~ /\bDS\s+filter\s*\=\s*([a-z])/ig) {
$ds_specific_filter = ($1);
}
if ($cfline =~ /\bGS\s+filter\s*\=\s*([a-z])/ig) {
$gs_specific_filter = ($1);
}
######################################################
#get the config info for dictionaries loading
if ($cfline =~ /\bPID\s+to\s+patient\s+name\s+mapping\s*\=\s*([a-z])/ig) {
$pid_patientname_list = ($1);
}
if ($cfline =~ /\bPID\s+to\s+date\s+offset\s+mapping\s*\=\s*([a-z])/ig) {
$pid_dateshift_list = ($1);
}
if ($cfline =~ /\bCountry\s+names\s*\=\s*([a-z])/ig) {
$country_list = ($1);
}
if ($cfline =~ /\bCompany\s+names\s*\=\s*([a-z])/ig) {
$company_list = ($1);
}
if ($cfline =~ /\bEthnicities\s*\=\s*([a-z])/ig) {
$ethnicity_list = ($1);
}
if ($cfline =~ /\bHospital\s+names\s*\=\s*([a-z])/ig) {
$hospital_list = ($1);
}
if ($cfline =~ /\bLocation\s+names\s*\=\s*([a-z])/ig) {
$location_list = ($1);
}
if ($cfline =~ /\bDoctor\s+names\s*\=\s*([a-z])/ig) {
$doctor_list = ($1);
}
if ($cfline =~ /\bLocalPlaces\s+names\s*\=\s*([a-z])/ig) {
$local_list = ($1);
}
if ($cfline =~ /\bState\s+names\s*\=\s*([a-z])/ig) {
$state_list = ($1);
}
}
}
# Prints an error message on the screen if number of arguments is incorrect
else {
print "\n===========================================================================================";
print "\nError: Wrong number of arguments entered";
print "\nThe algorithm takes 2 arguments:";
print "\n 1. filename (the filename of medical notes, without extension, where extension must be .text)";
print "\n 2. config_filename (the configuration filename)";
print "\nExample (for Gold Standard Comparison): perl deid.pl id deid.config";
print "\nExample (for output mode using Gold Standard): perl deid.pl id deid-output.config";
print "\nFor further documentation, please consult the README.txt file";
print "\n===========================================================================================\n";
exit;
}
# After setting file names and configuring the run, indicates that de-identification has commenced
print "\n\nStarting de-identification (version 1.1) ...\n\n";
#check if we can open the .phi file
open F, ">$output_file" or die "Cannot open $output_file";
close F;
# Calls setup to create some lookup lists in memory
setup();
if ($comparison==1) {
print "Running deid in performance comparison mode.\n";
print "Using PHI locations in $gs_file as comparison. Output files will be:\n";
print "$output_file: the PHI locations found by the code.\n";
print "$debug_file: debug info about the PHI locations.\n";
#check if the gold std file exists
open GS, $gs_file or die "Cannot open $gs_file. Make sure that the gold standard file exists!\n"; # GS = Gold Standard file
close GS;
}
else {
#check if we can open the .res file
open F, ">$deid_text_file" or die "Cannot open $deid_text_file";
close F;
print "Running deid in output mode. Output files will be: \n";
print "$output_file: the PHI locations found by the code.\n";
print "$deid_text_file: the scrubbed text.\n";
print "$debug_file: debug info about the PHI locations.\n";
}
deid();
# Calls function stat() to calculate code performance statistics, if comparison mode = 1
if ($comparison==1) {
require "stat.pm";
&stat($gs_file, $output_file);
}
# End of top level of code
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
sub numerically {
#print "a is $a b is $b\n";
$a <=> $b;
}
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Reads in a file and pushes each line onto an array. Returns the array.
sub preload {
my ($file) = @_;
my @res = ();
open FILE, $file or die "Cannot open file $file";
while ($line = <FILE>) {
chomp $line;
push(@res, uc($line));
}
close FILE;
return @res;
}
# End of preload()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Reads in a file and pushes each line onto an array. Returns the array.
sub preload_uc {
my ($file) = @_;
my @res = ();
open FILE, $file or die "Cannot open file $file";
while ($line = <FILE>) {
chomp $line;
push(@res, uc($line));
}
close FILE;
return @res;
}
# End of preload_uc()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Reads in a file and creates a dictionary that records each line in that file under the given association, by mapping the line to a '1' in the dictionary of the association
sub preload_assoc {
my ($file,$assoc) = @_;
open FILE, $file or die "Cannot open file $file";
while ($line = <FILE>) {
chomp $line;
$$assoc{uc($line)}=1;
}
close FILE;
}
# End of preload_assoc()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Reads in a file and calls setup_hash on each line
sub setup_hash {
my ($file, $tname) = @_;
my @entry;
$typename[$ntype]= $tname;
open FILE, $file or die "Cannot open file $file";
while ($line = <FILE>) {
chomp $line;
&setup_item($ntype,$line);
}
$ntype++;
close FILE;
}
# End of setup_hash()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Reads in a file and calls setup_hash on each line
sub setup_lst_hash {
my ($tname, @hlst) = @_;
$typename[$ntype]= $tname;
foreach $line (@hlst) {
&setup_item($ntype,$line);
}
$ntype++;
}
# End of setup_lst_hash()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
sub setup_item {
my ($type,$line) = @_;
my ($head, @lst) = split (/([^a-zA-Z0-9_\']+)/,uc($line));
my $ix = $type;
if(@lst){
push @extend, [@lst];
$ix = "$type,$#extend";
}
my $entry = $lhash{$head};
if ($entry){
$lhash{$head} .= "|" . $ix;
}
else{$lhash{$head}=$ix;
}
}
# End of setup_item()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
sub typename {
my ($num) = @_;
return($typename[$num]);
}
# End of typename()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Takes in an array of words and compares them with hashes of known PHI. Recognizes and adds PHI using addType().
sub lookhash {
my @txtlst = @_;
my $pos = 0;
my $npos = 0;
my $tl,$ty;
my $txt = 1; # item is text not separator
my $item;
while (@txtlst) {
$item = shift(@txtlst);
$npos = $pos + length($item);
if ($item =~ /([a-zA-Z\']+)/ig) {
if($item){
$item = uc($item);
$tl = $lhash{$item};
#if the term ends with 's, remove it and see if
#there is a match in PHI hash
#if (!($tl) && $item =~/([a-zA-Z\'\-]+)\'s$/ig) {
if (!($tl) && $item =~/([a-zA-Z\']+)\'s$/ig) {
$tl = $lhash {$1};
}
if($tl){
# Compares with known PHI by calling bestmatch()
($xpos, $done, @types)=&bestmatch($tl,@txtlst);
splice(@txtlst,0,$#txtlst-$done);
$npos += $xpos;
foreach $typ (@types){
#print "item $item, adding type $type for position $pos-$npos\n";
#print "type is $typ , key is $pos - $npos \n";
addType("$pos-$npos",$typ);
#print "positions are $pos-$npos, typ is $typ\n";
}
}
} #end if $item
$txt = 0;
} #end if $txt
else {
$txt = 1;
}
$pos = $npos;
}
}
# End of lookhash()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
sub bestmatch {
my ($tl,@txtlst) = @_;
my $pos = 0;
my $bestpos = 0;
my $bestrest = $#txtlst;
my @besttyp = ();
my ($type, $rest, $xpos, @nlst);
foreach $ck (split '\|',$tl) {
($type, $rest) = split ',',$ck;
if($rest) {
($xpos , @nlst) = &matchrest($rest,@txtlst);
if ($xpos) {
if($xpos > $bestpos) {
$bestrest = $#nlst; $bestpos = $xpos;
@besttyp = ($typename[$type]);
}
elsif($xpos == $bestpos) {
push @besttyp,$typename[$type];
}
}
}
elsif ($bestpos == 0) {
push @besttyp,$typename[$type];
}
}
return ($bestpos, $bestrest, @besttyp);
}
# End of bestmatch()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
sub matchrest {
my ($rest, @txtlst) = @_;
my @mlst = @{$extend[$rest]};
my $item;
my $pos = 0;
my $pm = 0;
my $tmppos = 0;
if ($mlst[0] eq '|') {
$pm = 1; shift(@mlst);
}
foreach $i (@mlst) {
if ($i !~ /([a-zA-Z\'\-]+)$/ig){
next;
}
$item = shift(@txtlst);
$pos += length($item);
while ( $#txtlst >= 0 && ($item !~ /([a-zA-Z\'\-]+)/ig)){
$item = shift(@txtlst);
$pos += length ($item);
#print "item is $item, len is $#txtlst";
}
if ($pm ? (uc($item) !~ /$i/) : ($i ne uc($item))) {
#print "pm is $pm, returning zero\n";
return 0;
}
}
return ($pos, @txtlst);
}
# End of matchrest()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Function: setup()
# Arguments: None
# Returns: None
# Called by: Topmost level of code
# Description: Creates some lookup lists to have in memory
sub setup {
# This part is not necessary
open LP, $last_name_prefix_file or die "Cannot open $last_name_prefix_file";
while ($line = <LP>) {
chomp $line;
$prefixes{uc($line)} = 1;
}
close LP;
#Added to reduce false positives
&setup_hash($medical_phrases_file,"MedicalPhrase");
# Sets up hashes of some PHI lists for direct identification
if ($namefilter =~ /y/) {
&setup_hash($female_unambig_file,"Female First Name (un)");
&setup_hash($female_ambig_file,"Female First Name (ambig)");
&setup_hash($male_unambig_file,"Male First Name (un)");
&setup_hash($male_ambig_file,"Male First Name (ambig)");
&setup_hash($last_unambig_file,"Last Name (un)");
&setup_hash($last_popular_file,"Last Name (popular/ambig)");
&setup_hash($last_ambig_file,"Last Name (ambig)");
&setup_hash($female_popular_file, "Female First Name (popular/ambig)");
&setup_hash($male_popular_file, "Male First Name (popular/ambig)");
if ($doctor_list =~ /y/) {
&setup_hash($doctor_first_unambig_file, "Doctor First Name");
&setup_hash($doctor_last_unambig_file, "Doctor Last Name");
}
}
if ($locfilter =~ /y/) {
if ($location_list =~ /y/) {
&setup_hash($locations_ambig_file,"Location (ambig)");
&setup_hash($locations_unambig_file,"Location (un)");
} else {
@loc_unambig = ();
@more_loc_unambig = ();
@loc_ambig = ();
}
if ($hospital_list =~ /y/) {
&setup_hash($hospital_file,"Hospital");
}
if ($ethnicity_list =~ /y/) {
&setup_hash($ethnicities_unambig_file, "Ethnicity");
}
if ($company_list =~ /y/) {
&setup_hash($companies_file, "Company");
&setup_hash($companies_ambig_file, "Company (ambig)");
}
if ($country_list =~ /y/) {
&setup_hash($countries_file, "Country");
}
if ($local_list =~ /y/){
&setup_hash($local_places_unambig_file, "Location (un)");
&setup_hash($local_places_ambig_file, "Location (ambig)");
}
}
# Preloads PHI in some lists into corresponding arrays
@female_popular = &preload($female_popular_file);
@male_popular = &preload($male_popular_file);
#@last_name_prefixes = &preload_uc($last_name_prefixes_file);
@prefixes_unambig = &preload_uc($prefixes_unambig_file);
if ($hospital_list =~ /y/) {
@hospital = &preload($hospital_file);
} else {@hospital = ();}
if ($state_list =~ /y/){
@us_states = &preload($us_states_file);
@us_states_abbre = &preload($us_states_abbre_file);
@more_us_states_abbre = &preload($more_us_states_abbre_file);
}
# Generates associations between PHI in some lists and PHI categories
&preload_assoc($common_words_file,"common_words");
&preload_assoc($medical_words_file,"common_words");
&preload_assoc($very_common_words_file,"very_common_words");
&preload_assoc($unambig_common_words_file, "unambig_common_words");
&preload_assoc($male_unambig_file, "male_unambig");
&preload_assoc($female_unambig_file, "female_unambig");
&preload_assoc($female_ambig_file, "female_ambig");
&preload_assoc($male_ambig_file, "male_ambig");
&preload_assoc($last_ambig_file, "last_ambig");
&preload_assoc($male_popular_file, "male_popular");
&preload_assoc($female_popular_file, "female_popular");
&preload_assoc($us_area_code_file,"us_area_code");
# Opens debug file for debugging
open D, ">".$debug_file;
close D;
}
# End of setup()
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
# Function: deid()
# Arguments: None
# Returns: None
# Called by: Topmost level of code
# Description: One of the 2 major branches of the code
# This function takes over de-identification if no performance statistic is required
# Function first loads the patient name list file.
# Then reads the medical text line by line.
# If the line indicates START_OF_RECORD, read the Patient ID (PID), Note ID (NID), (and Note Date if any) info
# Scan for PHI a paragraph at a time
# output PHI locations into .phi file
my $currentID;
my @known_phi;
my @known_first_name;
my @known_last_name;
my %pidPtNames; # key = pid, value = [0] first name [1] last name
#***********************************************************************************************************
#***********************************************************************************************************
#***********************************************************************************************************
sub deid {
$allText = "";
$allallText = "";
open DF, $data_file or die "Cannot open $data_file";
my $paraCount = 0;
my $stpos = 0;
my %deids; #key = start index, value = array of (end index, ID)
my %phiTerms; #key = lc(word), value = # of occurrences
my %phiT;
my %phiTT;
my $noteDate;
my $line;
$currentID = 0; #initialize current ID to a non-existent PID 0
# Code runs through text by paragraph so things that extend over lines aren't missed
$para = "";
#load the patient name file
if ($pid_patientname_list =~ /y/) {
open PF, $patient_file or die "Cannot open $patient_file";
while ($pfline = <PF>) {
chomp $pfline;
if ($pfline =~ /((.)+)\|\|\|\|((.)+)\|\|\|\|((.)+)/ig) {
my $pid = $1;
$known_first_names = $3;
$known_last_names = $5;
$pidPtNames{$pid}[0] = $known_first_names;
$pidPtNames{$pid}[1] = $known_last_names;
}# end if pfline = ~ /((.)+)\|\|\|\|((.)+)\|\|\|\|((.)+)/ig)
} # end while $pfline = <PF>
} #end if pid_patient_name_list ~= y
###End loading the patient names
while ($line = <DF>) {
#If this is a new record, set PID, Note ID
#we assume all notes for the same patient go together
if ( $line =~ /\ASTART_OF_RECORD=(([0-9]+)(\|)+([0-9]+)(\|)+(\d\d\/\d\d\/\d{4})?)/) {
# $currentNote = $2;
# $thePT = $4;
# $noteDate =$6; #noteDate is empty in gold std
#print "pt $thePT, currentNote $currentNote\n";
#if it's gold standard, the header contains PID then NID
$currentNote = $4;
$thePT = $2;
$noteDate =$6; #noteDate is empty in gold std
my $label = "Patient $thePT\tNote $currentNote";
open DEST, ">>".$debug_file or die "Cannot open $debug_file";
print DEST "$label\n";
close DEST;
#Gold Standard corpus does not specify note date, so assign a default
#If you would like deid to date shift the notes on a per note basis, make sure you
#specify the record date in the header!
if (length($noteDate) ==0){
#$noteDate="01/01/2020";
$noteDate = $DEFAULT_DATE;
}
#if this is a new patient, set the PID, and lookup patient name
if ($thePT != $currentID) { #This is a new patient!
$currentID = $thePT;
%phiTerms = (); #clear the phiTerms on new pt
# Find the patient name for the current PID
#lookup first and last name of this patient
if ($pid_patientname_list =~ /y/ && exists $pidPtNames{$currentID} ) {
$known_first_names = $pidPtNames{$currentID}[0];
$known_last_names = $pidPtNames{$currentID}[1];
#print "Found patient names, first = $known_first_names last = $known_last_names\n";
if ($known_first_names =~ /([a-z][a-z]+)[\s\-]([a-z][a-z]+)/ig) {
@known_first_name = ($1, $2);}
else {
if ($known_first_names =~ /\b([a-z])(\.?)\s([a-z]+)/ig) {
@known_first_name = ($3);
}
elsif ($known_first_names =~ /\b([a-z][a-z]+)\s([a-z])(\.?)/ig) {
@known_first_name = ($1);
}
else {
@known_first_name = ($known_first_names);
}
}
if ($known_last_names =~ /([a-z][a-z]+)[\s\-]([a-z][a-z]+)/ig) {
@known_last_name = ($1, $2);}
else {
if ($known_last_names =~ /\b([a-z])(\.?)\s([a-z]+)/ig) {
@known_last_name = ($3);
}
elsif ($known_last_names =~ /\b([a-z][a-z]+)\s([a-z])(\.?)/ig) {
@known_last_name = ($1);
}
else {
@known_last_name = ($known_last_names);
}
}
} else { #if no pid/patient name file, just set the first name and last name to null
@known_first_name = ();
@known_last_name = ();
}
} # end if this is a new patient
#output the header to output file
$allText = ""; #reset,
$allallText = ""; #reset
$stpos = 0;
$para = "";
#if output mode, output the header line (with patient and note ID) to .res file
if ($comparison == 0) {
open TF, ">>$deid_text_file" or die "Cannot open $deid_text_file"; #now open in append mode
print TF "\n$line";
close TF;
}
next; #skip to next line
} #end if this is start of a record
else { #else this is not the start of a record, just append the line to the end of the current text
chomp $line;
$allText .= $line."\n";
$allallText .= $line."\n";
#$myline = $line;
#chomp $myline;
#$allText .= $myline."\n";
#$allallText .= $myline."\n";
}
#Look for paragraph separator: if this is a line is entirely non-alphanumeric or
#if it starts with spaces, or if it is an empty line, or if this line marks the end of record,
#then call findPHI() for the current paragraph we have so far.
#If end of record is encoutnered, output the de-id text; else if
#it's not end of record yet, append the line to the paragraph.
# if ( (!($line =~ /[a-zA-Z\d]+/)) || $line =~ /^ +/ || $line eq "" || ($line =~ /\|\|\|\|END_OF_RECORD/) ) {
if ( (!($line =~ /[a-zA-Z\d]+/)) || ($line eq "") || ($line =~ /\|\|\|\|END_OF_RECORD/) ) {
if ($para =~ /\w/ ){ #if para contains alphanumeric
# Calls findPHI() with current paragraph; resulting PHI locations are stored in %phiT
#%phiT = findPHI("Para $paraCount", $date, $stpos, $para);
%phiT = findPHI("Para $paraCount", $noteDate, $stpos, $para);
$paraCount++;
# %phiT is copied over to %phiTT
foreach $x (sort numerically keys %phiT) {
@{$phiTT{$x}} = @{$phiT{$x}};
}
#Sorts keys in %phiT; outputs text accordingly
foreach $k (keys %phiT) {
my ($start, $end) = split '-', $k;
# $deids_end = ${@{$deids{$start}}}[0]; #does not work with perl v5.10
my @deidsval = ${@{$deids{$start}}};
$deids_end = $deidsval[0];
$found = $phiT{$k};
foreach $t (@{$phiT{$k}}) {
}
my $word = lc(substr $allallText, $start, ($end - $start));
#print "Key in PhiT = $k, word = $word\n"; #DEBUG
# if ($end > ${@{$deids{$start}}}[0]) {
if ($end > $deidsval[0]) {
$deids{$start}[0] = $end;
$deids{$start}[1] = $currentID;
$deids{$start}[2] = $noteDate;
}
#############################################################################
#Now remember the PHI terms that are important names for checking for repeated occurrences of PHIs
#PHI Name Tags
#(NI) Name indicators