forked from nethackscoreboard-org/matter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnhdb-stats.pl
executable file
·2474 lines (1978 loc) · 68 KB
/
nhdb-stats.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/env perl
#============================================================================
# NHDB Stat Generator
# """""""""""""""""""
# (c) 2013-2100 Borek Lupomesky
# (c) 2020-2100 Dr. Joanna Irina Zaitseva-Kinneberg
#============================================================================
use strict;
use warnings;
use bignum;
use feature 'state';
use utf8;
#use FindBin qw($Bin);
use lib "$ENV{HOME}/lib";
use Moo;
use DBI;
use JSON;
use Getopt::Long;
use List::MoreUtils qw(uniq);
use Try::Tiny;
use NetHack::Config;
use NetHack::Variant;
use NHdb::Config;
use NHdb::Db;
use NHdb::Stats::Cmdline;
use NHdb::Utils;
use Template;
use Log::Log4perl qw(get_logger);
use POSIX qw(strftime);
$| = 1;
#============================================================================
#=== globals ================================================================
#============================================================================
#--- list of sources ('logfiles') loaded from database
my $logfiles;
#--- Log4Perl instance
my $logger; # log4perl primary instance
#--- NetHack::Config instance
my $nh = new NetHack::Config(
config_file => "$ENV{HOME}/cfg/nethack_def.json"
);
#--- NHdb::Config instance
my $nhdb = NHdb::Config->instance;
#--- NHdb::Db instance (initalized later)
my $db;
#--- aggregate and summary pages generators
# this hash contains code references to code that generates aggregate pages;
my %aggr_pages = (
'recentgames' => sub { gen_page_recent('recent', @_) },
'recentascs' => sub { gen_page_recent('ascended', @_) },
'streaks' => \&gen_page_streaks,
'zscores' => \&gen_page_zscores,
'conducts' => \&gen_page_conducts,
'lowscore' => \&gen_page_lowscore,
'firstasc' => \&gen_page_first_to_ascend,
'turncount' => \&gen_page_turncount,
'realtime' => \&gen_page_realtime
);
my %summ_pages = (
'about' => \&gen_page_about,
'front' => \&gen_page_front,
);
#============================================================================
#=== definitions ============================================================
#============================================================================
my $lockfile = '/tmp/nhdb-stats.lock';
my $http_root = $nhdb->config()->{'http_root'};
my $tt = Template->new(
'OUTPUT_PATH' => $http_root,
'INCLUDE_PATH' => "$ENV{HOME}/templates",
'RELATIVE' => 1
);
#============================================================================
#===== __ ============== _ _ ===========================================
#=== / _|_ _ _ __ ___| |_(_) ___ _ __ ___ ===========================
#=== | |_| | | | '_ \ / __| __| |/ _ \| '_ \/ __| ===========================
#=== | _| |_| | | | | (__| |_| | (_) | | | \__ \ ===========================
#=== |_| \__,_|_| |_|\___|\__|_|\___/|_| |_|___/ ===========================
#=== ===========================
#============================================================================
#============================================================================
# Return current month and year
#============================================================================
sub get_month_year
{
my @time = gmtime();
my ($mo, $yr) = @time[4..5];
$yr += 1900;
return ($mo, $yr);
}
#============================================================================
# Return duration in seconds formatted as years, months, days, hours, minutes
# and seconds. Used for total time spent playing in player statistic pages.
#============================================================================
sub format_duration_plr
{
use integer;
my $t = shift;
my @a;
return undef if !$t;
my $years = $t / 31536000;
$t %= 31536000;
my $months = $t / 2592000;
$t %= 2592000;
my $days = $t / 86400;
$t %= 86400;
my $hours = $t / 3600;
$t %= 3600;
my $minutes = $t / 60;
$t %= 60;
my $seconds = $t;
push(@a, sprintf('%d years', $years)) if $years;
push(@a, sprintf('%d months', $months)) if $months;
push(@a, sprintf('%d days', $days)) if $days;
push(@a, sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds));
return join(', ', @a);
}
#============================================================================
# Order an array by using reference array
#============================================================================
sub array_sort_by_reference
{
my $ref = shift;
my $ary = shift;
my @result;
for my $x (@$ref) {
if(grep { $x eq $_ } @$ary) {
push(@result, $x);
}
}
return \@result;
}
#============================================================================
# Pluralize noun
#============================================================================
sub pl
{
my ($s, $n) = @_;
return sprintf('%d %s', $n, $n != 1 ? $s . 's' : $s);
}
#============================================================================
# Format age received as years, months, days and hours.
#============================================================================
sub fmt_age
{
my ($yr, $mo, $da, $hr) = @_;
my @result;
if($yr) {
push(@result, pl('year', $yr));
}
if($mo) {
push(@result, pl('month', $mo));
}
if($da) {
push(@result, pl('day', $da));
}
if($hr && !$yr) {
push(@result, pl('hour', $hr));
}
if(scalar(@result) == 0) {
push(@result, 'recently');
}
return join(' ', @result);
}
#============================================================================
# Load SQL query into array of hashref with some additional processing.
#============================================================================
sub sql_load
{
my $query = shift; # 1. database query
my $cnt_start = shift; # 2. counter start (opt)
my $cnt_incr = shift; # 3. counter increment (opt)
my $preproc = shift; # 4. subroutine to pre-process row
my (@args) = @_; # R. arguments to db query
my @result;
my $dbh = $db->handle();
my $sth = $dbh->prepare($query);
my $r = $sth->execute(@args);
if(!$r) { return $sth->errstr(); }
while(my $row = $sth->fetchrow_hashref()) {
&$preproc($row) if $preproc;
if(defined $cnt_start) {
$row->{'n'} = $cnt_start;
$cnt_start += $cnt_incr;
}
push(@result, $row);
}
$sth->finish();
return \@result;
}
#============================================================================
# Create list of player-variant pairs to be updated.
#============================================================================
sub update_schedule_players
{
#--- arguments
my (
$cmd_force, # 1. --force specified
$cmd_variant, # 2. list of variants from --variant
$cmd_player # 3. list of players from --player
) = @_;
#--- other variables
my ($sth, $r);
my $dbh = $db->handle();
#--- get list of allowed variants
# this is either all configured variants (in nhdb_def.json) or a list
# of variants supplied through --variant cmdline option (cross-checked
# against the configured variants, so that user cannot supply unconfigured
# variant). @variants_final will contain the result of this step.
my @variants_known = ('all', $nh->variants());
my @variants_final = @variants_known;
if(@$cmd_variant) {
@variants_final = map {
my $s = $_;
(grep { $_ eq $s } @variants_known) ? $s : ();
} @$cmd_variant;
}
#--- display information
$logger->info('Getting list of player pages to update');
$logger->info('Forced processing enabled') if $cmd_force;
$logger->info('Restricted to variants: ', join(',', @variants_final))
if @variants_known > @variants_final;
$logger->info('Restricted to players: ', join(',', @$cmd_player))
if scalar(@$cmd_player);
#--- get list of all known player names
$logger->info('Loading list of all players');
my @player_list;
$sth = $dbh->prepare(q{SELECT name FROM games GROUP BY name});
$r = $sth->execute();
if(!$r) {
my $errmsg = sprintf('Cannot get list of players (%s)', $sth->errstr());
$logger->error($errmsg);
die $errmsg;
}
while(my ($plr) = $sth->fetchrow_array()) {
push(@player_list, $plr);
}
$logger->info(sprintf('Loaded %d players', scalar(@player_list)));
#--- get list of existing (player, variant) combinations
#--- that have non-zero number of games in db
$logger->info('Loading list of (player,variant) combinations');
my %player_combos;
my $cnt_plrcombo = 0;
$sth = $dbh->prepare(
q{SELECT name, variant FROM update WHERE name <> ''}
);
$r = $sth->execute();
if(!$r) {
my $errmsg = sprintf(
'Cannot get list of player,variant combos (%s)', $sth->errstr()
);
$logger->error($errmsg);
die $errmsg;
}
while(my ($plr, $var) = $sth->fetchrow_array()) {
$player_combos{$plr}{$var} = 1;
$cnt_plrcombo++;
}
$logger->info(
sprintf('Loaded %d (player,variant) combinations', $cnt_plrcombo)
);
#--- forced update enabled
my @pages_forced;
if($cmd_force) {
for my $plr (@player_list) {
#--- if list of players is specified on the cmdline, then
#--- use it as filter here
if(
scalar(@$cmd_player) &&
!(grep { lc($plr) eq lc($_)} @$cmd_player)
) {
next;
}
#--- create cartesian product, but restricted
#--- to existing player,variant combos
for my $var (@variants_final) {
if(exists $player_combos{$plr}{$var}) {
push(@pages_forced, [$plr, $var]);
}
}
}
$logger->info(sprintf('Forcing update of %d pages', scalar(@pages_forced)));
return(\@pages_forced, \%player_combos);
}
#--- get list of updated players
$logger->info('Loading list of player updates');
my @pages_updated;
my $cnt = 0;
$sth = $dbh->prepare(q{SELECT * FROM update WHERE name <> '' AND upflag IS TRUE});
$r = $sth->execute();
if(!$r) {
my $errmsg = sprintf(
'Cannot get list of player updates (%s)', $sth->errstr()
);
$logger->error($errmsg);
die $errmsg;
}
while(my ($var, $plr) = $sth->fetchrow_array()) {
$cnt++;
# skip entries with variants not in @variants_final
if(!grep { $var eq $_ } @variants_final) { next; };
# skip entries with players not in @player_list
if(!grep { $plr eq $_ } @player_list) { next; }
# skip list of players not specified in cmdline (if relevant)
# NOTE: the matching is case-insensitive
if(scalar(@$cmd_player)) {
if(!grep { lc($plr) eq lc($_) } @$cmd_player) { next; }
}
#
push(@pages_updated, [$plr, $var]);
}
$logger->info(
sprintf(
'Loaded %d player updates, %d rejected',
scalar(@pages_updated),
$cnt - scalar(@pages_updated)
)
);
return(\@pages_updated, \%player_combos);
}
#============================================================================
# Create list of variants to be updated. Sources of the info about what
# should be update are:
# 1) --force command-line option
# 2) --variant command-line option
# 3) nethack_def.json statically defined variants
# 4) update table in the database
#============================================================================
sub update_schedule_variants
{
my $cmd_force = shift;
my $cmd_variant = shift;
my $logger = get_logger('Stats::update_schedule_variants');
my $dbh = $db->handle();
$logger->debug(
sprintf(
q{update_schedule_variants('%s',(%s)) started},
$cmd_force ? 'on' : 'off',
join(',', @$cmd_variant)
)
);
#--- list of allowed variants targets; anything not in this array
#--- is invalid
my @variants_known = ('all', $nh->variants());
$logger->debug('Known variants: (', join(',', @variants_known), ')');
#--- forced processing
my @candidates;
if($cmd_force) {
if(scalar(@$cmd_variant)) {
@candidates = @$cmd_variant;
} else {
@candidates = @variants_known;
}
} else {
#--- no forcing, using database
my $sth = $dbh->prepare(
q{SELECT variant FROM update WHERE name = '' AND upflag IS TRUE}
);
my $re = $sth->execute();
if(!$re) {
my $errmsg = sprintf(
"Failed to read from update table (%s)" . $sth->errstr()
);
$logger->error($errmsg);
die $errmsg;
}
while(my ($a) = $sth->fetchrow_array()) {
if(scalar(@$cmd_variant)) {
if(!grep { lc($_) eq $a } @$cmd_variant) {
next;
}
}
push(@candidates, $a);
}
}
#--- validation
my @final;
for my $x (@candidates) {
if(grep {$_ eq $x} @variants_known) {
push(@final, $x);
}
}
#--- finish
$logger->debug('update_schedule_variants() finished');
return \@final;
}
#============================================================================
# Load logfiles configuration info from db
#============================================================================
sub sql_load_logfiles
{
my $dbh = $db->handle();
my $sth = $dbh->prepare('SELECT * FROM logfiles');
my $r = $sth->execute();
if(!$r) {
return sprintf('Failed to query database (%s)', $sth->errstr());
}
while(my $row = $sth->fetchrow_hashref()) {
my $logfiles_i = $row->{'logfiles_i'};
$logfiles->{$logfiles_i} = $row;
}
}
#============================================================================
# Load streak information from database. The streaks are ordered by number
# of games and sum of turns in streak games (lower is better).
#
# The data structure built in memory here is following:
#
# --- this defines streak ordering and is just array of integers - row ids
# --- into the 'streaks' table
# @streaks_ord = ( streak_i, streak_i, ..., streak_i );
#
# --- this contains all the data needed; the %ROW is one row from join
# --- query accross 'games', 'logfiles' and 'streaks' tables
# %streaks = (
# streaks_i => {
# 'turncount' => TURNCOUNT,
# 'num_games' => NUMGAMES,
# 'games' => [ %ROW, %ROW, ... , %ROW ]
# },
# ...
# )
#
# Arguments:
# 1. variant id, 'all' or undef
# 2. player name (optional)
# 3. LIMIT value
# 4. list streaks with at least this many games (no value or value of 0-1
# means listing even potential streaks)
# 5. select only open streaks
#============================================================================
sub sql_load_streaks
{
#--- arguments
my (
$variant, # 1. variant
$name, # 2. player name
$limit, # 3. limit the query
$num_games, # 4. games-in-a-streak cutoff value
$open_only # 5. select only open streaks
) = @_;
#--- other variables
my $dbh = $db->handle();
my @streaks_ord; # ordered list of streaks_i
my %streaks; # streaks_i-keyed hash with all info
my ($query, $sth, $r, @conds, @args);
#---------------------------------------------------------------------------
#--- get ordered list of streaks with turncounts ---------------------------
#---------------------------------------------------------------------------
#--- the query -> ( streaks_i, turns_sum, num_games, open )
$query =
q{SELECT streaks_i, sum(turns) AS turns_sum, num_games, open } .
q{FROM streaks } .
q{JOIN logfiles USING ( logfiles_i ) } .
q{JOIN map_games_streaks USING ( streaks_i ) } .
q{JOIN games USING ( rowid ) } .
q{WHERE %s } .
q{GROUP BY num_games, streaks_i } .
q{ORDER BY num_games DESC, turns_sum ASC};
#--- conditions
if($num_games) {
push(@conds, 'num_games >= ?');
push(@args, $num_games);
}
if($variant && $variant ne 'all') {
push(@conds, 'variant = ?');
push(@args, $variant);
}
if($name) {
push(@conds, 'games.name = ?');
push(@args, $name);
}
if($open_only) {
push(@conds, 'open is true');
}
#--- assemble the query
$query = sprintf($query, join(' AND ', @conds));
#--- append query limit
if($limit) {
$query .= sprintf(' LIMIT %d', $limit);
}
#--- execute query
$sth = $dbh->prepare($query);
$r = $sth->execute(@args);
if(!$r) { return $sth->errstr(); }
while(my $row = $sth->fetchrow_hashref()) {
push(@streaks_ord, $row->{'streaks_i'});
$streaks{$row->{'streaks_i'}} = {
'turncount' => $row->{'turns_sum'},
'num_games' => $row->{'num_games'},
'open' => $row->{'open'},
'games' => []
};
}
#-------------------------------------------------------------------------
#--- get list of streak games --------------------------------------------
#-------------------------------------------------------------------------
#--- prepare query
# FIXME: this query pulls down too much data; the query above pulls down
# first 100 streaks, but this query pulls down everything with streak length
# 2 or more
$query =
q{SELECT } .
# direct fields
q{g.name, g.name_orig, } .
q{role, race, gender, gender0, align, align0, server, variant, } .
q{g.version, elbereths, scummed, conduct, achieve, dumplog, turns, hp, } .
q{maxhp, realtime, rowid, starttime_raw, endtime_raw, g.logfiles_i, } .
q{streaks_i, } .
# computed fields
q{to_char(starttime,'YYYY-MM-DD HH24:MI') AS starttime_fmt, } .
q{to_char(endtime,'YYYY-MM-DD HH24:MI') AS endtime_fmt, } .
q{floor(extract(epoch from age(endtime))/86400) AS age_day } .
# the rest of the query
q{FROM streaks } .
q{JOIN logfiles USING ( logfiles_i ) } .
q{JOIN map_games_streaks USING ( streaks_i ) } .
q{JOIN games g USING ( rowid ) } .
q{WHERE %s } .
q{ORDER BY endtime};
#--- conditions
@conds = ();
@args = ();
if($num_games) {
push(@conds, 'num_games >= ?');
push(@args, $num_games);
}
if($variant && $variant ne 'all') {
push(@conds, 'variant = ?');
push(@args, $variant);
}
if($name) {
push(@conds, 'streaks.name = ?');
push(@args, $name);
}
if($open_only) {
push(@conds, 'open is true');
}
$query = sprintf($query, join(' AND ', @conds));
#--- execute query
$sth = $dbh->prepare($query);
$r = $sth->execute(@args);
if(!$r) { return $sth->errstr(); }
while(my $row = $sth->fetchrow_hashref()) {
if(exists($streaks{$row->{'streaks_i'}})) {
row_fix($row);
push(
@{$streaks{$row->{'streaks_i'}}{'games'}},
$row
);
#--- save streak age (days from last game's endtime)
if(exists $streaks{$row->{'streaks_i'}}{'age'}) {
$streaks{$row->{'streaks_i'}}{'age'} = $row->{'age_day'}
if $streaks{$row->{'streaks_i'}}{'age'} > $row->{'age_day'};
} else {
$streaks{$row->{'streaks_i'}}{'age'} = $row->{'age_day'};
}
}
}
#--- finish
return (\@streaks_ord, \%streaks);
}
#============================================================================
# Function takes streak information loaded from database using
# sql_load_streaks() and creates data structure that is used by templates
# to produce final HTML.
#============================================================================
sub process_streaks
{
#--- arguments
my (
$streaks_ord, # 1. (aref) list of streak_i's
$streaks # 2. (href) info about streaks (key is streak_i)
) = @_;
#--- other variables
my $dbh = $db->handle();
my @result;
#--- processing
for(my $i = 0; $i < @$streaks_ord; $i++) {
my $streak = $streaks->{$streaks_ord->[$i]};
my $games_num = $streak->{'num_games'};
my $game_first = $streak->{'games'}[0];
my $game_last = $streak->{'games'}[$games_num - 1];
$result[$i] = my $row = {};
$row->{'n'} = $i + 1;
$row->{'wins'} = $games_num;
$row->{'server'} = $game_first->{'server'};
$row->{'open'} = $streak->{'open'};
$row->{'variant'} = $game_first->{'variant'};
$row->{'version'} = nhdb_version($game_first->{'version'});
$row->{'start'} = $game_first->{'endtime_fmt'};
$row->{'start_dump'} = $game_first->{'dump'};
$row->{'end'} = $game_last->{'endtime_fmt'};
$row->{'end_dump'} = $game_last->{'dump'};
$row->{'turns'} = $streak->{'turncount'};
$row->{'name'} = $game_first->{'name'};
$row->{'plrpage'} = $game_first->{'plrpage'};
$row->{'name_orig'} = $game_first->{'name_orig'};
$row->{'age'} = $streak->{'age'};
$row->{'glist'} = [];
my $games_cnt = 1;
for my $game (@{$streak->{'games'}}) {
$game->{'n'} = $games_cnt++;
push(@{$row->{'glist'}}, $game);
}
# version / if the version of the first and last game are not the same
# we display version range
$row->{'version'} = $game_first->{'version'};
if($game_first->{'version'} ne $game_last->{'version'}) {
$row->{'version'} = sprintf(
'%s-%s', $game_first->{'version'}, $game_last->{'version'}
);
}
#--- truncate time for games without endtime field
if(!$game_first->{'endtime'}) {
$row->{'start'} =~ s/\s.*$//;
}
if(!$game_last->{'endtime'}) {
$row->{'end'} =~ s/\s.*$//;
}
}
#--- return
return \@result;
}
#============================================================================
# Some additional processing of a row of data from games table (formats
# fields into human readable format, mostly).
#============================================================================
sub row_fix
{
my $row = shift;
my $logfiles_i = $row->{'logfiles_i'};
my $logfile = $logfiles->{$logfiles_i};
my $variant = $nh->variant($row->{'variant'});
#--- extract extra fields from misc_json
my $json = JSON->new;
if($row->{'misc'}) {
my $data = $json->decode($row->{'misc'});
foreach my $key (keys %$data)
{
if (!defined $row->{$key})
{
$row->{$key} = $data->{$key};
}
else
{
$row->{"_$key"} = $data->{$key};
}
}
}
#--- convert realtime to human-readable form
if($row->{'realtime'}) {
$row->{'realtime_raw'} = defined $row->{'realtime'} ? $row->{'realtime'} : 0;
$row->{'realtime'} = format_duration($row->{'realtime'});
}
#--- format version string
$row->{'version'} = nhdb_version($row->{'version'});
#--- include conducts in the ascended message
if($row->{'ascended'} && defined $row->{'conduct'}) {
my @c = $variant->conduct(@{$row}{'conduct', 'elbereths', 'achieve'});
$row->{'ncond'} = scalar(@c);
$row->{'tcond'} = join(' ', @c);
if(scalar(@c) == 0) {
$row->{'death'} = 'ascended with all conducts broken';
} else {
$row->{'death'} = sprintf(
qq{ascended with %d conduct%s intact (%s)},
scalar(@c), (scalar(@c) == 1 ? '' : 's'), $row->{'tcond'}
);
}
}
#--- game dump URL
# special case is NAO 3.4.3 xlogfile where it seems that dumplogs became
# available on Mar 19, 2008 (the same time where xlogfile was significantly
# extended). To accommodate this, we will not create the 'dump' key if
# the 'endtime' field doesn't exist in the xlogfile (signalled by
# endtime_raw being undefined).
if($logfile->{'dumpurl'} && $row->{'endtime_raw'}) {
$row->{'dump'} = url_substitute(
$logfile->{'dumpurl'},
$row
);
}
#--- realtime (aka duration)
if(
$row->{'variant'} eq 'ace' ||
$row->{'variant'} eq 'nh4' ||
$row->{'variant'} eq 'nhf' ||
$row->{'variant'} eq 'dyn' ||
$row->{'variant'} eq 'fh' ||
grep(/^bug360duration$/, @{$logfile->{'options'}})
) {
$row->{'realtime'} = '';
}
#--- player page
$row->{'plrpage'} = url_substitute(
sprintf("players/%%U/%%u.%s.html", $row->{'variant'}),
$row
);
#--- truncate time if needed
#--- this is not a perfect test, but if the start time and end time match
#--- $date 00:00:00 and $date 23:59:59 (respectively), they were probably
#--- upgraded from old xlogs with only birthdate and deathdate
my @st = gmtime($row->{'starttime_raw'});
my @et = gmtime($row->{'endtime_raw'});
my $st_hhmmss = strftime("%H:%M:%S", @st);
my $et_hhmmss = strftime("%H:%M:%S", @et);
if($st_hhmmss eq '00:00:00' && $et_hhmmss eq '23:59:59') {
$row->{'endtime_fmt'} =~ s/\s.*$//;
}
}
#============================================================================
# Create structure for calendar view of ascensions (ie. ascensions by years/
# /months)
#============================================================================
sub ascensions_calendar_view
{
my $data = shift;
my %acc;
my @result;
#--- assert data received
if(scalar(@$data) == 0) { die 'No data received by ascensions_calendar_view()'; }
#--- create year/months counts in hash
for my $ascension (@$data) {
$ascension->{'endtime'} =~ /^(\d{4})-(\d{2})-\d{2}\s/;
my ($year, $month) = ($1, $2+0);
if(!exists($acc{$year}{$month})) { $acc{$year}{$month} = 0; }
$acc{$year}{$month}++;
if(!defined($acc{'year_low'}) || $year < $acc{'year_low'}) {
$acc{'year_low'} = $year;
}
if(!defined($acc{'year_hi'}) || $year > $acc{'year_hi'}) {
$acc{'year_hi'} = $year;
}
}
#--- now turn the data into an array
for(my $year = $acc{'year_low'}; $year <= $acc{'year_hi'}; $year++) {
my @row = ($year);
my $yearly_total = 0;
for my $month (1..12) {
my $value = exists($acc{$year}{$month}) ? $acc{$year}{$month} : 0;
push(@row, $value);
$yearly_total += $value;
}
push(@row, $yearly_total);
push(@result, \@row);
}
#--- finish
return \@result;
}
#============================================================================
# Calculate partial sum of harmonic series for given number.
#============================================================================
sub harmonic_number
{
my $n = shift;
state %cache;
#--- return cached result
return $cache{$n} if exists $cache{$n};
#--- calculation
my $v = 0;
for(my $i = 0; $i < $n; $i++) {
$v += 1 / ($i+1);
}
$cache{$n} = $v;
return $v;
}
#============================================================================
# Calculate zscore from list of all ascensions. This function builds the
# complete %zscore structure that is reused for all pages displaying zscore.
#============================================================================
sub zscore
{
#--- logging
my $logger = get_logger('Stats::zscore');
$logger->debug('zscore() entry');
#--- zscore structure instantiation
state %zscore;
state $zscore_loaded;
#--- just return current state if already processed
if($zscore_loaded) {
$logger->debug('zscore() finish (cached)');
return \%zscore;
}
#--- zscore structure definition
# val ... z-score values (player->variant->role)
# max ... maximum values (variant->role)
# ord ... ordering of player within variant (including 'all' pseudovariant)
my $zval = $zscore{'val'} = {};
my $zmax = $zscore{'max'} = {};
my $zord = $zscore{'ord'} = {};
#--- retrieve the data from database
my $ascs = sql_load(q{SELECT * FROM v_ascended}, 1, 1);
if(!ref($ascs)) {
$logger->error('zscore() failed, ', $ascs);
return $ascs;
}
$logger->debug(sprintf('zscore() data loaded from db, %d rows', scalar(@$ascs)));
#--- get the counts
# this creates hash with counts of (player, variant, role)
# triples