3 // No frameworks, no compilers, no npm, just JavaScript. :-)
6 let global_filters = [];
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); });
14 function format_time(t)
16 const ms = t % 1000 + '';
17 t = Math.floor(t / 1000);
18 const sec = t % 60 + '';
19 t = Math.floor(t / 60);
20 const min = t % 60 + '';
21 const hour = Math.floor(t / 60) + '';
22 return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
25 function attribute_player_time(player, to, from, offense) {
27 if (player.on_field_since > from) {
28 // Player came in while play happened (without a stoppage!?).
29 delta_time = to - player.on_field_since;
31 delta_time = to - from;
33 player.playing_time_ms += delta_time;
34 if (offense === true) {
35 player.offensive_playing_time_ms += delta_time;
36 } else if (offense === false) {
37 player.defensive_playing_time_ms += delta_time;
41 function take_off_field(player, t, live_since, offense, keep) {
43 if (live_since === null) {
44 // Play isn't live, so nothing to do.
46 attribute_player_time(player, t, live_since, offense);
48 if (player.on_field_since !== null) { // Just a safeguard; out without in should never happen.
49 player.field_time_ms += t - player.on_field_since;
52 player.on_field_since = null;
55 function add_cell(tr, element_type, text) {
56 let element = document.createElement(element_type);
57 element.textContent = text;
58 tr.appendChild(element);
62 function add_th(tr, text, colspan) {
63 let element = document.createElement('th');
64 let link = document.createElement('a');
65 link.style.cursor = 'pointer';
66 link.addEventListener('click', (e) => {
68 process_matches(global_json, global_filters);
70 link.textContent = text;
71 element.appendChild(link);
72 tr.appendChild(element);
75 element.setAttribute('colspan', colspan);
77 element.setAttribute('colspan', '3');
82 function add_3cell(tr, text, cls) {
83 let p1 = add_cell(tr, 'td', '');
84 let element = add_cell(tr, 'td', text);
85 let p2 = add_cell(tr, 'td', '');
87 p1.classList.add('pad');
88 p2.classList.add('pad');
89 if (cls === undefined) {
90 element.classList.add('num');
92 element.classList.add(cls);
97 function add_3cell_with_filler_ci(tr, text, cls) {
98 let element = add_3cell(tr, text, cls);
100 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
101 svg.classList.add('fillerci');
102 svg.setAttribute('width', ci_width);
103 svg.setAttribute('height', ci_height);
104 element.appendChild(svg);
109 function add_3cell_ci(tr, ci) {
111 add_3cell_with_filler_ci(tr, 'N/A');
116 if (ci.format === 'percentage') {
117 text = (100 * ci.val).toFixed(0) + '%';
119 text = ci.val.toFixed(2);
121 let element = add_3cell(tr, text);
122 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
125 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
126 if (ci.inverted === true) {
127 svg.classList.add('invertedci');
129 svg.classList.add('ci');
131 svg.setAttribute('width', ci_width);
132 svg.setAttribute('height', ci_height);
134 // The good (green) and red (bad) ranges.
135 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
136 s0.classList.add('range');
137 s0.classList.add('s0');
138 s0.setAttribute('width', to_x(ci.desired));
139 s0.setAttribute('height', ci_height);
140 s0.setAttribute('x', '0');
142 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
143 s1.classList.add('range');
144 s1.classList.add('s1');
145 s1.setAttribute('width', ci_width - to_x(ci.desired));
146 s1.setAttribute('height', ci_height);
147 s1.setAttribute('x', to_x(ci.desired));
150 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
151 bar.classList.add('bar');
152 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
153 bar.setAttribute('height', ci_height / 3);
154 bar.setAttribute('x', to_x(ci.lower_ci));
155 bar.setAttribute('y', ci_height / 3);
157 // Marker line for average.
158 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
159 marker.classList.add('marker');
160 marker.setAttribute('x1', to_x(ci.val));
161 marker.setAttribute('x2', to_x(ci.val));
162 marker.setAttribute('y1', ci_height / 6);
163 marker.setAttribute('y2', ci_height * 5 / 6);
167 svg.appendChild(bar);
168 svg.appendChild(marker);
170 element.appendChild(svg);
173 function process_matches(json, filters) {
175 for (const player of json['players']) {
176 players[player['player_id']] = {
177 'name': player['name'],
178 'number': player['number'],
193 'playing_time_ms': 0,
194 'offensive_playing_time_ms': 0,
195 'defensive_playing_time_ms': 0,
199 'offensive_points_completed': 0,
200 'offensive_points_won': 0,
201 'defensive_points_completed': 0,
202 'defensive_points_won': 0,
204 'offensive_soft_plus': 0,
205 'offensive_soft_minus': 0,
206 'defensive_soft_plus': 0,
207 'defensive_soft_minus': 0,
214 'last_point_seen': null,
215 'on_field_since': null,
220 players['globals'] = {
222 'playing_time_ms': 0,
223 'offensive_playing_time_ms': 0,
224 'defensive_playing_time_ms': 0,
227 'offensive_points_completed': 0,
228 'offensive_points_won': 0,
229 'defensive_points_completed': 0,
230 'defensive_points_won': 0,
232 let globals = players['globals'];
234 for (const match of json['matches']) {
235 if (!keep_match(match['match_id'], filters)) {
242 let prev_handler = null;
243 let live_since = null;
244 let offense = null; // True/false/null (unknown).
246 let pull_started = null;
247 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
249 let game_started = null;
250 let last_goal = null;
252 // The last used formations of the given kind, if any; they may be reused
253 // when the point starts, if nothing else is set.
254 let last_offensive_formation = null;
255 let last_defensive_formation = null;
257 // Formations we've set, but haven't really had the chance to use yet
258 // (e.g., we get a “use zone defense” event while we're still on offense).
259 let pending_offensive_formation = null;
260 let pending_defensive_formation = null;
262 // Formations that we have played at least once this point, after all
263 // heuristics and similar.
264 let formations_used_this_point = new Set();
266 for (const [q,p] of Object.entries(players)) {
267 p.on_field_since = null;
268 p.last_point_seen = null;
270 for (const e of match['events']) {
272 let type = e['type'];
273 let p = players[e['player']];
276 let keep = keep_event(players, formations_used_this_point, filters);
277 if (type === 'in' && p.on_field_since === null) {
278 p.on_field_since = t;
279 if (!keep && keep_event(players, formations_used_this_point, filters)) {
280 // A player needed for the filters went onto the field,
281 // so pretend people walked on right now (to start their
283 for (const [q,p2] of Object.entries(players)) {
284 if (p2.on_field_since !== null) {
285 p2.on_field_since = t;
289 } else if (type === 'out') {
290 take_off_field(p, t, live_since, offense, keep);
291 if (keep && !keep_event(players, formations_used_this_point, filters)) {
292 // A player needed for the filters went off the field,
293 // so we need to attribute time for all the others.
294 // Pretend they walked off and then immediately on again.
296 // TODO: We also need to take care of this to get the globals right.
297 for (const [q,p2] of Object.entries(players)) {
298 if (p2.on_field_since !== null) {
299 take_off_field(p2, t, live_since, offense, keep);
300 p2.on_field_since = t;
306 keep = keep_event(players, formations_used_this_point, filters); // Recompute after in/out.
308 // Liveness management
309 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
311 } else if (type === 'catch' && last_pull_was_ours === null) {
312 // Someone forgot to add the pull, so we'll need to wing it.
313 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
315 last_pull_was_ours = !offense;
316 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
317 for (const [q,p] of Object.entries(players)) {
318 if (p.on_field_since === null) {
321 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
323 // In case the player did nothing this point,
324 // not even subbing in.
325 p.last_point_seen = point_num;
329 if (keep) attribute_player_time(p, t, live_since, offense);
331 if (type !== 'stoppage') {
333 if (last_pull_was_ours === true) { // D point.
334 ++p.defensive_points_completed;
335 if (type === 'goal') {
336 ++p.defensive_points_won;
338 } else if (last_pull_was_ours === false) { // O point.
339 ++p.offensive_points_completed;
340 if (type === 'goal') {
341 ++p.offensive_points_won;
349 if (type !== 'stoppage') {
351 ++globals.points_played;
352 if (last_pull_was_ours === true) { // D point.
353 ++globals.defensive_points_completed;
354 if (type === 'goal') {
355 ++globals.defensive_points_won;
357 } else if (last_pull_was_ours === false) { // O point.
358 ++globals.offensive_points_completed;
359 if (type === 'goal') {
360 ++globals.offensive_points_won;
364 if (live_since !== null) {
365 globals.playing_time_ms += t - live_since;
366 if (offense === true) {
367 globals.offensive_playing_time_ms += t - live_since;
368 } else if (offense === false) {
369 globals.defensive_playing_time_ms += t - live_since;
378 if (type === 'goal') {
380 } else if (type === 'their_goal') {
384 // Point count management
385 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
387 p.last_point_seen = point_num;
391 if (type === 'goal' || type === 'their_goal') {
395 if (type !== 'out' && game_started === null) {
400 if (type === 'pull') {
401 puller = e['player'];
404 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
405 // No effect on pull.
406 } else if (type === 'pull_landed' && puller !== null) {
407 if (keep) players[puller].pull_times.push(t - pull_started);
408 } else if (type === 'pull_oob' && puller !== null) {
409 if (keep) ++players[puller].oob_pulls;
411 // Not pulling (if there was one, we never recorded its outcome, but still count it).
412 puller = pull_started = null;
415 // Offense/defense management
416 let last_offense = offense;
417 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
419 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
422 if (last_offense !== offense && live_since !== null) {
423 // Switched offense/defense status, so attribute this drive as needed,
424 // and update live_since to take that into account.
426 for (const [q,p] of Object.entries(players)) {
427 if (p.on_field_since === null) {
430 attribute_player_time(p, t, live_since, last_offense);
432 globals.playing_time_ms += t - live_since;
433 if (offense === true) {
434 globals.offensive_playing_time_ms += t - live_since;
435 } else if (offense === false) {
436 globals.defensive_playing_time_ms += t - live_since;
442 if (type === 'pull') {
443 last_pull_was_ours = true;
444 } else if (type === 'their_pull') {
445 last_pull_was_ours = false;
446 } else if (type === 'set_offense' && last_pull_was_ours === null) {
447 // set_offense could either be “changed to offense for some reason
448 // we could not express”, or “we started in the middle of a point,
449 // and we are offense”. We assume that if we already saw the pull,
450 // it's the former, and if not, it's the latter; thus, the === null
451 // test above. (It could also be “we set offense before the pull,
452 // so that we get the right button enabled”, in which case it will
453 // be overwritten by the next pull/their_pull event anyway.)
454 last_pull_was_ours = false;
455 } else if (type === 'set_defense' && last_pull_was_ours === null) {
457 last_pull_was_ours = true;
458 } else if (type === 'goal' || type === 'their_goal') {
459 last_pull_was_ours = null;
462 // Formation management
463 if (type === 'formation_offense' || type === 'formation_defense') {
464 let id = e.formation === null ? 0 : e.formation;
465 let for_offense = (type === 'formation_offense');
466 if (offense === for_offense) {
467 formations_used_this_point.add(id);
468 } else if (for_offense) {
469 pending_offensive_formation = id;
471 pending_defensive_formation = id;
474 last_offensive_formation = id;
476 last_defensive_formation = id;
478 } else if (last_offense !== offense) {
479 if (offense === true && pending_offensive_formation !== null) {
480 formations_used_this_point.add(pending_offensive_formation);
481 pending_offensive_formation = null;
482 } else if (offense === false && pending_defensive_formation !== null) {
483 formations_used_this_point.add(pending_defensive_formation);
484 pending_defensive_formation = null;
485 } else if (offense === true && last_defensive_formation !== null) {
486 if (should_reuse_last_formation(match['events'], t)) {
487 formations_used_this_point.add(last_defensive_formation);
489 } else if (offense === false && last_offensive_formation !== null) {
490 if (should_reuse_last_formation(match['events'], t)) {
491 formations_used_this_point.add(last_offensive_formation);
496 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
497 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
499 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
500 // The handler subbed out and was replaced with another handler,
501 // so this wasn't a pass.
506 if (type === 'catch' || type === 'goal') {
507 if (handler !== null) {
509 ++players[handler].num_throws;
514 if (keep) ++p.touches;
515 if (type === 'goal') {
517 if (prev_handler !== null) {
518 ++players[prev_handler].hockey_assists;
520 if (handler !== null) {
521 ++players[handler].assists;
525 handler = prev_handler = null;
527 // Update hold history.
528 prev_handler = handler;
529 handler = e['player'];
531 } else if (type === 'throwaway') {
536 handler = prev_handler = null;
537 } else if (type === 'drop') {
539 handler = prev_handler = null;
540 } else if (type === 'stallout') {
541 if (keep) ++p.stallouts;
542 handler = prev_handler = null;
543 } else if (type === 'was_d') {
544 if (keep) ++p.was_ds;
545 handler = prev_handler = null;
546 } else if (type === 'defense') {
547 if (keep) ++p.defenses;
548 } else if (type === 'interception') {
555 handler = e['player'];
556 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
558 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
559 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
560 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
561 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
562 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
563 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
564 type !== 'formation_offense' && type !== 'formation_defense') {
565 console.log(format_time(t) + ": Unknown event “" + e + "”");
568 if (type === 'goal' || type === 'their_goal') {
569 formations_used_this_point.clear();
573 // Add field time for all players still left at match end.
574 const keep = keep_event(players, formations_used_this_point, filters);
576 for (const [q,p] of Object.entries(players)) {
577 if (p.on_field_since !== null && last_goal !== null) {
578 p.field_time_ms += last_goal - p.on_field_since;
581 if (game_started !== null && last_goal !== null) {
582 globals.field_time_ms += last_goal - game_started;
584 if (live_since !== null && last_goal !== null) {
585 globals.playing_time_ms += last_goal - live_since;
586 if (offense === true) {
587 globals.offensive_playing_time_ms += last_goal - live_since;
588 } else if (offense === false) {
589 globals.defensive_playing_time_ms += last_goal - live_since;
595 let chosen_category = get_chosen_category();
596 write_main_menu(chosen_category);
599 if (chosen_category === 'general') {
600 rows = make_table_general(players);
601 } else if (chosen_category === 'offense') {
602 rows = make_table_offense(players);
603 } else if (chosen_category === 'defense') {
604 rows = make_table_defense(players);
605 } else if (chosen_category === 'playing_time') {
606 rows = make_table_playing_time(players);
607 } else if (chosen_category === 'per_point') {
608 rows = make_table_per_point(players);
610 document.getElementById('stats').replaceChildren(...rows);
613 function get_chosen_category() {
614 if (window.location.hash === '#offense') {
616 } else if (window.location.hash === '#defense') {
618 } else if (window.location.hash === '#playing_time') {
619 return 'playing_time';
620 } else if (window.location.hash === '#per_point') {
627 function write_main_menu(chosen_category) {
629 if (chosen_category === 'general') {
630 let span = document.createElement('span');
631 span.innerText = 'General';
634 let a = document.createElement('a');
635 a.appendChild(document.createTextNode('General'));
636 a.setAttribute('href', '#general');
640 if (chosen_category === 'offense') {
641 let span = document.createElement('span');
642 span.innerText = 'Offense';
645 let a = document.createElement('a');
646 a.appendChild(document.createTextNode('Offense'));
647 a.setAttribute('href', '#offense');
651 if (chosen_category === 'defense') {
652 let span = document.createElement('span');
653 span.innerText = 'Defense';
656 let a = document.createElement('a');
657 a.appendChild(document.createTextNode('Defense'));
658 a.setAttribute('href', '#defense');
662 if (chosen_category === 'playing_time') {
663 let span = document.createElement('span');
664 span.innerText = 'Playing time';
667 let a = document.createElement('a');
668 a.appendChild(document.createTextNode('Playing time'));
669 a.setAttribute('href', '#playing_time');
673 if (chosen_category === 'per_point') {
674 let span = document.createElement('span');
675 span.innerText = 'Per point';
678 let a = document.createElement('a');
679 a.appendChild(document.createTextNode('Per point'));
680 a.setAttribute('href', '#per_point');
684 document.getElementById('mainmenu').replaceChildren(...elems);
687 // https://en.wikipedia.org/wiki/1.96#History
690 const ci_width = 100;
691 const ci_height = 20;
693 function make_binomial_ci(val, num, z) {
696 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
697 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
698 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
700 // Fix the signs so that we don't get -0.00.
701 low = Math.max(low, 0.0);
711 // These can only happen once per point, but you get -1 and +1
712 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
713 // and then we can rewrite back.
714 function make_efficiency_ci(points_won, points_completed, z)
716 let ci = make_binomial_ci(points_won, points_completed, z);
717 ci.val = 2.0 * ci.val - 1.0;
718 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
719 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
722 ci.desired = 0.0; // Desired = positive efficiency.
726 // Ds, throwaways and drops can happen multiple times per point,
727 // so they are Poisson distributed.
729 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
730 // since our rates are definitely below 2 per point).
731 function make_poisson_ci(val, num, z, inverted)
733 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
734 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
736 // Fix the signs so that we don't get -0.00.
737 low = Math.max(low, 0.0);
739 // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
748 'inverted': inverted,
752 function make_table_general(players) {
755 let header = document.createElement('tr');
756 add_th(header, 'Player');
757 add_th(header, '+/-');
758 add_th(header, 'Soft +/-');
759 add_th(header, 'O efficiency');
760 add_th(header, 'D efficiency');
761 add_th(header, 'Points played');
765 for (const [q,p] of get_sorted_players(players)) {
766 if (q === 'globals') continue;
767 let row = document.createElement('tr');
768 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
769 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
770 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
771 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
772 let name = add_3cell(row, p.name, 'name'); // TODO: number?
773 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
774 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
775 add_3cell_ci(row, o_efficiency);
776 add_3cell_ci(row, d_efficiency);
777 add_3cell(row, p.points_played);
778 row.dataset.player = q;
783 let globals = players['globals'];
784 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
785 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
786 let row = document.createElement('tr');
790 add_3cell_ci(row, o_efficiency);
791 add_3cell_ci(row, d_efficiency);
792 add_3cell(row, globals.points_played);
798 function make_table_offense(players) {
801 let header = document.createElement('tr');
802 add_th(header, 'Player');
803 add_th(header, 'Goals');
804 add_th(header, 'Assists');
805 add_th(header, 'Hockey assists');
806 add_th(header, 'Throws');
807 add_th(header, 'Throwaways');
808 add_th(header, '%OK');
809 add_th(header, 'Catches');
810 add_th(header, 'Drops');
811 add_th(header, 'D-ed');
812 add_th(header, '%OK');
813 add_th(header, 'Stalls');
814 add_th(header, 'Soft +/-', 6);
824 for (const [q,p] of get_sorted_players(players)) {
825 if (q === 'globals') continue;
826 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
827 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
829 throw_ok.format = 'percentage';
830 catch_ok.format = 'percentage';
832 // Desire at least 90% percentage. Fairly arbitrary.
833 throw_ok.desired = 0.9;
834 catch_ok.desired = 0.9;
836 let row = document.createElement('tr');
837 add_3cell(row, p.name, 'name'); // TODO: number?
838 add_3cell(row, p.goals);
839 add_3cell(row, p.assists);
840 add_3cell(row, p.hockey_assists);
841 add_3cell(row, p.num_throws);
842 add_3cell(row, p.throwaways);
843 add_3cell_ci(row, throw_ok);
844 add_3cell(row, p.catches);
845 add_3cell(row, p.drops);
846 add_3cell(row, p.was_ds);
847 add_3cell_ci(row, catch_ok);
848 add_3cell(row, p.stallouts);
849 add_3cell(row, '+' + p.offensive_soft_plus);
850 add_3cell(row, '-' + p.offensive_soft_minus);
851 row.dataset.player = q;
854 num_throws += p.num_throws;
855 throwaways += p.throwaways;
856 catches += p.catches;
859 stallouts += p.stallouts;
863 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
864 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
865 throw_ok.format = 'percentage';
866 catch_ok.format = 'percentage';
867 throw_ok.desired = 0.9;
868 catch_ok.desired = 0.9;
870 let row = document.createElement('tr');
875 add_3cell(row, num_throws);
876 add_3cell(row, throwaways);
877 add_3cell_ci(row, throw_ok);
878 add_3cell(row, catches);
879 add_3cell(row, drops);
880 add_3cell(row, was_ds);
881 add_3cell_ci(row, catch_ok);
882 add_3cell(row, stallouts);
890 function make_table_defense(players) {
893 let header = document.createElement('tr');
894 add_th(header, 'Player');
895 add_th(header, 'Ds');
896 add_th(header, 'Pulls');
897 add_th(header, 'OOB pulls');
898 add_th(header, 'OOB%');
899 add_th(header, 'Avg. hang time (IB)');
900 add_th(header, 'Soft +/-', 6);
903 for (const [q,p] of get_sorted_players(players)) {
904 if (q === 'globals') continue;
906 for (const t of p.pull_times) {
909 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
910 let oob_pct = 100 * p.oob_pulls / p.pulls;
912 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
913 ci_oob.format = 'percentage';
914 ci_oob.desired = 0.2; // Arbitrary.
915 ci_oob.inverted = true;
917 let row = document.createElement('tr');
918 add_3cell(row, p.name, 'name'); // TODO: number?
919 add_3cell(row, p.defenses);
920 add_3cell(row, p.pulls);
921 add_3cell(row, p.oob_pulls);
922 add_3cell_ci(row, ci_oob);
923 if (p.pulls > p.oob_pulls) {
924 add_3cell(row, avg_time.toFixed(1) + ' sec');
926 add_3cell(row, 'N/A');
928 add_3cell(row, '+' + p.defensive_soft_plus);
929 add_3cell(row, '-' + p.defensive_soft_minus);
930 row.dataset.player = q;
936 function make_table_playing_time(players) {
939 let header = document.createElement('tr');
940 add_th(header, 'Player');
941 add_th(header, 'Points played');
942 add_th(header, 'Time played');
943 add_th(header, 'O time');
944 add_th(header, 'D time');
945 add_th(header, 'Time on field');
946 add_th(header, 'O points');
947 add_th(header, 'D points');
951 for (const [q,p] of get_sorted_players(players)) {
952 if (q === 'globals') continue;
953 let row = document.createElement('tr');
954 add_3cell(row, p.name, 'name'); // TODO: number?
955 add_3cell(row, p.points_played);
956 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
957 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
958 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
959 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
960 add_3cell(row, p.offensive_points_completed);
961 add_3cell(row, p.defensive_points_completed);
962 row.dataset.player = q;
967 let globals = players['globals'];
968 let row = document.createElement('tr');
970 add_3cell(row, globals.points_played);
971 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
972 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
973 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
974 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
975 add_3cell(row, globals.offensive_points_completed);
976 add_3cell(row, globals.defensive_points_completed);
982 function make_table_per_point(players) {
985 let header = document.createElement('tr');
986 add_th(header, 'Player');
987 add_th(header, 'Goals');
988 add_th(header, 'Assists');
989 add_th(header, 'Hockey assists');
990 add_th(header, 'Ds');
991 add_th(header, 'Throwaways');
992 add_th(header, 'Recv. errors');
993 add_th(header, 'Touches');
999 let hockey_assists = 0;
1002 let receiver_errors = 0;
1004 for (const [q,p] of get_sorted_players(players)) {
1005 if (q === 'globals') continue;
1007 // Can only happen once per point, so these are binomials.
1008 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1009 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1010 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1011 // Arbitrarily desire at least 10% (not everybody can score or assist).
1012 ci_goals.desired = 0.1;
1013 ci_assists.desired = 0.1;
1014 ci_hockey_assists.desired = 0.1;
1016 let row = document.createElement('tr');
1017 add_3cell(row, p.name, 'name'); // TODO: number?
1018 add_3cell_ci(row, ci_goals);
1019 add_3cell_ci(row, ci_assists);
1020 add_3cell_ci(row, ci_hockey_assists);
1021 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1022 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1023 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1024 if (p.points_played > 0) {
1025 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1027 add_3cell(row, 'N/A');
1029 row.dataset.player = q;
1033 assists += p.assists;
1034 hockey_assists += p.hockey_assists;
1035 defenses += p.defenses;
1036 throwaways += p.throwaways;
1037 receiver_errors += p.drops + p.was_ds;
1038 touches += p.touches;
1042 let globals = players['globals'];
1043 let row = document.createElement('tr');
1045 if (globals.points_played > 0) {
1046 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
1047 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
1048 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
1049 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
1050 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
1051 add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
1052 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1054 add_3cell_with_filler_ci(row, 'N/A');
1055 add_3cell_with_filler_ci(row, 'N/A');
1056 add_3cell_with_filler_ci(row, 'N/A');
1057 add_3cell_with_filler_ci(row, 'N/A');
1058 add_3cell_with_filler_ci(row, 'N/A');
1059 add_3cell_with_filler_ci(row, 'N/A');
1060 add_3cell(row, 'N/A');
1067 function open_filter_menu() {
1068 document.getElementById('filter-submenu').style.display = 'none';
1070 let menu = document.getElementById('filter-add-menu');
1071 menu.style.display = 'block';
1072 menu.replaceChildren();
1074 // Place the menu directly under the “click to add” label;
1075 // we don't anchor it since that label will move around
1076 // and the menu shouldn't.
1077 let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1078 menu.style.left = rect.left + 'px';
1079 menu.style.top = (rect.bottom + 10) + 'px';
1081 add_menu_item(menu, 0, 'match', 'Match (any)');
1082 add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
1083 add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
1084 add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
1085 add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
1088 function add_menu_item(menu, menu_idx, filter_type, title) {
1089 let item = document.createElement('div');
1090 item.classList.add('option');
1091 item.appendChild(document.createTextNode(title));
1093 let arrow = document.createElement('div');
1094 arrow.classList.add('arrow');
1095 arrow.textContent = '▸';
1096 item.appendChild(arrow);
1098 menu.appendChild(item);
1100 item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
1103 function show_submenu(menu_idx, pill, filter_type) {
1104 let submenu = document.getElementById('filter-submenu');
1106 const filter = find_filter(filter_type);
1109 if (filter_type === 'match') {
1110 for (const match of global_json['matches']) {
1112 'title': match['description'],
1113 'id': match['match_id']
1116 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1117 for (const player of global_json['players']) {
1119 'title': player['name'],
1120 'id': player['player_id']
1123 } else if (filter_type === 'formation_offense') {
1125 'title': '(None/unknown)',
1128 for (const formation of global_json['formations']) {
1129 if (formation['offense']) {
1131 'title': formation['name'],
1132 'id': formation['formation_id']
1136 } else if (filter_type === 'formation_defense') {
1138 'title': '(None/unknown)',
1141 for (const formation of global_json['formations']) {
1142 if (!formation['offense']) {
1144 'title': formation['name'],
1145 'id': formation['formation_id']
1151 for (const choice of choices) {
1152 let label = document.createElement('label');
1154 let subitem = document.createElement('div');
1155 subitem.classList.add('option');
1157 let check = document.createElement('input');
1158 check.setAttribute('type', 'checkbox');
1159 check.setAttribute('id', 'choice' + choice.id);
1160 if (filter !== null && filter.elements.has(choice.id)) {
1161 check.setAttribute('checked', 'checked');
1163 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1165 subitem.appendChild(check);
1166 subitem.appendChild(document.createTextNode(choice.title));
1168 label.appendChild(subitem);
1169 subitems.push(label);
1171 submenu.replaceChildren(...subitems);
1172 submenu.style.display = 'block';
1174 if (pill !== null) {
1175 let rect = pill.getBoundingClientRect();
1176 submenu.style.top = (rect.bottom + 10) + 'px';
1177 submenu.style.left = rect.left + 'px';
1179 // Position just outside the selected menu.
1180 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1181 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1182 submenu.style.left = (rect.right - 1) + 'px';
1186 // Find the right filter, if it exists.
1187 function find_filter(filter_type) {
1188 for (let f of global_filters) {
1189 if (f.type === filter_type) {
1196 function checkbox_changed(e, filter_type, id) {
1197 let filter = find_filter(filter_type);
1198 if (e.target.checked) {
1199 // See if we must add a new filter to the list.
1200 if (filter === null) {
1202 'type': filter_type,
1203 'elements': new Set([ id ]),
1205 filter.pill = make_filter_pill(filter);
1206 global_filters.push(filter);
1207 document.getElementById('filters').appendChild(filter.pill);
1209 filter.elements.add(id);
1210 let new_pill = make_filter_pill(filter);
1211 document.getElementById('filters').replaceChild(new_pill, filter.pill);
1212 filter.pill = new_pill;
1215 filter.elements.delete(id);
1216 if (filter.elements.size === 0) {
1217 document.getElementById('filters').removeChild(filter.pill);
1218 global_filters = global_filters.filter(f => f !== filter);
1220 let new_pill = make_filter_pill(filter);
1221 document.getElementById('filters').replaceChild(new_pill, filter.pill);
1222 filter.pill = new_pill;
1226 process_matches(global_json, global_filters);
1229 function make_filter_pill(filter) {
1230 let pill = document.createElement('div');
1231 pill.classList.add('filter-pill');
1233 if (filter.type === 'match') {
1237 for (const match_id of filter.elements) {
1238 all_names.push(find_match(match_id)['description']);
1240 let common_prefix = find_common_prefix_of_all(all_names);
1241 if (common_prefix !== null) {
1242 text += common_prefix + '(';
1246 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1247 for (const match_id of sorted_match_id) {
1251 let desc = find_match(match_id)['description'];
1252 if (common_prefix === null) {
1255 text += desc.substr(common_prefix.length);
1260 if (common_prefix !== null) {
1263 } else if (filter.type === 'player_any') {
1264 text = 'Player (any): ';
1265 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1267 for (const player_id of sorted_players) {
1271 text += find_player(player_id)['name'];
1274 } else if (filter.type === 'player_all') {
1276 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1278 for (const player_id of sorted_players) {
1282 text += find_player(player_id)['name'];
1285 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1286 const offense = (filter.type === 'formation_offense');
1294 for (const formation_id of filter.elements) {
1295 all_names.push(find_formation(formation_id)['name']);
1297 let common_prefix = find_common_prefix_of_all(all_names);
1298 if (common_prefix !== null) {
1299 text += common_prefix + '(';
1303 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1304 for (const formation_id of sorted_formation_id) {
1308 let desc = find_formation(formation_id)['name'];
1309 if (common_prefix === null) {
1312 text += desc.substr(common_prefix.length);
1317 if (common_prefix !== null) {
1322 let text_node = document.createElement('span');
1323 text_node.innerText = text;
1324 text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1325 pill.appendChild(text_node);
1327 pill.appendChild(document.createTextNode(' '));
1329 let delete_node = document.createElement('span');
1330 delete_node.innerText = '✖';
1331 delete_node.addEventListener('click', (e) => {
1332 // Delete this filter entirely.
1333 document.getElementById('filters').removeChild(pill);
1334 global_filters = global_filters.filter(f => f !== filter);
1335 process_matches(global_json, global_filters);
1337 let add_menu = document.getElementById('filter-add-menu');
1338 let add_submenu = document.getElementById('filter-submenu');
1339 add_menu.style.display = 'none';
1340 add_submenu.style.display = 'none';
1342 pill.appendChild(delete_node);
1343 pill.style.cursor = 'pointer';
1348 function find_common_prefix(a, b) {
1350 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1351 if (a[i] === b[i]) {
1360 function find_common_prefix_of_all(values) {
1361 if (values.length < 2) {
1364 let common_prefix = null;
1365 for (const desc of values) {
1366 if (common_prefix === null) {
1367 common_prefix = desc;
1369 common_prefix = find_common_prefix(common_prefix, desc);
1372 if (common_prefix.length >= 3) {
1373 return common_prefix;
1379 function find_match(match_id) {
1380 for (const match of global_json['matches']) {
1381 if (match['match_id'] === match_id) {
1388 function find_formation(formation_id) {
1389 for (const formation of global_json['formations']) {
1390 if (formation['formation_id'] === formation_id) {
1397 function find_player(player_id) {
1398 for (const player of global_json['players']) {
1399 if (player['player_id'] === player_id) {
1406 function player_pos(player_id) {
1408 for (const player of global_json['players']) {
1409 if (player['player_id'] === player_id) {
1417 function keep_match(match_id, filters) {
1418 for (const filter of filters) {
1419 if (filter.type === 'match') {
1420 return filter.elements.has(match_id);
1426 function filter_passes(players, formations_used_this_point, filter) {
1427 if (filter.type === 'player_any') {
1428 for (const p of Array.from(filter.elements)) {
1429 if (players[p].on_field_since !== null) {
1434 } else if (filter.type === 'player_all') {
1435 for (const p of Array.from(filter.elements)) {
1436 if (players[p].on_field_since === null) {
1441 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1442 for (const f of Array.from(filter.elements)) {
1443 if (formations_used_this_point.has(f)) {
1452 function keep_event(players, formations_used_this_point, filters) {
1453 for (const filter of filters) {
1454 if (!filter_passes(players, formations_used_this_point, filter)) {
1461 // Heuristic: If we go at least ten seconds without the possession changing
1462 // or the operator specifying some other formation, we probably play the
1463 // same formation as the last point.
1464 function should_reuse_last_formation(events, t) {
1465 for (const e of events) {
1469 if (e.t > t + 10000) {
1472 const type = e.type;
1473 if (type === 'their_goal' || type === 'goal' ||
1474 type === 'set_defense' || type === 'set_offense' ||
1475 type === 'throwaway' || type === 'their_throwaway' ||
1476 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1477 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1478 type === 'formation_offense' || type === 'formation_defense') {
1485 function possibly_close_menu(e) {
1486 if (e.target.closest('#filter-click-to-add') === null &&
1487 e.target.closest('#filter-add-menu') === null &&
1488 e.target.closest('#filter-submenu') === null &&
1489 e.target.closest('.filter-pill') === null) {
1490 let add_menu = document.getElementById('filter-add-menu');
1491 let add_submenu = document.getElementById('filter-submenu');
1492 add_menu.style.display = 'none';
1493 add_submenu.style.display = 'none';
1497 let global_sort = {};
1499 function sort_by(th) {
1500 let tr = th.parentElement;
1502 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1503 let element = tr.children[column_idx];
1504 if (element === th) {
1505 ++child_idx; // Pad.
1508 if (element.hasAttribute('colspan')) {
1509 child_idx += parseInt(element.getAttribute('colspan'));
1516 let table = tr.parentElement;
1517 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
1518 let row = table.children[row_idx];
1519 let player = parseInt(row.dataset.player);
1520 let value = row.children[child_idx].textContent;
1521 global_sort[player] = value;
1525 function get_sorted_players(players)
1527 let p = Object.entries(players);
1528 if (global_sort.length !== 0) {
1530 let ai = parseFloat(global_sort[a[0]]);
1531 let bi = parseFloat(global_sort[b[0]]);
1532 if (ai == ai && bi == bi) {
1533 return bi - ai; // Reverse numeric.
1534 } else if (global_sort[a[0]] < global_sort[b[0]]) {
1536 } else if (global_sort[a[0]] > global_sort[b[0]]) {