]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Implement filter-by-player-on-field.
[pkanalytics] / ultimate.js
1 'use strict';
2
3 // No frameworks, no compilers, no npm, just JavaScript. :-)
4
5 let global_json;
6 let global_filters = [];
7
8 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
9 addEventListener('click', possibly_close_menu);
10 fetch('ultimate.json')
11    .then(response => response.json())
12    .then(response => { global_json = response; process_matches(global_json, global_filters); });
13
14 function attribute_player_time(player, to, from, offense) {
15         let delta_time;
16         if (player.on_field_since > from) {
17                 // Player came in while play happened (without a stoppage!?).
18                 delta_time = to - player.on_field_since;
19         } else {
20                 delta_time = to - from;
21         }
22         player.playing_time_ms += delta_time;
23         if (offense === true) {
24                 player.offensive_playing_time_ms += delta_time;
25         } else if (offense === false) {
26                 player.defensive_playing_time_ms += delta_time;
27         }
28 }
29
30 function take_off_field(player, t, live_since, offense, keep) {
31         if (keep) {
32                 if (live_since === null) {
33                         // Play isn't live, so nothing to do.
34                 } else {
35                         attribute_player_time(player, t, live_since, offense);
36                 }
37                 if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
38                         player.field_time_ms += t - player.on_field_since;
39                 }
40         }
41         player.on_field_since = null;
42 }
43
44 function add_cell(tr, element_type, text) {
45         let element = document.createElement(element_type);
46         element.textContent = text;
47         tr.appendChild(element);
48         return element;
49 }
50
51 function add_th(tr, text, colspan) {
52         let element = add_cell(tr, 'th', text);
53         if (colspan > 0) {
54                 element.setAttribute('colspan', colspan);
55         } else {
56                 element.setAttribute('colspan', '3');
57         }
58         return element;
59 }
60
61 function add_3cell(tr, text, cls) {
62         let p1 = add_cell(tr, 'td', '');
63         let element = add_cell(tr, 'td', text);
64         let p2 = add_cell(tr, 'td', '');
65
66         p1.classList.add('pad');
67         p2.classList.add('pad');
68         if (cls === undefined) {
69                 element.classList.add('num');
70         } else {
71                 element.classList.add(cls);
72         }
73         return element;
74 }
75
76 function add_3cell_with_filler_ci(tr, text, cls) {
77         let element = add_3cell(tr, text, cls);
78
79         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
80         svg.classList.add('fillerci');
81         svg.setAttribute('width', ci_width);
82         svg.setAttribute('height', ci_height);
83         element.appendChild(svg);
84
85         return element;
86 }
87
88 function add_3cell_ci(tr, ci) {
89         if (isNaN(ci.val)) {
90                 add_3cell_with_filler_ci(tr, 'N/A');
91                 return;
92         }
93
94         let text;
95         if (ci.format === 'percentage') {
96                 text = (100 * ci.val).toFixed(0) + '%';
97         } else {
98                 text = ci.val.toFixed(2);
99         }
100         let element = add_3cell(tr, text);
101         let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
102
103         // Container.
104         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
105         if (ci.inverted === true) {
106                 svg.classList.add('invertedci');
107         } else {
108                 svg.classList.add('ci');
109         }
110         svg.setAttribute('width', ci_width);
111         svg.setAttribute('height', ci_height);
112
113         // The good (green) and red (bad) ranges.
114         let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
115         s0.classList.add('range');
116         s0.classList.add('s0');
117         s0.setAttribute('width', to_x(ci.desired));
118         s0.setAttribute('height', ci_height);
119         s0.setAttribute('x', '0');
120
121         let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
122         s1.classList.add('range');
123         s1.classList.add('s1');
124         s1.setAttribute('width', ci_width - to_x(ci.desired));
125         s1.setAttribute('height', ci_height);
126         s1.setAttribute('x', to_x(ci.desired));
127
128         // Confidence bar.
129         let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
130         bar.classList.add('bar');
131         bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
132         bar.setAttribute('height', ci_height / 3);
133         bar.setAttribute('x', to_x(ci.lower_ci));
134         bar.setAttribute('y', ci_height / 3);
135
136         // Marker line for average.
137         let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
138         marker.classList.add('marker');
139         marker.setAttribute('x1', to_x(ci.val));
140         marker.setAttribute('x2', to_x(ci.val));
141         marker.setAttribute('y1', ci_height / 6);
142         marker.setAttribute('y2', ci_height * 5 / 6);
143
144         svg.appendChild(s0);
145         svg.appendChild(s1);
146         svg.appendChild(bar);
147         svg.appendChild(marker);
148
149         element.appendChild(svg);
150 }
151
152 function process_matches(json, filters) {
153         let players = {};
154         for (const player of json['players']) {
155                 players[player['player_id']] = {
156                         'name': player['name'],
157                         'number': player['number'],
158
159                         'goals': 0,
160                         'assists': 0,
161                         'hockey_assists': 0,
162                         'catches': 0,
163                         'touches': 0,
164                         'num_throws': 0,
165                         'throwaways': 0,
166                         'drops': 0,
167
168                         'defenses': 0,
169                         'interceptions': 0,
170                         'points_played': 0,
171                         'playing_time_ms': 0,
172                         'offensive_playing_time_ms': 0,
173                         'defensive_playing_time_ms': 0,
174                         'field_time_ms': 0,
175
176                         // For efficiency.
177                         'offensive_points_completed': 0,
178                         'offensive_points_won': 0,
179                         'defensive_points_completed': 0,
180                         'defensive_points_won': 0,
181
182                         'offensive_soft_plus': 0,
183                         'offensive_soft_minus': 0,
184                         'defensive_soft_plus': 0,
185                         'defensive_soft_minus': 0,
186
187                         'pulls': 0,
188                         'pull_times': [],
189                         'oob_pulls': 0,
190
191                         // Internal.
192                         'last_point_seen': null,
193                         'on_field_since': null,
194                 };
195         }
196
197         // Globals.
198         players['globals'] = {
199                 'points_played': 0,
200                 'playing_time_ms': 0,
201                 'offensive_playing_time_ms': 0,
202                 'defensive_playing_time_ms': 0,
203                 'field_time_ms': 0,
204
205                 'offensive_points_completed': 0,
206                 'offensive_points_won': 0,
207                 'defensive_points_completed': 0,
208                 'defensive_points_won': 0,
209         };
210         let globals = players['globals'];
211
212         for (const match of json['matches']) {
213                 if (!keep_match(match['match_id'], filters)) {
214                         continue;
215                 }
216
217                 let our_score = 0;
218                 let their_score = 0;
219                 let handler = null;
220                 let prev_handler = null;
221                 let live_since = null;
222                 let offense = null;  // True/false/null (unknown).
223                 let puller = null;
224                 let pull_started = null;
225                 let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
226                 let point_num = 0;
227                 let game_started = null;
228                 let last_goal = null;
229                 for (const [q,p] of Object.entries(players)) {
230                         p.on_field_since = null;
231                         p.last_point_seen = null;
232                 }
233                 for (const e of match['events']) {
234                         let t = e['t'];
235                         let type = e['type'];
236                         let p = players[e['player']];
237
238                         // Sub management
239                         let keep = keep_event(players, filters);
240                         if (type === 'in' && p.on_field_since === null) {
241                                 p.on_field_since = t;
242                                 if (!keep && keep_event(players, filters)) {
243                                         // A player needed for the filters went onto the field,
244                                         // so pretend people walked on right now (to start their
245                                         // counting time).
246                                         for (const [q,p2] of Object.entries(players)) {
247                                                 if (p2.on_field_since !== null) {
248                                                         p2.on_field_since = t;
249                                                 }
250                                         }
251                                 }
252                         } else if (type === 'out') {
253                                 take_off_field(p, t, live_since, offense, keep);
254                                 if (keep && !keep_event(players, filters)) {
255                                         // A player needed for the filters went off the field,
256                                         // so we need to attribute time for all the others.
257                                         // Pretend they walked off and then immediately on again.
258                                         //
259                                         // TODO: We also need to take care of this to get the globals right.
260                                         for (const [q,p2] of Object.entries(players)) {
261                                                 if (p2.on_field_since !== null) {
262                                                         take_off_field(p2, t, live_since, offense, keep);
263                                                         p2.on_field_since = t;
264                                                 }
265                                         }
266                                 }
267                         }
268
269                         keep = keep_event(players, filters);  // Recompute after in/out.
270
271                         // Liveness management
272                         if (type === 'pull' || type === 'their_pull' || type === 'restart') {
273                                 live_since = t;
274                         } else if (type === 'catch' && last_pull_was_ours === null) {
275                                 // Someone forgot to add the pull, so we'll need to wing it.
276                                 console.log('Missing pull on ' + our_score + '\u2013' + their_score + ' in ' + match['description'] + '; pretending to have one.');
277                                 live_since = t;
278                                 last_pull_was_ours = !offense;
279                         } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
280                                 for (const [q,p] of Object.entries(players)) {
281                                         if (p.on_field_since === null) {
282                                                 continue;
283                                         }
284                                         if (type !== 'stoppage' && p.last_point_seen !== point_num) {
285                                                 if (keep) {
286                                                         // In case the player did nothing this point,
287                                                         // not even subbing in.
288                                                         p.last_point_seen = point_num;
289                                                         ++p.points_played;
290                                                 }
291                                         }
292                                         if (keep) attribute_player_time(p, t, live_since, offense);
293
294                                         if (type !== 'stoppage') {
295                                                 if (keep) {
296                                                         if (last_pull_was_ours === true) {  // D point.
297                                                                 ++p.defensive_points_completed;
298                                                                 if (type === 'goal') {
299                                                                         ++p.defensive_points_won;
300                                                                 }
301                                                         } else if (last_pull_was_ours === false) {  // O point.
302                                                                 ++p.offensive_points_completed;
303                                                                 if (type === 'goal') {
304                                                                         ++p.offensive_points_won;
305                                                                 }
306                                                         }
307                                                 }
308                                         }
309                                 }
310
311                                 if (keep) {
312                                         if (type !== 'stoppage') {
313                                                 // Update globals.
314                                                 ++globals.points_played;
315                                                 if (last_pull_was_ours === true) {  // D point.
316                                                         ++globals.defensive_points_completed;
317                                                         if (type === 'goal') {
318                                                                 ++globals.defensive_points_won;
319                                                         }
320                                                 } else if (last_pull_was_ours === false) {  // O point.
321                                                         ++globals.offensive_points_completed;
322                                                         if (type === 'goal') {
323                                                                 ++globals.offensive_points_won;
324                                                         }
325                                                 }
326                                         }
327                                         if (live_since !== null) {
328                                                 globals.playing_time_ms += t - live_since;
329                                                 if (offense === true) {
330                                                         globals.offensive_playing_time_ms += t - live_since;
331                                                 } else if (offense === false) {
332                                                         globals.defensive_playing_time_ms += t - live_since;
333                                                 }
334                                         }
335                                 }
336
337                                 live_since = null;
338                         }
339
340                         // Score management
341                         if (type === 'goal') {
342                                 ++our_score;
343                         } else if (type === 'their_goal') {
344                                 ++their_score;
345                         }
346
347                         // Point count management
348                         if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
349                                 if (keep) {
350                                         p.last_point_seen = point_num;
351                                         ++p.points_played;
352                                 }
353                         }
354                         if (type === 'goal' || type === 'their_goal') {
355                                 ++point_num;
356                                 last_goal = t;
357                         }
358                         if (type !== 'out' && game_started === null) {
359                                 game_started = t;
360                         }
361
362                         // Pull management
363                         if (type === 'pull') {
364                                 puller = e['player'];
365                                 pull_started = t;
366                                 if (keep) ++p.pulls;
367                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
368                                 // No effect on pull.
369                         } else if (type === 'pull_landed' && puller !== null) {
370                                 if (keep) players[puller].pull_times.push(t - pull_started);
371                         } else if (type === 'pull_oob' && puller !== null) {
372                                 if (keep) ++players[puller].oob_pulls;
373                         } else {
374                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
375                                 puller = pull_started = null;
376                         }
377
378                         // Offense/defense management
379                         let last_offense = offense;
380                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop') {
381                                 offense = false;
382                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
383                                 offense = true;
384                         }
385                         if (last_offense !== offense && live_since !== null) {
386                                 // Switched offense/defense status, so attribute this drive as needed,
387                                 // and update live_since to take that into account.
388                                 if (keep) {
389                                         for (const [q,p] of Object.entries(players)) {
390                                                 if (p.on_field_since === null) {
391                                                         continue;
392                                                 }
393                                                 attribute_player_time(p, t, live_since, last_offense);
394                                         }
395                                         globals.playing_time_ms += t - live_since;
396                                         if (offense === true) {
397                                                 globals.offensive_playing_time_ms += t - live_since;
398                                         } else if (offense === false) {
399                                                 globals.defensive_playing_time_ms += t - live_since;
400                                         }
401                                 }
402                                 live_since = t;
403                         }
404
405                         if (type === 'pull') {
406                                 last_pull_was_ours = true;
407                         } else if (type === 'their_pull') {
408                                 last_pull_was_ours = false;
409                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
410                                 // set_offense could either be “changed to offense for some reason
411                                 // we could not express”, or “we started in the middle of a point,
412                                 // and we are offense”. We assume that if we already saw the pull,
413                                 // it's the former, and if not, it's the latter; thus, the === null
414                                 // test above. (It could also be “we set offense before the pull,
415                                 // so that we get the right button enabled”, in which case it will
416                                 // be overwritten by the next pull/their_pull event anyway.)
417                                 last_pull_was_ours = false;
418                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
419                                 // Similar.
420                                 last_pull_was_ours = true;
421                         } else if (type === 'goal' || type === 'their_goal') {
422                                 last_pull_was_ours = null;
423                         }
424
425                         // Event management
426                         if (type === 'catch' || type === 'goal') {
427                                 if (handler !== null) {
428                                         if (keep) {
429                                                 ++players[handler].num_throws;
430                                                 ++p.catches;
431                                         }
432                                 }
433
434                                 if (keep) ++p.touches;
435                                 if (type === 'goal') {
436                                         if (keep) {
437                                                 if (prev_handler !== null) {
438                                                         ++players[prev_handler].hockey_assists;
439                                                 }
440                                                 if (handler !== null) {
441                                                         ++players[handler].assists;
442                                                 }
443                                                 ++p.goals;
444                                         }
445                                         handler = prev_handler = null;
446                                 } else {
447                                         // Update hold history.
448                                         prev_handler = handler;
449                                         handler = e['player'];
450                                 }
451                         } else if (type === 'throwaway') {
452                                 if (keep) {
453                                         ++p.num_throws;
454                                         ++p.throwaways;
455                                 }
456                                 handler = prev_handler = null;
457                         } else if (type === 'drop') {
458                                 if (keep) ++p.drops;
459                                 handler = prev_handler = null;
460                         } else if (type === 'defense') {
461                                 if (keep) ++p.defenses;
462                         } else if (type === 'interception') {
463                                 if (keep) {
464                                         ++p.interceptions;
465                                         ++p.defenses;
466                                         ++p.touches;
467                                 }
468                                 prev_handler = null;
469                                 handler = e['player'];
470                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
471                                 if (keep) ++p[type];
472                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
473                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
474                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
475                                    type !== 'drop' && type !== 'set_offense' && type !== 'their_goal' &&
476                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
477                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception') {
478                                 console.log("Unknown event:", e);
479                         }
480                 }
481
482                 // Add field time for all players still left at match end.
483                 const keep = keep_event(players, filters);
484                 if (keep) {
485                         for (const [q,p] of Object.entries(players)) {
486                                 if (p.on_field_since !== null && last_goal !== null) {
487                                         p.field_time_ms += last_goal - p.on_field_since;
488                                 }
489                         }
490                         if (game_started !== null && last_goal !== null) {
491                                 globals.field_time_ms += last_goal - game_started;
492                         }
493                         if (live_since !== null && last_goal !== null) {
494                                 globals.playing_time_ms += last_goal - live_since;
495                                 if (offense === true) {
496                                         globals.offensive_playing_time_ms += last_goal - live_since;
497                                 } else if (offense === false) {
498                                         globals.defensive_playing_time_ms += last_goal - live_since;
499                                 }
500                         }
501                 }
502         }
503
504         let chosen_category = get_chosen_category();
505         write_main_menu(chosen_category);
506
507         let rows = [];
508         if (chosen_category === 'general') {
509                 rows = make_table_general(players);
510         } else if (chosen_category === 'offense') {
511                 rows = make_table_offense(players);
512         } else if (chosen_category === 'defense') {
513                 rows = make_table_defense(players);
514         } else if (chosen_category === 'playing_time') {
515                 rows = make_table_playing_time(players);
516         } else if (chosen_category === 'per_point') {
517                 rows = make_table_per_point(players);
518         }
519         document.getElementById('stats').replaceChildren(...rows);
520 }
521
522 function get_chosen_category() {
523         if (window.location.hash === '#offense') {
524                 return 'offense';
525         } else if (window.location.hash === '#defense') {
526                 return 'defense';
527         } else if (window.location.hash === '#playing_time') {
528                 return 'playing_time';
529         } else if (window.location.hash === '#per_point') {
530                 return 'per_point';
531         } else {
532                 return 'general';
533         }
534 }
535
536 function write_main_menu(chosen_category) {
537         let elems = [];
538         if (chosen_category === 'general') {
539                 let span = document.createElement('span');
540                 span.innerText = 'General';
541                 elems.push(span);
542         } else {
543                 let a = document.createElement('a');
544                 a.appendChild(document.createTextNode('General'));
545                 a.setAttribute('href', '#general');
546                 elems.push(a);
547         }
548
549         if (chosen_category === 'offense') {
550                 let span = document.createElement('span');
551                 span.innerText = 'Offense';
552                 elems.push(span);
553         } else {
554                 let a = document.createElement('a');
555                 a.appendChild(document.createTextNode('Offense'));
556                 a.setAttribute('href', '#offense');
557                 elems.push(a);
558         }
559
560         if (chosen_category === 'defense') {
561                 let span = document.createElement('span');
562                 span.innerText = 'Defense';
563                 elems.push(span);
564         } else {
565                 let a = document.createElement('a');
566                 a.appendChild(document.createTextNode('Defense'));
567                 a.setAttribute('href', '#defense');
568                 elems.push(a);
569         }
570
571         if (chosen_category === 'playing_time') {
572                 let span = document.createElement('span');
573                 span.innerText = 'Playing time';
574                 elems.push(span);
575         } else {
576                 let a = document.createElement('a');
577                 a.appendChild(document.createTextNode('Playing time'));
578                 a.setAttribute('href', '#playing_time');
579                 elems.push(a);
580         }
581
582         if (chosen_category === 'per_point') {
583                 let span = document.createElement('span');
584                 span.innerText = 'Per point';
585                 elems.push(span);
586         } else {
587                 let a = document.createElement('a');
588                 a.appendChild(document.createTextNode('Per point'));
589                 a.setAttribute('href', '#per_point');
590                 elems.push(a);
591         }
592
593         document.getElementById('mainmenu').replaceChildren(...elems);
594 }
595
596 // https://en.wikipedia.org/wiki/1.96#History
597 const z = 1.959964;
598
599 const ci_width = 100;
600 const ci_height = 20;
601
602 function make_binomial_ci(val, num, z) {
603         let avg = val / num;
604
605         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
606         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
607         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
608
609         // Fix the signs so that we don't get -0.00.
610         low = Math.max(low, 0.0);
611         return {
612                 'val': avg,
613                 'lower_ci': low,
614                 'upper_ci': high,
615                 'min': 0.0,
616                 'max': 1.0,
617         };
618 }
619
620 // These can only happen once per point, but you get -1 and +1
621 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
622 // and then we can rewrite back.
623 function make_efficiency_ci(points_won, points_completed, z)
624 {
625         let ci = make_binomial_ci(points_won, points_completed, z);
626         ci.val = 2.0 * ci.val - 1.0;
627         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
628         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
629         ci.min = -1.0;
630         ci.max = 1.0;
631         ci.desired = 0.0;  // Desired = positive efficiency.
632         return ci;
633 }
634
635 // Ds, throwaways and drops can happen multiple times per point,
636 // so they are Poisson distributed.
637 //
638 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
639 // since our rates are definitely below 2 per point).
640 function make_poisson_ci(val, num, z, inverted)
641 {
642         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
643         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
644
645         // Fix the signs so that we don't get -0.00.
646         low = Math.max(low, 0.0);
647
648         // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
649         let avg = val / num;
650         return {
651                 'val': avg,
652                 'lower_ci': low,
653                 'upper_ci': high,
654                 'min': 0.0,
655                 'max': 0.25,
656                 'desired': 0.05,
657                 'inverted': inverted,
658         };
659 }
660
661 function make_table_general(players) {
662         let rows = [];
663         {
664                 let header = document.createElement('tr');
665                 add_th(header, 'Player');
666                 add_th(header, '+/-');
667                 add_th(header, 'Soft +/-');
668                 add_th(header, 'O efficiency');
669                 add_th(header, 'D efficiency');
670                 add_th(header, 'Points played');
671                 rows.push(header);
672         }
673
674         for (const [q,p] of Object.entries(players)) {
675                 if (q === 'globals') continue;
676                 let row = document.createElement('tr');
677                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops;
678                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
679                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
680                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
681                 add_3cell(row, p.name, 'name');  // TODO: number?
682                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
683                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
684                 add_3cell_ci(row, o_efficiency);
685                 add_3cell_ci(row, d_efficiency);
686                 add_3cell(row, p.points_played);
687                 rows.push(row);
688         }
689
690         // Globals.
691         let globals = players['globals'];
692         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
693         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
694         let row = document.createElement('tr');
695         add_3cell(row, '');
696         add_3cell(row, '');
697         add_3cell(row, '');
698         add_3cell_ci(row, o_efficiency);
699         add_3cell_ci(row, d_efficiency);
700         add_3cell(row, globals.points_played);
701         rows.push(row);
702
703         return rows;
704 }
705
706 function make_table_offense(players) {
707         let rows = [];
708         {
709                 let header = document.createElement('tr');
710                 add_th(header, 'Player');
711                 add_th(header, 'Goals');
712                 add_th(header, 'Assists');
713                 add_th(header, 'Hockey assists');
714                 add_th(header, 'Throws');
715                 add_th(header, 'Throwaways');
716                 add_th(header, '%OK');
717                 add_th(header, 'Catches');
718                 add_th(header, 'Drops');
719                 add_th(header, '%OK');
720                 add_th(header, 'Soft +/-', 6);
721                 rows.push(header);
722         }
723
724         let num_throws = 0;
725         let throwaways = 0;
726         let catches = 0;
727         let drops = 0;
728         for (const [q,p] of Object.entries(players)) {
729                 if (q === 'globals') continue;
730                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
731                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops, z);
732
733                 throw_ok.format = 'percentage';
734                 catch_ok.format = 'percentage';
735
736                 // Desire at least 90% percentage. Fairly arbitrary.
737                 throw_ok.desired = 0.9;
738                 catch_ok.desired = 0.9;
739
740                 let row = document.createElement('tr');
741                 add_3cell(row, p.name, 'name');  // TODO: number?
742                 add_3cell(row, p.goals);
743                 add_3cell(row, p.assists);
744                 add_3cell(row, p.hockey_assists);
745                 add_3cell(row, p.num_throws);
746                 add_3cell(row, p.throwaways);
747                 add_3cell_ci(row, throw_ok);
748                 add_3cell(row, p.catches);
749                 add_3cell(row, p.drops);
750                 add_3cell_ci(row, catch_ok);
751                 add_3cell(row, '+' + p.offensive_soft_plus);
752                 add_3cell(row, '-' + p.offensive_soft_minus);
753                 rows.push(row);
754
755                 num_throws += p.num_throws;
756                 throwaways += p.throwaways;
757                 catches += p.catches;
758                 drops += p.drops;
759         }
760
761         // Globals.
762         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
763         let catch_ok = make_binomial_ci(catches, catches + drops, z);
764         throw_ok.format = 'percentage';
765         catch_ok.format = 'percentage';
766         throw_ok.desired = 0.9;
767         catch_ok.desired = 0.9;
768
769         let row = document.createElement('tr');
770         add_3cell(row, '');
771         add_3cell(row, '');
772         add_3cell(row, '');
773         add_3cell(row, '');
774         add_3cell(row, num_throws);
775         add_3cell(row, throwaways);
776         add_3cell_ci(row, throw_ok);
777         add_3cell(row, catches);
778         add_3cell(row, drops);
779         add_3cell_ci(row, catch_ok);
780         add_3cell(row, '');
781         add_3cell(row, '');
782         rows.push(row);
783
784         return rows;
785 }
786
787 function make_table_defense(players) {
788         let rows = [];
789         {
790                 let header = document.createElement('tr');
791                 add_th(header, 'Player');
792                 add_th(header, 'Ds');
793                 add_th(header, 'Pulls');
794                 add_th(header, 'OOB pulls');
795                 add_th(header, 'OOB%');
796                 add_th(header, 'Avg. hang time (IB)');
797                 add_th(header, 'Soft +/-', 6);
798                 rows.push(header);
799         }
800         for (const [q,p] of Object.entries(players)) {
801                 if (q === 'globals') continue;
802                 let sum_time = 0;
803                 for (const t of p.pull_times) {
804                         sum_time += t;
805                 }
806                 let avg_time = 1e-3 * sum_time / p.pulls;
807                 let oob_pct = 100 * p.oob_pulls / p.pulls;
808
809                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
810                 ci_oob.format = 'percentage';
811                 ci_oob.desired = 0.2;  // Arbitrary.
812                 ci_oob.inverted = true;
813
814                 let row = document.createElement('tr');
815                 add_3cell(row, p.name, 'name');  // TODO: number?
816                 add_3cell(row, p.defenses);
817                 add_3cell(row, p.pulls);
818                 add_3cell(row, p.oob_pulls);
819                 add_3cell_ci(row, ci_oob);
820                 if (p.pulls > p.oob_pulls) {
821                         add_3cell(row, avg_time.toFixed(1) + ' sec');
822                 } else {
823                         add_3cell(row, 'N/A');
824                 }
825                 add_3cell(row, '+' + p.defensive_soft_plus);
826                 add_3cell(row, '-' + p.defensive_soft_minus);
827                 rows.push(row);
828         }
829         return rows;
830 }
831
832 function make_table_playing_time(players) {
833         let rows = [];
834         {
835                 let header = document.createElement('tr');
836                 add_th(header, 'Player');
837                 add_th(header, 'Points played');
838                 add_th(header, 'Time played');
839                 add_th(header, 'O time');
840                 add_th(header, 'D time');
841                 add_th(header, 'Time on field');
842                 add_th(header, 'O points');
843                 add_th(header, 'D points');
844                 rows.push(header);
845         }
846
847         for (const [q,p] of Object.entries(players)) {
848                 if (q === 'globals') continue;
849                 let row = document.createElement('tr');
850                 add_3cell(row, p.name, 'name');  // TODO: number?
851                 add_3cell(row, p.points_played);
852                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
853                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
854                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
855                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
856                 add_3cell(row, p.offensive_points_completed);
857                 add_3cell(row, p.defensive_points_completed);
858                 rows.push(row);
859         }
860
861         // Globals.
862         let globals = players['globals'];
863         let row = document.createElement('tr');
864         add_3cell(row, '');
865         add_3cell(row, globals.points_played);
866         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
867         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
868         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
869         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
870         add_3cell(row, globals.offensive_points_completed);
871         add_3cell(row, globals.defensive_points_completed);
872         rows.push(row);
873
874         return rows;
875 }
876
877 function make_table_per_point(players) {
878         let rows = [];
879         {
880                 let header = document.createElement('tr');
881                 add_th(header, 'Player');
882                 add_th(header, 'Goals');
883                 add_th(header, 'Assists');
884                 add_th(header, 'Hockey assists');
885                 add_th(header, 'Ds');
886                 add_th(header, 'Throwaways');
887                 add_th(header, 'Drops');
888                 add_th(header, 'Touches');
889                 rows.push(header);
890         }
891
892         let goals = 0;
893         let assists = 0;
894         let hockey_assists = 0;
895         let defenses = 0;
896         let throwaways = 0;
897         let drops = 0;
898         let touches = 0;
899         for (const [q,p] of Object.entries(players)) {
900                 if (q === 'globals') continue;
901
902                 // Can only happen once per point, so these are binomials.
903                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
904                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
905                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
906                 // Arbitrarily desire at least 10% (not everybody can score or assist).
907                 ci_goals.desired = 0.1;
908                 ci_assists.desired = 0.1;
909                 ci_hockey_assists.desired = 0.1;
910
911                 let row = document.createElement('tr');
912                 add_3cell(row, p.name, 'name');  // TODO: number?
913                 add_3cell_ci(row, ci_goals);
914                 add_3cell_ci(row, ci_assists);
915                 add_3cell_ci(row, ci_hockey_assists);
916                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
917                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
918                 add_3cell_ci(row, make_poisson_ci(p.drops, p.points_played, z, true));
919                 if (p.points_played > 0) {
920                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
921                 } else {
922                         add_3cell(row, 'N/A');
923                 }
924                 rows.push(row);
925
926                 goals += p.goals;
927                 assists += p.assists;
928                 hockey_assists += p.hockey_assists;
929                 defenses += p.defenses;
930                 throwaways += p.throwaways;
931                 drops += p.drops;
932                 touches += p.touches;
933         }
934
935         // Globals.
936         let globals = players['globals'];
937         let row = document.createElement('tr');
938         add_3cell(row, '');
939         if (globals.points_played > 0) {
940                 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
941                 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
942                 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
943                 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
944                 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
945                 add_3cell_with_filler_ci(row, drops == 0 ? 0 : (drops / globals.points_played).toFixed(2));
946                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
947         } else {
948                 add_3cell_with_filler_ci(row, 'N/A');
949                 add_3cell_with_filler_ci(row, 'N/A');
950                 add_3cell_with_filler_ci(row, 'N/A');
951                 add_3cell_with_filler_ci(row, 'N/A');
952                 add_3cell_with_filler_ci(row, 'N/A');
953                 add_3cell_with_filler_ci(row, 'N/A');
954                 add_3cell(row, 'N/A');
955         }
956         rows.push(row);
957
958         return rows;
959 }
960
961 function open_filter_menu() {
962         document.getElementById('filter-submenu').style.display = 'none';
963
964         let menu = document.getElementById('filter-add-menu');
965         menu.style.display = 'block';
966         menu.replaceChildren();
967
968         // Place the menu directly under the “click to add” label;
969         // we don't anchor it since that label will move around
970         // and the menu shouldn't.
971         let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
972         menu.style.left = rect.left + 'px';
973         menu.style.top = (rect.bottom + 10) + 'px';
974
975         add_menu_item(menu, 0, 'match', 'Match (any)');
976         add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
977         add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
978         // add_menu_item(menu, 'Formation played (any)');
979 }
980
981 function add_menu_item(menu, menu_idx, filter_type, title) {
982         let item = document.createElement('div');
983         item.classList.add('option');
984         item.appendChild(document.createTextNode(title));
985
986         let arrow = document.createElement('div');
987         arrow.classList.add('arrow');
988         arrow.textContent = '▸';
989         item.appendChild(arrow);
990
991         menu.appendChild(item);
992
993         item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
994 }
995
996 function show_submenu(menu_idx, pill, filter_type) {
997         let submenu = document.getElementById('filter-submenu');
998         let subitems = [];
999         const filter = find_filter(filter_type);
1000
1001         let choices = [];
1002         if (filter_type === 'match') {
1003                 for (const match of global_json['matches']) {
1004                         choices.push({
1005                                 'title': match['description'],
1006                                 'id': match['match_id']
1007                         });
1008                 }
1009         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1010                 for (const player of global_json['players']) {
1011                         choices.push({
1012                                 'title': player['name'],
1013                                 'id': player['player_id']
1014                         });
1015                 }
1016         }
1017
1018         for (const choice of choices) {
1019                 let label = document.createElement('label');
1020
1021                 let subitem = document.createElement('div');
1022                 subitem.classList.add('option');
1023
1024                 let check = document.createElement('input');
1025                 check.setAttribute('type', 'checkbox');
1026                 check.setAttribute('id', 'choice' + choice.id);
1027                 if (filter !== null && filter.elements.has(choice.id)) {
1028                         check.setAttribute('checked', 'checked');
1029                 }
1030                 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1031
1032                 subitem.appendChild(check);
1033                 subitem.appendChild(document.createTextNode(choice.title));
1034
1035                 label.appendChild(subitem);
1036                 subitems.push(label);
1037         }
1038         submenu.replaceChildren(...subitems);
1039         submenu.style.display = 'block';
1040
1041         if (pill !== null) {
1042                 let rect = pill.getBoundingClientRect();
1043                 submenu.style.top = (rect.bottom + 10) + 'px';
1044                 submenu.style.left = rect.left + 'px';
1045         } else {
1046                 // Position just outside the selected menu.
1047                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1048                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1049                 submenu.style.left = (rect.right - 1) + 'px';
1050         }
1051 }
1052
1053 // Find the right filter, if it exists.
1054 function find_filter(filter_type) {
1055         for (let f of global_filters) {
1056                 if (f.type === filter_type) {
1057                         return f;
1058                 }
1059         }
1060         return null;
1061 }
1062
1063 function checkbox_changed(e, filter_type, id) {
1064         let filter = find_filter(filter_type);
1065         if (e.target.checked) {
1066                 // See if we must add a new filter to the list.
1067                 if (filter === null) {
1068                         filter = {
1069                                 'type': filter_type,
1070                                 'elements': new Set([ id ]),
1071                         };
1072                         filter.pill = make_filter_pill(filter);
1073                         global_filters.push(filter);
1074                         document.getElementById('filters').appendChild(filter.pill);
1075                 } else {
1076                         filter.elements.add(id);
1077                         let new_pill = make_filter_pill(filter);
1078                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1079                         filter.pill = new_pill;
1080                 }
1081         } else {
1082                 filter.elements.delete(id);
1083                 if (filter.elements.size === 0) {
1084                         document.getElementById('filters').removeChild(filter.pill);
1085                         global_filters = global_filters.filter(f => f !== filter);
1086                 } else {
1087                         let new_pill = make_filter_pill(filter);
1088                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1089                         filter.pill = new_pill;
1090                 }
1091         }
1092
1093         process_matches(global_json, global_filters);
1094 }
1095
1096 function make_filter_pill(filter) {
1097         let pill = document.createElement('div');
1098         pill.classList.add('filter-pill');
1099         let text;
1100         if (filter.type === 'match') {
1101                 text = 'Match: ';
1102
1103                 // See if there's a common prefix.
1104                 let num_matches = filter.elements.size;
1105                 let common_prefix = null;
1106                 if (num_matches > 1)  {
1107                         for (const match_id of filter.elements) {
1108                                 let desc = find_match(match_id)['description'];
1109                                 if (common_prefix === null) {
1110                                         common_prefix = desc;
1111                                 } else {
1112                                         common_prefix = find_common_prefix(common_prefix, desc);
1113                                 }
1114                         }
1115                         if (common_prefix.length < 3) {
1116                                 common_prefix = null;
1117                         }
1118                 }
1119
1120                 if (common_prefix !== null) {
1121                         text += common_prefix + '(';
1122                 }
1123
1124                 let first = true;
1125                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1126                 for (const match_id of sorted_match_id) {
1127                         if (!first) {
1128                                 text += ', ';
1129                         }
1130                         let desc = find_match(match_id)['description'];
1131                         if (common_prefix === null) {
1132                                 text += desc;
1133                         } else {
1134                                 text += desc.substr(common_prefix.length);
1135                         }
1136                         first = false;
1137                 }
1138
1139                 if (common_prefix !== null) {
1140                         text += ')';
1141                 }
1142         } else if (filter.type === 'player_any') {
1143                 text = 'Player (any): ';
1144                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1145                 let first = true;
1146                 for (const player_id of sorted_players) {
1147                         if (!first) {
1148                                 text += ', ';
1149                         }
1150                         text += find_player(player_id)['name'];
1151                         first = false;
1152                 }
1153         } else if (filter.type === 'player_all') {
1154                 text = 'Players: ';
1155                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1156                 let first = true;
1157                 for (const player_id of sorted_players) {
1158                         if (!first) {
1159                                 text += ' AND ';
1160                         }
1161                         text += find_player(player_id)['name'];
1162                         first = false;
1163                 }
1164         }
1165
1166         let text_node = document.createElement('span');
1167         text_node.innerText = text;
1168         text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1169         pill.appendChild(text_node);
1170
1171         pill.appendChild(document.createTextNode(' '));
1172
1173         let delete_node = document.createElement('span');
1174         delete_node.innerText = '✖';
1175         delete_node.addEventListener('click', (e) => {
1176                 // Delete this filter entirely.
1177                 document.getElementById('filters').removeChild(pill);
1178                 global_filters = global_filters.filter(f => f !== filter);
1179                 process_matches(global_json, global_filters);
1180
1181                 let add_menu = document.getElementById('filter-add-menu');
1182                 let add_submenu = document.getElementById('filter-submenu');
1183                 add_menu.style.display = 'none';
1184                 add_submenu.style.display = 'none';
1185         });
1186         pill.appendChild(delete_node);
1187         pill.style.cursor = 'pointer';
1188
1189         return pill;
1190 }
1191
1192 function find_common_prefix(a, b) {
1193         let ret = '';
1194         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1195                 if (a[i] === b[i]) {
1196                         ret += a[i];
1197                 } else {
1198                         break;
1199                 }
1200         }
1201         return ret;
1202 }
1203
1204 function find_match(match_id) {
1205         for (const match of global_json['matches']) {
1206                 if (match['match_id'] === match_id) {
1207                         return match;
1208                 }
1209         }
1210         return null;
1211 }
1212
1213 function find_player(player_id) {
1214         for (const player of global_json['players']) {
1215                 if (player['player_id'] === player_id) {
1216                         return player;
1217                 }
1218         }
1219         return null;
1220 }
1221
1222 function player_pos(player_id) {
1223         let i = 0;
1224         for (const player of global_json['players']) {
1225                 if (player['player_id'] === player_id) {
1226                         return i;
1227                 }
1228                 ++i;
1229         }
1230         return null;
1231 }
1232
1233 function keep_match(match_id, filters) {
1234         for (const filter of filters) {
1235                 if (filter.type === 'match') {
1236                         return filter.elements.has(match_id);
1237                 }
1238         }
1239         return true;
1240 }
1241
1242 function keep_event(players, filters) {
1243         for (const filter of filters) {
1244                 if (filter.type === 'player_any') {
1245                         for (const p of Array.from(filter.elements)) {
1246                                 if (players[p].on_field_since !== null) {
1247                                         return true;
1248                                 }
1249                         }
1250                         return false;
1251                 } else if (filter.type === 'player_all') {
1252                         for (const p of Array.from(filter.elements)) {
1253                                 if (players[p].on_field_since === null) {
1254                                         return false;
1255                                 }
1256                         }
1257                         return true;
1258                 }
1259         }
1260         return true;
1261 }
1262
1263 function possibly_close_menu(e) {
1264         if (e.target.closest('#filter-click-to-add') === null &&
1265             e.target.closest('#filter-add-menu') === null &&
1266             e.target.closest('#filter-submenu') === null &&
1267             e.target.closest('.filter-pill') === null) {
1268                 let add_menu = document.getElementById('filter-add-menu');
1269                 let add_submenu = document.getElementById('filter-submenu');
1270                 add_menu.style.display = 'none';
1271                 add_submenu.style.display = 'none';
1272         }
1273 }