script/CUICollector.pl untested

filter: Statementstmt 0.0% 0 / 243 Branchbran 0.0% 0 / 92 Conditioncond 0.0% 0 / 15 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 381 SCAR 65.5
CC
26
Cov
0%
update_database
56.0
update_row
30.0
read_utterance
20.0
CRAP 702.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 =item N_1P
118  
119 cui_1 n_1p
120
121 This shows the count (n_11) for every time a particular CUI (cui_1) is followed by any CUI in an utterance.
122  
123 =item N_P1
124  
125 cui_2 n_p1
126
127 This shows the count (n_p1) for every time a particular CUI (cui_2) is immediately preceded by any CUI in an utterance.
128  
129 =item N_PP
130  
131 n_pp
132
133 This single value is the total count of all cui_1, cui_2 bigram pairs.
134  
135 =back
136  
137 =head1 AUTHOR
138  
139 Keith Herbert, Virginia Commonwealth University
140 Amy Olex, Virginia Commonwealth University
141  
142 =head1 COPYRIGHT
143  
144 Copyright (c) 2015,
145 Keith Herbert, Virginia Commonwealth University
146 herbertkb at vcu edu
147  
148 Amy Olex, Virginia Commonwealth University
149 alolex at vcu dot edu
150  
151 Bridget McInnes, Virginia Commonwealth University
152 btmcinnes at vcu dot edu
153  
154  
155 This program is free software; you can redistribute it and/or modify it under
156 the terms of the GNU General Public License as published by the Free Software
157 Foundation; either version 2 of the License, or (at your option) any later
158 version.
159  
160 This program is distributed in the hope that it will be useful, but WITHOUT
161 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
162 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
163  
164 You should have received a copy of the GNU General Public License along with
165 this program; if not, write to:
166  
167 The Free Software Foundation, Inc.,
168 59 Temple Place - Suite 330,
169 Boston, MA 02111-1307, USA.
170  
171 =cut
172  
173 ###############################################################################
174 # THE CODE STARTS HERE
175 ###############################################################################
176  
177 use strict;
178 use warnings;
179 use Time::HiRes;
180  
181 use Compress::Zlib; # Read compress .gz files
182 use Data::Dumper; # Helps with debugging
183 use DBI; # Database stuff
184 use Getopt::Long; # Parse command line options
185 use File::Type; # Know when a file is compressed
186 #use Graph::Directed; # Model an utternace as a directed graph
187 #use List::MoreUtils; # these should be built-in
188  
189  
190 use feature qw(say);
191  
192 $|=1; # toggle buffering to STDOUT. Essential when CPU is fully worked.
193  
194 ###############################################################################
195 # CONSTANT STRINGS
196 ###############################################################################
197  
198 my $version = "0.20";
199 my $header =
200 "CUICollector $version - (C) 2015 Keith Herbert and Bridget McInnes, PhD\n"
201 ."Released under the GNU GPL.";
202  
203 my $usage = $header."\n"
204 ."FLAGS\n"
205 ."--debug Print EVERYTHING to STDERR.\n"
206 ."--verbose Print log of files processed to STDOUT (DEFAULT)\n"
207 ."--quiet Print NOTHING to STDERR or STDOUT.\n"
208 ."--help Print this help screen.\n"
209 ."DATABASE OPTIONS\n"
210 ."--database Name of MySQL database to store CUI data. (Default=CUI_Bigrams)\n"
211 ."--hostname Hostname for MySQL database. (Default=localhost)\n"
212 ."--socket Socket where the mysql.sock or mysqld.sock is located.\n"
213 ."--username Username for MySQL access. (Optional, but will be prompted)\n"
214 ."--password Password for MySQL access. (Optional, but will be prompted)\n"
215 ."MetaMap Machine Output File Options\n"
216 ."--directory Path to directory containing *only* MetaMap Baseline files\n"
217 ."--files Explicit list of one or more MetaMap Baseline files\n"
218 ."--file_step How many files to read between database writes. (DEFAULT=5)\n"
219 ."--plain All input files are uncompressed.\n"
220 ."\nUSAGE EXAMPLES\n"
221 ."Open directory ./metamap/ and write to database CUIs on localhost:\n"
222 ."\tperl CUICollector.pl --database CUIs --directory metamap/\n\n"
223 ."Open single file test.mmb and write to default database:\n"
224 ."\tperl CUICollector.pl --file test.mmb\n"
225 ;
226  
227 ###############################################################################
228 # Parse command line options
229 ###############################################################################
230 my $DEBUG = 0; # Prints EVERYTHING. Use with small testing files.
231 my $VERBOSE = 1; # Only print for reading from files, writing to database
232 my $HELP = ''; # Prints usage and exits if true.
233  
234  
235 my $database = "CUI_Bigrams"; # Values needed to connect to MySQL dbase.
236 my $hostname = "localhost";
237 my $socket = "/var/run/mysqld/mysqld.sock";
238 my $port = "3306";
239 my $username;
240 my $password;
241  
242 my $file_step = 5; # How many files to read between writes to database.
243 my $gzipped = 1;
244 my @dirs = (); # Directories containing *only* MetaMap Baseline files
245 my @files = (); # Explicit list of MetaMap Baseline files.
246  
247 GetOptions( 'debug' => \$DEBUG,
248 'help' => \$HELP,
249 'verbose!' => \$VERBOSE,
250 'quiet' => sub { $VERBOSE = 0 },
251 'plain' => sub { $gzipped = 0 },
252 'database=s' => \$database,
253 'hostname=s' => \$hostname,
254 'socket=s' => \$socket,
255 'port=s' => \$port,
256 'username=s' => \$username,
257 'password=s' => \$password,
258 'file_step=i' => \$file_step,
259 'directory=s{1,}' => \@dirs,
260 'files=s{1,}' => \@files
261 );
262  
263 die $usage unless $#ARGV;
264 die $usage if $HELP;
265 die("Invalid file_step. Must be positive integer") if $file_step < 1;
266 die "*** No input files ***\n$usage" unless @dirs or @files;
267  
268 say $header if $VERBOSE;
269  
270 ## Prompt for username/pass if they weren't provided.
271 if (not defined $username){
272 print "Enter username for MySQL server on $hostname: ";
273 $username = <STDIN>;
274 chomp $username;
275 }
276 if (not defined $password){
277 print "Enter password for $username: ";
278 $password = <STDIN>;
279 chomp $password;
280 }
281
282  
283 ## Collect all files from input into one massive list.
284 for my $dir (@dirs) {
285 opendir(DIR, $dir) || die "Could not open dir ($dir)\n";
286 push @files, grep { $_ ne "$dir." and $_ ne "$dir.." } map { "$dir$_" } readdir DIR;
287 close DIR;
288 }
289  
290 ## Test if all these files are readable to avoid a nasty surprise later.
291 for my $file (@files) {
292 die "Cannot read $file" unless -r $file;
293 }
294  
295 # Presorting makes the console output easier to read.
296 @files = sort @files;
297  
298 ###############################################################################
299 # Main
300 ###############################################################################
301 {
302
303 say "Connecting to $database on $hostname" if $VERBOSE;
304 my $dbh = open_mysql_database($database, $hostname, $port, $username, $password, $socket);
305  
306 my($filetime_s,$filetime_e,$dbtime_s,$dbtime_e,$total_time_s);
307  
308  
309 $total_time_s = Time::HiRes::gettimeofday() if $DEBUG;
310  
311  
312 while (@files) {
313 my @curr_files = splice @files, 0, $file_step;
314
315 $filetime_s = Time::HiRes::gettimeofday() if $DEBUG;
316 my($bigram_ref, $n1p_ref, $np1_ref, $npp) = process_files(@curr_files);
317 $filetime_e = Time::HiRes::gettimeofday() if $DEBUG;
318
319 say "Entering scores into $database..." if $VERBOSE;
320 $dbtime_s = Time::HiRes::gettimeofday() if $DEBUG;
321 update_database($dbh, $bigram_ref, $n1p_ref, $np1_ref, $npp);
322 $dbtime_e = Time::HiRes::gettimeofday() if $DEBUG;
323
324 if ($DEBUG) {
325 print Dumper($bigram_ref);
326 print Dumper($n1p_ref);
327 print Dumper($np1_ref);
328 say $npp;
329 }
330 }
331  
332 my $total_time_e = Time::HiRes::gettimeofday() if $DEBUG;
333  
334 printf("Serial elapsed time for file processing only: %.2f sec\n", $filetime_e - $filetime_s) if $DEBUG;
335 printf("Serial elapsed time for database update only: %.2f sec\n", $dbtime_e - $dbtime_s) if $DEBUG;
336 printf("Serial elapsed time for entire Main: %.2f sec\n", $total_time_e - $total_time_s) if $DEBUG;
337  
338 # Close connection to database
339 $dbh->disconnect;
340  
341 say "Finished." if $VERBOSE;
342 }
343  
344 ###############################################################################
345 # Database Subroutines
346 ###############################################################################
347 sub open_mysql_database {
348 my ($dbase, $host, $port, $user, $pass, $socket) = (@_);
349
350 # See if database exists in the specified DBMS
351 my @dbases = DBI->data_sources("mysql",
352 {"host" => $host, "user" => $user,
353 password => $pass, "socket"=> $socket});
354 my $dbase_exists = grep /DBI:mysql:$dbase/, @dbases;
355  
356 # Connect to the database if it exists. Otherwise create it from scratch.
357 my $dbh;
358 if ($dbase_exists) {
359  
360 $dbh = DBI->connect("DBI:mysql:database=$dbase;host=$host;"
361 ."mysql_socket=$socket",
362 $user, $pass,
363 {'RaiseError' => 1});
364 }
365 else {
366 $dbh = DBI->connect("DBI:mysql:host=$host", $user, $pass,
367 {'RaiseError' => 1});
368 create_database($dbh, $dbase);
369 }
370
371 return $dbh; # Return the handler to keep connection alive.
372 }
373  
374 ###############################################################################
375 sub create_database {
376 my $dbh = shift;
377 my $dbase = shift;
378
379 $dbh->do("CREATE DATABASE $dbase");
380 $dbh->do("USE $dbase");
381
382 $dbh->do("CREATE TABLE N_PP (n_pp BIGINT UNSIGNED KEY)");
383 $dbh->do("INSERT INTO N_PP (n_pp) VALUES (?)", undef, 0);
384
385
386 $dbh->do("CREATE TABLE N_11 (
387 cui_1 CHAR(10) NOT NULL,
388 cui_2 CHAR(10) NOT NULL,
389 n_11 BIGINT NOT NULL,
390 PRIMARY KEY (cui_1, cui_2) )" );
391
392 $dbh->do("CREATE TABLE N_1P (
393 cui_1 CHAR(10) NOT NULL,
394 n_1p BIGINT NOT NULL,
395 PRIMARY KEY (cui_1) )" );
396
397 $dbh->do("CREATE TABLE N_P1 (
398 cui_2 CHAR(10) NOT NULL,
399 n_p1 BIGINT NOT NULL,
400 PRIMARY KEY (cui_2) )" );
401
402 }
403  
404 ###############################################################################
405 sub update_row {
406 my ($dbh, # database handler
407 $table, # name of table being updated
408 $updated_field, # field being updated
409 $updated_value, # value to change in field
410 $key_names_ref, # array ref for key names of table
411 $key_values_ref # array ref to values to locate row in table
412 ) = @_;
413
414
415 # Build conditional statement to locate row in table.
416 my $conditional = "";
417 if (@$key_names_ref) {
418 $conditional = join ' AND ', map {"$_ = ? "} @$key_names_ref;
419 }
420 else {
421 $conditional = "$updated_field > -1";
422 }
423 # Check if row to update is already in table
424 my $select = "SELECT * FROM $table WHERE $conditional LIMIT 1";
425 say $select if $DEBUG;
426 my $sth = $dbh->prepare($select);
427 $sth->execute(@$key_values_ref);
428
429 # If it is, update entry with new sum.
430 my @match = $sth->fetchrow_array();
431 if ( @match ) {
432
433 $updated_value += $match[-1];
434
435 my $update = "UPDATE $table SET $updated_field = ? WHERE $conditional";
436
437 $dbh->do( $update,undef, $updated_value, @$key_values_ref );
438 }
439 # Otherwise, insert a new row into the table.
440 else {
441
442 # Build the insert statement
443 my $key_list = join ', ', @$key_names_ref;
444 my $field_length = @$key_names_ref;
445 my $insert ="INSERT INTO $table ($key_list, $updated_field) " .
446 "VALUES (" . '?, ' x $field_length . '?' . ")";
447 say $insert if $DEBUG;
448 $dbh->do($insert, undef, @$key_values_ref, $updated_value);
449 }
450 }
451  
452 ##############################################################################
453 sub update_database {
454 my($dbh, $bigram_ref, $n1p_ref, $np1_ref, $npp) = (@_);
455
456 # Add all of the bigram counts to the database
457 say STDERR "n11:" if $DEBUG;
458 foreach my $cui_1 (keys %$bigram_ref){
459 foreach my $cui_2 (keys %{$$bigram_ref{$cui_1}}) {
460 my $n_11 = $$bigram_ref{$cui_1}{$cui_2};
461
462 say STDERR "$cui_1\t$cui_2\t$n_11" if $DEBUG;
463
464 update_row($dbh, 'N_11', 'n_11', $n_11,
465 ['cui_1', 'cui_2'], [$cui_1, $cui_2] );
466 }
467 }
468
469 # Add all of the CUI_1 sums to database
470 print STDERR "n1p: \n" if $DEBUG;
471 foreach my $cui_1 (keys %$n1p_ref) {
472 my $n_1p = $$n1p_ref{$cui_1};
473  
474 print STDERR "$cui_1 $n_1p \n" if $DEBUG;
475
476 update_row($dbh, 'N_1P', 'n_1p', $n_1p, ['cui_1'], [$cui_1] );
477
478 }
479
480 # Add all of the CUI_2 sums to database
481 print STDERR "np1: \n" if $DEBUG;
482 foreach my $cui_2 (keys %$np1_ref) {
483 my $n_p1 = $$np1_ref{$cui_2};
484 say "$cui_2 $n_p1" if $DEBUG;
485
486 update_row($dbh, 'N_P1', 'n_p1', $n_p1, ['cui_2'], [$cui_2] );
487 }
488
489 # Finally, update the table with the total sum of all bigrams observed.
490 update_row($dbh, 'N_PP', 'n_pp', $npp, [], [] );
491 }
492  
493 ###############################################################################
494 # This is where the magic happens
495 ###############################################################################
496  
497 sub process_files {
498 my @files = @_;
499
500 my %bigrams; # cui_1 => cui_2 => sum of cui_1 preceeding cui_2
501 my %n1p; # cui => sum of cui as cui_1
502 my %np1; # cui => sum of cui as cui_2
503 my $npp; # total sum of all bigram observations
504
505 # Anonymous subroutine to update the bigram and marginal counts
506 my $incrementor = sub {
507 my($cui_1, $cui_2, $same_phrase) = @_;
508
509 unless (exists $$same_phrase{$cui_1}{$cui_2}) {
510 $bigrams{$cui_1}{$cui_2}++;
511 $n1p{$cui_1}++;
512 $np1{$cui_2}++;
513 $npp++;
514 }
515
516 $$same_phrase{$cui_1}{$cui_2} = 1;
517 };
518
519 for my $file (@files) {
520
521 if( File::Type->mime_type($file) =~ /x-gzip/) {
522 process_gz_file($file, $incrementor);
523 }
524 else {
525 process_file($file, $incrementor);
526 }
527 }
528
529 return (\%bigrams, \%n1p, \%np1, $npp);
530 }
531 ###############################################################################
532 sub process_file {
533 my $file = shift; # text/plain file to process
534 my $incrementor = shift; # ref to anon sub that updates bigram counts
535
536 open(my $fh, '<', $file) or die "Cannot read $file: $!"; #fh = filehandle
537 say "Parsing uncompressed file: $file" if $VERBOSE;
538
539 until (eof $fh ){
540 count_bigrams( read_utterance( $fh ), $incrementor );
541 }
542 }
543  
544 sub process_gz_file {
545  
546 my $file = shift; # compressed .gz file to process
547 my $incrementor = shift; # ref to anon sub that updates bigram counts
548
549 my $gz = gzopen("$file", "rb") or die "Cannot read gzip compressed $file\n";
550 say "Parsing gzip compressed file: $file" if $VERBOSE;
551
552 # Count the bigrams in each utterance until the end of the file.
553 until ($gz->gzeof()) {
554 count_bigrams( read_gz_utterance($gz), $incrementor );
555 }
556
557 $gz->gzclose();
558 }
559  
560 ###############################################################################
561 # take filehandle as lexical variable
562 # returns ref to array of phrases for single utterance
563 sub read_utterance {
564 my $fh = shift;
565
566 my @phrases_in_utterance;
567
568 # The following loop will iterate over all the phrases for this utterance
569 while (<$fh>) {
570
571 # Finish when we reach the End Of Utterance (EOU) marker
572 last if /^'EOU'/;
573
574 # Skip all lines that aren't mappings for a phrase in the utterance
575 next unless /^mappings/;
576
577 my @mappings = @{ get_mappings($_) };
578  
579 push @phrases_in_utterance, \@mappings if @mappings;
580 }
581
582 return \@phrases_in_utterance;
583 }
584  
585 ###############################################################################
586 # takes the gzip "filehandle" object
587 # returns ref to array of phrases for single utterance
588 sub read_gz_utterance {
589 my $gz = shift;
590
591 my @phrases;
592
593 # The following loop will iterate over all the phrases for this utterance
594 while ($gz->gzreadline($_)) {
595
596 # Finish when we reach the End Of Utterance (EOU) marker
597 last if /^'EOU'/;
598
599 # Skip all lines that aren't mappings for a phrase in the utterance
600 next unless /^mappings/;
601
602 my @mappings = @{ get_mappings($_) };
603  
604 push @phrases, \@mappings if @mappings;
605 }
606
607 return \@phrases;
608 }
609  
610 ###############################################################################
611 sub get_mappings {
612 my $mapping_string = shift; # the line for which /^mappings/ is true
613
614 # Break mappings into each possible mapping of phrase into CUIs
615 my @maps = split /map\(/, $mapping_string;
616  
617 # Collect the CUIs in each possible mapping (assumes format 'C1234567')
618 # as a set of strings
619 my @mappings;
620 for my $map (@maps) {
621
622 my $CUI_string = join " ", ( $map =~ m/C\d{7}/g );
623
624 say $CUI_string if $CUI_string and $DEBUG;
625
626 push @mappings, $CUI_string if $CUI_string;
627 }
628  
629 return \@mappings;
630 }
631  
632 ###############################################################################
633 sub count_bigrams {
634 my( $phrases_ref, # reference to list of mappings for single utterance
635 $incrementor # anonymous subroutine to update counting hashes
636 ) = @_;
637
638 my @phrases = @$phrases_ref;
639
640 # Iterate through n-1 phrases in utterance
641 for (my $i = 0; $i <= $#phrases; $i++) {
642
643 my @phrase_1 = @{ $phrases[$i] }; # Mappings for current phrase
644 my @phrase_2 = @{ $phrases[$i + 1] } if $i < $#phrases;; # Mappings for the next phrase
645  
646 my %prior; # Tracks bigrams within same phrase to avoid double counting
647
648 # Loop through each of the mappings of the current phrase
649 foreach my $map_str_p1 ( @phrase_1 ) {
650 my @cuis = split ' ', $map_str_p1;
651
652 # Count bigrams up to the k-1th CUI
653 for (my $k = 0; $k < $#cuis; $k++) {
654 my $cui_1 = $cuis[$k];
655 my $cui_2 = $cuis[$k+1];
656
657 $incrementor->($cui_1, $cui_2, \%prior);
658 }
659 if ( $i < $#phrases ) {
660 # Count the kth CUI with the first of each of the next phrases maps
661 foreach my $map_str_p2 ( @phrase_2 ) {
662 (my $first_of_next_phrase) = $map_str_p2 =~ /(C\d{7})/;
663
664 $incrementor->($cuis[-1], $first_of_next_phrase, \%prior);
665 }
666 }
667 }
668 }
669 }