forked from amazon-science/tanl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpc_eval.py
1781 lines (1493 loc) · 69.4 KB
/
pc_eval.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Implementation of BioNLP Shared Task evaluation.
import sys
import re
import os
import optparse
import copy
entity_types = set([
"Simple_chemical",
"Gene_or_gene_product",
"Complex",
"Cellular_component",
])
given_types = set([
"Simple_chemical",
"Gene_or_gene_product",
"Complex",
"Cellular_component",
])
event_types = set([
"Conversion",
"Phosphorylation",
"Dephosphorylation",
"Acetylation",
"Deacetylation",
"Methylation",
"Demethylation",
"Ubiquitination",
"Deubiquitination",
"Localization",
"Transport",
"Gene_expression",
"Transcription",
"Translation",
"Degradation",
"Activation",
"Inactivation",
"Binding",
"Dissociation",
"Regulation",
"Positive_regulation",
"Negative_regulation",
"Pathway",
])
output_event_type_order = [
"Conversion",
"Phosphorylation",
"Dephosphorylation",
"Acetylation",
"Deacetylation",
"Methylation",
"Demethylation",
"Ubiquitination",
"Deubiquitination",
"Localization",
"Transport",
"Gene_expression",
"Transcription",
"Translation",
' =[SIMPLE-TOTAL]= ',
"Degradation",
"Activation",
"Inactivation",
"Binding",
"Dissociation",
"Pathway",
'==[NONREG-TOTAL]==',
"Regulation",
"Positive_regulation",
"Negative_regulation",
' ==[REG-TOTAL]== ',
' ====[TOTAL]==== ',
]
subtotal_event_set = {
' =[SIMPLE-TOTAL]= ': [
"Conversion",
"Phosphorylation",
"Dephosphorylation",
"Acetylation",
"Deacetylation",
"Methylation",
"Demethylation",
"Ubiquitination",
"Deubiquitination",
"Localization",
"Transport",
"Gene_expression",
"Transcription",
"Translation",
],
'==[NONREG-TOTAL]==': [
"Conversion",
"Phosphorylation",
"Dephosphorylation",
"Acetylation",
"Deacetylation",
"Methylation",
"Demethylation",
"Ubiquitination",
"Deubiquitination",
"Localization",
"Transport",
"Gene_expression",
"Transcription",
"Translation",
"Degradation",
"Activation",
"Inactivation",
"Binding",
"Dissociation",
"Pathway",
],
' ==[REG-TOTAL]== ': [
'Regulation',
'Positive_regulation',
'Negative_regulation',
],
' ====[TOTAL]==== ': [
"Conversion",
"Phosphorylation",
"Dephosphorylation",
"Acetylation",
"Deacetylation",
"Methylation",
"Demethylation",
"Ubiquitination",
"Deubiquitination",
"Localization",
"Transport",
"Gene_expression",
"Transcription",
"Translation",
"Degradation",
"Activation",
"Inactivation",
"Binding",
"Dissociation",
"Pathway",
"Regulation",
"Positive_regulation",
"Negative_regulation",
]
}
# allowed types for text-bound annotation
textbound_types = entity_types | event_types
# allowed types for modification annotation
modification_types = set(["Negation", "Speculation"])
# punctuation characters halting "soft match" span extension
punctuation_chars = set(".!?,\"'")
# generator, returns all permutations of the given list.
# Following http://code.activestate.com/recipes/252178/.
def all_permutations(lst):
if len(lst) <= 1:
yield lst
else:
for perm in all_permutations(lst[1:]):
for i in range(len(perm) + 1):
yield perm[:i] + lst[0:1] + perm[i:]
# returns (prec, rec, F) 3-tuple given TPa, TPg, FP, FN.
# (See comment after "scoring starts here" for details.)
def prec_rec_F(match_answer, match_gold, false_positive, false_negative):
precision, recall, F = 0, 0, 0
if match_answer + false_positive > 0:
precision = float(match_answer) / (match_answer + false_positive)
if match_gold + false_negative > 0:
recall = float(match_gold) / (match_gold + false_negative)
if precision + recall > 0:
F = 2 * precision * recall / (precision + recall)
# corner case: if gold is empty, an empty answer gives a perfect
# score
if match_answer + match_gold + false_positive + false_negative == 0:
precision = recall = F = 1
# return percentages
return 100.0 * precision, 100.0 * recall, 100.0 * F
# allowed arguments
def valid_argument_name(a):
return re.match(r'^Cause|CSite|ToLoc|AtLoc|FromLoc|(Theme|Site|Product|Participant)\d*$', a) is not None
# allowed (argument, referred-type) combinations
def valid_argument_type(arg, reftype):
if arg == "Cause" or re.match(r'^(Theme|Product)\d*$', arg):
return reftype in given_types or reftype in event_types
elif arg in ("ToLoc", "AtLoc", "FromLoc"):
return reftype in ("Cellular_component",)
elif re.match(r'^C?Site\d*$', arg):
return reftype in ("Simple_chemical",)
elif re.match(r'^Participant\d*$', arg):
return reftype in given_types
else:
assert False, "INTERNAL ERROR: unexpected argument type %s" % arg
# represents a text-bound annotation (entity/event trigger)
class Textbound:
def __init__(self, id, type, start, end, text):
self.id, self.type, self.start, self.end, self.text = id, type, start, end, text
self.equivs = None
self.extended_start, self.extended_end = None, None
# for merged output, store matching
self.matching = []
def verify_text(self, document_text, fn):
# checks that text matches the span in the given document text
# identified by (start, end].
assert self.start < len(document_text) and self.end <= len(
document_text), "FORMAT ERROR: textbound offsets extend over document length: '%s' in %s" % (
self.to_string(), fn)
assert document_text[self.start:self.end].strip().replace("\n",
" ") == self.text.strip(), "FORMAT ERROR: text '%s' referenced by [start, end) doesn't match given text '%s': '%s' in %s" % (
document_text[self.start:self.end], self.text, self.to_string(), fn)
def identify_extended_span(self, document_text, reserved_index):
# find "extended" start and end points. reserved_index
# values are taked to be "off limits" and stop extension.
estart, eend = self.start, self.end
# implementation copying evaluation.pl
# try to back off start by one, skipping possible intervening space
for i in range(0, 1):
estart -= 1
# avoid invalid and reserved
if estart < 0 or estart in reserved_index:
estart += 1
# back of until space or punctuation
while (estart - 1 >= 0 and not estart - 1 in reserved_index and
not document_text[estart - 1].isspace() and not document_text[estart - 1] in punctuation_chars):
estart -= 1
# symmetric for the end
for i in range(0, 1):
eend += 1
if eend > len(document_text) or eend - 1 in reserved_index:
eend -= 1
while (eend < len(document_text) and not eend in reserved_index and
not document_text[eend].isspace() and not document_text[eend] in punctuation_chars):
eend += 1
self.extended_start, self.extended_end = estart, eend
# sanity: the extended range must be at least as large as the original
assert self.extended_start <= self.start, "INTERNAL ERROR"
assert self.extended_end >= self.end, "INTERNAL ERROR"
def resolve_idrefs(self, annotation_by_id):
# none to resolve
pass
def to_string(self):
return "%s\t%s %d %d\t%s" % (self.id, self.type, self.start, self.end, self.text)
def to_notbid_string(self):
# the type is too obvious in my current work
# return '%s:"%s"' % (self.type, self.text)
return '"%s"[%d-%d]' % (self.text, self.start, self.end)
def matches_self(self, t):
# match, doesn't consider 'Equiv' textbounds but only self.
global options
if self.type != t.type:
return False
if options.softboundary:
# containment in extended span.
# As we're now allowing matches() to be invoked also on
# given entities, we need to check which one is extended
# and check against that.
# assert t.extended_start is not None and t.extended_end is not None, "INTERNAL ERROR"
# return t.extended_start <= self.start and t.extended_end >= self.end
if t.extended_start is not None:
assert t.extended_end is not None, "INTERNAL ERROR"
return t.extended_start <= self.start and t.extended_end >= self.end
else:
assert self.extended_start is not None and self.extended_end is not None, "INTERNAL ERROR"
return self.extended_start <= t.start and self.extended_end >= t.end
else:
# strict equality
return self.start == t.start and self.end == t.end
def matches_impl(self, t):
# Textbound can only match Textbound
if not isinstance(t, Textbound):
return False
# a match between any 'Equiv' textbounds is a match
self_equiv_entities = [self]
other_equiv_entities = [t]
if self.equivs is not None:
self_equiv_entities += self.equivs
if t.equivs is not None:
other_equiv_entities += t.equivs
for se in self_equiv_entities:
for te in other_equiv_entities:
if se.matches_self(te):
return True
return False
# dummy to allow uniform argument structure with Event matches().
def matches(self, t, dummy=False):
m = self.matches_impl(t)
if m and t is not self and t not in self.matching:
self.matching.append(t)
return m
def get_start(self):
return self.start
def get_end(self):
return self.end
# represents Equiv annotation (equivalent entities)
class Equiv:
def __init__(self, ids):
self.ids = ids
self.entities = None
def resolve_idrefs(self, annotation_by_id):
self.entities = []
for id in self.ids:
assert id in annotation_by_id, "ERROR: undefined ID %s referenced in Equiv" % id
e = annotation_by_id[id]
# check: only given types can be Equiv
assert e.type in given_types, "ERROR: Equiv for non-given, type %s ID %s" % (e.type, id)
assert e not in self.entities, "ERROR: %s with ID %s occurs multiple times in Equiv" % (e.type, id)
self.entities.append(e)
def to_string(self):
return "*\tEquiv %s" % " ".join(self.ids)
# represents event annotation
class Event:
def __init__(self, id, type, tid, args):
self.id, self.type, self.tid, self.args = id, type, tid, args
self.trigger = None
self.matching = []
# sanity: no argument can refer back to the event itself
for arg, aid in self.args:
assert aid != self.id, "ERROR: event ID %s contains argument %s referring to itself" % (self.id, arg)
def resolve_idrefs(self, annotation_by_id):
global options
assert self.tid in annotation_by_id, "ERROR: undefined trigger ID %s referenced in event %s" % (
self.tid, self.id)
self.trigger = annotation_by_id[self.tid]
assert self.trigger.type == self.type, "ERROR: trigger %s type disagrees with event %s type" % (
self.tid, self.id)
# store args as a dict keyed by arg name. The exception is
# Themes and Sites, which will be stored as a list of
# (argnum, Theme, Site) tuples. Construct theme_site using a
# dict indexed by arg name containing a list of the values:
# multiple Themes may share the same number as long as there
# are no Sites (the connection between Theme and Site must be
# unambiguous).
self.arg = {}
self.theme_sites = []
theme_site_dict = {}
theme_site_nums = set()
for arg, aid in self.args:
assert aid in annotation_by_id, "ERROR: undefined ID %s referenced in event %s" % (aid, self.id)
ref = annotation_by_id[aid]
assert valid_argument_type(arg, ref.type), "ERROR: argument %s for %s event %s has invalid type %s" % (
arg, self.type, self.id, ref.type)
m = re.match(r'^(Theme|Site)(\d*)$', arg)
if not m:
assert arg not in self.arg, "ERROR: event %s has multiple %s arguments" % (self.id, arg)
self.arg[arg] = ref
else:
argname, argnum = m.groups()
if arg not in theme_site_dict:
theme_site_dict[arg] = []
theme_site_dict[arg].append(ref)
theme_site_nums.add(argnum)
# construct theme_sites list, with sanity checks
for argnum in theme_site_nums:
t_arg, s_arg = "Theme%s" % argnum, "Site%s" % argnum
# there must be a Theme for each Theme/Site number that appears (except in split event eval)
if not options.spliteventeval:
assert t_arg in theme_site_dict, "ERROR: event %s has Site%s without Theme%s" % (
self.id, argnum, argnum)
# Theme-Site pairings must be unambiguous
s_val = None
if s_arg in theme_site_dict:
assert len(theme_site_dict[
s_arg]) == 1, "ERROR: event %s has multiple Site%s arguments, Site-Theme pairing is ambiguous" % (
self.id, argnum)
# ("not in" for spliteventeval)
assert t_arg not in theme_site_dict or len(theme_site_dict[
t_arg]) == 1, "ERROR: event %s has Site%s and multiple Theme%s arguments, Site-Theme pairing is ambiguous" % (
self.id, argnum, argnum)
s_val = theme_site_dict[s_arg][0]
if t_arg in theme_site_dict:
for t_val in theme_site_dict[t_arg]:
self.theme_sites.append((argnum, t_val, s_val))
else:
assert options.spliteventeval, "INTERNAL ERROR"
assert s_val is not None, "INTERNAL ERROR: neither theme nor site"
self.theme_sites.append((argnum, None, s_val))
# reorder numbering for Product and Participant arguments so
# that the one appearing first is "Product", the second
# "Product2", then "Product3", etc. (and the same for
# Participant.
argmap = {}
for arg in ("Participant", "Product",):
args = [a for a in self.arg if arg in a]
args.sort(lambda a, b: cmp(self.arg[a].get_start(),
self.arg[b].get_start()))
for i, a in enumerate(args):
mapped = arg + ('' if i == 0 else str(i + 1))
argmap[a] = mapped
argval = {}
for a, m in argmap.items():
argval[m] = self.arg[a]
del self.arg[a]
for a, v in argval.items():
assert a not in self.arg, "INTERNAL ERROR"
self.arg[a] = v
# finally, there can be no CSite without a corresponding Cause. (except in split event eval mode)
if not options.spliteventeval:
assert not (
"CSite" in self.arg and not "Cause" in self.arg), "ERROR: event %s has CSite without Cause" % self.id
def clear_matching(self):
self.matching = []
self.partially_matched = []
self.partially_matched_by = []
def has_matched(self):
return len(self.matching) != 0
def has_partially_matched(self):
return len(self.partially_matched) != 0
def mark_matching(self, matching):
assert matching is not None, "INTERNAL ERROR: None given as matched event"
self.matching.append(matching)
def mark_partially_matched(self, matching):
assert matching is not None, "INTERNAL ERROR: None given as matched event"
self.partially_matched.append(matching)
def mark_partially_matched_by(self, matching):
assert matching is not None, "INTERNAL ERROR: None given as matched event"
self.partially_matched_by.append(matching)
def to_string(self):
return "%s\t%s:%s %s" % (self.id, self.type, self.trigger.id, " ".join(["%s:%s" % a for a in self.args]))
def to_notbid_string(self):
# returns a string with no IDs for textbounds
argstrs = []
for ts in self.theme_sites:
argstrs.append("%s:%s" % ("Theme", ts[1].to_notbid_string()))
if ts[2] is not None:
argstrs.append("%s:%s" % ("Site", ts[2].to_notbid_string()))
for a in self.arg:
argstrs.append("%s:%s" % (a, self.arg[a].to_notbid_string()))
return '%s:%s\t(%s)' % (self.type, self.trigger.to_notbid_string(), "\t".join(argstrs))
def matches(self, e, match_theme_only=False, match_partial=False):
global options
# Event can only match Event
if not isinstance(e, Event):
return False
# events with different types cannot match
if self.type != e.type:
return False
# triggers must match
if not self.trigger.matches(e.trigger):
return False
# determine fixed argument (non-Theme/Site) matches
self_matched_args, other_matched_args = [], []
self_only_args, other_only_args = [], []
for a in self.arg:
if a in e.arg:
try:
self.arg[a].matches(e.arg[a], options.partialrecursive)
except RuntimeError as re:
print(
'Sorry but this maze solver was not able to finish analyzing the maze: {} {} {}'.format(self.id,
self.tid,
self.args))
exit()
if self.arg[a].matches(e.arg[a], options.partialrecursive):
self_matched_args.append(a)
other_matched_args.append(a)
else:
# both have the argument, but different values
self_only_args.append(a)
other_only_args.append(a)
else:
self_only_args.append(a)
for a in e.arg:
if a in self.arg:
# handled above
pass
else:
other_only_args.append(a)
# TODO: verify and uncomment this
# can short-circuit here in some cases.
# if match_theme_only:
# # non-theme arguments ignored
# pass
# if match_partial:
# # other-only not allowed (self-only OK)
# if len(other_only_args) > 0:
# return False
# else:
# # normal; all must match
# if len(self_only_args) > 0 or len(other_only_args) > 0:
# return False
# determine Theme/Site matches.
# if "theme only" is specified, drop sites on local
# copies of the lists for the comparison.
if match_theme_only:
self_theme_sites = [(x[0], x[1], None) for x in self.theme_sites]
other_theme_sites = [(x[0], x[1], None) for x in e.theme_sites]
else:
self_theme_sites = self.theme_sites[:]
other_theme_sites = e.theme_sites[:]
# to simplify processing, first determine full Theme/Site pair
# matches.
matched_self_ts, matched_other_ts = [], []
for sts in self_theme_sites:
for ots in other_theme_sites:
# only match once
if ots in matched_other_ts:
continue
# TODO: support split event evaluation mode, where one or both
# of the themes may be None
if sts[1].matches(ots[1], options.partialrecursive):
# theme match
if ((sts[2] is None and ots[2] is None) or
(sts[2] is not None and sts[2].matches(ots[2], options.partialrecursive))):
# site match
matched_self_ts.append(sts)
matched_other_ts.append(ots)
break
unmatched_self_ts = [st for st in self_theme_sites if st not in matched_self_ts]
unmatched_other_ts = [st for st in other_theme_sites if st not in matched_other_ts]
# TODO: verify and uncomment this
# normal match can short-circuit remaining processing
# if not match_partial:
# return len(unmatched_self_ts) == 0 and len(unmatched_other_ts) == 0
# partial match still possible.
# analyse remaining: we can still have Theme matches with
# differences in Sites.
# TODO: in split event eval mode there may also be Site
# matches without a corresponding Theme; support this.
theme_matched_self_ts, theme_matched_other_ts = [], []
self_only_ts, other_only_ts = [], []
for sts in unmatched_self_ts:
match_found = False
for ots in unmatched_other_ts:
if sts[1].matches(ots[1], options.partialrecursive):
theme_matched_self_ts.append(sts)
theme_matched_other_ts.append(ots)
match_found = True
break
if not match_found:
self_only_ts.append(sts)
other_only_ts = [ots for ots in unmatched_other_ts if ots not in theme_matched_other_ts]
# break Theme/Site pairs into their constituents
# TODO: this is horrible, clean up
for st in matched_self_ts:
if st[1] is not None:
self_matched_args.append("Theme%s" % st[0])
if st[2] is not None:
self_matched_args.append("Site%s" % st[0])
for st in matched_other_ts:
if st[1] is not None:
other_matched_args.append("Theme%s" % st[0])
if st[2] is not None:
other_matched_args.append("Site%s" % st[0])
for st in theme_matched_self_ts:
if st[1] is not None:
self_matched_args.append("Theme%s" % st[0])
if st[2] is not None:
self_only_args.append("Site%s" % st[0])
for st in theme_matched_other_ts:
if st[1] is not None:
other_matched_args.append("Theme%s" % st[0])
if st[2] is not None:
other_only_args.append("Site%s" % st[0])
for st in self_only_ts:
if st[1] is not None:
self_only_args.append("Theme%s" % st[0])
if st[2] is not None:
self_only_args.append("Site%s" % st[0])
for st in other_only_ts:
if st[1] is not None:
other_only_args.append("Theme%s" % st[0])
if st[2] is not None:
other_only_args.append("Site%s" % st[0])
# decide.
if match_theme_only:
# discard differences not relating to theme
self_only_args = [a for a in self_only_args if a[:5] == "Theme"]
other_only_args = [a for a in other_only_args if a[:5] == "Theme"]
if match_partial:
return len(other_only_args) == 0
else:
# normal
return len(self_only_args) == 0 and len(other_only_args) == 0
def get_start(self):
return self.trigger.start
def get_end(self):
return self.trigger.end
# represents event modification annotation
class Modification:
def __init__(self, id, type, eid):
self.id, self.type, self.eid = id, type, eid
self.event = None
def resolve_idrefs(self, annotation_by_id):
assert self.eid in annotation_by_id, "ERROR: undefined ID %s referenced in %s" % (self.eid, self.id)
self.event = annotation_by_id[self.eid]
assert self.event.type in event_types, "ERROR: non-Event %s referenced in %s" % (self.eid, self.id)
# represents a modification (negation or speculation) pseudo-event.
class ModificationEvent(Event):
def __init__(self, mod):
self.id, self.type, self.eid, self.event = mod.id, mod.type, mod.eid, mod.event
def matches(self, e, match_theme_only=False, match_partial=False):
global options
if not isinstance(e, ModificationEvent):
return False
if self.type != e.type:
return False
return self.event.matches(e.event, options.partialrecursive, match_partial)
def to_string(self):
return "%s\t%s %s" % (self.id, self.type, self.eid)
# parses and verifies the given text line as text-bound annotation
# (entity/event trigger), returns Textbound object.
def parse_textbound_line(l, fn):
# three tab-separated fields
fields = l.split("\t")
id, annotation, text = None, None, None
# allow two or three fields, with the last (reference text) allowed to be empty.
if len(fields) == 3:
id, annotation, text = fields
elif len(fields) == 2:
id, annotation = fields
text = ""
else:
assert False, "FORMAT ERROR: unexpected number (%d) of tab-separated fields: line '%s' in %s" % (
len(fields), l, fn)
# id is usually in format "GT[0-9]+", but may have other simiarl
if not re.match(r'^[GT]\d+$', id):
# print >> sys.stderr, "NOTE: ID not in format '[GT][0-9]+': line '%s' in %s" % (l, fn)
pass
assert re.match(r'^[A-Z]\d+$', id), "FORMAT ERROR: ID not in format '[GT][0-9]+': line '%s' in %s" % (l, fn)
# annotation is three space-separated fields
fields = re.split(' +', annotation)
assert len(fields) == 3, "FORMAT ERROR: unexpected number of space-separated fields: line '%s' in %s" % (l, fn)
type, start, end = fields
assert type in textbound_types, "FORMAT ERROR: disallowed type for text-bound annotation: line '%s' in %s" % (l, fn)
# start and end are offsets into the text
assert re.match(r'^\d+$', start) and re.match(r'^\d+$',
end), "FORMAT ERROR: offsets not in '[0-9]+' format: line '%s' in %s" % (
l, fn)
start, end = int(start), int(end)
assert start < end, "FORMAT ERROR: start offset not smaller than end offset: line '%s' in %s" % (l, fn)
return Textbound(id, type, start, end, text)
# parses and verifies the given text line as an given entity (Protein
# etc.) annotation, returns Textbound object.
def parse_given_entity_line(l, fn, document_text):
global options
l = l.strip(' \n\r')
e = parse_textbound_line(l, fn)
if options.verifytext:
e.verify_text(document_text, fn)
assert e.type in given_types, "FORMAT ERROR: non-given type not allowed here: line '%s' in %s" % (l, fn)
# OK, checks out.
return e
# parses and verifies the given text line as event annotation,
# return Event object.
def parse_event_line(l, fn):
global options
# print(fn)
# two tab-separated fields
fields = l.split("\t")
assert len(fields) == 2, "FORMAT ERROR: unexpected number of tab-separated fields: line '%s' in %s" % (l, fn)
id, annotation = fields
# id must be in format "E[0-9]+" (unless split eval)
if not options.spliteventeval:
assert re.match(r'^E\d+$', id), "FORMAT ERROR: ID not in format 'E[0-9]+': line '%s' in %s" % (l, fn)
# annotation is two or more space-separated fields
fields = re.split(' +', annotation)
# exception: there may be no-argument events; in this case fill in
# a fake second field
if len(fields) == 1:
fields.append("")
assert len(fields) >= 2, "FORMAT ERROR: unexpected number of space-separated fields: line '%s' in %s" % (l, fn)
type_tid, args = fields[0], fields[1:]
# first field is "TYPE:ID", where ID is for the event trigger
parts = type_tid.split(":")
assert len(parts) == 2, "FORMAT ERROR: event type not in 'TYPE:ID' format: line '%s' in %s" % (l, fn)
type, tid = parts
assert type in event_types, "FORMAT ERROR: disallowed type for event annotation: line '%s' in %s" % (l, fn)
assert re.match(r'^T\d+$', tid), "FORMAT ERROR: event trigger ID not in format 'T[0-9]+': line '%s' in %s" % (l, fn)
# each argument is "ARG:ID", where ID is either for an event or text-bound.
split_args = []
for a in args:
# for no-argument events
if a == "":
continue
parts = a.split(":")
assert len(parts) == 2, "FORMAT ERROR: argument type not in 'ARG:ID' format: line '%s' in %s" % (l, fn)
arg, aid = parts
assert valid_argument_name(arg), "FORMAT ERROR: invalid argument name: line '%s' in %s" % (l, fn)
assert re.match(r'^[A-Z]\d+', aid), "FORMAT ERROR: invalid id in argument: line '%s' in %s" % (l, fn)
# old restricted test
# assert re.match(r'^[TEG]\d+', aid), "FORMAT ERROR: invalid id in argument: line '%s' in %s" % (l, fn)
split_args.append((arg, aid))
return Event(id, type, tid, split_args)
# parses and verifies the given text line as modification annotation,
# returns Modification object.
def parse_modification_line(l, fn):
global options
# two tab-separated fields
fields = l.split("\t")
assert len(fields) == 2, "FORMAT ERROR: unexpected number of tab-separated fields: line '%s' in %s" % (l, fn)
id, annotation = fields
# id must be in format "[AM][0-9]+" (unless split eval)
if not options.spliteventeval:
assert re.match(r'^[AM]\d+$', id), "FORMAT ERROR: ID not in format 'M[0-9]+': line '%s' in %s" % (l, fn)
# annotation is two space-separated fields
fields = re.split(' +', annotation)
assert len(fields) == 2, "FORMAT ERROR: unexpected number of space-separated fields: line '%s' in %s" % (l, fn)
type, eid = fields
assert type in modification_types, "FORMAT ERROR: disallowed type for modification annotation: line '%s' in %s" % (
l, fn)
return Modification(id, type, eid)
# parses and verifies an "Equiv" line, returns Equiv object.
def parse_equiv_line(l, fn):
# two tab-separated fields
fields = l.split("\t")
assert len(fields) == 2, "FORMAT ERROR: unexpected number of tab-separated fields: line '%s' in %s" % (l, fn)
id, annotation = fields
# "id" must be "*"
assert id == "*", "FORMAT ERROR: invalid ID field: line '%s' in %s" % (l, fn)
# annotation is three or more space-separated fields
fields = re.split(' +', annotation)
assert len(fields) >= 3, "FORMAT ERROR: unexpected number of space-separated fields: line '%s' in %s" % (l, fn)
type, ids = fields[0], fields[1:]
assert type == "Equiv", "FORMAT ERROR: non-'Equiv' type for '*' id: line '%s' in %s" % (l, fn)
# IDs are in the "T[0-9]+" format.
for id in ids:
assert re.match(r'^[A-Z]\d+$', id), "FORMAT ERROR: IDs not in format 'T[0-9]+': line '%s' in %s" % (l, fn)
# IDs should be unique; allow but ignore other
seen_ids = set()
unique_ids = []
for id in ids:
if id in seen_ids:
print >> sys.stderr, "Note: id '%s' appears multiple times in Equiv '%s', ignoring repetition" % (id, l)
else:
seen_ids.add(id)
unique_ids.append(id)
ids = unique_ids
return Equiv(ids)
def open_annotation_file(fn):
try:
f = open(fn)
except IOError, e:
usage_exit("error: " + str(e) + " (try '-r' option?)")
return f
def check_unique_and_store(key, val, map, fn):
assert key not in map, "ERROR: duplicate ID %s in %s" % (key, fn)
map[key] = val
# reads in and verifies event annotation (".a2 file") from the given
# file, with reference to the given original document text.
# Last argument is a map (id to annotation obj) of previously read
# annotations. Returns a pair of (annotation_map, equiv_list) where
# annotation_map is a map from ID to the corresponding annotation and
# equiv_list is a list of Equiv's.
def parse_event_file(a2file, document_text, annotation_by_id):
global options
equiv_annotations = []
for l in a2file:
l = l.strip(' \n\r')
# skip comments or cross references
if len(l) > 0 and (l[0] == "#" or l[0] == "X"):
continue
# decide how to parse this based on first character of ID
assert len(l) > 0 and l[0] in ("*", "E", "M", "T", "G", "L", "D", "P", "A",
"N"), "FORMAT ERROR: line doesn't start with valid ID: line '%s' in %s" % (
l, a2file.name)
# parse and store as appropriate.
if l[0] == "*":
equiv = parse_equiv_line(l, a2file.name)
equiv_annotations.append(equiv)
elif l[0] in ("T", "G", "L", "D", "P", "N"):
t = parse_textbound_line(l, a2file.name)
if options.verifytext:
t.verify_text(document_text, a2file.name)
check_unique_and_store(t.id, t, annotation_by_id, a2file.name)
elif l[0] == "E":
# special case: generate-task-specific-a2-file.pl may
# create events with an empty set of arguments in
# processing "split event" data. In "split event" mode, ignore
# these without error.
if options.spliteventeval and re.match(r'^E\S+\t[A-Za-z_]+:T\d+\s*$', l):
continue
e = parse_event_line(l, a2file.name)
check_unique_and_store(e.id, e, annotation_by_id, a2file.name)
elif l[0] == "M" or l[0] == "A":
m = parse_modification_line(l, a2file.name)
check_unique_and_store(m.id, m, annotation_by_id, a2file.name)
else:
assert False, "INTERNAL ERROR"
return annotation_by_id, equiv_annotations
# helper for a special circumstance in "split event" evaluation:
# recursively removes all events that fail idref resolutions (i.e.
# refer to an event that doesn't exist)
def remove_idref_failing_events(annotation_by_id, fn):
while True:
dropped_event = False
annids = annotation_by_id.keys()
for i in annids:
a = annotation_by_id[i]
try:
a.resolve_idrefs(annotation_by_id)
except AssertionError, e:
print >> sys.stderr, "Dropping event %s in %s:" % (i, fn), str(e)
del annotation_by_id[i]
dropped_event = True
if not dropped_event:
return
# reads in and verifies the reference files. Returns tuples
# (document_text, annotation_map, equiv_list) where document_text is
# the raw unannotated text of the original document, annotation_map is
# a map from ID to the corresponding annotation objects and equiv_list
# is a list of Equiv annotation objects.
#
# Argument t2_tasksuffix gives a suffix to append to the ".a2"
# filename from which event annotations are read. So, to e.g. evaluate
# specifically against task 1 reference files, provide ".t1".
def parse_reference_files(PMID, t2_tasksuffix=""):
# store all other annotations by id, Equivs as a list (no id)
annotation_by_id = {}
# read text
txt_fn = os.path.join(options.refdir, PMID + ".txt")
txt_f = open_annotation_file(txt_fn)
document_text = txt_f.read()
txt_f.close()
# read given entities (".a1 file").
a1_fn = os.path.join(options.refdir, PMID + ".a1")
a1_f = open_annotation_file(a1_fn)
for l in a1_f:
e = parse_given_entity_line(l, a1_fn, document_text)
check_unique_and_store(e.id, e, annotation_by_id, a1_fn)
a1_f.close()
# read other annotations (".a2 file"). The file to read may be modified by
# a task suffix if provided.
# exception: the ".unified" suffix should be ignored
if t2_tasksuffix != ".unified":
a2_fn = os.path.join(options.refdir, PMID + ".a2" + t2_tasksuffix)
else:
a2_fn = os.path.join(options.refdir, PMID + ".a2")
a2_f = open_annotation_file(a2_fn)
annotation_by_id, equiv_annotations = parse_event_file(a2_f, document_text, annotation_by_id)
a2_f.close()
# now that we have all the annotations, check and resolve ID
# references. Exception for "split event" evaluation: allow broken
# idrefs (these are sometimes generated in processing ... a bit
# of a long story) and just remove the events.
if options.spliteventeval:
remove_idref_failing_events(annotation_by_id, a2_fn)
for a in annotation_by_id.values():
a.resolve_idrefs(annotation_by_id)
for e in equiv_annotations:
e.resolve_idrefs(annotation_by_id)
# then, convert Modifications into events: Negation and Speculation are
# converted into pseudo-Events for the purposes of matching.
pseudoEvents = {}