blib/script/umls_similarity_server.pl untested

filter: Statementstmt 0.0% 0 / 421 Branchbran 0.0% 0 / 108 Conditioncond 0.0% 0 / 34 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 617 SCAR 62.3
CC
22
Cov
0%
setInterface
30.0
getCuis
20.0
getAllForms
20.0
CRAP 506.0
1 #!/usr/local/bin/perl -wT
2  
3 # umls_similarity_server.pl version 0.01
4 # (Last updated $Id: umls_similarity_server.pl,v 1.16 2013/04/16 23:29:40 btmcinnes Exp $)
5 #
6 # ---------------------------------------------------------------------
7  
8 # Include external packages
9 use strict;
10 use Getopt::Long;
11 use File::Temp;
12 use File::Spec;
13 use UMLS::Similarity;
14 use POSIX ':sys_wait_h'; # for waitpid() and friends; used by reaper()
15 use POSIX qw(setsid); # to daemonize
16  
17 my $doc_base = '/var/www/umls_similarity';
18  
19 # Get the command-line options
20 our($opt_port, $opt_logfile, $opt_maxchild, $opt_version, $opt_help);
21 &GetOptions("port=i", "logfile=s", "maxchild=i", "version", "help");
22  
23 # Check for version
24 if(defined($opt_version))
25 {
26 print "umls_similarity_server.pl version 0.01\n";
27 print "UMLS::Similarity version ".($UMLS::Similarity::VERSION)."\n";
28 print "Copyright (c) 2010-2011, Ted Pedersen, Bridget McInnes\n";
29 exit;
30 }
31  
32 # Check for help
33 if(defined($opt_help))
34 {
35 print "Usage: umls_similarity_server.pl [--port PORTNUMBER] [--logfile LOGFILE] [--maxchild NUM] \n";
36  
37 print " | --help\n";
38 print " | --version\n";
39  
40 print "\nStarts the similarity server, which listens for requests on a predefined\n";
41 print "port. It presents a network interface to the UMLS::Similarity modules.\n\n";
42 print "Options:\n";
43  
44 print "--port Specify the port PORTNUMBER for the server to listen on.\n";
45 print "--logfile The output LOGFILE where any error or warning messages\n";
46 print " should be written out.\n";
47 print "--maxchild Specify the maximum number NUM of the processes that should\n";
48 print " be forked to handle the requests.\n";
49 print "--help Display this help message and quit.\n";
50 print "--version Display the version information and quit.\n";
51 exit;
52 }
53  
54 # Local variables
55 my $localport = 31135;
56 my $error_log = undef;
57 my $maxchild = 4; # max number of child processes at one time
58 sub reaper;
59  
60 # Set the log file, if specified
61 $error_log = $1 if(defined($opt_logfile) and $opt_logfile ne "" and $opt_logfile =~ /^(.*)$/);
62 print STDERR "Error log = ".($error_log?$error_log:"<none>")."\n";
63  
64 # Set the port
65 $localport = $opt_port if(defined($opt_port));
66 print STDERR "Local port = $localport\n";
67  
68 # Set the maxchild
69 $maxchild = $opt_maxchild if(defined($opt_maxchild));
70 print STDERR "Maxchild = $maxchild\n";
71  
72 # Create the temporary lock file
73 my $lockfh = File::Temp->new();
74 my $lock_file = $lockfh->filename();
75 die "Error: Unable to create temporary lock file.\n" if(!$lockfh);
76 print $lockfh $$;
77 close $lockfh or die "Error: Cannot close lock file: $! \n";
78 print STDERR "Loading modules... ";
79  
80 # prototypes:
81 sub getAllForms ($ $);
82 sub getAllDefForms ($ $);
83 sub getlock ();
84 sub releaselock ();
85 sub timestamp ($);
86  
87 use sigtrap handler => \&bailout, 'normal-signals';
88 use IO::Socket::INET;
89  
90 use UMLS::Interface;
91 use UMLS::Similarity::path;
92 use UMLS::Similarity::lch;
93 use UMLS::Similarity::wup;
94 use UMLS::Similarity::res;
95 use UMLS::Similarity::lin;
96 use UMLS::Similarity::jcn;
97 use UMLS::Similarity::cdist;
98 use UMLS::Similarity::nam;
99 use UMLS::Similarity::zhong;
100 use UMLS::Similarity::vector;
101 use UMLS::Similarity::lesk;
102 use UMLS::Similarity::random;
103  
104 # reset (untaint) the PATH
105 $ENV{PATH} = '/bin:/usr/bin:/usr/local/bin';
106 print STDERR "done.\n";
107 print STDERR "Starting server... going into background.\n";
108  
109 # Daemonize
110 open STDIN, '/dev/null' or die "Can't read /dev/null: $! \n";
111 open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $! \n";
112  
113 # The is the socket we listen to
114 my $socket = IO::Socket::INET->new(
115 LocalPort => $localport,
116 Listen => SOMAXCONN,
117 Reuse => 1,
118 Type => SOCK_STREAM
119 ) or die "Could not bind to network port: $! \n";
120 print STDERR "Closing output to terminal.\n";
121  
122 if(defined($error_log))
123 {
124 print STDERR "All future messages will be routed to the log file.\n";
125 if(!open(STDERR, '>>', $error_log))
126 {
127 print "Error: Could open error log.\n";
128 die "Error: Could not re-open STDERR.\n";
129 }
130 chmod 0664, $error_log;
131 }
132 else
133 {
134 print STDERR "No more messages will be printed (even if the server dies).\n";
135 open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $! \n";
136 }
137  
138 chdir '/' or die(&timestamp("Can't chdir to /: $! \n"));
139 defined(my $pid = fork) or die(&timestamp("Can't fork: $! \n"));
140 exit if $pid;
141 setsid or die(&timestamp("Can't start a new session: $! \n"));
142 umask 0;
143  
144 my %option_hash = ();
145  
146 our $interface;
147 our $path;
148 our $lch;
149 our $wup;
150 our $res;
151 our $lin;
152 our $jcn;
153 our $nam;
154 our $zhong;
155 our $cdist;
156 our $vector;
157 our $lesk;
158 our $random;
159  
160 my @measures = ();
161  
162 &setInterface("MSH", "PAR/CHD", "path");
163  
164  
165 # this variable is incremented after every fork, and is
166 # updated by reaper() when a child process dies
167 my $num_children = 0;
168 ## SEE BELOW
169 # automatically reap child processes
170 #$SIG{CHLD} = 'IGNORE';
171 ##
172 ## BETTER WAY:
173 # handle death of child process
174 $SIG{CHLD} = \&reaper;
175 my $interrupted = 0;
176 ACCEPT:
177  
178 while((my $client = $socket->accept) or $interrupted)
179 {
180 $interrupted = 0;
181 next unless $client; # a SIGCHLD was raised
182  
183 # check to see if it's okay to handle this request
184 if($num_children >= $maxchild)
185 {
186 print $client "busy\015\012";
187 $client->close;
188 undef $client;
189 next ACCEPT;
190 }
191 my $childpid;
192  
193 # fork; let the child handle the actual request
194 if($childpid = fork)
195 {
196  
197 # This is the parent
198 $num_children++;
199  
200 # go wait for next request
201 undef $client;
202 next ACCEPT;
203 }
204  
205 # This is the child process
206 defined $childpid or die(&timestamp("Could not fork: $! \n"));
207  
208 # here we're the child, so we actually handle the request
209 my @requests;
210 while(my $request = <$client>)
211 {
212 last if $request eq "\015\012";
213 push @requests, $request;
214 }
215 foreach my $i (0..$#requests)
216 {
217 my $request = $requests[$i];
218 my $rnum = $i + 1;
219 my $type = 'UNDEFINED';
220 if($request =~ m/^(\w)\b/)
221 {
222 $type = $1;
223 }
224 else
225 {
226 $type = 'UNDEFINED';
227 }
228  
229 print STDERR "TYPE: $type\n";
230
231 if($type eq 't') {
232
233 my (undef, $cui) = split/\|/, $request;
234 my $preferred = "";
235 if($cui=~/C0000000/) {
236 $preferred = "UMLS_ROOT";
237 }
238 else {
239 print STDERR "CUI: $cui\n";
240 $preferred = $interface->getAllPreferredTerm($cui);
241 }
242
243 $preferred=~s/\s+/ /g;
244 $preferred=~s/^\s+//g;
245 $preferred=~s/\s+$//g;
246 $preferred=~s/\s/_/g;
247  
248 print $client "t $cui $preferred\015\012";
249 }
250  
251 elsif($type eq 'v')
252 {
253 eval{
254 # get version information
255 my $u_version = $interface->version();
256 my $i_version = $UMLS::Interface::VERSION;
257 my $s_version = $UMLS::Similarity::VERSION;
258 print $client "v UMLS $u_version\015\012";
259 print $client "v UMLS::Interface $i_version\015\012";
260 print $client "v UMLS::Similarity $s_version\015\012";
261 };
262 print(STDERR &timestamp("$@\n")) if($@);
263 }
264 elsif($type eq 'r')
265 {
266 my (undef, $word1, $word2, $button, $measure, $sab, $rel)= split /\|/, $request;
267  
268 print STDERR "$word1 $word2 $button $measure $sab $rel\n";
269  
270 &setInterface($sab, $rel, $measure);
271  
272 unless(defined $word1 and defined $word2)
273 {
274 print $client "! Error: undefined input words\015\012";
275 sleep 2;
276 goto EXIT_CHILD;
277 }
278 my $module;
279 if($measure =~ /^(?:path|lch|wup|res|lin|jcn|nam|zhong|cdist|lesk|vector|random)$/){
280 no strict 'refs';
281 $module = $$measure;
282 unless(defined $module) {
283 print $client "! Error: Couldn't get reference to measure\015\012";
284 sleep 2;
285 goto EXIT_CHILD;
286 }
287 }
288 else
289 {
290 print $client "! Error: no such measure $measure\015\012";
291 sleep 2;
292 goto EXIT_CHILD;
293 }
294
295 my @wps1 = ();
296 my @wps2 = ();
297  
298 if($button eq "Compute Similarity") {
299 @wps1 = getAllForms($word1, $interface);
300 @wps2 = getAllForms($word2, $interface);
301 }
302 else {
303 @wps1 = getAllDefForms($word1, $interface);
304 @wps2 = getAllDefForms($word2, $interface);
305 }
306  
307 unless(scalar @wps1) {
308 print $client "! $word1 was not found in $sab\015\012";
309 goto EXIT_CHILD;
310 }
311 unless(scalar @wps2) {
312 print $client "! $word2 was not found in $sab\015\012";
313 goto EXIT_CHILD;
314 }
315
316 getlock;
317 foreach my $wps1 (@wps1)
318 {
319 foreach my $wps2 (@wps2)
320 {
321 eval{
322 my $score = $module->getRelatedness($wps1, $wps2);
323 print $client "r $measure $wps1 $wps2 $score\015\012";
324 };
325
326 print(STDERR &timestamp("$@\n")) if($@);
327 }
328 }
329 releaselock;
330
331 getlock;
332 }
333 elsif($type eq 'g') {
334  
335 my (undef, $button, $word) = split/\|/, $request;
336  
337 print STDERR "HERE ($button) g ($word)\n";
338 my @cuis = ();
339 if($word =~/[Cc][0-9]+/) {
340 push @cuis, uc($word);
341 }
342 else {
343 if($button eq "Compute Similarity") {
344 @cuis = getAllForms($word, $interface);
345 }
346 else {
347 @cuis = getAllDefForms($word, $interface);
348 }
349 print STDERR "CUIS: @cuis\n";
350 }
351 foreach my $cui (@cuis) {
352 my $defs = $interface->getCuiDef($cui, 1);
353 my $string = "";
354 foreach my $def (@{$defs}) {
355 my @array = split/\s+/, $def;
356 my $sab = shift @array;
357 $string .= "$sab : @array|";
358 }
359 print $client "g $cui $string\015\012";
360 print STDERR "g $cui $string\n";
361 }
362 }
363 elsif($type eq 'p') {
364
365 my (undef, $word1, $word2) = split/\|/, $request;
366
367 my @cuis1 = ();
368 if($word1 =~/[Cc][0-9]+/) {
369 push @cuis1, uc($word1);
370 }
371 else {
372 @cuis1 = getAllForms($word1, $interface);
373 }
374  
375 my @cuis2 = ();
376 if($word2 =~/[Cc][0-9]+/) {
377 push @cuis2, uc($word2);
378 }
379 else {
380 @cuis2 = getAllForms($word2, $interface);
381 }
382  
383 my $string = "";
384 foreach my $cui1 (@cuis1) {
385 my $t1 = $interface->getAllPreferredTerm($cui1);
386 foreach my $cui2 (@cuis2) {
387 my $t2 = $interface->getAllPreferredTerm($cui2);
388 my $paths = $interface->findShortestPath($cui1, $cui2);
389 print STDERR "HERE: $cui1 $t1 $cui2 $t2\n";
390 foreach my $path (@{$paths}) {
391 my @array = split/\s+/, $path;
392 $string .= "$cui1 ($t1)|$cui2 ($t2)|";
393 foreach my $i (0..$#array) {
394 my $concept = $array[$i];
395 my $t = $interface->getAllPreferredTerm($concept);
396 $string.= "$concept ($t) => ";
397 }
398 chop $string; chop $string; chop $string; chop $string;
399 $string .= "|"
400 }
401 }
402 }
403 chop $string;
404 print $client "p $string\015\012";
405 print STDERR "p $string\n";
406 }
407 else
408 {
409 print $client "! Bad request type `$type'\015\012";
410 }
411 }
412
413 # Terminate ALL messages with CRLF (\015\012). Do NOT use
414 # \r\n (the meaning of \r and \n varies on different platforms).
415 EXIT_CHILD:
416 print $client "\015\012";
417 $client->close;
418 $socket->close;
419
420 # don't let the child accept:
421 exit;
422 }
423 $socket->close;
424 exit;
425  
426 sub setInterface {
427
428 my $sab = shift;
429 my $rel = shift;
430 my $measure = shift;
431  
432 %option_hash = ();
433  
434 my @rels = split/\//, $rel;
435 my $rstring = join ", ", @rels;
436
437 print STDERR "In setInterface($sab, $rel, $measure)\n";
438  
439 ## create config file
440 my $fh = File::Temp->new();
441 my $cfg = $fh->filename();
442 die "Error: Unable to create temporary config file.\n" if(!$fh);
443  
444 if($measure=~/lesk|vector/) {
445 print $fh "SABDEF :: include $sab\n";
446 print $fh "RELDEF :: include $rstring\n";
447 }
448 else {
449 print $fh "SAB :: include $sab\n";
450 print $fh "REL :: include $rstring\n";
451 }
452 close $fh or die "Error: Unable to close config file.\n";
453  
454 print STDERR "FILENAME: $cfg\n";
455  
456 # set the information content default files
457 my %ic_options = ();
458 my $relname = join ".", @rels;
459 my $sabname = lc($sab);
460 $relname = lc($relname);
461 my $icfilename = "icprop.$sabname.$relname";
462 $ic_options{"icpropagation"} = "$doc_base/icpropagation/$icfilename";
463
464 # set the vector default files
465 my %vector_options = ();
466 $vector_options{"vectormatrix"} = "$doc_base/vectorfiles/mtx.remove75.uremove1k";
467 $vector_options{"vectorindex"} = "$doc_base/vectorfiles/idx.remove75.uremove1k";
468
469 $option_hash{"config"} = $cfg;
470 #$option_hash{"debug"} = 1;
471 $option_hash{"forcerun"} = 1;
472  
473 $interface = UMLS::Interface->new(\%option_hash);
474  
475 if($measure=~/path|lch|wup|res|lin|jcn|nam|zhong|cdist|random/) {
476 print STDERR "Setting measures\n";
477
478 $path = UMLS::Similarity::path->new($interface);
479 $lch = UMLS::Similarity::lch->new($interface);
480 $wup = UMLS::Similarity::wup->new($interface);
481 $res = UMLS::Similarity::res->new($interface, \%ic_options);
482 $lin = UMLS::Similarity::lin->new($interface, \%ic_options);
483 $jcn = UMLS::Similarity::jcn->new($interface, \%ic_options);
484 $nam = UMLS::Similarity::nam->new($interface);
485 $zhong = UMLS::Similarity::zhong->new($interface);
486 $cdist = UMLS::Similarity::cdist->new($interface);
487 $random = UMLS::Similarity::random->new($interface);
488 }
489 if($measure=~/lesk|vector/) {
490 $lesk = UMLS::Similarity::lesk->new($interface);
491 $vector = UMLS::Similarity::vector->new($interface, \%vector_options);
492 }
493  
494 @measures = ($path, $wup, $lch, $res, $lin, $jcn, $nam, $zhong, $cdist, $lesk, $vector, $random);
495 }
496  
497 sub getCuis {
498 my $word = shift;
499  
500 my $forms = undef;
501  
502 # check if the string is a CUI just use it
503 if($word =~ m/C[0-9]+/) { push @{$forms}, $word; }
504
505 # otherwise find the CUIs
506 else {
507 getlock;
508 my @temp = $interface->getConceptList($word);
509 eval{$forms = $interface->getConceptList($word);};
510 print(STDERR &timestamp("$@\n")) if($@);
511 releaselock;
512 return () unless scalar @{$forms};
513 }
514 # return the forms
515 return @{$forms};
516 }
517  
518 sub getAllForms ($ $)
519 {
520 my $word = shift;
521 my $umls = shift;
522
523 print STDERR "In getAllForms ($word)\n";
524  
525 my $forms = undef;
526  
527
528 # check if the string is a CUI just use it
529 if($word =~ m/[cC][0-9]+/) { $word = uc($word); push @{$forms}, $word; }
530
531 # otherwise find the CUIs
532 else {
533 getlock;
534 eval{$forms = $umls->getConceptList($word);};
535 print STDERR "Forms ($word) : @{$forms}\n";
536 print(STDERR &timestamp("$@\n")) if($@);
537 releaselock;
538 return () unless scalar @{$forms};
539 }
540 # return the forms
541 print STDERR "Returning Forms ($word) : @{$forms}\n";
542 return @{$forms};
543 }
544  
545 sub getAllDefForms ($ $)
546 {
547 my $word = shift;
548 my $umls = shift;
549
550 print STDERR "In getDefAllForms ($word)\n";
551  
552 my $forms = undef;
553
554 # check if the string is a CUI just use it
555 if($word =~ m/[cC][0-9]+/) { $word = uc($word); push @{$forms}, $word; }
556
557 # otherwise find the CUIs
558 else {
559 getlock;
560 eval{$forms = $umls->getDefConceptList($word);};
561 print STDERR "Forms ($word) : @{$forms}\n";
562 print(STDERR &timestamp("$@\n")) if($@);
563 releaselock;
564 return () unless scalar @{$forms};
565 }
566 # return the forms
567 print STDERR "Returning Forms ($word) : @{$forms}\n";
568 return @{$forms};
569 }
570  
571  
572 # A signal handler, good for most normal signals (esp. INT). Mostly we just
573 # want to close the socket we're listening to and delete the lock file.
574 sub bailout
575 {
576 my $sig = shift;
577 $sig = defined $sig ? $sig : "?UNKNOWN?";
578 $socket->close if defined $socket;
579 print(STDERR &timestamp("Bailing out (SIG$sig).\n"));
580 releaselock if($lockfh);
581 exit 1;
582 }
583 use Fcntl qw/:flock/;
584  
585 # gets a lock on $lockfh. The return value is that of flock.
586 sub getlock ()
587 {
588 open($lockfh, '>>', $lock_file) or die(&timestamp("Cannot open lock file $lock_file: $! \n"));
589 eval{flock $lockfh, LOCK_EX;};
590 print(STDERR &timestamp("$@\n")) if($@);
591 }
592  
593 # releases a lock on $lockfh. The return value is that of flock.
594 sub releaselock ()
595 {
596 eval{
597 flock $lockfh, LOCK_UN;
598 close $lockfh;
599 };
600 print(STDERR &timestamp("$@\n")) if($@);
601 }
602  
603 # attach a time stamp
604 sub timestamp ($)
605 {
606 my $instring = shift;
607 return $instring if(!defined($instring));
608 my @monthNames = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
609 my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear) = localtime();
610 my $year = 1900 + $yearOffset;
611 return "["."$dayOfMonth/$monthNames[$month]/$year:$hour:$minute:$second"."] $instring";
612 }
613  
614 # sub to reap child processes (so they don't become zombies)
615 # also updates the num_children variable
616 #
617 # Sub was loosely inspired by an example at
618 # http://www.india-seo.com/perl/cookbook/ch16_20.htm
619 sub reaper
620 {
621 my $moribund;
622 if(my $pid = waitpid(-1, WNOHANG) > 0)
623 {
624 $num_children-- if WIFEXITED($?);
625 }
626 $interrupted = 1;
627 $SIG{CHLD} = \&reaper; # cursed be SysV
628 }
629  
630 __END__