-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCS-Score-MASTER.pl
1647 lines (1509 loc) · 61.7 KB
/
CS-Score-MASTER.pl
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/perl
use warnings;
use strict;
use utf8;
use Carp;
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
### DO NOT INCLUDE
use ColdStartLib;
### DO INCLUDE
#####################################################################################
# This program scores Cold Start 2015 submissions. It takes as input
# the evaluation queries, the appropriate assessment files, and a
# submission file. The submission file is either a Slot Filling
# variant submission file, or the result of applying the evaluation
# queries to a submitted knowledge base (typically obtained by running
# CS-ResolveQueries.pl)
#
# Authors: James Mayfield, Shahzad Rajput
# Please send questions or comments to jamesmayfield "at" gmail "dot" com
#
# For usage, run with no arguments
#####################################################################################
### DO NOT INCLUDE
# Shahzad: I have not upped any version numbers. We should up them all just prior to
# the release of the new code
### DO INCLUDE
my $version = "2017.2.0";
# Filehandles for program and error output
my @output_postfix = qw(DEBUG AP SF LDCMAX LDCMEAN SUMMARY SAMPLE SAMPLESCORES CONFIDENCE PARAMS);
my %program_output;
my $error_output;
# The default sequence of output fields
### DO NOT INCLUDE
# Shahzad: I've omitted some of our agreed upon default fields just to get it working.
# Something like the following is what we had discussed:
#my $default_fields = "EC:GT:CORRECT:INCORRECT:INEXACT:RIGHT:WRONG:REDUNDANT:IGNORED:P:R:F";
### DO INCLUDE
my $default_fields = "EC:RUNID:LEVEL:GT:SUBMITTED:CORRECT:INCORRECT:INEXACT:INCORRECT_PARENT:UNASSESSED:REDUNDANT:RIGHT:WRONG:IGNORED:P:R:F";
my $default_right = "CORRECT";
my $default_wrong = "INCORRECT:INCORRECT_PARENT:INEXACT";
my $default_ignore = "UNASSESSED:DUPLICATE";
### DO NOT INCLUDE
#####################################################################################
# Library inclusions
#####################################################################################
### DO INCLUDE
### DO INCLUDE Utils ColdStartLib.pm
### DO INCLUDE Patterns ColdStartLib.pm
### DO INCLUDE Logger ColdStartLib.pm
### DO INCLUDE Provenance ColdStartLib.pm
### DO INCLUDE Predicates ColdStartLib.pm
### DO INCLUDE Query ColdStartLib.pm
### DO INCLUDE QuerySet ColdStartLib.pm
### DO INCLUDE EvaluationQueryOutput ColdStartLib.pm
### DO INCLUDE Scoring ColdStartLib.pm
### DO INCLUDE Switches ColdStartLib.pm
### DO NOT INCLUDE
# Hush up perl worrywart module. FIXME: Not sure this is still needed.
my $pattern = $main::comment_pattern;
### DO INCLUDE
package SamplesScoresPrinter;
# This package prepares sample summary scores given the samples and scores_printer
my %code = (
ALL_ENTRYPOINT => "ALLEP",
ONE_ENTRYPOINT => "ONEEP",
LDCMAX => "LDCMAXI",
LDCMEAN => "LDCMEAN",
SF => "SLOTFLG",
F1 => "F",
PRECISION => "P",
RECALL => "R",
0 => "0",
1 => "1",
ALL => "A",
"ALL-Macro" => "Ma",
"ALL-Micro" => "Mi"
);
my %inverse_code = reverse %code;
sub new {
my ($class, $logger, $samples, $scores_printer) = @_;
my $self = {
LOGGER => $logger,
SAMPLES => $samples,
SCORES_PRINTER => $scores_printer,
ORIGINAL_STATS => {$scores_printer->get_summary_stats()},
};
bless($self, $class);
foreach my $score(@{$self->{SCORES_PRINTER}{SCORES}}) {
my $duplicate_score = $score->duplicate();
push(@{$self->{SCORES}}, $duplicate_score);
}
$self;
}
sub get {
my ($self, $field, @args) = @_;
return $self->{$field} if defined $self->{$field};
my $method = $self->can("get_$field");
return $method->($self, @args) if $method;
}
sub get_QUERIES_TO_SCORE {
my ($self, $sample_num, $projection_type) = @_;
$self->{SAMPLES}->get("QUERIES_TO_SCORE", $sample_num, $projection_type);
}
sub get_ORIGINAL_SCORE {
my ($self, $field_code) = @_;
my $score;
my $score_str;
my ($ep, $type, $aggregate_type, $level, $metric) = map {$inverse_code{$_}} split("_", $field_code);
$score = $self->{ORIGINAL_STATS}{$type}{$aggregate_type}{$level}{$metric}
if $ep eq "ALL_ENTRYPOINT";
$score_str = sprintf("%0.4f", $score) if defined $score;
$score_str = sprintf("%6s","-") unless $score;
$score_str;
}
sub manage_duplicates {
my ($self, $sample_num, $projection_type) = @_;
my %queries_to_score = $self->{SAMPLES}->get("QUERIES_TO_SCORE", $sample_num, $projection_type);
my @scores;
foreach my $score(@{$self->{SCORES}}) {
my $query_id = $score->{QUERY_ID_BASE};
if(exists $queries_to_score{$query_id}) {
for(my $i=1; $i<=$queries_to_score{$query_id}; $i++) {
my $duplicate_score = $score->duplicate();
push(@scores, $duplicate_score);
}
}
}
@{$self->{SCORES_PRINTER}{SCORES}} = @scores;
}
sub get_samples_summary_evals {
my ($self) = @_;
my %samples_summary_evals;
foreach my $i(sort keys %{$self->{SAMPLES}{SAMPLES}}){
my %stats;
%{$self->{SCORES_PRINTER}{QUERIES_TO_SCORE}} = $self->get("QUERIES_TO_SCORE", $i, "ALL_ENTRYPOINT");
$self->manage_duplicates($i, "ALL_ENTRYPOINT");
%stats = $self->{SCORES_PRINTER}->get_summary_stats();
$samples_summary_evals{$i}{ALL_ENTRYPOINT} = {%stats};
%{$self->{SCORES_PRINTER}{QUERIES_TO_SCORE}} = $self->get("QUERIES_TO_SCORE", $i, "ONE_ENTRYPOINT");
$self->manage_duplicates($i, "ONE_ENTRYPOINT");
%stats = $self->{SCORES_PRINTER}->get_summary_stats();
$samples_summary_evals{$i}{ONE_ENTRYPOINT} = {%stats};
}
%samples_summary_evals;
}
sub print_lines {
my ($self) = @_;
my $runid = $self->{SCORES_PRINTER}{RUNID};
my %samples_summary_evals = $self->get_samples_summary_evals();
foreach my $sample(sort {$a<=>$b} keys %{$self->{SAMPLES}{SAMPLES}}) {
print {$program_output{SAMPLE}} "$sample";
foreach my $query_num(sort {$a<=>$b} keys %{$self->{SAMPLES}{SAMPLES}{$sample}}) {
my $ldc_queryid = $self->{SAMPLES}{SAMPLES}{$sample}{$query_num}{LDC_QUERY_ID};
my $sf_queryid = $self->{SAMPLES}{SAMPLES}{$sample}{$query_num}{SF_QUERY_ID_FULL}{0};
print {$program_output{SAMPLE}} " $ldc_queryid:$sf_queryid";
}
print {$program_output{SAMPLE}} "\n";
}
my $skip = qr/^...EP_LDCMEAN_Mi|^ONEEP_LDCMAXI|^ONEEP_LDCMEAN_Ma/;
# Print header
my @ep_types = qw(ONE_ENTRYPOINT ALL_ENTRYPOINT);
my @ev_types = qw(LDCMAX LDCMEAN SF);
my @ag_types = qw(ALL-Micro ALL-Macro);
my @levels = qw(0 1 ALL);
my @metrices = qw(PRECISION RECALL F1);
print {$program_output{SAMPLESCORES}} "Sample#";
foreach my $ep_type(@ep_types) {
foreach my $ev_type(@ev_types){
foreach my $ag_type(@ag_types) {
foreach my $level(@levels) {
foreach my $metric(@metrices) {
my $header = join "_", map {$code{$_}} ($ep_type, $ev_type, $ag_type, $level, $metric);
next if ($header=~$skip);
print {$program_output{SAMPLESCORES}} " $header";
}
}
}
}
}
print {$program_output{SAMPLESCORES}} " #RUNID\n";
# Print lines
my %scores;
foreach my $sample(sort {$a<=>$b} keys %samples_summary_evals) {
print {$program_output{SAMPLESCORES}} sprintf("%6d", $sample);
foreach my $ep_type(@ep_types) {
foreach my $ev_type(@ev_types){
foreach my $ag_type(@ag_types) {
foreach my $level(@levels) {
foreach my $metric(@metrices) {
my $header = join "_", map {$code{$_}} ($ep_type, $ev_type, $ag_type, $level, $metric);
next if ($header=~$skip);
my $score = $samples_summary_evals{$sample}{$ep_type}{$ev_type}{$ag_type}{$level}{$metric};
$scores{$header}{$sample} = $score;
print {$program_output{SAMPLESCORES}} sprintf(" %0.4f", $score);
}
}
}
}
}
print {$program_output{SAMPLESCORES}} " #$runid\n";
}
# Print confidence intervals
print {$program_output{CONFIDENCE}} " "x22, "99%( 95%( 90%( mean scr. )90% )95% )99%\n";
foreach my $header(sort keys %scores) {
my @scores = values %{$scores{$header}};
my $mean = $self->{SAMPLES}->mean(@scores);
my $original_score = $self->get("ORIGINAL_SCORE", $header);
my %confidence_intervals;
foreach my $confidence((99, 95, 90)) {
@{$confidence_intervals{$confidence}} = $self->{SAMPLES}->get_confidence_interval($confidence, @scores);
}
print {$program_output{CONFIDENCE}} "$header $confidence_intervals{99}[0] $confidence_intervals{95}[0] $confidence_intervals{90}[0] $mean $original_score $confidence_intervals{90}[1] $confidence_intervals{95}[1] $confidence_intervals{99}[1]\n";
}
}
package APScoresPrinter;
our %printable_fields = (
EC => {
NAME => 'EC',
DESCRIPTION => "Query or equivalence class name",
HEADER => 'QID/EC',
FORMAT => '%s',
JUSTIFY => 'L',
FN => sub { $_[0]{EC} },
},
RUNID => {
NAME => 'RUNID',
DESCRIPTION => "Run ID",
HEADER => 'RunID',
FORMAT => '%s',
JUSTIFY => 'L',
FN => sub { $_[0]{RUNID} },
},
LEVEL => {
NAME => 'LEVEL',
DESCRIPTION => "Hop level",
HEADER => 'Hop',
FORMAT => '%s',
JUSTIFY => 'L',
FN => sub { $_[0]{LEVEL} },
},
AP => {
NAME => 'AP',
DESCRIPTION => "Average Precision",
HEADER => 'AP',
FORMAT => '%6.4f',
JUSTIFY => 'L',
FN => sub { $_[0]->get('AP') },
},
);
our %metrices = (
SF => {
ORDER => 1,
NAME => "SF",
DESCRIPTION => "SF: Slot-filling score variant considering all entrypoints as a separate query",
AGGREGATES => [qw(MACRO)],
},
LDCMEAN => {
ORDER => 2,
NAME => "LDC-MEAN",
DESCRIPTION => "LDC-MEAN: LDC level score variant considering averaging scores for all coressponding entrypoints",
AGGREGATES => [qw(MACRO)],
},
);
sub get_fields_to_print {
my ($spec, $logger) = @_;
[map {$printable_fields{$_} || $logger->NIST_die("Unknown field: $_")} split(/:/, $spec)];
}
sub new {
my ($class, $separator, $queries, $runid, $index, $queries_to_score, $spec, $logger) = @_;
my $fields_to_print = &get_fields_to_print($spec, $logger);
my $self = {RUNID => $runid,
INDEX => $index,
QUERIES => $queries,
QUERIES_TO_SCORE => $queries_to_score,
FIELDS_TO_PRINT => $fields_to_print,
WIDTHS => {map {$_->{NAME} => length($_->{HEADER})} @{$fields_to_print}},
HEADERS => [map {$_->{HEADER}} @{$fields_to_print}],
LINES => [],
};
$self->{SEPARATOR} = $separator if defined $separator;
bless($self, $class);
$self;
}
sub aggregate_score {
my ($aggregates, $runid, $level, $scores) = @_;
# Make sure the necessary aggregate structures are present
unless (defined $aggregates->{$runid}{$level}) {
my $scoreset = ScoreSet->new();
$scoreset->put('RUNID', $runid);
$scoreset->put('EC', 'ALL-Micro');
$scoreset->put('LEVEL', $level);
$aggregates->{$runid}{$level} = $scoreset;
}
# Aggregate this set of scores for regular slots
$aggregates->{$runid}{$level}->add($scores);
}
sub add_scores {
my ($self, @scores) = @_;
foreach my $score(@scores) {
next if ($score->{LEVEL} ne "ALL" && $self->{QUERIES_TO_SCORE}{$score->{QUERY_ID_BASE}} < $score->{LEVEL});
push(@{$self->{SCORES}}, $score);
}
}
sub compare_ec_names {
my ($qa, @a) = split(/:/, $a->{EC});
my ($qb, @b) = split(/:/, $b->{EC});
$qa cmp $qb ||
eval(join(" || ", map {$a[$_] <=> $b[$_]} 0..&main::min($#a, $#b))) ||
scalar @a <=> scalar @b;
}
sub get_line {
my ($self, $score) = @_;
my %line;
foreach my $field (@{$self->{FIELDS_TO_PRINT}}) {
my $value = &{$field->{FN}}($score);
# FIXME: Is this always the appropriate default value?
$value = 0 unless defined $value;
my $text = sprintf($field->{FORMAT}, $value);
$line{$field->{NAME}} = $text;
$self->{WIDTHS}{$field->{NAME}} = length($text) if length($text) > $self->{WIDTHS}{$field->{NAME}};
}
%line;
}
sub print_line {
my ($self, $line, $fields, $metric_name, $program_output) = @_;
my $separator = "";
$fields = $self->{FIELDS_TO_PRINT} unless $fields;
foreach my $field (@{$fields}) {
my $value = (defined $line ? $line->{$field->{NAME}} : $field->{HEADER});
$value = "$metric_name-$value" if $field->{NAME} eq "EC" && $metric_name;
print $program_output $separator;
my $numspaces = defined $self->{SEPARATOR} ? 0 : $self->{WIDTHS}{$field->{NAME}} - length($value);
print $program_output ' ' x $numspaces if $field->{JUSTIFY} eq 'R' && !defined $self->{SEPARATOR};
print $program_output $value;
print $program_output ' ' x $numspaces if $field->{JUSTIFY} eq 'L' && !defined $self->{SEPARATOR};
$separator = defined $self->{SEPARATOR} ? $self->{SEPARATOR} : ' ';
}
print $program_output "\n";
}
sub add_macro_average {
my ($self, $metric, @scores) = @_;
my $aggregates = {};
foreach my $score(sort compare_ec_names @scores ) {
&aggregate_score($aggregates, $score->{RUNID}, $score->{LEVEL}, $score);
}
foreach my $level (sort keys %{$aggregates->{$self->{RUNID}}}) {
# Print the macro-averaged scores
my %line;
foreach my $field (@{$self->{FIELDS_TO_PRINT}}) {
my $value = "";
if ($field->{NAME} eq 'QUERY_ID' ||
$field->{NAME} eq 'EC' ||
$field->{NAME} eq 'RUNID' ||
$field->{NAME} eq 'LEVEL') {
$value = $aggregates->{$self->{RUNID}}{$level}->get($field->{NAME});
}
elsif ($field->{NAME} eq 'AP') {
$value = $aggregates->{$self->{RUNID}}{$level}->getadjustedmean($field->{NAME});
}
$value = 'ALL-Macro' if $value eq 'ALL-Micro' && $field->{NAME} eq 'EC';
my $format = $field->{FORMAT};
$format =~ s/[df]/s/ if $value eq "";
$format =~ s/\.\d// if $value eq "";
my $text = sprintf($format, $value);
$line{$field->{NAME}} = $text;
$self->{WIDTHS}{$field->{NAME}} = length($text) if length($text) > $self->{WIDTHS}{$field->{NAME}};
}
push(@{$self->{LINES}}, \%line);
push(@{$self->{SUMMARY}{$metric}}, \%line);
}
}
sub projectLDCMEAN {
my ($self) = @_;
my %index = %{$self->{INDEX}};
my @scores = @{$self->{SCORES}};
my %evaluation_queries = map {$_=>1} keys %{$self->{QUERIES_TO_SCORE}};
my %new_scores;
my %duplicate_queries;
foreach my $scores(@scores){
my $full_cssf_queryid = $scores->{EC};
my (undef, $cssf_queryid) = &Query::parse_queryid($full_cssf_queryid);
my $csldc_queryid = $index{$cssf_queryid};
my $full_csldc_queryid = $self->{QUERIES}->get_full_queryid($index{$cssf_queryid});
my $level = $scores->{LEVEL};
if( (scalar keys %evaluation_queries > 0 && exists $evaluation_queries{$cssf_queryid})
|| scalar keys %evaluation_queries == 0) {
$new_scores{$level}{$full_csldc_queryid}{$cssf_queryid} = $scores;
}
}
my @combined_scores;
foreach my $level(sort keys %new_scores) {
foreach my $csldc_queryid(sort keys %{$new_scores{$level}}) {
my $combined_scores = Score->new;
my $i = 0;
foreach my $cssf_queryid(keys %{$new_scores{$level}{$csldc_queryid}}) {
my $scores = $new_scores{$level}{$csldc_queryid}{$cssf_queryid};
if(not exists $combined_scores->{EC}) {
$combined_scores->put('QUERY_ID_BASE', $scores->get('QUERY_ID_BASE'));
$combined_scores->put('EC', $csldc_queryid);
$combined_scores->put('RUNID', $scores->get('RUNID'));
$combined_scores->put('LEVEL', $scores->get('LEVEL'));
$combined_scores->put('NUM_GROUND_TRUTH', $scores->get('NUM_GROUND_TRUTH'));
$combined_scores->put('AP', $scores->get('AP'));
}
else{
$combined_scores->put('AP', $combined_scores->get('AP') + $scores->get('AP'));
}
$combined_scores->put('NUM_GROUND_TRUTH', $scores->get('NUM_GROUND_TRUTH'))
if($scores->get('NUM_GROUND_TRUTH') > $combined_scores->get('NUM_GROUND_TRUTH'));
$i++;
}
$combined_scores->put('AP', $combined_scores->get('AP')/$i);
push(@combined_scores, $combined_scores);
}
}
@combined_scores;
}
sub prepare_lines {
my ($self, $metric) = @_;
@{$self->{SUMMARY}{$metric}} = ();
my @scores = @{$self->{SCORES}};
@scores = $self->projectLDCMEAN() if($metric eq "LDCMEAN");
# Prepare lookup for associating parent scores
my %scores;
foreach my $score(@scores) {
$scores{$score->{EC}} = $score;
}
# Prepare lines
foreach my $score(sort compare_ec_names @scores) {
next if not exists $self->{QUERIES_TO_SCORE}{$score->{QUERY_ID_BASE}};
$score->{PARENT_SCORE} = $scores{&get_parent_ec($score)}
if &get_parent_ec($score);
my %line = $self->get_line($score);
push(@{$self->{LINES}}, \%line);
}
# Add aggregates
$self->add_macro_average($metric, @scores)
if(grep {$_ =~ /MACRO/} @{$metrices{$metric}{AGGREGATES}});
}
sub print_headers {
my ($self, @args) = @_;
$self->print_line( undef, @args );
}
sub print_lines {
my ($self) = @_;
foreach my $metric(sort {$metrices{$a}{ORDER}<=>$metrices{$b}{ORDER}} keys %metrices) {
# Skip over if the sf-queries file passed as argument
# This is determined by looking up keys in %{$self->{INDEX}}
# which stores a mapping between LDC and SF query ids
next if( ($metric eq "LDCMEAN") && (scalar keys %{$self->{INDEX}} == 0) );
my $description = $metrices{$metric}{DESCRIPTION};
my $fields_to_print = $self->{FIELDS_TO_PRINT};
$self->prepare_lines($metric);
$self->print_details() if $metric eq "SF";
print {$program_output{AP}} "$metrices{$metric}{DESCRIPTION}\n\n";
$self->print_headers($fields_to_print, undef, $program_output{AP}) if @{$self->{LINES}};
foreach my $line (@{$self->{LINES}}) {
$self->print_line($line, $fields_to_print, undef, $program_output{AP});
}
print {$program_output{AP}} "\n";
@{$self->{LINES}} = ();
}
$self->print_summary($program_output{AP});
print {$program_output{"AP"}} "\n*ALL-Macro AP refer to mean of corresponding AP values.\n";
}
sub print_details {
my ($self) = @_;
print {$program_output{DEBUG}} "AP COMPUTATION DEBUG INFO BEGINS:\n";
foreach my $score(sort {$a->{EC} cmp $b->{EC} || $a->{LEVEL} cmp $b->{LEVEL}} @{$self->{SCORES}}) {
my $query_id = $score->{EC};
my $level = $score->{LEVEL};
my $ap = sprintf("%0.4f", $score->{AP});
my $num_ground_truth = $score->{NUM_GROUND_TRUTH};
print {$program_output{DEBUG}} "="x80, "\n";
print {$program_output{DEBUG}} "QUERY_ID: $query_id\n";
print {$program_output{DEBUG}} "LEVEL: $level\n";
print {$program_output{DEBUG}} "AP: $ap\n";
print {$program_output{DEBUG}} "NUM_GROUND_TRUTH: $num_ground_truth\n";
print {$program_output{DEBUG}} "GROUND TRUTH:\n";
print {$program_output{DEBUG}} join("\n", map {" $_"} sort @{$score->{DEBUG}{ECS} || []}), "\n";
print {$program_output{DEBUG}} "RANKING:\n........\nRANK NODEID CONFIDENCE MAPPED_EC V\n";
my $rank = 1;
foreach my $nodeid(sort {$score->{DEBUG}{NODES}{$b}{CONFIDENCE} <=> $score->{DEBUG}{NODES}{$a}{CONFIDENCE} ||
$score->{DEBUG}{NODES}{$a}{LINENUM} <=> $score->{DEBUG}{NODES}{$b}{LINENUM}}
keys %{$score->{DEBUG}{NODES}}) {
my $confidence = sprintf("%0.4f", $score->{DEBUG}{NODES}{$nodeid}{CONFIDENCE});
my $ec = $score->{DEBUG}{NODES}{$nodeid}{EC};
$ec = "-" unless $ec;
my $v = sprintf("%0.4f", $score->{DEBUG}{NODES}{$nodeid}{V});
print {$program_output{DEBUG}} "$rank $nodeid $confidence $ec $v\n";
$rank++;
}
}
print {$program_output{DEBUG}} "AP COMPUTATION DEBUG INFO ENDS\n";
}
sub print_summary {
my ($self, $output_handle) = @_;
my $fields_to_print = $self->{FIELDS_TO_PRINT};
print $output_handle "SUMMARY: This section provides summary of AP scores\n\n";
$self->print_headers($fields_to_print, undef, $output_handle);
foreach my $metric(sort {$metrices{$a}{ORDER}<=>$metrices{$b}{ORDER}} keys %metrices) {
my $metric_name = $metrices{$metric}{NAME};
foreach my $line (@{$self->{SUMMARY}{$metric}}) {
$self->print_line($line, $fields_to_print, $metric_name, $output_handle);
}
}
}
sub get_parent_ec {
my ($score) = @_;
if($score->{EC} =~ /:/) {
my @elements = split(":", $score->{EC});
pop @elements;
return join(":", @elements);
}
return;
}
sub get_summary_stats {
my ($self) = @_;
foreach my $metric(sort {$metrices{$a}{ORDER}<=>$metrices{$b}{ORDER}} keys %metrices) {
@{$self->{SUMMARY}{$metric}} = ();
$self->prepare_lines($metric);
}
my %summary = %{$self->{SUMMARY}};
my @fields = qw(AP);
my %stats;
foreach my $metric(keys %summary) {
foreach my $line( @{$summary{$metric}} ){
my $ec = $line->{EC};
my $level = $line->{LEVEL};
$stats{$metric}{$ec}{$level} = {map {$_=>$line->{$_}} @fields};
}
}
%stats;
}
# Determine which queries should be scored
sub get_queries_to_score {
my ($logger, $spec, $queries) = @_;
my %query_slots;
# Spec can be empty (meaning score all queries), a colon-separated
# list of IDs, or a filename
if (!defined $spec) {
my @query_ids = $queries->get_all_top_level_query_ids();
%query_slots = map {$_=>scalar @{$queries->get($_)->{SLOTS}}-1} @query_ids;
}
elsif (-f $spec) {
open(my $infile, "<:utf8", $spec) or $logger->NIST_die("Could not open $spec: $!");
my %index;
while(<$infile>) {
chomp;
my ($csldc_query_id, $cssf_query_id_full, $num_slots) = split(/\s+/, $_);
if (not exists $index{$csldc_query_id}) {
$index{$csldc_query_id} = defined $num_slots ? $num_slots : -1;
}
else {
my $target_value = defined $num_slots ? $num_slots : -1;
$logger->NIST_die("$csldc_query_id has multiple/conflicting num_slots in $spec")
if($target_value != $index{$csldc_query_id});
}
my ($base, $cssf_query_id) = &Query::parse_queryid($cssf_query_id_full);
unless ($queries->get($cssf_query_id)) {
$logger->record_problem('UNKNOWN_QUERY_ID_WARNING', $cssf_query_id, 'NO_SOURCE');
next;
}
my $max_num_slot = scalar @{$queries->get($cssf_query_id)->{SLOTS}}-1;
$num_slots = $max_num_slot unless defined $num_slots;
$logger->NIST_die("Unexpected num_slots value $num_slots for $csldc_query_id in $spec")
if $num_slots > $max_num_slot || $num_slots < 0;
$query_slots{$cssf_query_id} = $num_slots;
}
close $infile;
}
else {
my @query_ids = split(/:/, $spec);
foreach my $full_query_id(@query_ids) {
my ($base, $query_id) = &Query::parse_queryid($full_query_id);
unless ($queries->get($query_id)) {
$logger->record_problem('UNKNOWN_QUERY_ID_WARNING', $query_id, 'NO_SOURCE');
next;
}
my $num_slots = scalar @{$queries->get($query_id)->{SLOTS}}-1;
$query_slots{$query_id} = $num_slots;
}
}
my %query_ids_to_score;
foreach my $query_id (keys %query_slots) {
my $root = $queries->get_ancestor($query_id);
my $num_slots = $query_slots{$query_id};
$query_ids_to_score{$root->get("QUERY_ID")} = $num_slots unless @{$root->get("EXPANDED_QUERY_IDS")};
# If we've requested an unexpanded query ID, we need to add each of the expanded queries
foreach my $expanded_query_id (@{$root->get("EXPANDED_QUERY_IDS")}) {
$num_slots = $query_slots{$expanded_query_id};
$query_ids_to_score{$expanded_query_id} = $num_slots;
}
}
%query_ids_to_score;
}
package ScoresPrinter;
# This package converts scoring output to printable form.
### DO NOT INCLUDE
# Shahzad: the FNs in the following need to be kept in sync with the output of
# EvaluationQueryOutput::score_query(). Either the FIXMEs need to be replaced
# with the appropriate field name, or if we can calculate the value from that
# output, FN needs to do the calculation and return the appropriate string.
### DO INCLUDE
our %printable_fields = (
EC => {
NAME => 'EC',
DESCRIPTION => "Query or equivalence class name",
HEADER => 'QID/EC',
FORMAT => '%s',
JUSTIFY => 'L',
FN => sub { $_[0]{EC} },
},
RUNID => {
NAME => 'RUNID',
DESCRIPTION => "Run ID",
HEADER => 'RunID',
FORMAT => '%s',
JUSTIFY => 'L',
FN => sub { $_[0]{RUNID} },
},
LEVEL => {
NAME => 'LEVEL',
DESCRIPTION => "Hop level",
HEADER => 'Hop',
FORMAT => '%s',
JUSTIFY => 'L',
FN => sub { $_[0]{LEVEL} },
},
GT => {
NAME => 'NUM_GROUND_TRUTH',
DESCRIPTION => "Number of ground truth values",
HEADER => 'GT',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_GROUND_TRUTH} },
},
CORRECT => {
NAME => 'NUM_CORRECT_PRE_POLICY',
DESCRIPTION => "Number of assessed correct responses (pre-policy)",
HEADER => 'Correct',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_CORRECT} },
},
INCORRECT => {
NAME => 'NUM_INCORRECT_PRE_POLICY',
DESCRIPTION => "Number of assessed incorrect responses (pre-policy)",
HEADER => 'Incorrect',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_INCORRECT} },
},
INEXACT => {
NAME => 'NUM_INEXACT_PRE_POLICY',
DESCRIPTION => "Number of assessed inexact responses (pre-policy)",
HEADER => 'Inexact',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_INEXACT} },
},
REDUNDANT => {
NAME => 'NUM_REDUNDANT_POST_POLICY',
DESCRIPTION => "Number of duplicate submitted values in equivalence clase (post-policy)",
HEADER => 'Dup',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_REDUNDANT} },
},
RIGHT => {
NAME => 'NUM_CORRECT_POST_POLICY',
DESCRIPTION => "Number of submitted values counted as right (post-policy)",
HEADER => 'Right',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_RIGHT} },
},
WRONG => {
NAME => 'NUM_INCORRECT_POST_POLICY',
DESCRIPTION => "Number of submitted values counted as wrong (post-policy)",
HEADER => 'Wrong',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_WRONG} },
},
IGNORED => {
NAME => 'NUM_IGNORED_POST_POLICY',
HEADER => 'Ignored',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
DESCRIPTION => "Number of responses that were ignored (post-policy)",
FN => sub { $_[0]{NUM_IGNORED} },
},
SUBMITTED => {
NAME => 'NUM_SUBMITTED',
DESCRIPTION => "Total number of submitted entries",
HEADER => 'Submitted',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_SUBMITTED} },
},
UNASSESSED => {
NAME => 'NUM_UNASSESSED',
DESCRIPTION => "Total number of unassessed submitted entries",
HEADER => 'Unassessed',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_UNASSESSED} },
},
INCORRECT_PARENT => {
NAME => 'INCORRECT_PARENT',
DESCRIPTION => "Total number of submitted entries with parents incorrect",
HEADER => 'PIncorrect',
FORMAT => '%4d',
JUSTIFY => 'R',
MEAN_FORMAT => '%4.2f',
FN => sub { $_[0]{NUM_INCORRECT_PARENT} },
},
P => {
NAME => 'PRECISION',
DESCRIPTION => "Precision",
HEADER => 'Prec',
FORMAT => '%6.4f',
JUSTIFY => 'L',
FN => sub { $_[0]->get('PRECISION') },
},
R => {
NAME => 'RECALL',
DESCRIPTION => "Recall",
HEADER => 'Recall',
FORMAT => '%6.4f',
JUSTIFY => 'L',
FN => sub { $_[0]->get('RECALL') },
},
F => {
NAME => 'F1',
DESCRIPTION => "F1 = 2PR/(P+R)",
HEADER => 'F1',
FORMAT => '%6.4f',
JUSTIFY => 'L',
FN => sub { $_[0]->get('F1') },
},
);
my %policy_options = (
CORRECT => {
NAME => 'CORRECT',
DESCRIPTION => "Number of assessed correct responses. Legal choice for -right.",
VALUE_MAP => 'NUM_CORRECT',
CHOICES => [qw(RIGHT)],
},
DUPLICATE=> {
NAME => 'DUPLICATE',
DESCRIPTION => "Number of duplicate responses. Legal choice for -right, -wrong and -ignore.",
VALUE_MAP => 'NUM_IGNORED',
CHOICES => [qw(RIGHT WRONG IGNORE)],
},
INCORRECT => {
NAME => 'INCORRECT',
DESCRIPTION => "Number of assessed incorrect responses. Legal choice for -wrong.",
VALUE_MAP => 'NUM_INCORRECT',
CHOICES => [qw(WRONG)],
},
INCORRECT_PARENT => {
NAME => 'INCORRECT_PARENT',
DESCRIPTION => "Number of responses that had incrorrect (grand-)parent. Legal choice for -wrong and -ignore.",
VALUE_MAP => 'NUM_INCORRECT_PARENT',
CHOICES => [qw(WRONG IGNORE)],
},
INEXACT => {
NAME => 'INEXACT',
DESCRIPTION => "Number of assessed inexact responses. Legal choice for -right, -wrong and -ignore.",
VALUE_MAP => 'NUM_INEXACT',
CHOICES => [qw(RIGHT WRONG IGNORE)],
},
UNASSESSED=> {
NAME => 'UNASSESSED',
DESCRIPTION => "Number of unassessed responses. Legal choice for -wrong and -ignore.",
VALUE_MAP => 'NUM_UNASSESSED',
CHOICES => [qw(WRONG IGNORE)],
},
);
our %metrices = (
SF => {
ORDER => 1,
NAME => "SF",
DESCRIPTION => "SF: Slot-filling score variant considering all entrypoints as a separate query",
AGGREGATES => [qw(MICRO MACRO)],
},
LDCMAX => {
ORDER => 2,
NAME => "LDC-MAX",
DESCRIPTION => "LDC-MAX: LDC level score variant considering the run's best entrypoint per LDC query",
AGGREGATES => [qw(MICRO MACRO)],
},
LDCMEAN => {
ORDER => 3,
NAME => "LDC-MEAN",
DESCRIPTION => "LDC-MEAN: LDC level score variant considering averaging scores for all coressponding entrypoints",
AGGREGATES => [qw(MACRO)],
},
);
sub get_fields_to_print {
my ($spec, $logger) = @_;
[map {$printable_fields{$_} || $logger->NIST_die("Unknown field: $_")} split(/:/, $spec)];
}
sub new {
my ($class, $separator, $queries, $runid, $index, $queries_to_score, $spec, $logger) = @_;
my $fields_to_print = &get_fields_to_print($spec, $logger);
my $ldc_mean_spec = "EC:RUNID:LEVEL:P:R:F";
my $ldc_mean_fields_to_print = &get_fields_to_print($ldc_mean_spec, $logger);
my $self = {RUNID => $runid,
INDEX => $index,
QUERIES => $queries,
QUERIES_TO_SCORE => $queries_to_score,
FIELDS_TO_PRINT => $fields_to_print,
LDC_MEAN_FIELDS_TO_PRINT => $ldc_mean_fields_to_print,
WIDTHS => {map {$_->{NAME} => length($_->{HEADER})} @{$fields_to_print}},
HEADERS => [map {$_->{HEADER}} @{$fields_to_print}],
LINES => [],
};
$self->{SEPARATOR} = $separator if defined $separator;
bless($self, $class);
$self;
}
sub aggregate_score {
my ($aggregates, $runid, $level, $scores) = @_;
# Make sure the necessary aggregate structures are present
unless (defined $aggregates->{$runid}{$level}) {
my $scoreset = ScoreSet->new();
$scoreset->put('RUNID', $runid);
$scoreset->put('EC', 'ALL-Micro');
$scoreset->put('LEVEL', $level);
$aggregates->{$runid}{$level} = $scoreset;
}
# Aggregate this set of scores for regular slots
$aggregates->{$runid}{$level}->add($scores);
}
sub add_scores {
my ($self, @scores) = @_;
push(@{$self->{SCORES}}, @scores);
}
# Compare two equivalence class names; comparison is alphabetic for
# the first component, and numerical for all subsequent
# components. This is broken out as a separate function to ensure that
# queries with more than two hops are supported in some fantasized
# future
sub compare_ec_names {
my ($qa, @a) = split(/:/, $a->{EC});
my ($qb, @b) = split(/:/, $b->{EC});
$qa cmp $qb ||
eval(join(" || ", map {$a[$_] <=> $b[$_]} 0..&main::min($#a, $#b))) ||
scalar @a <=> scalar @b;
}
sub get_line {
my ($self, $score) = @_;
my %line;
foreach my $field (@{$self->{FIELDS_TO_PRINT}}) {
my $value = &{$field->{FN}}($score);
# FIXME: Is this always the appropriate default value?
$value = 0 unless defined $value;
my $text = sprintf($field->{FORMAT}, $value);
$line{$field->{NAME}} = $text;
$self->{WIDTHS}{$field->{NAME}} = length($text) if length($text) > $self->{WIDTHS}{$field->{NAME}};
}
$self->{CATEGORIZED_SUBMISSIONS}{$score->{EC}} = $score->{CATEGORIZED_SUBMISSIONS}
if($score->{CATEGORIZED_SUBMISSIONS});
%line;
}
sub print_line {
my ($self, $line, $fields, $metric_name, $program_output) = @_;
my $separator = "";
$fields = $self->{FIELDS_TO_PRINT} unless $fields;
foreach my $field (@{$fields}) {
my $value = (defined $line ? $line->{$field->{NAME}} : $field->{HEADER});
$value = "$metric_name-$value" if $field->{NAME} eq "EC" && $metric_name;
print $program_output $separator;
my $numspaces = defined $self->{SEPARATOR} ? 0 : $self->{WIDTHS}{$field->{NAME}} - length($value);
print $program_output ' ' x $numspaces if $field->{JUSTIFY} eq 'R' && !defined $self->{SEPARATOR};
print $program_output $value;
print $program_output ' ' x $numspaces if $field->{JUSTIFY} eq 'L' && !defined $self->{SEPARATOR};
$separator = defined $self->{SEPARATOR} ? $self->{SEPARATOR} : ' ';
}
print $program_output "\n";
}
sub add_micro_average {
my ($self, $metric, @scores) = @_;
my $aggregates = {};
foreach my $score(sort compare_ec_names @scores ) {
&aggregate_score($aggregates, $score->{RUNID}, $score->{LEVEL}, $score);
&aggregate_score($aggregates, $score->{RUNID}, 'ALL', $score);
}
foreach my $level (sort keys %{$aggregates->{$self->{RUNID}}}) {
my %line = $self->get_line($aggregates->{$self->{RUNID}}{$level});
push(@{$self->{LINES}}, \%line);
push(@{$self->{SUMMARY}{$metric}}, \%line);
}
}
sub add_macro_average {
my ($self, $metric, @scores) = @_;
my $aggregates = {};
foreach my $score(sort compare_ec_names @scores ) {
&aggregate_score($aggregates, $score->{RUNID}, $score->{LEVEL}, $score);
&aggregate_score($aggregates, $score->{RUNID}, 'ALL', $score);
}
foreach my $level (sort keys %{$aggregates->{$self->{RUNID}}}) {
# Print the macro-averaged scores
my %line;
foreach my $field (@{$self->{FIELDS_TO_PRINT}}) {
my $value = "";
if ($field->{NAME} eq 'QUERY_ID' ||
$field->{NAME} eq 'EC' ||