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 'gender': player['gender'],
179 'number': player['number'],
195 'playing_time_ms': 0,
196 'offensive_playing_time_ms': 0,
197 'defensive_playing_time_ms': 0,
201 'offensive_points_completed': 0,
202 'offensive_points_won': 0,
203 'defensive_points_completed': 0,
204 'defensive_points_won': 0,
206 'offensive_soft_plus': 0,
207 'offensive_soft_minus': 0,
208 'defensive_soft_plus': 0,
209 'defensive_soft_minus': 0,
216 'last_point_seen': null,
217 'on_field_since': null,
222 players['globals'] = {
224 'playing_time_ms': 0,
225 'offensive_playing_time_ms': 0,
226 'defensive_playing_time_ms': 0,
229 'offensive_points_completed': 0,
230 'offensive_points_won': 0,
231 'defensive_points_completed': 0,
232 'defensive_points_won': 0,
234 let globals = players['globals'];
236 for (const match of json['matches']) {
237 if (!keep_match(match['match_id'], filters)) {
244 let handler_got_by_interception = false; // Only relevant if handler !== null.
245 let prev_handler = null;
246 let live_since = null;
247 let offense = null; // True/false/null (unknown).
249 let pull_started = null;
250 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
252 let game_started = null;
253 let last_goal = null;
255 // The last used formations of the given kind, if any; they may be reused
256 // when the point starts, if nothing else is set.
257 let last_offensive_formation = null;
258 let last_defensive_formation = null;
260 // Formations we've set, but haven't really had the chance to use yet
261 // (e.g., we get a “use zone defense” event while we're still on offense).
262 let pending_offensive_formation = null;
263 let pending_defensive_formation = null;
265 // Formations that we have played at least once this point, after all
266 // heuristics and similar.
267 let formations_used_this_point = new Set();
269 for (const [q,p] of Object.entries(players)) {
270 p.on_field_since = null;
271 p.last_point_seen = null;
273 for (const e of match['events']) {
275 let type = e['type'];
276 let p = players[e['player']];
279 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
280 if (type === 'in' && p.on_field_since === null) {
281 p.on_field_since = t;
282 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
283 // A player needed for the filters went onto the field,
284 // so pretend people walked on right now (to start their
286 for (const [q,p2] of Object.entries(players)) {
287 if (p2.on_field_since !== null) {
288 p2.on_field_since = t;
292 } else if (type === 'out') {
293 take_off_field(p, t, live_since, offense, keep);
294 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
295 // A player needed for the filters went off the field,
296 // so we need to attribute time for all the others.
297 // Pretend they walked off and then immediately on again.
299 // TODO: We also need to take care of this to get the globals right.
300 for (const [q,p2] of Object.entries(players)) {
301 if (p2.on_field_since !== null) {
302 take_off_field(p2, t, live_since, offense, keep);
303 p2.on_field_since = t;
309 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
311 // Liveness management
312 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
314 } else if (type === 'catch' && last_pull_was_ours === null) {
315 // Someone forgot to add the pull, so we'll need to wing it.
316 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
318 last_pull_was_ours = !offense;
319 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
320 for (const [q,p] of Object.entries(players)) {
321 if (p.on_field_since === null) {
324 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
326 // In case the player did nothing this point,
327 // not even subbing in.
328 p.last_point_seen = point_num;
332 if (keep) attribute_player_time(p, t, live_since, offense);
334 if (type !== 'stoppage') {
336 if (last_pull_was_ours === true) { // D point.
337 ++p.defensive_points_completed;
338 if (type === 'goal') {
339 ++p.defensive_points_won;
341 } else if (last_pull_was_ours === false) { // O point.
342 ++p.offensive_points_completed;
343 if (type === 'goal') {
344 ++p.offensive_points_won;
352 if (type !== 'stoppage') {
354 ++globals.points_played;
355 if (last_pull_was_ours === true) { // D point.
356 ++globals.defensive_points_completed;
357 if (type === 'goal') {
358 ++globals.defensive_points_won;
360 } else if (last_pull_was_ours === false) { // O point.
361 ++globals.offensive_points_completed;
362 if (type === 'goal') {
363 ++globals.offensive_points_won;
367 if (live_since !== null) {
368 globals.playing_time_ms += t - live_since;
369 if (offense === true) {
370 globals.offensive_playing_time_ms += t - live_since;
371 } else if (offense === false) {
372 globals.defensive_playing_time_ms += t - live_since;
381 if (type === 'goal') {
383 } else if (type === 'their_goal') {
387 // Point count management
388 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
390 p.last_point_seen = point_num;
394 if (type === 'goal' || type === 'their_goal') {
398 if (type !== 'out' && game_started === null) {
403 if (type === 'pull') {
404 puller = e['player'];
407 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
408 // No effect on pull.
409 } else if (type === 'pull_landed' && puller !== null) {
410 if (keep) players[puller].pull_times.push(t - pull_started);
411 } else if (type === 'pull_oob' && puller !== null) {
412 if (keep) ++players[puller].oob_pulls;
414 // Not pulling (if there was one, we never recorded its outcome, but still count it).
415 puller = pull_started = null;
418 // Offense/defense management
419 let last_offense = offense;
420 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
422 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
425 if (last_offense !== offense && live_since !== null) {
426 // Switched offense/defense status, so attribute this drive as needed,
427 // and update live_since to take that into account.
429 for (const [q,p] of Object.entries(players)) {
430 if (p.on_field_since === null) {
433 attribute_player_time(p, t, live_since, last_offense);
435 globals.playing_time_ms += t - live_since;
436 if (offense === true) {
437 globals.offensive_playing_time_ms += t - live_since;
438 } else if (offense === false) {
439 globals.defensive_playing_time_ms += t - live_since;
445 if (type === 'pull') {
446 last_pull_was_ours = true;
447 } else if (type === 'their_pull') {
448 last_pull_was_ours = false;
449 } else if (type === 'set_offense' && last_pull_was_ours === null) {
450 // set_offense could either be “changed to offense for some reason
451 // we could not express”, or “we started in the middle of a point,
452 // and we are offense”. We assume that if we already saw the pull,
453 // it's the former, and if not, it's the latter; thus, the === null
454 // test above. (It could also be “we set offense before the pull,
455 // so that we get the right button enabled”, in which case it will
456 // be overwritten by the next pull/their_pull event anyway.)
457 last_pull_was_ours = false;
458 } else if (type === 'set_defense' && last_pull_was_ours === null) {
460 last_pull_was_ours = true;
461 } else if (type === 'goal' || type === 'their_goal') {
462 last_pull_was_ours = null;
465 // Formation management
466 if (type === 'formation_offense' || type === 'formation_defense') {
467 let id = e.formation === null ? 0 : e.formation;
468 let for_offense = (type === 'formation_offense');
469 if (offense === for_offense) {
470 formations_used_this_point.add(id);
471 } else if (for_offense) {
472 pending_offensive_formation = id;
474 pending_defensive_formation = id;
477 last_offensive_formation = id;
479 last_defensive_formation = id;
481 } else if (last_offense !== offense) {
482 if (offense === true && pending_offensive_formation !== null) {
483 formations_used_this_point.add(pending_offensive_formation);
484 pending_offensive_formation = null;
485 } else if (offense === false && pending_defensive_formation !== null) {
486 formations_used_this_point.add(pending_defensive_formation);
487 pending_defensive_formation = null;
488 } else if (offense === true && last_defensive_formation !== null) {
489 if (should_reuse_last_formation(match['events'], t)) {
490 formations_used_this_point.add(last_defensive_formation);
492 } else if (offense === false && last_offensive_formation !== null) {
493 if (should_reuse_last_formation(match['events'], t)) {
494 formations_used_this_point.add(last_offensive_formation);
499 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
500 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
502 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
503 // The handler subbed out and was replaced with another handler,
504 // so this wasn't a pass.
509 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
510 // Self-pass to goal after an interception; this is not a real pass,
511 // just how we represent a Callahan right now -- so don't
512 // count the throw, any assists or similar.
514 // It's an open question how we should handle a self-pass that is
515 // _not_ after an interception, or a self-pass that's not a goal.
516 // (It must mean we tipped off someone.) We'll count it as a regular one
517 // for the time being, although it will make hockey assists weird.
520 handler = prev_handler = null;
521 } else if (type === 'catch' || type === 'goal') {
522 if (handler !== null) {
524 ++players[handler].num_throws;
529 if (keep) ++p.touches;
530 if (type === 'goal') {
532 if (prev_handler !== null) {
533 ++players[prev_handler].hockey_assists;
535 if (handler !== null) {
536 ++players[handler].assists;
540 handler = prev_handler = null;
542 // Update hold history.
543 prev_handler = handler;
544 handler = e['player'];
545 handler_got_by_interception = false;
547 } else if (type === 'throwaway') {
552 handler = prev_handler = null;
553 } else if (type === 'drop') {
555 handler = prev_handler = null;
556 } else if (type === 'stallout') {
557 if (keep) ++p.stallouts;
558 handler = prev_handler = null;
559 } else if (type === 'was_d') {
560 if (keep) ++p.was_ds;
561 handler = prev_handler = null;
562 } else if (type === 'defense') {
563 if (keep) ++p.defenses;
564 } else if (type === 'interception') {
571 handler = e['player'];
572 handler_got_by_interception = true;
573 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
575 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
576 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
577 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
578 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
579 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
580 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
581 type !== 'formation_offense' && type !== 'formation_defense') {
582 console.log(format_time(t) + ": Unknown event “" + e + "”");
585 if (type === 'goal' || type === 'their_goal') {
586 formations_used_this_point.clear();
590 // Add field time for all players still left at match end.
591 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
593 for (const [q,p] of Object.entries(players)) {
594 if (p.on_field_since !== null && last_goal !== null) {
595 p.field_time_ms += last_goal - p.on_field_since;
598 if (game_started !== null && last_goal !== null) {
599 globals.field_time_ms += last_goal - game_started;
601 if (live_since !== null && last_goal !== null) {
602 globals.playing_time_ms += last_goal - live_since;
603 if (offense === true) {
604 globals.offensive_playing_time_ms += last_goal - live_since;
605 } else if (offense === false) {
606 globals.defensive_playing_time_ms += last_goal - live_since;
612 let chosen_category = get_chosen_category();
613 write_main_menu(chosen_category);
616 if (chosen_category === 'general') {
617 rows = make_table_general(players);
618 } else if (chosen_category === 'offense') {
619 rows = make_table_offense(players);
620 } else if (chosen_category === 'defense') {
621 rows = make_table_defense(players);
622 } else if (chosen_category === 'playing_time') {
623 rows = make_table_playing_time(players);
624 } else if (chosen_category === 'per_point') {
625 rows = make_table_per_point(players);
627 document.getElementById('stats').replaceChildren(...rows);
630 function get_chosen_category() {
631 if (window.location.hash === '#offense') {
633 } else if (window.location.hash === '#defense') {
635 } else if (window.location.hash === '#playing_time') {
636 return 'playing_time';
637 } else if (window.location.hash === '#per_point') {
644 function write_main_menu(chosen_category) {
646 if (chosen_category === 'general') {
647 let span = document.createElement('span');
648 span.innerText = 'General';
651 let a = document.createElement('a');
652 a.appendChild(document.createTextNode('General'));
653 a.setAttribute('href', '#general');
657 if (chosen_category === 'offense') {
658 let span = document.createElement('span');
659 span.innerText = 'Offense';
662 let a = document.createElement('a');
663 a.appendChild(document.createTextNode('Offense'));
664 a.setAttribute('href', '#offense');
668 if (chosen_category === 'defense') {
669 let span = document.createElement('span');
670 span.innerText = 'Defense';
673 let a = document.createElement('a');
674 a.appendChild(document.createTextNode('Defense'));
675 a.setAttribute('href', '#defense');
679 if (chosen_category === 'playing_time') {
680 let span = document.createElement('span');
681 span.innerText = 'Playing time';
684 let a = document.createElement('a');
685 a.appendChild(document.createTextNode('Playing time'));
686 a.setAttribute('href', '#playing_time');
690 if (chosen_category === 'per_point') {
691 let span = document.createElement('span');
692 span.innerText = 'Per point';
695 let a = document.createElement('a');
696 a.appendChild(document.createTextNode('Per point'));
697 a.setAttribute('href', '#per_point');
701 document.getElementById('mainmenu').replaceChildren(...elems);
704 // https://en.wikipedia.org/wiki/1.96#History
707 const ci_width = 100;
708 const ci_height = 20;
710 function make_binomial_ci(val, num, z) {
713 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
714 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
715 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
717 // Fix the signs so that we don't get -0.00.
718 low = Math.max(low, 0.0);
728 // These can only happen once per point, but you get -1 and +1
729 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
730 // and then we can rewrite back.
731 function make_efficiency_ci(points_won, points_completed, z)
733 let ci = make_binomial_ci(points_won, points_completed, z);
734 ci.val = 2.0 * ci.val - 1.0;
735 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
736 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
739 ci.desired = 0.0; // Desired = positive efficiency.
743 // Ds, throwaways and drops can happen multiple times per point,
744 // so they are Poisson distributed.
746 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
747 // since our rates are definitely below 2 per point).
748 function make_poisson_ci(val, num, z, inverted)
750 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
751 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
753 // Fix the signs so that we don't get -0.00.
754 low = Math.max(low, 0.0);
756 // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
765 'inverted': inverted,
769 function make_table_general(players) {
772 let header = document.createElement('tr');
773 add_th(header, 'Player');
774 add_th(header, '+/-');
775 add_th(header, 'Soft +/-');
776 add_th(header, 'O efficiency');
777 add_th(header, 'D efficiency');
778 add_th(header, 'Points played');
782 for (const [q,p] of get_sorted_players(players)) {
783 if (q === 'globals') continue;
784 let row = document.createElement('tr');
785 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
786 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
787 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
788 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
789 let name = add_3cell(row, p.name, 'name'); // TODO: number?
790 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
791 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
792 add_3cell_ci(row, o_efficiency);
793 add_3cell_ci(row, d_efficiency);
794 add_3cell(row, p.points_played);
795 row.dataset.player = q;
800 let globals = players['globals'];
801 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
802 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
803 let row = document.createElement('tr');
807 add_3cell_ci(row, o_efficiency);
808 add_3cell_ci(row, d_efficiency);
809 add_3cell(row, globals.points_played);
815 function make_table_offense(players) {
818 let header = document.createElement('tr');
819 add_th(header, 'Player');
820 add_th(header, 'Goals');
821 add_th(header, 'Assists');
822 add_th(header, 'Hockey assists');
823 add_th(header, 'Throws');
824 add_th(header, 'Throwaways');
825 add_th(header, '%OK');
826 add_th(header, 'Catches');
827 add_th(header, 'Drops');
828 add_th(header, 'D-ed');
829 add_th(header, '%OK');
830 add_th(header, 'Stalls');
831 add_th(header, 'Soft +/-', 6);
841 for (const [q,p] of get_sorted_players(players)) {
842 if (q === 'globals') continue;
843 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
844 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
846 throw_ok.format = 'percentage';
847 catch_ok.format = 'percentage';
849 // Desire at least 90% percentage. Fairly arbitrary.
850 throw_ok.desired = 0.9;
851 catch_ok.desired = 0.9;
853 let row = document.createElement('tr');
854 add_3cell(row, p.name, 'name'); // TODO: number?
855 add_3cell(row, p.goals);
856 add_3cell(row, p.assists);
857 add_3cell(row, p.hockey_assists);
858 add_3cell(row, p.num_throws);
859 add_3cell(row, p.throwaways);
860 add_3cell_ci(row, throw_ok);
861 add_3cell(row, p.catches);
862 add_3cell(row, p.drops);
863 add_3cell(row, p.was_ds);
864 add_3cell_ci(row, catch_ok);
865 add_3cell(row, p.stallouts);
866 add_3cell(row, '+' + p.offensive_soft_plus);
867 add_3cell(row, '-' + p.offensive_soft_minus);
868 row.dataset.player = q;
871 num_throws += p.num_throws;
872 throwaways += p.throwaways;
873 catches += p.catches;
876 stallouts += p.stallouts;
880 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
881 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
882 throw_ok.format = 'percentage';
883 catch_ok.format = 'percentage';
884 throw_ok.desired = 0.9;
885 catch_ok.desired = 0.9;
887 let row = document.createElement('tr');
892 add_3cell(row, num_throws);
893 add_3cell(row, throwaways);
894 add_3cell_ci(row, throw_ok);
895 add_3cell(row, catches);
896 add_3cell(row, drops);
897 add_3cell(row, was_ds);
898 add_3cell_ci(row, catch_ok);
899 add_3cell(row, stallouts);
907 function make_table_defense(players) {
910 let header = document.createElement('tr');
911 add_th(header, 'Player');
912 add_th(header, 'Ds');
913 add_th(header, 'Pulls');
914 add_th(header, 'OOB pulls');
915 add_th(header, 'OOB%');
916 add_th(header, 'Avg. hang time (IB)');
917 add_th(header, 'Callahans');
918 add_th(header, 'Soft +/-', 6);
921 for (const [q,p] of get_sorted_players(players)) {
922 if (q === 'globals') continue;
924 for (const t of p.pull_times) {
927 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
928 let oob_pct = 100 * p.oob_pulls / p.pulls;
930 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
931 ci_oob.format = 'percentage';
932 ci_oob.desired = 0.2; // Arbitrary.
933 ci_oob.inverted = true;
935 let row = document.createElement('tr');
936 add_3cell(row, p.name, 'name'); // TODO: number?
937 add_3cell(row, p.defenses);
938 add_3cell(row, p.pulls);
939 add_3cell(row, p.oob_pulls);
940 add_3cell_ci(row, ci_oob);
941 if (p.pulls > p.oob_pulls) {
942 add_3cell(row, avg_time.toFixed(1) + ' sec');
944 add_3cell(row, 'N/A');
946 add_3cell(row, p.callahans);
947 add_3cell(row, '+' + p.defensive_soft_plus);
948 add_3cell(row, '-' + p.defensive_soft_minus);
949 row.dataset.player = q;
955 function make_table_playing_time(players) {
958 let header = document.createElement('tr');
959 add_th(header, 'Player');
960 add_th(header, 'Points played');
961 add_th(header, 'Time played');
962 add_th(header, 'O time');
963 add_th(header, 'D time');
964 add_th(header, 'Time on field');
965 add_th(header, 'O points');
966 add_th(header, 'D points');
970 for (const [q,p] of get_sorted_players(players)) {
971 if (q === 'globals') continue;
972 let row = document.createElement('tr');
973 add_3cell(row, p.name, 'name'); // TODO: number?
974 add_3cell(row, p.points_played);
975 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
976 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
977 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
978 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
979 add_3cell(row, p.offensive_points_completed);
980 add_3cell(row, p.defensive_points_completed);
981 row.dataset.player = q;
986 let globals = players['globals'];
987 let row = document.createElement('tr');
989 add_3cell(row, globals.points_played);
990 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
991 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
992 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
993 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
994 add_3cell(row, globals.offensive_points_completed);
995 add_3cell(row, globals.defensive_points_completed);
1001 function make_table_per_point(players) {
1004 let header = document.createElement('tr');
1005 add_th(header, 'Player');
1006 add_th(header, 'Goals');
1007 add_th(header, 'Assists');
1008 add_th(header, 'Hockey assists');
1009 add_th(header, 'Ds');
1010 add_th(header, 'Throwaways');
1011 add_th(header, 'Recv. errors');
1012 add_th(header, 'Touches');
1018 let hockey_assists = 0;
1021 let receiver_errors = 0;
1023 for (const [q,p] of get_sorted_players(players)) {
1024 if (q === 'globals') continue;
1026 // Can only happen once per point, so these are binomials.
1027 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1028 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1029 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1030 // Arbitrarily desire at least 10% (not everybody can score or assist).
1031 ci_goals.desired = 0.1;
1032 ci_assists.desired = 0.1;
1033 ci_hockey_assists.desired = 0.1;
1035 let row = document.createElement('tr');
1036 add_3cell(row, p.name, 'name'); // TODO: number?
1037 add_3cell_ci(row, ci_goals);
1038 add_3cell_ci(row, ci_assists);
1039 add_3cell_ci(row, ci_hockey_assists);
1040 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1041 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1042 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1043 if (p.points_played > 0) {
1044 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1046 add_3cell(row, 'N/A');
1048 row.dataset.player = q;
1052 assists += p.assists;
1053 hockey_assists += p.hockey_assists;
1054 defenses += p.defenses;
1055 throwaways += p.throwaways;
1056 receiver_errors += p.drops + p.was_ds;
1057 touches += p.touches;
1061 let globals = players['globals'];
1062 let row = document.createElement('tr');
1064 if (globals.points_played > 0) {
1065 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
1066 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
1067 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
1068 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
1069 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
1070 add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
1071 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1073 add_3cell_with_filler_ci(row, 'N/A');
1074 add_3cell_with_filler_ci(row, 'N/A');
1075 add_3cell_with_filler_ci(row, 'N/A');
1076 add_3cell_with_filler_ci(row, 'N/A');
1077 add_3cell_with_filler_ci(row, 'N/A');
1078 add_3cell_with_filler_ci(row, 'N/A');
1079 add_3cell(row, 'N/A');
1086 function open_filter_menu() {
1087 document.getElementById('filter-submenu').style.display = 'none';
1089 let menu = document.getElementById('filter-add-menu');
1090 menu.style.display = 'block';
1091 menu.replaceChildren();
1093 // Place the menu directly under the “click to add” label;
1094 // we don't anchor it since that label will move around
1095 // and the menu shouldn't.
1096 let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1097 menu.style.left = rect.left + 'px';
1098 menu.style.top = (rect.bottom + 10) + 'px';
1100 add_menu_item(menu, 0, 'match', 'Match (any)');
1101 add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
1102 add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
1103 add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
1104 add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
1105 add_menu_item(menu, 5, 'starting_on', 'Starting on');
1106 add_menu_item(menu, 6, 'gender_ratio', 'Gender ratio');
1109 function add_menu_item(menu, menu_idx, filter_type, title) {
1110 let item = document.createElement('div');
1111 item.classList.add('option');
1112 item.appendChild(document.createTextNode(title));
1114 let arrow = document.createElement('div');
1115 arrow.classList.add('arrow');
1116 arrow.textContent = '▸';
1117 item.appendChild(arrow);
1119 menu.appendChild(item);
1121 item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
1124 function find_all_ratios(json)
1128 for (const player of json['players']) {
1129 players[player['player_id']] = {
1130 'gender': player['gender'],
1131 'last_point_seen': null,
1134 for (const match of json['matches']) {
1135 for (const [q,p] of Object.entries(players)) {
1136 p.on_field_since = null;
1138 for (const e of match['events']) {
1139 let p = players[e['player']];
1140 let type = e['type'];
1141 if (type === 'in') {
1142 p.on_field_since = 1;
1143 } else if (type === 'out') {
1144 p.on_field_since = null;
1145 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1146 let code = find_gender_ratio_code(players);
1147 if (ratios[code] === undefined) {
1148 ratios[code] = code;
1149 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1150 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1151 match['description'] + ', ' + format_time(e['t']));
1160 function show_submenu(menu_idx, pill, filter_type) {
1161 let submenu = document.getElementById('filter-submenu');
1163 const filter = find_filter(filter_type);
1166 if (filter_type === 'match') {
1167 for (const match of global_json['matches']) {
1169 'title': match['description'],
1170 'id': match['match_id']
1173 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1174 for (const player of global_json['players']) {
1176 'title': player['name'],
1177 'id': player['player_id']
1180 } else if (filter_type === 'formation_offense') {
1182 'title': '(None/unknown)',
1185 for (const formation of global_json['formations']) {
1186 if (formation['offense']) {
1188 'title': formation['name'],
1189 'id': formation['formation_id']
1193 } else if (filter_type === 'formation_defense') {
1195 'title': '(None/unknown)',
1198 for (const formation of global_json['formations']) {
1199 if (!formation['offense']) {
1201 'title': formation['name'],
1202 'id': formation['formation_id']
1206 } else if (filter_type === 'starting_on') {
1209 'id': false, // last_pull_was_ours
1213 'id': true, // last_pull_was_ours
1215 } else if (filter_type === 'gender_ratio') {
1216 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1224 for (const choice of choices) {
1225 let label = document.createElement('label');
1227 let subitem = document.createElement('div');
1228 subitem.classList.add('option');
1230 let check = document.createElement('input');
1231 check.setAttribute('type', 'checkbox');
1232 check.setAttribute('id', 'choice' + choice.id);
1233 if (filter !== null && filter.elements.has(choice.id)) {
1234 check.setAttribute('checked', 'checked');
1236 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1238 subitem.appendChild(check);
1239 subitem.appendChild(document.createTextNode(choice.title));
1241 label.appendChild(subitem);
1242 subitems.push(label);
1244 submenu.replaceChildren(...subitems);
1245 submenu.style.display = 'block';
1247 if (pill !== null) {
1248 let rect = pill.getBoundingClientRect();
1249 submenu.style.top = (rect.bottom + 10) + 'px';
1250 submenu.style.left = rect.left + 'px';
1252 // Position just outside the selected menu.
1253 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1254 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1255 submenu.style.left = (rect.right - 1) + 'px';
1259 // Find the right filter, if it exists.
1260 function find_filter(filter_type) {
1261 for (let f of global_filters) {
1262 if (f.type === filter_type) {
1269 function checkbox_changed(e, filter_type, id) {
1270 let filter = find_filter(filter_type);
1271 if (e.target.checked) {
1272 // See if we must add a new filter to the list.
1273 if (filter === null) {
1275 'type': filter_type,
1276 'elements': new Set([ id ]),
1278 filter.pill = make_filter_pill(filter);
1279 global_filters.push(filter);
1280 document.getElementById('filters').appendChild(filter.pill);
1282 filter.elements.add(id);
1283 let new_pill = make_filter_pill(filter);
1284 document.getElementById('filters').replaceChild(new_pill, filter.pill);
1285 filter.pill = new_pill;
1288 filter.elements.delete(id);
1289 if (filter.elements.size === 0) {
1290 document.getElementById('filters').removeChild(filter.pill);
1291 global_filters = global_filters.filter(f => f !== filter);
1293 let new_pill = make_filter_pill(filter);
1294 document.getElementById('filters').replaceChild(new_pill, filter.pill);
1295 filter.pill = new_pill;
1299 process_matches(global_json, global_filters);
1302 function make_filter_pill(filter) {
1303 let pill = document.createElement('div');
1304 pill.classList.add('filter-pill');
1306 if (filter.type === 'match') {
1310 for (const match_id of filter.elements) {
1311 all_names.push(find_match(match_id)['description']);
1313 let common_prefix = find_common_prefix_of_all(all_names);
1314 if (common_prefix !== null) {
1315 text += common_prefix + '(';
1319 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1320 for (const match_id of sorted_match_id) {
1324 let desc = find_match(match_id)['description'];
1325 if (common_prefix === null) {
1328 text += desc.substr(common_prefix.length);
1333 if (common_prefix !== null) {
1336 } else if (filter.type === 'player_any') {
1337 text = 'Player (any): ';
1338 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1340 for (const player_id of sorted_players) {
1344 text += find_player(player_id)['name'];
1347 } else if (filter.type === 'player_all') {
1349 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1351 for (const player_id of sorted_players) {
1355 text += find_player(player_id)['name'];
1358 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1359 const offense = (filter.type === 'formation_offense');
1367 for (const formation_id of filter.elements) {
1368 all_names.push(find_formation(formation_id)['name']);
1370 let common_prefix = find_common_prefix_of_all(all_names);
1371 if (common_prefix !== null) {
1372 text += common_prefix + '(';
1376 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1377 for (const formation_id of sorted_formation_id) {
1381 let desc = find_formation(formation_id)['name'];
1382 if (common_prefix === null) {
1385 text += desc.substr(common_prefix.length);
1390 if (common_prefix !== null) {
1393 } else if (filter.type === 'starting_on') {
1394 text = 'Starting on: ';
1396 if (filter.elements.has(false) && filter.elements.has(true)) {
1398 } else if (filter.elements.has(false)) {
1403 } else if (filter.type === 'gender_ratio') {
1407 for (const name of Array.from(filter.elements).sort()) {
1416 let text_node = document.createElement('span');
1417 text_node.innerText = text;
1418 text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1419 pill.appendChild(text_node);
1421 pill.appendChild(document.createTextNode(' '));
1423 let delete_node = document.createElement('span');
1424 delete_node.innerText = '✖';
1425 delete_node.addEventListener('click', (e) => {
1426 // Delete this filter entirely.
1427 document.getElementById('filters').removeChild(pill);
1428 global_filters = global_filters.filter(f => f !== filter);
1429 process_matches(global_json, global_filters);
1431 let add_menu = document.getElementById('filter-add-menu');
1432 let add_submenu = document.getElementById('filter-submenu');
1433 add_menu.style.display = 'none';
1434 add_submenu.style.display = 'none';
1436 pill.appendChild(delete_node);
1437 pill.style.cursor = 'pointer';
1442 function find_common_prefix(a, b) {
1444 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1445 if (a[i] === b[i]) {
1454 function find_common_prefix_of_all(values) {
1455 if (values.length < 2) {
1458 let common_prefix = null;
1459 for (const desc of values) {
1460 if (common_prefix === null) {
1461 common_prefix = desc;
1463 common_prefix = find_common_prefix(common_prefix, desc);
1466 if (common_prefix.length >= 3) {
1467 return common_prefix;
1473 function find_match(match_id) {
1474 for (const match of global_json['matches']) {
1475 if (match['match_id'] === match_id) {
1482 function find_formation(formation_id) {
1483 for (const formation of global_json['formations']) {
1484 if (formation['formation_id'] === formation_id) {
1491 function find_player(player_id) {
1492 for (const player of global_json['players']) {
1493 if (player['player_id'] === player_id) {
1500 function player_pos(player_id) {
1502 for (const player of global_json['players']) {
1503 if (player['player_id'] === player_id) {
1511 function keep_match(match_id, filters) {
1512 for (const filter of filters) {
1513 if (filter.type === 'match') {
1514 return filter.elements.has(match_id);
1520 function find_gender_ratio_code(players) {
1522 for (const [q,p] of Object.entries(players)) {
1523 if (p.on_field_since === null) {
1526 let gender = p.gender;
1527 if (gender === '' || gender === undefined || gender === null) {
1530 if (map[gender] === undefined) {
1536 let all_genders = Array.from(Object.keys(map)).sort(
1538 if (map[a] !== map[b]) {
1539 return map[b] - map[a]; // Reverse numeric.
1549 for (const g of all_genders) {
1560 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1561 if (filter.type === 'player_any') {
1562 for (const p of Array.from(filter.elements)) {
1563 if (players[p].on_field_since !== null) {
1568 } else if (filter.type === 'player_all') {
1569 for (const p of Array.from(filter.elements)) {
1570 if (players[p].on_field_since === null) {
1575 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1576 for (const f of Array.from(filter.elements)) {
1577 if (formations_used_this_point.has(f)) {
1582 } else if (filter.type === 'starting_on') {
1583 return filter.elements.has(last_pull_was_ours);
1584 } else if (filter.type === 'gender_ratio') {
1585 return filter.elements.has(find_gender_ratio_code(players));
1590 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
1591 for (const filter of filters) {
1592 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
1599 // Heuristic: If we go at least ten seconds without the possession changing
1600 // or the operator specifying some other formation, we probably play the
1601 // same formation as the last point.
1602 function should_reuse_last_formation(events, t) {
1603 for (const e of events) {
1607 if (e.t > t + 10000) {
1610 const type = e.type;
1611 if (type === 'their_goal' || type === 'goal' ||
1612 type === 'set_defense' || type === 'set_offense' ||
1613 type === 'throwaway' || type === 'their_throwaway' ||
1614 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1615 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1616 type === 'formation_offense' || type === 'formation_defense') {
1623 function possibly_close_menu(e) {
1624 if (e.target.closest('#filter-click-to-add') === null &&
1625 e.target.closest('#filter-add-menu') === null &&
1626 e.target.closest('#filter-submenu') === null &&
1627 e.target.closest('.filter-pill') === null) {
1628 let add_menu = document.getElementById('filter-add-menu');
1629 let add_submenu = document.getElementById('filter-submenu');
1630 add_menu.style.display = 'none';
1631 add_submenu.style.display = 'none';
1635 let global_sort = {};
1637 function sort_by(th) {
1638 let tr = th.parentElement;
1640 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1641 let element = tr.children[column_idx];
1642 if (element === th) {
1643 ++child_idx; // Pad.
1646 if (element.hasAttribute('colspan')) {
1647 child_idx += parseInt(element.getAttribute('colspan'));
1654 let table = tr.parentElement;
1655 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
1656 let row = table.children[row_idx];
1657 let player = parseInt(row.dataset.player);
1658 let value = row.children[child_idx].textContent;
1659 global_sort[player] = value;
1663 function get_sorted_players(players)
1665 let p = Object.entries(players);
1666 if (global_sort.length !== 0) {
1668 let ai = parseFloat(global_sort[a[0]]);
1669 let bi = parseFloat(global_sort[b[0]]);
1670 if (ai == ai && bi == bi) {
1671 return bi - ai; // Reverse numeric.
1672 } else if (global_sort[a[0]] < global_sort[b[0]]) {
1674 } else if (global_sort[a[0]] > global_sort[b[0]]) {