summaryrefslogtreecommitdiffstats
path: root/bin/csvconv.pl
blob: 55b2d36eba49a47ec135569ce79e72263d187e95 (plain)
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
#!/usr/bin/perl

use sort 'stable';
use feature 'state';
use Math::BigInt try => 'GMP';
use Fcntl;

# Gets a random number from /dev/urandom, and adjust it to the range
# 0 <= value < $n without bias
sub get_random($) {
    my($n) = @_;
    state $fh;

    if (!defined($fh)) {
	sysopen($fh, '/dev/urandom', O_RDONLY) or die;
    }

    my $nbytes;
    while ($nbytes < 8 && $n > (1 << $nbytes)) {
	$nbytes++;
    }

    die if (sysread($fh, my $x, $nbytes) != $nbytes);

    # Eliminate bias by rejecting numbers at the bottom of the range
    # so that we end up with a whole number of

    my $xtoosmall = Math::BigInt::bmodpow(256, $nbytes, $n)->numify();

    do {
	$x = unpack('Q<', $x . ("\0" x (8 - $nbytes)));
    } while ($x < $xtoosmall);

    return $x % $n;
}

sub make_random_list($$) {
    my($start, $n) = @_;

    # Generate a list of numbers $start..$start+$n-1
    my @list = ();
    for (my $i = 0; $i < $n; $i++) {
	push(@list, $i + $start);
    }

    # Standard Fisher-Yates-Knuth shuffle
    for (my $i = $n-1; $i >= 1; $i--) {
	my $j = get_random($i+1);
	@list[$i,$j] = @list[$j,$i];
    }

    return @list;
}

# Nonfatal error: print to STDERR and log
sub error(@) {
    my $err = join('', @_);
    state $efh;

    if (!defined($efh)) {
	open($efh, '>', $proj.'/csvconv.errors') or die;
    }

    print STDERR $err;
    print $efh $err;
}

sub read_ids($) {
    my($file) = @_;

    my $ids, $line;
    open($ids, '<', $file) or die;
    while (defined($line = <$ids>)) {
	chomp $line;

	if ($line =~ /^[A-Z0-9_-]+$/) {
	    $valid_ids{$line} = 0;
	    print STDERR "valid id: $line\n";
	} elsif ($line ne '') {
	    error("$file: Invalid ID found in file: $line\n");
	}
    }
    close($ids);
}

sub read_csv($) {
    my($file) = @_;
    open(my $csv, '<', $file) or die "$0: $file: $!\n";
    my $line = <$csv>;
    chomp $line;
    @header = split(',', $line);
    my $n = 0;
    my $nline = 0;
    my $nblank = 0;
    while (defined($line = <$csv>)) {
	chomp $line;
	$nline++;
	my @dline = split(',', $line);
	$dline[0] =~ s/^\[\'(.*)\'\]$/\1/;
	if ($dline[1] eq 'None' && $dline[0] eq 'None' &&
	    $dline[2]) {
	    # Blank page
	    $nblank++;
	} elsif ($dline[1] ne $global_id) {
	    error("$file:$nline: Not counting incorrect survey ID: $dline[1]\n");
	    next;
	} elsif (!defined($valid_ids{$dline[0]})) {
	    error("$file:$nline: Not counting nonexistent ballot ID: $dline[0]\n");
	    next;
	} elsif ($valid_ids{$dline[0]}++) {
	    error("$file:$nline: Not counting duplicate ballot ID: $dline[0]\n");
	    next;
	}

	push(@ballots, [@dline]);
	for (my $i = 0; $i < scalar @dline; $i++) {
	    if ($header[$i] =~ /^1_1_([0-9]+)_0$/) {
		$totals[$i] += $dline[$i];
	    }
	}
    }
    close($csv);
    if ($nblank) {
	error("$file: $nblank blank pages ignored\n");
    }
}

($proj) = @ARGV;

open(SDAPS, '<', $proj.'/questionnaire.sdaps') or die;
while (defined($line = <SDAPS>)) {
    chomp $line;
    if ($line =~ /^GlobalID=(.*)$/) {
	$global_id = $1;
    } elsif ($line =~ /^QObject-Choice=XAUTO\. (.*)$/) {
	push(@cands, $1);
    } elsif ($line =~ /^Author=(.*)$/) {
	$author = $1;
    } elsif ($line =~ /^Title=(.*)$/) {
	$title = $1;
    }
}
close(SDAPS);

%valid_ids = ();

undef $csvfile, $csvn;
opendir(DIR, $proj) or die;
while (defined($file = readdir(DIR))) {
    my $path = $proj.'/'.$file;
    next if ( ! -f $path );
    print STDERR "file: $file path: $path ";
    if ($file =~ /^data_([0-9]+)\.csv$/) {
	if (!defined($csvfile) || $1 > $csvn) {
	    print STDERR "data\n";
	    $csvn = $1 + 0;
	    $csvfile = $path;
	}
    } elsif ( $file =~ /^id[0-9]+\.list$/) {
	print STDERR "id\n";
	read_ids($path);
    } else {
	print STDERR "none\n";
    }
}
closedir(DIR);

printf STDERR "$0: %d ballot IDs found\n", scalar keys(%valid_ids);

# Only read the most recent CSV file
read_csv($csvfile);

sub sort_ballots {
    # Rather than sorting lexically, sort by numeric suffix
    my($na) = ($$a[0] =~ /([0-9]+)$/);
    my($nb) = ($$b[0] =~ /([0-9]+)$/);
    return $na <=> $nb;
}
@ballots = sort sort_ballots @ballots;

$n = 0;
for ($i = 0; $i < scalar @header; $i++) {
    if ($header[$i] =~ /^1_1_([0-9]+)_0$/) {
	$candcol{$cands[$1 - 1]} = $i;
    }
}

if (open(TB, '<', $proj.'/tiebreakers.csv')) {
    $line = <TB>;
    chomp $line;
    @tiebreakers = split(',', $line);
    close(TB);
}

if (scalar(@tiebreakers) != scalar(@cands)) {
    @tiebreakers = make_random_list(1,scalar(@cands));
    if (open(TB, '>', $proj.'/tiebreakers.csv')) {
	print TB join(',',@tiebreakers), "\n";
	close(TB);
    }
}

foreach $cand ( @cands ) {
    $tiebreaker{$candcol{$cand}} = shift @tiebreakers;
}

sub sort_cands {
    my $cca = $candcol{$a};
    my $ccb = $candcol{$b};
    return ($totals[$ccb] <=> $totals[$cca]) ||
           ($tiebreaker{$ccb} <=> $tiebreaker{$cca});
}

@cands = sort sort_cands @cands;

print "\"$author\"\n";
print "\"$title\"\n";
print "\n";
print "\"Name\",\"Total\",\"Tiebreak\"";
foreach $b ( @ballots ) {
    print ",\"$$b[0]\"";
}
print "\n";
foreach $cand ( @cands ) {
    $cc = $candcol{$cand};
    printf "\"%s\",%d,%d", $cand, $totals[$cc], $tiebreaker{$cc};
    foreach $b ( @ballots ) {
	print ',', $$b[$cc];
    }
    print "\n";
}