-
Notifications
You must be signed in to change notification settings - Fork 14
/
MetaMapLite.java
1618 lines (1530 loc) · 68.3 KB
/
MetaMapLite.java
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
//
package gov.nih.nlm.nls.ner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.HashSet;
import java.lang.reflect.InvocationTargetException;
import gov.nih.nlm.nls.utils.StringUtils;
import gov.nih.nlm.nls.metamap.lite.pipeline.plugins.Plugin;
import gov.nih.nlm.nls.metamap.lite.pipeline.plugins.PluginRegistry;
import gov.nih.nlm.nls.metamap.lite.pipeline.plugins.PipelineRegistry;
import gov.nih.nlm.nls.metamap.lite.types.Entity;
import gov.nih.nlm.nls.metamap.lite.MarkAbbreviations;
import gov.nih.nlm.nls.metamap.lite.SentenceExtractor;
import gov.nih.nlm.nls.metamap.lite.OpenNLPSentenceExtractor;
import gov.nih.nlm.nls.metamap.lite.SentenceAnnotator;
import gov.nih.nlm.nls.metamap.lite.OpenNLPPoSTagger;
import gov.nih.nlm.nls.metamap.lite.IVFLookup;
import gov.nih.nlm.nls.metamap.lite.EntityLookup;
import gov.nih.nlm.nls.metamap.lite.EntityLookup4;
import gov.nih.nlm.nls.metamap.lite.EntityLookup5;
import gov.nih.nlm.nls.metamap.lite.SemanticGroupFilter;
import gov.nih.nlm.nls.metamap.lite.SemanticGroups;
import gov.nih.nlm.nls.metamap.lite.EntityAnnotation;
import gov.nih.nlm.nls.metamap.lite.resultformats.mmi.MMI;
import gov.nih.nlm.nls.metamap.lite.resultformats.Brat;
import gov.nih.nlm.nls.metamap.lite.resultformats.CuiList;
import gov.nih.nlm.nls.metamap.lite.resultformats.BcEvaluate;
import gov.nih.nlm.nls.metamap.lite.resultformats.FullJson;
import gov.nih.nlm.nls.metamap.lite.BioCUtilities;
import gov.nih.nlm.nls.metamap.lite.Phrase;
import gov.nih.nlm.nls.metamap.lite.OpenNLPChunker;
import gov.nih.nlm.nls.metamap.lite.ChunkerMethod;
import gov.nih.nlm.nls.metamap.prefix.ERToken;
import gov.nih.nlm.nls.metamap.document.ChemDNER;
import gov.nih.nlm.nls.metamap.document.ChemDNERSLDI;
import gov.nih.nlm.nls.metamap.document.FreeText;
import gov.nih.nlm.nls.metamap.document.NCBICorpusDocument;
import gov.nih.nlm.nls.metamap.document.SingleLineInput;
import gov.nih.nlm.nls.metamap.document.SingleLineDelimitedInputWithID;
import gov.nih.nlm.nls.metamap.document.BioCDocumentLoader;
import gov.nih.nlm.nls.metamap.document.BioCDocumentLoaderImpl;
import gov.nih.nlm.nls.metamap.document.BioCDocumentLoaderRegistry;
import gov.nih.nlm.nls.metamap.document.SemEvalDocument;
import gov.nih.nlm.nls.metamap.document.PubMedXMLDocument;
import gov.nih.nlm.nls.metamap.document.PubTator;
import gov.nih.nlm.nls.metamap.document.MedlineDocument;
import gov.nih.nlm.nls.metamap.lite.resultformats.ResultFormatter;
import gov.nih.nlm.nls.metamap.lite.resultformats.ResultFormatterRegistry;
import gov.nih.nlm.nls.metamap.lite.dictionary.AugmentedDictionary;
// import gov.nih.nlm.nls.metamap.lite.context.ContextWrapper;
import gov.nih.nlm.nls.types.Sentence;
import bioc.BioCDocument;
import bioc.BioCPassage;
import bioc.BioCAnnotation;
import bioc.BioCRelation;
import bioc.BioCSentence;
import bioc.tool.AbbrConverter;
import bioc.tool.AbbrInfo;
import bioc.tool.ExtractAbbrev;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import opennlp.tools.util.Span;
import gov.nih.nlm.nls.utils.Configuration;
import gov.nih.nlm.nls.metamap.mmi.TermFrequency;
import gov.nih.nlm.nls.metamap.mmi.Ranking;
/**
* <h2>Using MetaMapLite from a Java program:</h2>
* <pre>
* Properties myProperties = MetaMapLite.getDefaultConfiguration();
* myProperties.setProperty("opennlp.models.directory",
* "/Projects/metamaplite/data/models");
* MetaMapLite.expandModelsDir(myProperties);
* myProperties.setProperty("metamaplite.index.directory",
* "/Projects/metamaplite/data/ivf/strict");
* myProperties.setProperty("metamaplite.excluded.termsfile",
* "/Projects/metamaplite/data/specialterms.txt");
* MetaMapLite.expandIndexDir(myProperties);
* MetaMapLite metaMapLiteInst = new MetaMapLite(myProperties);
* BioCDocument document = FreeText.instantiateBioCDocument("FDA has strengthened the warning ...");
* List<BioCDocument> documentList = new ArrayList<BioCDocument>();
* documentList.add(document);
* List<Entity> entityList = metaMapLiteInst.processDocumentList(documentList);
* for (Entity entity: entityList) {
* for (Ev ev: entity.getEvSet()) {
* System.out.print(ev.getConceptInfo().getCUI() + "|" + entity.getMatchedText());
* System.out.println();
* }
* }
* </pre>
* <h2>Properties precedence (from highest to lowest)</h2>
* <ul>
* <li>Command line options</li>
* <li>System properties</li>
* <li>MetaMap property file</li>
* <li>Defaults</li>
* </ul>
*
* <h2>Configuration Properties:</h2>
* <dl>
* <dt>metamaplite.semanticgroup</dt><dd>restrict output to concepts with specified semantic types</dd>
* <dt>metamaplite.sourceset</dt><dd>restrict output to concepts in specified sources</dd>
* <dt>metamaplite.segmentation.method</dt><dd>Set method for text segmentation (values: SENTENCES, BLANKLINES, LINES; default: SENTENCES)</dd>
* <dt>metamaplite.negation.detector</dt><dd>negation detector class: default: gov.nih.nlm.nls.metamap.lite.NegEx</dd>
* <dt>opennlp.models.directory</dt><dd>parent location of opennlp models</dd>
* <dt>opennlp.en-sent.bin.path</dt><dd>path for sentence detector model (default: data/models/en-sent.bin)</dd>
* <dt>opennlp.en-token.bin.path</dt><dd>path for tokenizer model (default: data/models/en-token.bin)</dd>
* <dt>opennlp.en-pos.bin.path</dt><dd>path for part-of-speech model (default: data/models/en-pos-maxent.bin)</dd>
* <dt>opennlp.en-chunker.bin.path</dt><dd>path for chunker model (default: data/models/en-chunker.bin)</dd>
* <dt>metamaplite.index.directory</dt><dd>parent location of metamap indexes, sets the following properties:</dd>
* <dt>metamaplite.ivf.cuiconceptindex</dt><dd>location of cui-concept index</dd>
* <dt>metamaplite.ivf.cuisourceinfoindex</dt><dd>location of cui-sourceinfo index</dd>
* <dt>metamaplite.ivf.cuisemantictypeindex</dt><dd>location of cui-semantictype index</dd>
* <dt>metamaplite.ivf.varsindex</dt><dd>location of variants to path/distance index</dd>
* <dt>metamaplite.ivf.meshtcrelaxedindex</dt><dd>location of term to treecodes index</dd>
* </dl>
*
* <h2>Command line frontend properties </h2>
* <dl>
* <dt>metamaplite.document.inputtype</dt><dd>document input type (default: freetext)</dd>
* <dt>metamaplite.inputfilelist</dt><dd>list input files separated by commas in value of property.</dd>
* <dt>metamaplite.inputfilelistfile</dt><dd>use file containing list of files for input, one file per line.</dd>
* <dt>metamaplite.list.acronyms</dt><dd>list document acronyms</dd>
* <dt>metamaplite.list.sentences.with.postags</dt><dd>list document sentences only with part-of-speech tags</dd>
* <dt>metamaplite.list.sentences</dt><dd>list document sentences only.</dd>
* <dt>metamaplite.outputextension</dt><dd>set output file extension for result file(s).</dd>
* <dt>metamaplite.outputformat</dt><dd>entity list result format (default: mmi)</dd>
* <dt>metamaplite.property.file</dt><dd>load configuration from file (default: ./config/metamaplite.properties)</dd>
* </dl>
*
* <h2>User supplied document loader/reader properties</h2>
* <p>
* Properties are prefixed with string: "bioc.document.loader.freetext"
* followed by a period with the name of the document loader.
* <dl>
* <dt>bioc.document.loader.{name}</dt><dd>classname</dd>
* </dl>
* The class must implement the {@link gov.nih.nlm.nls.metamap.document.BioCDocumentLoader BioCDocumentLoader} interface.
* <p>
* Example property values
* <dl>
* <dt>bioc.document.loader.freetext</dt><dd>{@link gov.nih.nlm.nls.metamap.document.FreeText gov.nih.nlm.nls.metamap.document.FreeText}</dd>
* <dt>bioc.document.loader.chemdner</dt><dd>{@link gov.nih.nlm.nls.metamap.document.ChemDNER gov.nih.nlm.nls.metamap.document.ChemDNER}</dd>
* </dl>
* <p>
* User supplied result formatter properties
* <p>
* Properties are prefixed with string: "metamaplite.result.formatter"
* followed by a period with the name of the formatter.
* <dl>
* <dt>metamaplite.result.formatter.{name}</dt><dd>classname</dd>
* </dl>
* The class must implement interface
* {@link gov.nih.nlm.nls.metamap.lite.resultformats.ResultFormatter ResultFormatter.}
* <p>
* Example property values:
* <dl>
* <dt>metamaplite.result.formatter.cuilist</dt><dd>{@link gov.nih.nlm.nls.metamap.lite.resultformats.CuiList gov.nih.nlm.nls.metamap.lite.resultformats.CuiList}</dd>
* <dt>metamaplite.result.formatter.brat</dt><dd>{@link gov.nih.nlm.nls.metamap.lite.resultformats.Brat gov.nih.nlm.nls.metamap.lite.resultformats.Brat}</dd>
* </dl>
*/
public class MetaMapLite {
/** log4j logger instance */
private static final Logger logger = LoggerFactory.getLogger(MetaMapLite.class);
/** location of metamaplite.properties configuration file */
static String configPropertyFilename =
System.getProperty("metamaplite.property.file", "config/metamaplite.properties");
static Map<String,String> outputExtensionMap = new HashMap<String,String>();
static {
outputExtensionMap.put("bioc",".bioc");
outputExtensionMap.put("brat",".ann");
outputExtensionMap.put("mmi",".mmi");
outputExtensionMap.put("cdi",".cdi");
outputExtensionMap.put("cuilist",".cuis");
outputExtensionMap.put("json",".json");
}
Set<String> semanticGroup = new HashSet<String>(); // initially empty
Set<String> sourceSet = new HashSet<String>(); // initially empty
AbbrConverter abbrConverter = new AbbrConverter();
static ExtractAbbrev extractAbbr = new ExtractAbbrev();
Properties properties;
boolean detectNegationsFlag = false;
SentenceAnnotator sentenceAnnotator;
SentenceExtractor sentenceExtractor;
EntityLookup entityLookup;
enum SegmentatonType {
SENTENCES,
BLANKLINES,
LINES
};
SegmentatonType segmentationMethod = SegmentatonType.SENTENCES;
/** end of citation output marker */
public static String eotString = "<<< EOT >>>";
/** did user specify part-of-speech tagging? */
boolean addPartOfSpeechTagsFlag;
ChunkerMethod chunkerMethod;
public MetaMapLite(Properties properties)
throws ClassNotFoundException, InstantiationException,
NoSuchMethodException, IllegalAccessException,
IOException
{
this.properties = properties;
this.sentenceExtractor = new OpenNLPSentenceExtractor(properties);
this.addPartOfSpeechTagsFlag =
Boolean.parseBoolean(properties.getProperty("metamaplite.enable.postagging",
Boolean.toString(addPartOfSpeechTagsFlag)));
boolean enableScoring = false;
if (properties.containsKey("metamaplite.enable.scoring")) {
if (Boolean.parseBoolean(properties.getProperty("metamaplite.enable.scoring"))) {
enableScoring = true;
}
}
BioCDocumentLoaderRegistry.register("bioc",
"For BioC XML documents.",
new BioCDocumentLoaderImpl());
BioCDocumentLoaderRegistry.register("freetext",
"For freetext documents that are grammatically well behaved.",
new FreeText());
BioCDocumentLoaderRegistry.register("chemdner",
"ChemDNER format document sets",
new ChemDNER());
BioCDocumentLoaderRegistry.register("chemdnersldi",
"ChemDNER single line delimited with id format document sets",
new ChemDNERSLDI());
BioCDocumentLoaderRegistry.register("ncbicorpus",
"NCBI Disease Corpus format document sets",
new NCBICorpusDocument());
// BioCDocumentLoaderRegistry.register("semeval14",
// "SemEval Document (Almost FreeText)",
// new SemEvalDocument());
BioCDocumentLoaderRegistry.register("sli",
"Single Line Input document sets",
new SingleLineInput());
BioCDocumentLoaderRegistry.register("sldi",
"Single Line Input document sets",
new SingleLineInput());
BioCDocumentLoaderRegistry.register("sldiwi",
"Single Line Input document sets with id",
new SingleLineDelimitedInputWithID());
BioCDocumentLoaderRegistry.register("pubmed",
"PubMed XML Abstract",
new PubMedXMLDocument());
BioCDocumentLoaderRegistry.register("pubtator",
"PubTator format",
new PubTator());
BioCDocumentLoaderRegistry.register("medline",
"Medline format",
new MedlineDocument());
ResultFormatterRegistry.register("bc",
"BioCreative Evaluation Format",
new BcEvaluate());
ResultFormatterRegistry.register("bc-evaluate",
"BioCreative Evaluation Format",
new BcEvaluate());
ResultFormatterRegistry.register("bioc",
"BioCreative Evaluation Format",
new BcEvaluate());
ResultFormatterRegistry.register("cdi",
"BioCreative Evaluation Format",
new BcEvaluate());
ResultFormatterRegistry.register("brat",
"BRAT Annotation format (.ann)",
new Brat());
ResultFormatterRegistry.register("json",
"JSON format (.json)",
new FullJson());
ResultFormatterRegistry.register("fulljson",
"JSON format (.json)",
new FullJson());
ResultFormatterRegistry.register("mmi",
"Fielded MetaMap Indexing-like Output",
new MMI());
ResultFormatterRegistry.register("cuilist",
"UMLS CUI List Output",
new CuiList());
/** augment or override any built-in formats with ones specified by property file. */
BioCDocumentLoaderRegistry.register(properties);
ResultFormatterRegistry.register(properties);
this.setSemanticGroup(properties.getProperty("metamaplite.semanticgroup", "all").split(","));
this.setSourceSet(properties.getProperty("metamaplite.sourceset","all").split(","));
if (properties.containsKey("metamaplite.cuitermlistfile.filename")) {
// add semantic type and semantic group used by
// AugmentedDictionary if user is adding his own concepts.
this.semanticGroup.addAll(AugmentedDictionary.getCustomSemanticTypeSet());
this.sourceSet.addAll(AugmentedDictionary.getCustomSourceSet());
}
System.setProperty("metamaplite.result.formatter.property.brat.typename",
properties.getProperty("metamaplite.result.formatter.property.brat.typename",
"metamaplite"));
this.detectNegationsFlag =
Boolean.parseBoolean(properties.getProperty("metamaplite.detect.negations", "true"));
this.setSegmentationMethod
(properties.getProperty("metamaplite.segmentation.method","SENTENCE"));
}
/**
* Set list of semantic types concepts must belong to be retrieved.
* @param semanticTypeList list of semantic type strings
*/
public void setSemanticGroup(String[] semanticTypeList) {
this.semanticGroup = new HashSet<String>(Arrays.asList(semanticTypeList));
}
/**
* Set list of sources concepts must belong to be retrieved.
* @param sourceList list of source strings
*/
public void setSourceSet(String[] sourceList) {
this.sourceSet = new HashSet<String>(Arrays.asList(sourceList));
}
/**
* Set seqmentation method used by passage segmenter.
* segmentation methods:
* <dl>
* <dt><tt>SENTENCES</tt> <dd>seqment text using sentence breaker.
* <dt><tt>BLANKLINES</tt> <dd>seqment text using blank lines as delimitor
* <dt><tt>LINES</tt> <dd>seqment text using newlines as delimitor
* </dl>
* @param typeName name of segmentation method to use
*/
public void setSegmentationMethod(String typeName) {
if (typeName.equals("SENTENCES")) {
this.segmentationMethod = SegmentatonType.SENTENCES;
} else if (typeName.equals("BLANKLINES")) {
this.segmentationMethod = SegmentatonType.BLANKLINES;
} else if (typeName.equals("LINES")) {
this.segmentationMethod = SegmentatonType.LINES;
}
}
/**
* Set tagger using input stream, usually from a resource
* (classpath, servlet context, etc.)
*
* @param instream input stream
*/
public void setPoSTagger(InputStream instream) {
if (this.entityLookup instanceof EntityLookup4) {
((EntityLookup4)(this.entityLookup)).setPoSTagger
(properties, instream);
}
}
/**
* Invoke sentence processing pipeline on a sentence
* @param sentence BioC sentence containing passage
* @param passage BioC sentence containing sentences
* @return updated sentence
* @throws Exception general exception
* @throws IOException IO Exception
* @throws IllegalAccessException illegal access of class
* @throws InvocationTargetException exception while invoking target class
*/
public BioCSentence processSentence(BioCSentence sentence, BioCPassage passage)
throws IllegalAccessException, InvocationTargetException,
IOException, Exception
{
logger.debug("enter processSentence");
// BioCSentence annotatedSentence = SentenceAnnotator.tokenizeSentence(passage, sentence);
BioCSentence result0 =
BioCUtilities.addEntities(this.entityLookup, this.sentenceAnnotator, sentence);
// System.out.println("unfiltered entity list: ");
// Brat.listEntities(result0);
BioCSentence result = result0;
if ((! this.semanticGroup.contains("all")) &&
(this.semanticGroup.size() > 0)) {
result = SemanticGroupFilter.keepEntitiesInSemanticGroup
(this.semanticGroup, result0);
}
// // look for negation and other relations using Context.
// if (this.detectNegationsFlag) {
// ContextWrapper.applyContext(result);
// }
// System.out.println("filtered entity list: ");
// Brat.listEntities(result);
logger.debug("exit processSentence");
return result;
}
/**
* Invoke sentence processing pipeline on each sentence in supplied sentence list.
* @param passage containing list of sentences
* @return list of results from sentence processing pipeline, one per sentence in input list.
* @throws IllegalAccessException illegal access of class
* @throws InvocationTargetException exception while invoking target class
* @throws Exception general exception
* @throws IOException IO Exception
*/
public BioCPassage processSentences(BioCPassage passage)
throws IllegalAccessException, InvocationTargetException, IOException, Exception
{
logger.debug("enter processSentences");
List<BioCSentence> resultList = new ArrayList<BioCSentence>();
for (BioCSentence sentence: passage.getSentences()) {
logger.info("Processing: " + sentence.getText());
resultList.add(this.processSentence(sentence, passage));
}
/*passage.setSentences(resultList);*/
for (BioCSentence sentence: resultList) {
passage.addSentence(sentence);
}
logger.debug("exit processSentences");
return passage;
}
public List<Entity> processPassage(BioCPassage passage)
throws IllegalAccessException, InvocationTargetException, IOException, Exception
{
logger.debug("enter processPassage");
logger.debug(passage.getText());
BioCPassage passage0;
List<BioCSentence> sentenceList;
int offset;
int passageOffset;
String text;
String[] segmentList;
switch (segmentationMethod) {
case SENTENCES:
passage0 = this.sentenceExtractor.createSentences(passage);
passage0.setInfons(passage.getInfons()); // copy docid and section info
break;
case BLANKLINES:
sentenceList = new ArrayList<BioCSentence>();
offset = passage.getOffset();
passageOffset = passage.getOffset();
text = passage.getText();
segmentList = text.split("\n\n");
for (String segment: segmentList) {
BioCSentence sentence = new BioCSentence();
offset = text.indexOf(segment, offset);
sentence.setOffset(offset);
sentence.setText(segment);
sentence.setInfons(passage.getInfons());
sentenceList.add(sentence);
passage.addSentence(sentence);
offset = segment.length();
}
passage0 = passage;
break;
case LINES:
sentenceList = new ArrayList<BioCSentence>();
offset = passage.getOffset();
passageOffset = passage.getOffset();
text = passage.getText();
segmentList = text.split("\n");
for (String segment: segmentList) {
offset = text.indexOf(segment, offset);
if (segment.trim().length() > 0) {
BioCSentence sentence = new BioCSentence();
sentence.setOffset(offset);
sentence.setText(segment);
sentence.setInfons(passage.getInfons());
sentenceList.add(sentence);
passage.addSentence(sentence);
}
offset = segment.length(); // preserve offsets even for blank lines.
}
passage0 = passage;
break;
default:
// copy entire text of passage into one sentence
sentenceList = new ArrayList<BioCSentence>();
offset = passage.getOffset();
BioCSentence sentence = new BioCSentence();
sentence.setText(passage.getText());
sentence.setOffset(offset);
sentence.setInfons(passage.getInfons());
sentenceList.add(sentence);
passage.addSentence(sentence);
passage0 = passage;
break;
}
BioCPassage passageWithSentsAndAbbrevs = new BioCPassage();
passageWithSentsAndAbbrevs.setInfons( passage0.getInfons() );
passageWithSentsAndAbbrevs.setOffset( passage0.getOffset() );
passageWithSentsAndAbbrevs.setText( passage0.getText() );
for (BioCAnnotation note : passage0.getAnnotations() ) {
passageWithSentsAndAbbrevs.addAnnotation( abbrConverter.getAnnotation(note) );
}
for (BioCRelation rel : passage0.getRelations() ) {
passageWithSentsAndAbbrevs.addRelation(rel);
}
for (BioCSentence sentence: passage0.getSentences()) {
// Find any abbreviations in sentence and add them as annotations referenced by relations.
BioCSentence newSentence = abbrConverter.getSentence(sentence);
passageWithSentsAndAbbrevs.addSentence(newSentence);
// Copy any annotations from sentences to passage.
for (BioCAnnotation note : newSentence.getAnnotations() ) {
passageWithSentsAndAbbrevs.addAnnotation( abbrConverter.getAnnotation(note) );
}
// Copy any relations from sentences to passage.
for (BioCRelation rel : newSentence.getRelations() ) {
passageWithSentsAndAbbrevs.addRelation(rel);
}
}
logger.info("passage relations: " + passageWithSentsAndAbbrevs.getRelations());
logger.info("passage annotations: " + passageWithSentsAndAbbrevs.getAnnotations());
// BioCPassage newPassage = processSentences(passageWithSentsAndAbbrevs);
String docid = (passage.getInfon("docid") != null) ? passage.getInfon("docid") : "00000000";
List<Entity> entityList =
this.entityLookup.processPassage(docid,
passageWithSentsAndAbbrevs,
this.detectNegationsFlag,
this.semanticGroup,
this.sourceSet);
logger.debug("exit processPassage");
return entityList;
}
public List<Entity> processDocument(BioCDocument document)
throws IllegalAccessException, InvocationTargetException, IOException, Exception
{
if (Boolean.parseBoolean(this.getProperties().getProperty("metamaplite.enable.scoring"))) {
// Don't re-instantiate EntityLookup5 if instance exists.
if ((this.entityLookup == null) ||
(! (this.entityLookup instanceof EntityLookup5))) {
this.entityLookup = new EntityLookup5(properties);
}
} else {
// Don't re-instantiate EntityLookup4 if instance exists.
if ((this.entityLookup == null) ||
(! (this.entityLookup instanceof EntityLookup4))) {
this.entityLookup = new EntityLookup4(properties);
}
}
List<Entity> entityList = new ArrayList<Entity>();
if (document.getID() == null) {
document.setID("0000000.TXT");
} else if (document.getID().trim().equals("")) {
document.setID("0000000.TXT");
}
// add docid to passage info namespace (infons)
Map<String,String> docInfoMap = document.getInfons();
if (docInfoMap == null) {
docInfoMap = new HashMap<String,String>();
document.setInfons(docInfoMap);
}
docInfoMap.put("docid", document.getID());
for (BioCPassage passage: document.getPassages()) {
Map<String,String> passageInfons = passage.getInfons();
if (! passageInfons.containsKey("docid")) {
passageInfons.put("docid", document.getID());
}
entityList.addAll(this.processPassage(passage));
}
return entityList;
}
public List<Entity> processDocumentList(List<BioCDocument> documentList)
throws IllegalAccessException, InvocationTargetException, IOException, Exception
{
if (Boolean.parseBoolean(this.getProperties().getProperty("metamaplite.enable.scoring"))) {
// Don't re-instantiate EntityLookup5 if instance exists.
if ((this.entityLookup == null) ||
(! (this.entityLookup instanceof EntityLookup5))) {
this.entityLookup = new EntityLookup5(properties);
}
} else {
if ((this.entityLookup == null) ||
(! (this.entityLookup instanceof EntityLookup4))) {
this.entityLookup = new EntityLookup4(properties);
}
}
List<Entity> entityList = new ArrayList<Entity>();
for (BioCDocument document: documentList) {
entityList.addAll(this.processDocument(document));
}
return entityList;
}
public List<Sentence> getSentenceList(List<BioCDocument> documentList) {
List<Sentence> sentenceList = new ArrayList<Sentence>();
for (BioCDocument document: documentList) {
for (BioCPassage passage: document.getPassages()) {
sentenceList.addAll(this.sentenceExtractor.createSentenceList(passage.getText(), passage.getOffset()));
}
}
return sentenceList;
}
public List<AbbrInfo> getAcronymList(List<BioCDocument> documentList) {
List <AbbrInfo> infos = new ArrayList<AbbrInfo>();
for (BioCDocument document: documentList) {
for (BioCPassage passage: document.getPassages()) {
for (Sentence sentence: this.sentenceExtractor.createSentenceList(passage.getText())) {
for (AbbrInfo abbrInfo: extractAbbr.extractAbbrPairsString(sentence.getText())) {
infos.add(new AbbrInfo(abbrInfo.shortForm.replace("\n", " "), abbrInfo.shortFormIndex,
abbrInfo.longForm.replace("\n", " "), abbrInfo.longFormIndex));
}
}
}
}
return infos;
}
/** Document abbreviation information class */
public class DocInfo {
/** document id */
String id;
/** list of abbreviation information instances */
List <AbbrInfo> infolist;
public DocInfo(String id, List <AbbrInfo> infos) {
this.id = id;
this.infolist = infos;
}
public String getId() { return this.id; }
public List<AbbrInfo> getInfolist() { return this.infolist; }
}
public List<DocInfo> getDocAcronymList(List<BioCDocument> documentList) {
List <DocInfo> docInfoList = new ArrayList<DocInfo>();
for (BioCDocument document: documentList) {
List <AbbrInfo> infos = new ArrayList<AbbrInfo>();
for (BioCPassage passage: document.getPassages()) {
// for (Sentence sentence: this.sentenceExtractor.createSentenceList(passage.getText())) {
for (AbbrInfo abbrInfo: extractAbbr.extractAbbrPairsString(passage.getText())) {
infos.add(new AbbrInfo(abbrInfo.shortForm.replace("\n", " "), abbrInfo.shortFormIndex,
abbrInfo.longForm.replace("\n", " "), abbrInfo.longFormIndex));
}
//}
}
docInfoList.add(new DocInfo(document.getID(), infos));
}
return docInfoList;
}
public static List<String> loadInputFileList(String inputfileListFileName)
throws FileNotFoundException, IOException
{
List<String> inputFileList = new ArrayList<String>();
BufferedReader br =
new BufferedReader(new FileReader(inputfileListFileName));
String line;
while ((line = br.readLine()) != null) {
inputFileList.add(line.trim());
}
br.close();
return inputFileList;
}
static void displayHelp() {
System.err.println("usage: [options] filenames");
System.err.println("input options:");
System.err.println(" -- Read from standard input, write to standard output");
System.err.println(" --pipe Read from standard input, write to standard output");
System.err.println("document processing options:");
System.err.println(" --freetext (default)");
System.err.println(" --inputformat=<document type>");
System.err.println(" Available document types:");
for (String name: BioCDocumentLoaderRegistry.listNameSet()) {
System.err.println(" " + name);
}
System.err.println("output options:");
System.err.println(" --cdi|bc|bc-evaluate");
System.err.println(" --mmilike");
System.err.println(" --mmi");
System.err.println(" --brat");
// System.err.println(" --luceneresultlen");
System.err.println(" --outputformat=<format type>");
System.err.println(" Available format types:");
for (String name: ResultFormatterRegistry.listNameSet()) {
System.err.println(" " + name);
}
System.err.println("processing options:");
System.err.println(" --restrict_to_sts=<semtype>[,<semtype>...]");
System.err.println(" --restrict_to_sources=<source>[,<source>...]");
System.err.println(" --segmentation_method=SENTENCES|BLANKLINES|LINES set method for text segmentation");
System.err.println(" --segment_sentences Set method for text segmentation to sentences");
System.err.println(" --segment_blanklines Set method for text segmentation to one text segment between each blankline");
System.err.println(" --segment_lines Set method for text segmentation to one text segment per line");
System.err.println(" --usecontext Use ConText negation algorithm.");
System.err.println(" --disable_chunker");
System.err.println(" --enable_postagging=[true|false] Use part-of-speech tagging (default: true).");
// System.err.println("performance/effectiveness options:");
// System.err.println(" --luceneresultlen=<length>");
System.err.println("alternate output options:");
System.err.println(" --list_sentences");
System.err.println(" --list_sentences_postags");
System.err.println(" --list_acronyms");
System.err.println(" --list_chunks");
System.err.println("configuration options:");
System.err.println(" --configfile=<filename> Use configuration file (default: config/metamaplite.properties");
System.err.println(" --indexdir=<directory> Set directory containing UMLS indexes");
System.err.println(" --modelsdir=<directory> Set OpenNLP model directory");
System.err.println(" --specialtermsfile=<filename> Set location of specialterms file");
System.err.println(" --filelistfn=<filename> name of file containing list of files to be processed.");
System.err.println(" --filelist=<file0,file1,...> comma-separated list of files to be processed.");
System.err.println(" --uda=<filename> user defined acronyms file.");
System.err.println(" --cuitermlistfile=<filename> user defined concepts file.");
System.err.println(" --set_property=<propertyname>=<propertyvalue> set property");
System.err.println("scheduler options:");
System.err.println(" --scheduler use: \"program inputfilename outputfilename\" scheduler convention.");
System.err.println(" -E (--indicate_citation_end) emit citation end at end of input.");
}
public static void expandModelsDir(Properties properties, String modelsDir) {
if (modelsDir != null) {
properties.setProperty("opennlp.en-sent.bin.path", modelsDir + "/en-sent.bin");
properties.setProperty("opennlp.en-token.bin.path", modelsDir + "/en-token.bin");
properties.setProperty("opennlp.en-pos.bin.path", modelsDir + "/en-pos-maxent.bin");
properties.setProperty("opennlp.en-chunker.bin.path", modelsDir + "/en-chunker.bin");
}
}
public static void expandModelsDir(Properties properties) {
String modelsDir = properties.getProperty("opennlp.models.directory");
expandModelsDir(properties, modelsDir);
}
public static void expandIndexDir(Properties properties, String indexDirName) {
if (indexDirName != null) {
properties.setProperty("metamaplite.ivf.cuiconceptindex", indexDirName + "/indices/cuiconcept");
properties.setProperty("metamaplite.ivf.firstwordsofonewideindex", indexDirName + "/indices/first_words_of_one_WIDE");
properties.setProperty("metamaplite.ivf.cuisourceinfoindex", indexDirName + "/indices/cuisourceinfo");
properties.setProperty("metamaplite.ivf.cuisemantictypeindex", indexDirName + "/indices/cuist");
properties.setProperty("metamaplite.ivf.varsindex", indexDirName + "/indices/vars");
properties.setProperty("metamaplite.ivf.meshtcrelaxedindex", indexDirName + "/indices/meshtcrelaxed");
}
}
public static void expandIndexDir(Properties properties) {
String indexDirName = properties.getProperty("metamaplite.index.directory");
expandIndexDir(properties, indexDirName);
}
public static void displayProperties(String label, Properties properties) {
System.out.println(label);
for (String name: properties.stringPropertyNames()) {
System.out.println(" " + name + ": " + properties.getProperty(name));
}
}
/** get current properties of MetaMapLite instance
* @return properties instance.
*/
public Properties getProperties() {
return this.properties;
}
public static Properties getDefaultConfiguration() {
String modelsDirectory = System.getProperty("opennlp.models.directory", "data/models");
String indexDirectory = System.getProperty("metamaplite.index.directory", "data/ivf/strict");
Properties defaultConfiguration = new Properties();
defaultConfiguration.setProperty("metamaplite.excluded.termsfile",
System.getProperty("metamaplite.excluded.termsfile",
"data/specialterms.txt"));
defaultConfiguration.setProperty("opennlp.models.directory", modelsDirectory);
defaultConfiguration.setProperty("metamaplite.index.directory", indexDirectory);
defaultConfiguration.setProperty("metamaplite.document.inputtype", "freetext");
defaultConfiguration.setProperty("metamaplite.outputformat", "mmi");
defaultConfiguration.setProperty("metamaplite.outputextension", ".mmi");
defaultConfiguration.setProperty("metamaplite.semanticgroup", "all");
defaultConfiguration.setProperty("metamaplite.sourceset", "all");
defaultConfiguration.setProperty("metamaplite.segmentation.method", "SENTENCES");
defaultConfiguration.setProperty("opennlp.en-sent.bin.path",
modelsDirectory + "/en-sent.bin");
defaultConfiguration.setProperty("opennlp.en-token.bin.path",
modelsDirectory + "/en-token.bin");
defaultConfiguration.setProperty("opennlp.en-pos.bin.path",
modelsDirectory + "/en-pos-maxent.bin");
defaultConfiguration.setProperty("opennlp.en-chunker.bin.path",
modelsDirectory + "/en-chunker.bin");
defaultConfiguration.setProperty("metamaplite.ivf.cuiconceptindex",
indexDirectory + "/strict/indices/cuiconcept");
defaultConfiguration.setProperty("metamaplite.ivf.cuisourceinfoindex",
indexDirectory + "/strict/indices/cuisourceinfo");
defaultConfiguration.setProperty("metamaplite.ivf.cuisemantictypeindex",
indexDirectory + "/strict/indices/cuist");
defaultConfiguration.setProperty("metamaplite.ivf.varsindex",
indexDirectory + "/strict/indices/varss");
defaultConfiguration.setProperty("metamaplite.ivf.meshtcrelaxedindex",
indexDirectory + "/strict/indices/meshtcrelaxed");
defaultConfiguration.setProperty("bioc.document.loader.chemdner",
"gov.nih.nlm.nls.metamap.document.ChemDNER");
defaultConfiguration.setProperty("bioc.document.loader.freetext",
"gov.nih.nlm.nls.metamap.document.FreeText");
defaultConfiguration.setProperty("bioc.document.loader.ncbicorpus",
"gov.nih.nlm.nls.metamap.document.NCBICorpusDocument");
defaultConfiguration.setProperty("bioc.document.loader.sldi",
"gov.nih.nlm.nls.metamap.document.SingleLineInput");
defaultConfiguration.setProperty("bioc.document.loader.sldiwi",
"gov.nih.nlm.nls.metamap.document.SingleLineDelimitedInputWithID");
defaultConfiguration.setProperty("metamaplite.result.formatter.cuilist",
"gov.nih.nlm.nls.metamap.lite.resultformats.CuiList");
defaultConfiguration.setProperty("metamaplite.result.formatter.brat",
"gov.nih.nlm.nls.metamap.lite.resultformats.Brat");
defaultConfiguration.setProperty("metamaplite.result.formatter.mmi",
"gov.nih.nlm.nls.metamap.lite.resultformats.mmi.MMI");
defaultConfiguration.setProperty("metamaplite.negation.detector",
"gov.nih.nlm.nls.metamap.lite.NegEx");
defaultConfiguration.setProperty("metamaplite.disable.chunker","true");
defaultConfiguration.setProperty("metamaplite.removeSubsumedEntities", "true");
return defaultConfiguration;
}
static Properties setConfiguration(String propertiesFilename,
Properties defaultConfiguration,
Properties systemConfiguration,
Properties optionsConfiguration,
boolean verbose)
throws IOException, FileNotFoundException
{
// Attempt to get local configuration from properties file on
// classpath and then from file system. file system has
// precedence of classpath and gets loaded last (if it exists).
Properties localConfiguration = new Properties();
// check classpath for "metamaplite.properties" resource
// get class loader
ClassLoader loader = MetaMapLite.class.getClassLoader();
if(loader==null)
loader = ClassLoader.getSystemClassLoader(); // use system class loader if class loader is null
java.net.URL url = loader.getResource(propertiesFilename);
try {
localConfiguration.load(url.openStream());
} catch(Exception e) {
logger.info("Could not load configuration file from classpath: " + propertiesFilename);
}
// check filesystem
File localConfigurationFile = new File(propertiesFilename);
if (localConfigurationFile.exists()) {
logger.info("loading local configuration from " + localConfigurationFile);
if (verbose) {
System.out.println("loading local configuration from " + localConfigurationFile);
}
FileReader fr = new FileReader(localConfigurationFile);
localConfiguration.load(fr);
fr.close();
logger.info("loaded " + localConfiguration.size() + " records from local configuration");
if (verbose) {
System.out.println("loaded " + localConfiguration.size() + " records from local configuration");
}
}
expandModelsDir(defaultConfiguration);
expandModelsDir(localConfiguration);
expandModelsDir(systemConfiguration);
expandModelsDir(optionsConfiguration);
expandIndexDir(defaultConfiguration);
expandIndexDir(localConfiguration);
expandIndexDir(systemConfiguration);
expandIndexDir(optionsConfiguration);
// displayProperties("defaultConfiguration:", defaultConfiguration);
// displayProperties("localConfiguration:", localConfiguration);
// displayProperties("optionsConfiguration:", optionsConfiguration);
Properties properties =
Configuration.mergeConfiguration(defaultConfiguration,
localConfiguration,
systemConfiguration,
optionsConfiguration);
return properties;
}
void listEntities(List<BioCDocument> documentList,
PrintWriter pw,
String outputFormatOption)
throws IllegalAccessException, InvocationTargetException, IOException, Exception
{
// process documents
List<Entity> entityList = this.processDocumentList(documentList);
logger.info("outputing results to standard output." );
// format output
ResultFormatter formatter = ResultFormatterRegistry.get(outputFormatOption);
if (formatter != null) {
formatter.initProperties(this.properties);
formatter.entityListFormatter(pw, entityList);
} else {
System.out.println("! Couldn't find formatter for output format option: " + outputFormatOption);
}
pw.flush();
}
/** list entities using document list from stdin
* @param documentList list of BioC documents
*/
void listSentences(List<BioCDocument> documentList)
{
// output results for file
// create output filename
logger.info("outputing results to Standard Output");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out,
Charset.forName("utf-8")));
for (Sentence sent: this.getSentenceList(documentList)) {
pw.println(sent.getOffset() + "|" + sent.getText().length() + "|" + sent.getText());
}
pw.flush();
}
void listAcronyms(List<BioCDocument> documentList) {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out,
Charset.forName("utf-8")));
for (DocInfo docInfo: this.getDocAcronymList(documentList)) {
for (AbbrInfo acronym: docInfo.getInfolist()) {
pw.println(docInfo.getId() + "|" +
acronym.shortForm + "|" + acronym.shortFormIndex + "|" +
acronym.longForm + "|" + acronym.longFormIndex );
}
}
pw.flush();
}
void listSentencesWithPosTags(List<BioCDocument> documentList)
throws IOException
{
this.sentenceAnnotator = new OpenNLPPoSTagger(properties);
logger.info("outputing results to Standard Output");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out,
Charset.forName("utf-8")));
for (Sentence sent: this.getSentenceList(documentList)) {
List<ERToken> tokenList = sentenceAnnotator.addPartOfSpeech(sent);
pw.println(sent.getOffset() + "|" + sent.getText().length() + "|" + sent.getText());
for (ERToken token: tokenList) {
pw.print(token.getText() + "(" + token.getPartOfSpeech() + "),");
}
pw.println();
}
pw.flush();
}
void listChunks(List<BioCDocument> documentList)
throws IOException
{
logger.info("outputing results to Standard Output");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out,
Charset.forName("utf-8")));
listChunks(pw, documentList);
pw.flush();
}
void listEntities(List<BioCDocument> documentList, String outputFormatOption)
throws IllegalAccessException, InvocationTargetException, IOException, Exception
{
logger.info("outputing results to standard output." );
// output results for file
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out,
Charset.forName("utf-8")));
listEntities(documentList, pw, outputFormatOption);
pw.flush();
}
/**
* Return basename of file, essentially the filename without the
* extension.
* @param filename filename of file including extension (if present)