script/CUICollector.pl untested

filter: Statementstmt 0.0% 0 / 229 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 20 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 357 SCAR 61.4
CC
21
Cov
0%
read_utterance
42.0
update_row
30.0
count_bigrams
30.0
CRAP 462.0
1 #!/usr/local/bin/perl
2  
3 =head1 NAME
4  
5 CUICollector.pl - Scrapes MetaMap Machine Output (MMO) files to build a database of CUI bigram scores.
6  
7 =head1 SYNOPSIS
8  
9 $ perl CUICollector.pl --directory metamapped-baseline/2014/
10 CUICollector 0.04 - (C) 2015 Keith Herbert and Bridget McInnes
11 Released under the GNU GPL.
12 Connecting to database CUI_Bigrams on localhost
13 Parsing file: /home/share/data/metamapped-baseline/2014/text.out_01.gz
14 Parsing file: /home/share/data/metamapped-baseline/2014/text.out_02.gz
15 Parsing file: /home/share/data/metamapped-baseline/2014/text.out_03.gz
16 Parsing file: /home/share/data/metamapped-baseline/2014/text.out_02.gz
17 Parsing file: /home/share/data/metamapped-baseline/2014/text.out_03.gz
18 Entering scores into CUI_Bigrams
19 ...
20 Finished
21  
22 =head1 USAGE
23  
24 Usage: CUICollector.pl [DATABASE OPTIONS] [OTHER OPTIONS] [FILES | DIRECTORIES]
25  
26 =head1 INPUT
27  
28 =head2 Required Arguments:
29  
30 =head3 [FILES | DIRECTORIES]
31  
32 Specify a directory containing *ONLY* compressed MetaMapped Medical Baseline files:
33 --directory /path/to/files/
34  
35 Multiple directories may also be supplied:
36 --directory /path/to/first/folder/ /path/to/second/folder/
37  
38 Likewise, specify a list of individual files
39 --files text.out_01.txt.gz text_mm_out_42.txt.gz text_mm_out_314.txt.gz
40  
41 a glob of files:
42 --files /path/to/dir/*.gz
43  
44 Or just one:
45 --files text.out_01.txt.gz
46  
47  
48 =head2 Optional Arguments:
49  
50  
51 =head3 --database STRING
52  
53 Database to contain the CUI bigram scores. DEFAULT: CUI_Bigrams
54  
55 If the database is not found in MySQL, CUICollector will create it for you.
56  
57 =head3 --username STRING
58  
59 Username is required to access the CUI bigram database on MySql. You will be prompted
60 for it if it is not supplied as an argument.
61  
62 =head3 --password STRING
63  
64 Password is required to access the CUI bigram database on MySql. You will be prompted
65 for it if it is not supplied as an argument.
66  
67 =head3 --hostname STRING
68  
69 Hostname where mysql is located. DEFAULT: localhost
70  
71 =head3 --socket STRING
72  
73 Socket where the mysql.sock or mysqld.sock is located.
74 DEFAULT: mysql.sock
75  
76 =head3 --port STRING
77  
78 The port your mysql is using. DEFAULT: 3306
79  
80 =head3 --file_step INTEGER
81  
82 How many MetaMap files to read between writes to the database.
83 DEFAULT: 5
84  
85 MMO files can be rather large so setting a low file_step reduces the memory footprint of the script. However, setting a higher file_step reduces the number of write operations to the database.
86  
87 =head3 --debug
88  
89 Sets the debug flag for testing. NOTE: extremely verbose.
90  
91 =head3 --verbose
92  
93 Print the current status of the program to STDOUT. This indicates the files being processed and when the program is writing to the database. This is the default output setting.
94  
95 =head3 --quiet
96  
97 Don't print anything to STDOUT.
98  
99 =head3 --help
100  
101 Displays the quick summary of program options.
102  
103 =head1 OUTPUT
104  
105 By default, CUICollector prints he current status of the program as it works through the Metamapped Medline Output files (disable with `--quiet`). It creates a database (or connects to an existing one) and adds bigram scores of the CUIs it encounters in the MMO files.
106  
107 The resulting database will have four tables:
108  
109 =over
110  
111 =item N_11
112  
113 cui_1 cui_2 n_11
114
115 This shows the count (n_11) for every time a particular CUI (cui_1) is immediately followed by another particular CUI (cui_2) in an utterance.
116  
117 =back
118  
119 =head1 AUTHOR
120  
121 Keith Herbert, Virginia Commonwealth University
122 Amy Olex, Virginia Commonwealth University
123 Bridget McInnes, Virginia Commonwealth University
124  
125 =head1 COPYRIGHT
126  
127 Copyright (c) 2015-2017
128 Keith Herbert, Virginia Commonwealth University
129 herbertkb at vcu edu
130  
131 Amy Olex, Virginia Commonwealth University
132 alolex at vcu dot edu
133  
134 Bridget McInnes, Virginia Commonwealth University
135 btmcinnes at vcu dot edu
136  
137  
138 This program is free software; you can redistribute it and/or modify it under
139 the terms of the GNU General Public License as published by the Free Software
140 Foundation; either version 2 of the License, or (at your option) any later
141 version.
142  
143 This program is distributed in the hope that it will be useful, but WITHOUT
144 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
145 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
146  
147 You should have received a copy of the GNU General Public License along with
148 this program; if not, write to:
149  
150 The Free Software Foundation, Inc.,
151 59 Temple Place - Suite 330,
152 Boston, MA 02111-1307, USA.
153  
154 =cut
155  
156 ###############################################################################
157 # THE CODE STARTS HERE
158 ###############################################################################
159  
160 use strict;
161 use warnings;
162 use Time::HiRes;
163  
164 use Data::Dumper; # Helps with debugging
165 use DBI; # Database stuff
166 use Getopt::Long; # Parse command line options
167 use File::Type; # Know when a file is compressed
168  
169 use feature qw(say);
170  
171 $|=1; # toggle buffering to STDOUT. Essential when CPU is fully worked.
172  
173 ###############################################################################
174 # CONSTANT STRINGS
175 ###############################################################################
176  
177 my $version = "0.20";
178 my $header =
179 "CUICollector $version - (C) 2015 Keith Herbert and Bridget McInnes, PhD\n"
180 ."Released under the GNU GPL.";
181  
182 my $usage = $header."\n"
183 ."FLAGS\n"
184 ."--debug Print EVERYTHING to STDERR.\n"
185 ."--verbose Print log of files processed to STDOUT (DEFAULT)\n"
186 ."--quiet Print NOTHING to STDERR or STDOUT.\n"
187 ."--help Print this help screen.\n"
188 ."DATABASE OPTIONS\n"
189 ."--database Name of MySQL database to store CUI data. (Default=CUI_Bigrams)\n"
190 ."--hostname Hostname for MySQL database. (Default=localhost)\n"
191 ."--socket Socket where the mysql.sock or mysqld.sock is located.\n"
192 ."--username Username for MySQL access. (Optional, but will be prompted)\n"
193 ."--password Password for MySQL access. (Optional, but will be prompted)\n"
194 ."MetaMap Machine Output File Options\n"
195 ."--directory Path to directory containing *only* MetaMap Baseline files\n"
196 ."--files Explicit list of one or more MetaMap Baseline files\n"
197 ."--file_step How many files to read between database writes. (DEFAULT=5)\n"
198 ."--plain All input files are uncompressed.\n"
199 ."NGRAM OPTIONS\n"
200 ."--window N Window size (DEFAULT: 1)\n"
201 ."--sliding Use a sliding window\n"
202 ."\nUSAGE EXAMPLES\n"
203 ."Open directory ./metamap/ and write to database CUIs on localhost:\n"
204 ."\tperl CUICollector.pl --database CUIs --directory metamap/\n\n"
205 ."Open single file test.mmb and write to default database:\n"
206 ."\tperl CUICollector.pl --file test.mmb\n"
207 ;
208  
209 ###############################################################################
210 # Parse command line options
211 ###############################################################################
212 my $DEBUG = 0; # Prints EVERYTHING. Use with small testing files.
213 my $VERBOSE = 1; # Only print for reading from files, writing to database
214 my $HELP = ''; # Prints usage and exits if true.
215  
216  
217 my $database = "CUI_Bigrams"; # Values needed to connect to MySQL dbase.
218 my $hostname = "localhost";
219 my $socket = "/var/run/mysqld/mysqld.sock";
220 my $port = "3306";
221 my $username;
222 my $password;
223  
224 my $sliding;
225 my $window = 1;
226  
227 my $file_step = 3; # How many files to read between writes to database.
228 my $gzipped = 1;
229 my @dirs = (); # Directories containing *only* MetaMap Baseline files
230 my @files = (); # Explicit list of MetaMap Baseline files.
231  
232 GetOptions( 'debug' => \$DEBUG,
233 'help' => \$HELP,
234 'verbose!' => \$VERBOSE,
235 'quiet' => sub { $VERBOSE = 0 },
236 'plain' => sub { $gzipped = 0 },
237 'database=s' => \$database,
238 'hostname=s' => \$hostname,
239 'socket=s' => \$socket,
240 'port=s' => \$port,
241 'username=s' => \$username,
242 'password=s' => \$password,
243 'file_step=i' => \$file_step,
244 'directory=s{1,}' => \@dirs,
245 'files=s{1,}' => \@files,
246 'window=i' => \$window,
247 'sliding' => \$sliding
248 );
249  
250 die $usage unless $#ARGV;
251 die $usage if $HELP;
252 die("Invalid file_step. Must be positive integer") if $file_step < 1;
253 die "*** No input files ***\n$usage" unless @dirs or @files;
254  
255 say $header if $VERBOSE;
256  
257 ## Prompt for username/pass if they weren't provided.
258 if (not defined $username){
259 print "Enter username for MySQL server on $hostname: ";
260 $username = <STDIN>;
261 chomp $username;
262 }
263 if (not defined $password){
264 print "Enter password for $username: ";
265 $password = <STDIN>;
266 chomp $password;
267 }
268
269  
270 ## Collect all files from input into one massive list.
271 for my $dir (@dirs) {
272 opendir(DIR, $dir) || die "Could not open dir ($dir)\n";
273 push @files, grep { $_ ne "$dir." and $_ ne "$dir.." } map { "$dir$_" } readdir DIR;
274 close DIR;
275 }
276  
277 ## Test if all these files are readable to avoid a nasty surprise later.
278 for my $file (@files) {
279 die "Cannot read $file" unless -r $file;
280 }
281  
282 # Presorting makes the console output easier to read.
283 @files = sort @files;
284  
285 ###############################################################################
286 # Main
287 ###############################################################################
288 {
289
290 say "Connecting to $database on $hostname" if $VERBOSE;
291 my $dbh = open_mysql_database($database, $hostname, $port, $username, $password, $socket);
292  
293 my($filetime_s,$filetime_e,$dbtime_s,$dbtime_e,$total_time_s);
294  
295  
296 $total_time_s = Time::HiRes::gettimeofday() if $DEBUG;
297  
298  
299 while (@files) {
300 my @curr_files = splice @files, 0, $file_step;
301
302 $filetime_s = Time::HiRes::gettimeofday() if $DEBUG;
303 my($bigram_ref) = process_files(@curr_files);
304 $filetime_e = Time::HiRes::gettimeofday() if $DEBUG;
305
306 say "Entering scores into $database..." if $VERBOSE;
307 $dbtime_s = Time::HiRes::gettimeofday() if $DEBUG;
308 update_database($dbh, $bigram_ref);
309 $dbtime_e = Time::HiRes::gettimeofday() if $DEBUG;
310
311 if ($DEBUG) {
312 print Dumper($bigram_ref);
313 }
314 }
315  
316 my $total_time_e = Time::HiRes::gettimeofday() if $DEBUG;
317  
318 printf("Serial elapsed time for file processing only: %.2f sec\n", $filetime_e - $filetime_s) if $DEBUG;
319 printf("Serial elapsed time for database update only: %.2f sec\n", $dbtime_e - $dbtime_s) if $DEBUG;
320 printf("Serial elapsed time for entire Main: %.2f sec\n", $total_time_e - $total_time_s) if $DEBUG;
321  
322 # Close connection to database
323 $dbh->disconnect;
324  
325 say "Finished." if $VERBOSE;
326 }
327  
328 ###############################################################################
329 # Database Subroutines
330 ###############################################################################
331 sub open_mysql_database {
332 my ($dbase, $host, $port, $user, $pass, $socket) = (@_);
333
334 # See if database exists in the specified DBMS
335 my @dbases = DBI->data_sources("mysql",
336 {"host" => $host, "user" => $user,
337 password => $pass, "socket"=> $socket});
338  
339 my $dbase_exists = grep /DBI:mysql:$dbase/, @dbases;
340  
341 # Connect to the database if it exists. Otherwise create it from scratch.
342 my $dbh;
343 if ($dbase_exists) {
344  
345 $dbh = DBI->connect("DBI:mysql:database=$dbase;host=$host;"
346 ."mysql_socket=$socket",
347 $user, $pass,
348 {'RaiseError' => 1, 'AutoCommit' => 0});
349 }
350 else {
351 #connect to the DB and turn AutoCommit Off (value of 1)
352 $dbh = DBI->connect("DBI:mysql:host=$host", $user, $pass,
353 {'RaiseError' => 1,'AutoCommit' => 0});
354 create_database($dbh, $dbase);
355 }
356  
357 return $dbh; # Return the handler to keep connection alive.
358 }
359  
360 ###############################################################################
361 sub create_database {
362 my $dbh = shift;
363 my $dbase = shift;
364
365 $dbh->do("CREATE DATABASE $dbase");
366 $dbh->do("USE $dbase");
367
368 $dbh->do("CREATE TABLE N_11 (
369 cui_1 CHAR(10) NOT NULL,
370 cui_2 CHAR(10) NOT NULL,
371 n_11 BIGINT NOT NULL,
372 PRIMARY KEY (cui_1, cui_2) )" );
373
374 }
375  
376 ###############################################################################
377 sub update_row {
378 my ($dbh, # database handler
379 $table, # name of table being updated
380 $updated_field, # field being updated
381 $updated_value, # value to change in field
382 $key_names_ref, # array ref for key names of table
383 $key_values_ref # array ref to values to locate row in table
384 ) = @_;
385
386
387 # Build conditional statement to locate row in table.
388 my $conditional = "";
389 if (@$key_names_ref) {
390 $conditional = join ' AND ', map {"$_ = ? "} @$key_names_ref;
391 }
392 else {
393 $conditional = "$updated_field > -1";
394 }
395 # Check if row to update is already in table
396 my $select = "SELECT * FROM $table WHERE $conditional LIMIT 1";
397 say $select if $DEBUG;
398 my $sth = $dbh->prepare($select);
399 $sth->execute(@$key_values_ref);
400
401 # If it is, update entry with new sum.
402 my @match = $sth->fetchrow_array();
403 if ( @match ) {
404
405 $updated_value += $match[-1];
406
407 my $update = "UPDATE $table SET $updated_field = ? WHERE $conditional";
408
409 $dbh->do( $update,undef, $updated_value, @$key_values_ref );
410 }
411 # Otherwise, insert a new row into the table.
412 else {
413
414 # Build the insert statement
415 my $key_list = join ', ', @$key_names_ref;
416 my $field_length = @$key_names_ref;
417 my $insert ="INSERT INTO $table ($key_list, $updated_field) " .
418 "VALUES (" . '?, ' x $field_length . '?' . ")";
419 say $insert if $DEBUG;
420 $dbh->do($insert, undef, @$key_values_ref, $updated_value);
421 }
422 }
423  
424 ##############################################################################
425 sub update_database {
426 my($dbh, $bigram_ref, $n1p_ref, $np1_ref, $npp) = (@_);
427
428 # Add all of the bigram counts to the database
429 say STDERR "n11:" if $DEBUG;
430 foreach my $cui_1 (keys %$bigram_ref){
431 foreach my $cui_2 (keys %{$$bigram_ref{$cui_1}}) {
432 my $n_11 = $$bigram_ref{$cui_1}{$cui_2};
433
434 say STDERR "$cui_1\t$cui_2\t$n_11" if $DEBUG;
435
436 update_row($dbh, 'N_11', 'n_11', $n_11,
437 ['cui_1', 'cui_2'], [$cui_1, $cui_2] );
438 }
439 }
440 $dbh->commit or die $dbh->errstr;
441 }
442  
443 ###############################################################################
444 # This is where the magic happens
445 ###############################################################################
446  
447 sub process_files {
448 my @files = @_;
449
450 my %bigrams; # cui_1 => cui_2 => sum of cui_1 preceeding cui_2
451
452 # Anonymous subroutine to update the bigram and marginal counts
453 my $incrementor = sub {
454 my($cui_1, $cui_2) = @_;
455 $bigrams{$cui_1}{$cui_2}++;
456 };
457
458 for my $file (@files) {
459
460 if( File::Type->mime_type($file) =~ /x-gzip/) {
461 #unzip file to temp
462 my $tempFileName = $file.'_temp';
463 !(system "gunzip -c $file >$tempFileName -f -q")
464 or die "error gunzipping $file\n";
465
466 #process temp as normal
467 process_file($tempFileName, $incrementor);
468  
469 #remove temp file
470 system "rm $tempFileName";
471 }
472 else {
473 process_file($file, $incrementor);
474 }
475 }
476
477 return (\%bigrams);
478 }
479 ###############################################################################
480 sub process_file {
481 my $file = shift; # text/plain file to process
482 my $incrementor = shift; # ref to anon sub that updates bigram counts
483
484 open(my $fh, '<', $file) or die "Cannot read $file: $!"; #fh = filehandle
485 say "Parsing uncompressed file: $file" if $VERBOSE;
486
487 until (eof $fh ){
488 count_bigrams( read_utterance( $fh ), $incrementor );
489 }
490 }
491  
492 ###############################################################################
493 # take filehandle as lexical variable
494 # returns ref to array of phrases for single utterance
495 sub read_utterance {
496 my $fh = shift;
497
498 my @phrases_in_utterance;
499  
500 my $pid = "";
501 # The following loop will iterate over all the phrases for this utterance
502 while (<$fh>) {
503 chomp;
504  
505 if($_=~/utterance\(\'(.*)\.(ti|ab)\.[0-9]+/) {
506 my $cid = $1;
507 if($DEBUG == 1) { print STDERR "IDs: $cid $pid\n"; }
508 if($pid ne "" && $cid ne $pid) {
509 seek($fh, -length($_), 1);
510 last;
511 }
512 $pid = $cid;
513 }
514
515 # Skip all lines that aren't mappings for a phrase in the utterance
516 next unless /^mappings/;
517
518 my @mappings = @{ get_mappings($_) };
519
520 push @phrases_in_utterance, \@mappings if @mappings;
521
522 }
523  
524 return \@phrases_in_utterance;
525 }
526  
527 ###############################################################################
528 sub get_mappings {
529 my $mapping_string = shift; # the line for which /^mappings/ is true
530
531 # Break mappings into each possible mapping of phrase into CUIs
532 my @maps = split /map\(/, $mapping_string;
533  
534 # Collect the CUIs in each possible mapping (assumes format 'C1234567')
535 # as a set of strings
536 my @mappings;
537 for my $map (@maps) {
538
539 my $CUI_string = join " ", ( $map =~ m/C\d{7}/g );
540
541 say $CUI_string if $CUI_string and $DEBUG;
542
543 push @mappings, $CUI_string if $CUI_string;
544 }
545  
546 return \@mappings;
547 }
548  
549 ###############################################################################
550 sub count_bigrams {
551 my( $phrases_ref, # reference to list of mappings for single utterance
552 $incrementor # anonymous subroutine to update counting hashes
553 ) = @_;
554
555 my @phrases = @$phrases_ref;
556  
557 my %tree = (); my $hid = 0;
558
559 for (my $i = 0; $i <= $#phrases; $i++) {
560 my @phrase = @{$phrases[$i]};
561 my $j = 0; my $increment = 1;
562 foreach $j (0..$#phrase) {
563 my @cuis = split/\s+/, $phrase[$j];
564 foreach my $k (0..$#cuis) {
565 $tree{$hid+$k}{$cuis[$k]}++;
566 my $temp = $hid + $k;
567 if($DEBUG == 1) { print STDERR "$cuis[$k] $temp\n"; }
568 }
569 $increment = $#cuis + 1;
570 }
571 $hid += $increment;
572 }
573  
574 if(defined $sliding) {
575 foreach my $id (sort {$a<=>$b} keys %tree) {
576 foreach my $cui (sort keys %{$tree{$id}}) {
577 for my $s (1..$window) {
578 for my $w (1..$s) {
579 my $k = $w+$id;
580 foreach my $c (sort keys %{$tree{$k}}) {
581 $incrementor->($cui, $c);
582 if($DEBUG == 1) { print STDERR "ADDING $cui $c\n"; }
583 }
584 }
585 }
586 }
587 }
588 }
589 else {
590 foreach my $id (sort {$a<=>$b} keys %tree) {
591 foreach my $cui (sort keys %{$tree{$id}}) {
592 for my $w (1..$window) {
593 my $k = $w+$id;
594 foreach my $c (sort keys %{$tree{$k}}) {
595 $incrementor->($cui, $c);
596 if($DEBUG == 1) { print STDERR "ADDING $cui $c\n"; }
597 }
598 }
599 }
600 }
601 }
602 }