#!/usr/bin/perl -w

use strict;

# Check a TAC 2011 KBP Track slot-filling task submission for various common errors, including:
#      * invalid run tag (should be a concatenation of your TAC 2011 team ID and the run number (1-3)
#      * multiple run tags
#      * invalid query id or slot name
#      * missing value for a question (at least one response required per question)
#      * answer from an invalid document (approximate check)
# [NB: "question" refers to a (query id, slot name) pair]
# Messages regarding submission are printed to an error log

# The submission file for the KBP slot-filling task has exactly one
# response per single-valued slot and at least one response for each
# list-valued slot, for each query (except that no response should be
# given for slots listed in the 'ignore' list of the query).

# A response is a line of the form
#    query_id slot_name run_id docid answer-string-as-the-remainder-of-the-line
# OR
#    query_id slot_name run_id NIL

# This script also creates a new file, "input", in the current directory
# that has a more standard format (there will not be leading whitespace;
# and columns will be separated by one tab)

# Usage is:
#    check_kbp_slot-filling.pl results_file
#  where results_file is the name of the results submission file to be checked

# Change this variable to the directory where the error log should be put
my $errlog_dir = ".";

my $MAX_ERRORS = 25;

# These values are specific to the TAC 2011 KBP track regular English slot-filling task
my %queries =
 (SF500 => {type => "ORG",
           ignore => []},
  SF501 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:stateorprovince_of_headquarters"]},
  SF502 => {type => "ORG",
           ignore => []},
  SF503 => {type => "ORG",
           ignore => []},
  SF504 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:stateorprovince_of_headquarters"]},
  SF505 => {type => "ORG",
           ignore => []},
  SF506 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:number_of_employees/members", "org:stateorprovince_of_headquarters", "org:website"]},
  SF507 => {type => "ORG",
           ignore => []},
  SF508 => {type => "ORG",
           ignore => []},
  SF509 => {type => "ORG",
           ignore => []},
  SF510 => {type => "ORG",
           ignore => []},
  SF511 => {type => "ORG",
           ignore => []},
  SF512 => {type => "ORG",
           ignore => []},
  SF513 => {type => "ORG",
           ignore => []},
  SF514 => {type => "ORG",
           ignore => []},
  SF515 => {type => "ORG",
           ignore => ["org:country_of_headquarters", "org:founded", "org:website"]},
  SF516 => {type => "ORG",
           ignore => []},
  SF517 => {type => "ORG",
           ignore => []},
  SF518 => {type => "ORG",
           ignore => []},
  SF519 => {type => "ORG",
           ignore => []},
  SF520 => {type => "ORG",
           ignore => []},
  SF521 => {type => "ORG",
           ignore => []},
  SF522 => {type => "ORG",
           ignore => []},
  SF523 => {type => "ORG",
           ignore => []},
  SF524 => {type => "ORG",
           ignore => []},
  SF525 => {type => "ORG",
           ignore => []},
  SF526 => {type => "ORG",
           ignore => []},
  SF527 => {type => "ORG",
           ignore => []},
  SF528 => {type => "ORG",
           ignore => []},
  SF529 => {type => "ORG",
           ignore => []},
  SF530 => {type => "ORG",
           ignore => []},
  SF531 => {type => "ORG",
           ignore => []},
  SF532 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:stateorprovince_of_headquarters"]},
  SF533 => {type => "ORG",
           ignore => []},
  SF534 => {type => "ORG",
           ignore => []},
  SF535 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:number_of_employees/members", "org:website"]},
  SF536 => {type => "ORG",
           ignore => []},
  SF537 => {type => "ORG",
           ignore => []},
  SF538 => {type => "ORG",
           ignore => []},
  SF539 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:number_of_employees/members", "org:stateorprovince_of_headquarters", "org:website"]},
  SF540 => {type => "ORG",
           ignore => []},
  SF541 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:stateorprovince_of_headquarters", "org:website"]},
  SF542 => {type => "ORG",
           ignore => []},
  SF543 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:number_of_employees/members", "org:website"]},
  SF544 => {type => "ORG",
           ignore => ["org:city_of_headquarters", "org:country_of_headquarters", "org:founded", "org:number_of_employees/members", "org:stateorprovince_of_headquarters", "org:website"]},
  SF545 => {type => "ORG",
           ignore => []},
  SF546 => {type => "ORG",
           ignore => []},
  SF547 => {type => "ORG",
           ignore => []},
  SF548 => {type => "ORG",
           ignore => []},
  SF549 => {type => "ORG",
           ignore => []},
  SF550 => {type => "PER",
           ignore => []},
  SF551 => {type => "PER",
           ignore => []},
  SF552 => {type => "PER",
           ignore => []},
  SF553 => {type => "PER",
           ignore => []},
  SF554 => {type => "PER",
           ignore => ["per:age", "per:date_of_birth"]},
  SF555 => {type => "PER",
           ignore => []},
  SF556 => {type => "PER",
           ignore => []},
  SF557 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:country_of_birth", "per:date_of_birth", "per:stateorprovince_of_birth"]},
  SF558 => {type => "PER",
           ignore => ["per:religion"]},
  SF559 => {type => "PER",
           ignore => ["per:religion"]},
  SF560 => {type => "PER",
           ignore => []},
  SF561 => {type => "PER",
           ignore => []},
  SF562 => {type => "PER",
           ignore => []},
  SF563 => {type => "PER",
           ignore => []},
  SF564 => {type => "PER",
           ignore => []},
  SF565 => {type => "PER",
           ignore => []},
  SF566 => {type => "PER",
           ignore => []},
  SF567 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:country_of_birth", "per:date_of_birth", "per:stateorprovince_of_birth"]},
  SF568 => {type => "PER",
           ignore => ["per:age", "per:date_of_birth"]},
  SF569 => {type => "PER",
           ignore => []},
  SF570 => {type => "PER",
           ignore => ["per:age", "per:city_of_death", "per:country_of_death", "per:date_of_birth", "per:date_of_death", "per:stateorprovince_of_death"]},
  SF571 => {type => "PER",
           ignore => []},
  SF572 => {type => "PER",
           ignore => []},
  SF573 => {type => "PER",
           ignore => []},
  SF574 => {type => "PER",
           ignore => []},
  SF575 => {type => "PER",
           ignore => []},
  SF576 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:city_of_death", "per:country_of_birth", "per:country_of_death", "per:date_of_birth", "per:date_of_death", "per:stateorprovince_of_birth", "per:stateorprovince_of_death"]},
  SF577 => {type => "PER",
           ignore => []},
  SF578 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:country_of_birth", "per:date_of_birth"]},
  SF579 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:date_of_birth", "per:stateorprovince_of_birth"]},
  SF580 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:country_of_birth", "per:date_of_birth"]},
  SF581 => {type => "PER",
           ignore => []},
  SF582 => {type => "PER",
           ignore => []},
  SF583 => {type => "PER",
           ignore => []},
  SF584 => {type => "PER",
           ignore => []},
  SF585 => {type => "PER",
           ignore => []},
  SF586 => {type => "PER",
           ignore => []},
  SF587 => {type => "PER",
           ignore => []},
  SF588 => {type => "PER",
           ignore => []},
  SF589 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:country_of_birth", "per:date_of_birth", "per:stateorprovince_of_birth"]},
  SF590 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:country_of_birth", "per:date_of_birth", "per:origin", "per:religion"]},
  SF591 => {type => "PER",
           ignore => []},
  SF592 => {type => "PER",
           ignore => []},
  SF593 => {type => "PER",
           ignore => []},
  SF594 => {type => "PER",
           ignore => []},
  SF595 => {type => "PER",
           ignore => ["per:city_of_birth", "per:country_of_birth", "per:origin"]},
  SF596 => {type => "PER",
           ignore => ["per:age", "per:city_of_birth", "per:date_of_birth"]},
  SF597 => {type => "PER",
           ignore => ["per:age", "per:city_of_death", "per:country_of_death", "per:date_of_birth", "per:stateorprovince_of_death"]},
  SF598 => {type => "PER",
           ignore => []},
  SF599 => {type => "PER",
           ignore => []});


# Slot Filler Type as defined in LDC publication 
# "TAC KBP Slots"; Version 1.2; June 2, 2011
my %slots = ('PER' => {'per:alternate_names' => {quantity => 'list',
					   content => 'name'},
		 'per:date_of_birth' => {quantity => 'single',
					   content => 'value'},
		 'per:age' => {quantity => 'single',
			       content => 'value'},
		 'per:country_of_birth' => {quantity => 'single',
					  content => 'name'},
		 'per:stateorprovince_of_birth' => {quantity => 'single',
					  content => 'name'},
		 'per:city_of_birth' => {quantity => 'single',
					  content => 'name'},
		 'per:origin' => {quantity => 'list',
				  content => 'name'}, 
		 'per:date_of_death' => {quantity => 'single',
					 content => 'value'}, 
		 'per:country_of_death' => {quantity => 'single',
					  content => 'name'}, 
		 'per:stateorprovince_of_death' => {quantity => 'single',
					  content => 'name'}, 
		 'per:city_of_death' => {quantity => 'single',
					  content => 'name'}, 
		 'per:cause_of_death' => {quantity => 'single',
					 content => 'string'}, 
		 'per:countries_of_residence' => {quantity => 'list',
				      content => 'name'}, 
		 'per:stateorprovinces_of_residence' => {quantity => 'list',
				      content => 'name'}, 
		 'per:cities_of_residence' => {quantity => 'list',
				      content => 'name'}, 
		 'per:schools_attended' => {quantity => 'list',
					    content => 'name'}, 
		 'per:title' => {quantity => 'list',
				 content => 'string'}, 
		 'per:member_of' => {quantity => 'list',
				     content => 'name'}, 
		 'per:employee_of' => {quantity => 'list',
				       content => 'name'}, 
		 'per:religion' => {quantity => 'single',
				    content => 'string'}, 
		 'per:spouse' => {quantity => 'list',
				  content => 'name'}, 
		 'per:children' => {quantity => 'list',
				    content => 'name'}, 
		 'per:parents' => {quantity => 'list',
				   content => 'name'}, 
		 'per:siblings' => {quantity => 'list',
				    content => 'name'}, 
		 'per:other_family' => {quantity => 'list',
					content => 'name'}, 
		 'per:charges' => {quantity => 'list',
				   content => 'string'}},

	     'ORG' => {'org:alternate_names' => {quantity => 'list',
						 content => 'name'}, 
		 'org:political/religious_affiliation' => {quantity => 'list',
							   content => 'name'}, 
		 'org:top_members/employees' => {quantity => 'list',
						 content => 'name'}, 
		 'org:number_of_employees/members' => {quantity => 'single',
						       content => 'value'}, 
		 'org:members' => {quantity => 'list',
				   content => 'name'}, 
		 'org:member_of' => {quantity => 'list',
				     content => 'name'}, 
		 'org:subsidiaries' => {quantity => 'list',
					content => 'name'}, 
		 'org:parents' => {quantity => 'list',
				   content => 'name'}, 
		 'org:founded_by' => {quantity => 'list',
				      content => 'name'}, 
		 'org:founded' => {quantity => 'single',
				   content => 'value'}, 
		 'org:dissolved' => {quantity => 'single',
				     content => 'value'}, 
		 'org:country_of_headquarters' => {quantity => 'single',
					content => 'name'}, 
		 'org:stateorprovince_of_headquarters' => {quantity => 'single',
					content => 'name'}, 
		 'org:city_of_headquarters' => {quantity => 'single',
					content => 'name'}, 
		 'org:shareholders' => {quantity => 'list',
					content => 'name'}, 
		 'org:website' => {quantity => 'single',
				   content => 'string'}});


my $results_file;		# input file name
my %qids;			# number of answers returned for question
my %nils;                       # number of NIL answers returned for question
my ($errlog,$num_errors,$line_num);
my ($run_id, $tag);
my ($q,$slot_name,$docid, $answer);
my ($i, $last_i, $line);

if ($#ARGV != 0) {
    print STDERR "Usage: $0 resultsfile\n";
    die "\n";
}
$results_file = $ARGV[0];
$num_errors = 0;

# set up output files 
$last_i = -1;
while ( ($i=index($results_file,"/",$last_i+1)) > -1) {
    $last_i = $i;
}
$errlog = $errlog_dir . "/" . substr($results_file,$last_i+1) . ".errlog";
open ERRLOG, ">$errlog" or
	die "Cannot open error log for writing\n";

open INPUT, ">input"   or die "Cannot create `input' file: $!\n";


open RESULTS, "<$results_file" or
    die "Unable to open results file $results_file: $!";
$line_num = 0;
$run_id = "";
while ($line = <RESULTS>) {
    chomp $line;
    $line_num++;

    next if ($line =~ /^\s*$/);

    undef $slot_name;
    undef $tag;
    undef $docid,
    undef $answer;
    ($q, $slot_name, $tag, $docid, $answer) = split " ", $line, 5;
    
    if (!defined $docid || length($docid) == 0 || !defined $tag || !defined $slot_name) {
	&error("Wrong number of fields -- missing fields");
	next;
    }
	
    # make sure runtag is ok
    if (! $run_id) { 	# very first line --- remember tag 
	$run_id = $tag;
        if ($run_id !~ /^[A-Za-z0-9._]{1,12}[1-3]$/) {
            &error("Run tag `$run_id' is malformed)");
            next;
        }
    }
    else {			# otherwise just make sure one tag used
	if ($tag ne $run_id) {
	    &error("Run tag inconsistent (`$tag' and `$run_id')");
	    next;
	}
    }

    # get query id
    if (!defined $queries{$q}) {
   	&error("Invalid query id ($q)");
	next;
    }
    # get slot name
    if (!defined $slots{$queries{$q}{'type'}}{$slot_name}) {
   	&error("Invalid slot name $slot_name for query $q with entity type $queries{$q}{'type'}");
	next;
    }

    $qids{$q}{$slot_name}++;

    if ($docid ne "NIL") {
	# make sure docid valid---
        # this is only an approximate test since so many docs for KBP track
        if ($docid !~ /(\.LDC.*[0-9]$)|(eng-WL-.*[0-9]$)|(eng-NG-.*[0-9]$)/) {
	    &error("Unknown document `$docid'");
            next;
        } elsif ($docid =~ /(\.sgm)/) {
	    &error("Unknown document ID `$docid' (looks like a file name instead of a document ID)");
            next;
	}

	# make sure answer exists
        if (!defined $answer || length($answer) == 0) {
	    &error("Missing answer-string for slot $slot_name for query $q");
	    next;
       	}
    } else {
	if ($answer) {
	    &error ("Answer string given when docid is NIL");
	    next;
	}
	$answer = "";
	$nils{$q}{$slot_name}++;
    }

    print INPUT "$q\t$slot_name\t$tag\t$docid\t$answer\n";
}


# Do global checks:
#   error if some question that is not in the 'ignore' list has no response given for it
#   error if some question that is in the 'ignore' list has a response given for it
#   error if single-valued question has more than one response given for it
#   error if more than one response is given for a question where NIL has been given as an answer
foreach $q (keys %queries) {
    foreach $slot_name (keys %{$slots{$queries{$q}{'type'}}}) {
	if (! defined $qids{$q}{$slot_name} && -1 == &is_member($slot_name, \@{$queries{$q}{'ignore'}})) {
	    &error("No response given for slot $slot_name for query $q of type $queries{$q}{'type'}");
	}
	if (defined $qids{$q}{$slot_name}  && -1 != &is_member($slot_name, \@{$queries{$q}{'ignore'}})) {
	    &error("$qids{$q}{$slot_name} responses given for slot $slot_name, which should be ignored for query $q");
	}
	if ($slots{$queries{$q}{'type'}}{$slot_name}{'quantity'} eq "single" && defined $qids{$q}{$slot_name} && $qids{$q}{$slot_name} > 1) {
	    &error("More than one response given for single-valued slot $slot_name for query $q");
	}
	if (defined $qids{$q}{$slot_name} && $qids{$q}{$slot_name} > 1 && defined $nils{$q}{$slot_name}) {
	    &error("More than one response given for slot $slot_name for query $q, where NIL has been given as an answer");
	}
    }
}
print ERRLOG "Finished processing $results_file\n";

close INPUT or die "Close failed for `input' file: $!\n";
close ERRLOG or die "Close failed for error log $errlog: $!\n";
if ($num_errors) { exit 255; }
exit 0;



 # print error message, keeping track of total number of errors
sub error {
   my $msg_string = pop(@_);

    print ERRLOG 
    "$0 of $results_file: Error on line $line_num --- $msg_string\n";

    $num_errors++;
    if ($num_errors > $MAX_ERRORS) {
        print ERRLOG "$0 of $results_file: Quit. Too many errors!\n";
        close ERRLOG or
		die "Close failed for error log $errlog: $!\n";
	exit 255;
    }
}

#  Returns index of string element in array if present, else -1
sub is_member {
    my($element,$arrayref) = @_;
 
    my $i;
    for ($i=0; $i<= $#{$arrayref}; $i++) {
        if ($element eq $$arrayref[$i]) {
            return($i);
        }
    }
    return(-1);
}  

