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.
502 console.log(match['description'] + ' ' + format_time(t) + ': Disc came from subbed-out player ' + players[handler].name + '; not counting a pass.');
507 if (type === 'catch' || type === 'goal') {
508 if (handler !== null) {
510 ++players[handler].num_throws;
515 if (keep) ++p.touches;
516 if (type === 'goal') {
518 if (prev_handler !== null) {
519 ++players[prev_handler].hockey_assists;
521 if (handler !== null) {
522 ++players[handler].assists;
526 handler = prev_handler = null;
528 // Update hold history.
529 prev_handler = handler;
530 handler = e['player'];
532 } else if (type === 'throwaway') {
537 handler = prev_handler = null;
538 } else if (type === 'drop') {
540 handler = prev_handler = null;
541 } else if (type === 'stallout') {
542 if (keep) ++p.stallouts;
543 handler = prev_handler = null;
544 } else if (type === 'was_d') {
545 if (keep) ++p.was_ds;
546 handler = prev_handler = null;
547 } else if (type === 'defense') {
548 if (keep) ++p.defenses;
549 } else if (type === 'interception') {
556 handler = e['player'];
557 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
559 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
560 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
561 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
562 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
563 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
564 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
565 type !== 'formation_offense' && type !== 'formation_defense') {
566 console.log(format_time(t) + ": Unknown event “" + e + "”");
569 if (type === 'goal' || type === 'their_goal') {
570 formations_used_this_point.clear();
574 // Add field time for all players still left at match end.
575 const keep = keep_event(players, formations_used_this_point, filters);
577 for (const [q,p] of Object.entries(players)) {
578 if (p.on_field_since !== null && last_goal !== null) {
579 p.field_time_ms += last_goal - p.on_field_since;
582 if (game_started !== null && last_goal !== null) {
583 globals.field_time_ms += last_goal - game_started;
585 if (live_since !== null && last_goal !== null) {
586 globals.playing_time_ms += last_goal - live_since;
587 if (offense === true) {
588 globals.offensive_playing_time_ms += last_goal - live_since;
589 } else if (offense === false) {
590 globals.defensive_playing_time_ms += last_goal - live_since;
596 let chosen_category = get_chosen_category();
597 write_main_menu(chosen_category);
600 if (chosen_category === 'general') {
601 rows = make_table_general(players);
602 } else if (chosen_category === 'offense') {
603 rows = make_table_offense(players);
604 } else if (chosen_category === 'defense') {
605 rows = make_table_defense(players);
606 } else if (chosen_category === 'playing_time') {
607 rows = make_table_playing_time(players);
608 } else if (chosen_category === 'per_point') {
609 rows = make_table_per_point(players);
611 document.getElementById('stats').replaceChildren(...rows);
614 function get_chosen_category() {
615 if (window.location.hash === '#offense') {
617 } else if (window.location.hash === '#defense') {
619 } else if (window.location.hash === '#playing_time') {
620 return 'playing_time';
621 } else if (window.location.hash === '#per_point') {
628 function write_main_menu(chosen_category) {
630 if (chosen_category === 'general') {
631 let span = document.createElement('span');
632 span.innerText = 'General';
635 let a = document.createElement('a');
636 a.appendChild(document.createTextNode('General'));
637 a.setAttribute('href', '#general');
641 if (chosen_category === 'offense') {
642 let span = document.createElement('span');
643 span.innerText = 'Offense';
646 let a = document.createElement('a');
647 a.appendChild(document.createTextNode('Offense'));
648 a.setAttribute('href', '#offense');
652 if (chosen_category === 'defense') {
653 let span = document.createElement('span');
654 span.innerText = 'Defense';
657 let a = document.createElement('a');
658 a.appendChild(document.createTextNode('Defense'));
659 a.setAttribute('href', '#defense');
663 if (chosen_category === 'playing_time') {
664 let span = document.createElement('span');
665 span.innerText = 'Playing time';
668 let a = document.createElement('a');
669 a.appendChild(document.createTextNode('Playing time'));
670 a.setAttribute('href', '#playing_time');
674 if (chosen_category === 'per_point') {
675 let span = document.createElement('span');
676 span.innerText = 'Per point';
679 let a = document.createElement('a');
680 a.appendChild(document.createTextNode('Per point'));
681 a.setAttribute('href', '#per_point');
685 document.getElementById('mainmenu').replaceChildren(...elems);
688 // https://en.wikipedia.org/wiki/1.96#History
691 const ci_width = 100;
692 const ci_height = 20;
694 function make_binomial_ci(val, num, z) {
697 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
698 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
699 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
701 // Fix the signs so that we don't get -0.00.
702 low = Math.max(low, 0.0);
712 // These can only happen once per point, but you get -1 and +1
713 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
714 // and then we can rewrite back.
715 function make_efficiency_ci(points_won, points_completed, z)
717 let ci = make_binomial_ci(points_won, points_completed, z);
718 ci.val = 2.0 * ci.val - 1.0;
719 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
720 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
723 ci.desired = 0.0; // Desired = positive efficiency.
727 // Ds, throwaways and drops can happen multiple times per point,
728 // so they are Poisson distributed.
730 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
731 // since our rates are definitely below 2 per point).
732 function make_poisson_ci(val, num, z, inverted)
734 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
735 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
737 // Fix the signs so that we don't get -0.00.
738 low = Math.max(low, 0.0);
740 // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
749 'inverted': inverted,
753 function make_table_general(players) {
756 let header = document.createElement('tr');
757 add_th(header, 'Player');
758 add_th(header, '+/-');
759 add_th(header, 'Soft +/-');
760 add_th(header, 'O efficiency');
761 add_th(header, 'D efficiency');
762 add_th(header, 'Points played');
766 for (const [q,p] of get_sorted_players(players)) {
767 if (q === 'globals') continue;
768 let row = document.createElement('tr');
769 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
770 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
771 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
772 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
773 let name = add_3cell(row, p.name, 'name'); // TODO: number?
774 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
775 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
776 add_3cell_ci(row, o_efficiency);
777 add_3cell_ci(row, d_efficiency);
778 add_3cell(row, p.points_played);
779 row.dataset.player = q;
784 let globals = players['globals'];
785 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
786 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
787 let row = document.createElement('tr');
791 add_3cell_ci(row, o_efficiency);
792 add_3cell_ci(row, d_efficiency);
793 add_3cell(row, globals.points_played);
799 function make_table_offense(players) {
802 let header = document.createElement('tr');
803 add_th(header, 'Player');
804 add_th(header, 'Goals');
805 add_th(header, 'Assists');
806 add_th(header, 'Hockey assists');
807 add_th(header, 'Throws');
808 add_th(header, 'Throwaways');
809 add_th(header, '%OK');
810 add_th(header, 'Catches');
811 add_th(header, 'Drops');
812 add_th(header, 'D-ed');
813 add_th(header, '%OK');
814 add_th(header, 'Stalls');
815 add_th(header, 'Soft +/-', 6);
825 for (const [q,p] of get_sorted_players(players)) {
826 if (q === 'globals') continue;
827 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
828 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
830 throw_ok.format = 'percentage';
831 catch_ok.format = 'percentage';
833 // Desire at least 90% percentage. Fairly arbitrary.
834 throw_ok.desired = 0.9;
835 catch_ok.desired = 0.9;
837 let row = document.createElement('tr');
838 add_3cell(row, p.name, 'name'); // TODO: number?
839 add_3cell(row, p.goals);
840 add_3cell(row, p.assists);
841 add_3cell(row, p.hockey_assists);
842 add_3cell(row, p.num_throws);
843 add_3cell(row, p.throwaways);
844 add_3cell_ci(row, throw_ok);
845 add_3cell(row, p.catches);
846 add_3cell(row, p.drops);
847 add_3cell(row, p.was_ds);
848 add_3cell_ci(row, catch_ok);
849 add_3cell(row, p.stallouts);
850 add_3cell(row, '+' + p.offensive_soft_plus);
851 add_3cell(row, '-' + p.offensive_soft_minus);
852 row.dataset.player = q;
855 num_throws += p.num_throws;
856 throwaways += p.throwaways;
857 catches += p.catches;
860 stallouts += p.stallouts;
864 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
865 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
866 throw_ok.format = 'percentage';
867 catch_ok.format = 'percentage';
868 throw_ok.desired = 0.9;
869 catch_ok.desired = 0.9;
871 let row = document.createElement('tr');
876 add_3cell(row, num_throws);
877 add_3cell(row, throwaways);
878 add_3cell_ci(row, throw_ok);
879 add_3cell(row, catches);
880 add_3cell(row, drops);
881 add_3cell(row, was_ds);
882 add_3cell_ci(row, catch_ok);
883 add_3cell(row, stallouts);
891 function make_table_defense(players) {
894 let header = document.createElement('tr');
895 add_th(header, 'Player');
896 add_th(header, 'Ds');
897 add_th(header, 'Pulls');
898 add_th(header, 'OOB pulls');
899 add_th(header, 'OOB%');
900 add_th(header, 'Avg. hang time (IB)');
901 add_th(header, 'Soft +/-', 6);
904 for (const [q,p] of get_sorted_players(players)) {
905 if (q === 'globals') continue;
907 for (const t of p.pull_times) {
910 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
911 let oob_pct = 100 * p.oob_pulls / p.pulls;
913 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
914 ci_oob.format = 'percentage';
915 ci_oob.desired = 0.2; // Arbitrary.
916 ci_oob.inverted = true;
918 let row = document.createElement('tr');
919 add_3cell(row, p.name, 'name'); // TODO: number?
920 add_3cell(row, p.defenses);
921 add_3cell(row, p.pulls);
922 add_3cell(row, p.oob_pulls);
923 add_3cell_ci(row, ci_oob);
924 if (p.pulls > p.oob_pulls) {
925 add_3cell(row, avg_time.toFixed(1) + ' sec');
927 add_3cell(row, 'N/A');
929 add_3cell(row, '+' + p.defensive_soft_plus);
930 add_3cell(row, '-' + p.defensive_soft_minus);
931 row.dataset.player = q;
937 function make_table_playing_time(players) {
940 let header = document.createElement('tr');
941 add_th(header, 'Player');
942 add_th(header, 'Points played');
943 add_th(header, 'Time played');
944 add_th(header, 'O time');
945 add_th(header, 'D time');
946 add_th(header, 'Time on field');
947 add_th(header, 'O points');
948 add_th(header, 'D points');
952 for (const [q,p] of get_sorted_players(players)) {
953 if (q === 'globals') continue;
954 let row = document.createElement('tr');
955 add_3cell(row, p.name, 'name'); // TODO: number?
956 add_3cell(row, p.points_played);
957 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
958 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
959 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
960 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
961 add_3cell(row, p.offensive_points_completed);
962 add_3cell(row, p.defensive_points_completed);
963 row.dataset.player = q;
968 let globals = players['globals'];
969 let row = document.createElement('tr');
971 add_3cell(row, globals.points_played);
972 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
973 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
974 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
975 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
976 add_3cell(row, globals.offensive_points_completed);
977 add_3cell(row, globals.defensive_points_completed);
983 function make_table_per_point(players) {
986 let header = document.createElement('tr');
987 add_th(header, 'Player');
988 add_th(header, 'Goals');
989 add_th(header, 'Assists');
990 add_th(header, 'Hockey assists');
991 add_th(header, 'Ds');
992 add_th(header, 'Throwaways');
993 add_th(header, 'Recv. errors');
994 add_th(header, 'Touches');
1000 let hockey_assists = 0;
1003 let receiver_errors = 0;
1005 for (const [q,p] of get_sorted_players(players)) {
1006 if (q === 'globals') continue;
1008 // Can only happen once per point, so these are binomials.
1009 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1010 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1011 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1012 // Arbitrarily desire at least 10% (not everybody can score or assist).
1013 ci_goals.desired = 0.1;
1014 ci_assists.desired = 0.1;
1015 ci_hockey_assists.desired = 0.1;
1017 let row = document.createElement('tr');
1018 add_3cell(row, p.name, 'name'); // TODO: number?
1019 add_3cell_ci(row, ci_goals);
1020 add_3cell_ci(row, ci_assists);
1021 add_3cell_ci(row, ci_hockey_assists);
1022 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1023 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1024 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1025 if (p.points_played > 0) {
1026 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1028 add_3cell(row, 'N/A');
1030 row.dataset.player = q;
1034 assists += p.assists;
1035 hockey_assists += p.hockey_assists;
1036 defenses += p.defenses;
1037 throwaways += p.throwaways;
1038 receiver_errors += p.drops + p.was_ds;
1039 touches += p.touches;
1043 let globals = players['globals'];
1044 let row = document.createElement('tr');
1046 if (globals.points_played > 0) {
1047 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
1048 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
1049 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
1050 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
1051 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
1052 add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
1053 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
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_with_filler_ci(row, 'N/A');
1061 add_3cell(row, 'N/A');
1068 function open_filter_menu() {
1069 document.getElementById('filter-submenu').style.display = 'none';
1071 let menu = document.getElementById('filter-add-menu');
1072 menu.style.display = 'block';
1073 menu.replaceChildren();
1075 // Place the menu directly under the “click to add” label;
1076 // we don't anchor it since that label will move around
1077 // and the menu shouldn't.
1078 let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1079 menu.style.left = rect.left + 'px';
1080 menu.style.top = (rect.bottom + 10) + 'px';
1082 add_menu_item(menu, 0, 'match', 'Match (any)');
1083 add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
1084 add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
1085 add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
1086 add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
1089 function add_menu_item(menu, menu_idx, filter_type, title) {
1090 let item = document.createElement('div');
1091 item.classList.add('option');
1092 item.appendChild(document.createTextNode(title));
1094 let arrow = document.createElement('div');
1095 arrow.classList.add('arrow');
1096 arrow.textContent = '▸';
1097 item.appendChild(arrow);
1099 menu.appendChild(item);
1101 item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
1104 function show_submenu(menu_idx, pill, filter_type) {
1105 let submenu = document.getElementById('filter-submenu');
1107 const filter = find_filter(filter_type);
1110 if (filter_type === 'match') {
1111 for (const match of global_json['matches']) {
1113 'title': match['description'],
1114 'id': match['match_id']
1117 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1118 for (const player of global_json['players']) {
1120 'title': player['name'],
1121 'id': player['player_id']
1124 } else if (filter_type === 'formation_offense') {
1126 'title': '(None/unknown)',
1129 for (const formation of global_json['formations']) {
1130 if (formation['offense']) {
1132 'title': formation['name'],
1133 'id': formation['formation_id']
1137 } else if (filter_type === 'formation_defense') {
1139 'title': '(None/unknown)',
1142 for (const formation of global_json['formations']) {
1143 if (!formation['offense']) {
1145 'title': formation['name'],
1146 'id': formation['formation_id']
1152 for (const choice of choices) {
1153 let label = document.createElement('label');
1155 let subitem = document.createElement('div');
1156 subitem.classList.add('option');
1158 let check = document.createElement('input');
1159 check.setAttribute('type', 'checkbox');
1160 check.setAttribute('id', 'choice' + choice.id);
1161 if (filter !== null && filter.elements.has(choice.id)) {
1162 check.setAttribute('checked', 'checked');
1164 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1166 subitem.appendChild(check);
1167 subitem.appendChild(document.createTextNode(choice.title));
1169 label.appendChild(subitem);
1170 subitems.push(label);
1172 submenu.replaceChildren(...subitems);
1173 submenu.style.display = 'block';
1175 if (pill !== null) {
1176 let rect = pill.getBoundingClientRect();
1177 submenu.style.top = (rect.bottom + 10) + 'px';
1178 submenu.style.left = rect.left + 'px';
1180 // Position just outside the selected menu.
1181 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1182 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1183 submenu.style.left = (rect.right - 1) + 'px';
1187 // Find the right filter, if it exists.
1188 function find_filter(filter_type) {
1189 for (let f of global_filters) {
1190 if (f.type === filter_type) {
1197 function checkbox_changed(e, filter_type, id) {
1198 let filter = find_filter(filter_type);
1199 if (e.target.checked) {
1200 // See if we must add a new filter to the list.
1201 if (filter === null) {
1203 'type': filter_type,
1204 'elements': new Set([ id ]),
1206 filter.pill = make_filter_pill(filter);
1207 global_filters.push(filter);
1208 document.getElementById('filters').appendChild(filter.pill);
1210 filter.elements.add(id);
1211 let new_pill = make_filter_pill(filter);
1212 document.getElementById('filters').replaceChild(new_pill, filter.pill);
1213 filter.pill = new_pill;
1216 filter.elements.delete(id);
1217 if (filter.elements.size === 0) {
1218 document.getElementById('filters').removeChild(filter.pill);
1219 global_filters = global_filters.filter(f => f !== filter);
1221 let new_pill = make_filter_pill(filter);
1222 document.getElementById('filters').replaceChild(new_pill, filter.pill);
1223 filter.pill = new_pill;
1227 process_matches(global_json, global_filters);
1230 function make_filter_pill(filter) {
1231 let pill = document.createElement('div');
1232 pill.classList.add('filter-pill');
1234 if (filter.type === 'match') {
1238 for (const match_id of filter.elements) {
1239 all_names.push(find_match(match_id)['description']);
1241 let common_prefix = find_common_prefix_of_all(all_names);
1242 if (common_prefix !== null) {
1243 text += common_prefix + '(';
1247 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1248 for (const match_id of sorted_match_id) {
1252 let desc = find_match(match_id)['description'];
1253 if (common_prefix === null) {
1256 text += desc.substr(common_prefix.length);
1261 if (common_prefix !== null) {
1264 } else if (filter.type === 'player_any') {
1265 text = 'Player (any): ';
1266 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1268 for (const player_id of sorted_players) {
1272 text += find_player(player_id)['name'];
1275 } else if (filter.type === 'player_all') {
1277 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1279 for (const player_id of sorted_players) {
1283 text += find_player(player_id)['name'];
1286 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1287 const offense = (filter.type === 'formation_offense');
1295 for (const formation_id of filter.elements) {
1296 all_names.push(find_formation(formation_id)['name']);
1298 let common_prefix = find_common_prefix_of_all(all_names);
1299 if (common_prefix !== null) {
1300 text += common_prefix + '(';
1304 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1305 for (const formation_id of sorted_formation_id) {
1309 let desc = find_formation(formation_id)['name'];
1310 if (common_prefix === null) {
1313 text += desc.substr(common_prefix.length);
1318 if (common_prefix !== null) {
1323 let text_node = document.createElement('span');
1324 text_node.innerText = text;
1325 text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1326 pill.appendChild(text_node);
1328 pill.appendChild(document.createTextNode(' '));
1330 let delete_node = document.createElement('span');
1331 delete_node.innerText = '✖';
1332 delete_node.addEventListener('click', (e) => {
1333 // Delete this filter entirely.
1334 document.getElementById('filters').removeChild(pill);
1335 global_filters = global_filters.filter(f => f !== filter);
1336 process_matches(global_json, global_filters);
1338 let add_menu = document.getElementById('filter-add-menu');
1339 let add_submenu = document.getElementById('filter-submenu');
1340 add_menu.style.display = 'none';
1341 add_submenu.style.display = 'none';
1343 pill.appendChild(delete_node);
1344 pill.style.cursor = 'pointer';
1349 function find_common_prefix(a, b) {
1351 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1352 if (a[i] === b[i]) {
1361 function find_common_prefix_of_all(values) {
1362 if (values.length < 2) {
1365 let common_prefix = null;
1366 for (const desc of values) {
1367 if (common_prefix === null) {
1368 common_prefix = desc;
1370 common_prefix = find_common_prefix(common_prefix, desc);
1373 if (common_prefix.length >= 3) {
1374 return common_prefix;
1380 function find_match(match_id) {
1381 for (const match of global_json['matches']) {
1382 if (match['match_id'] === match_id) {
1389 function find_formation(formation_id) {
1390 for (const formation of global_json['formations']) {
1391 if (formation['formation_id'] === formation_id) {
1398 function find_player(player_id) {
1399 for (const player of global_json['players']) {
1400 if (player['player_id'] === player_id) {
1407 function player_pos(player_id) {
1409 for (const player of global_json['players']) {
1410 if (player['player_id'] === player_id) {
1418 function keep_match(match_id, filters) {
1419 for (const filter of filters) {
1420 if (filter.type === 'match') {
1421 return filter.elements.has(match_id);
1427 function filter_passes(players, formations_used_this_point, filter) {
1428 if (filter.type === 'player_any') {
1429 for (const p of Array.from(filter.elements)) {
1430 if (players[p].on_field_since !== null) {
1435 } else if (filter.type === 'player_all') {
1436 for (const p of Array.from(filter.elements)) {
1437 if (players[p].on_field_since === null) {
1442 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1443 for (const f of Array.from(filter.elements)) {
1444 if (formations_used_this_point.has(f)) {
1453 function keep_event(players, formations_used_this_point, filters) {
1454 for (const filter of filters) {
1455 if (!filter_passes(players, formations_used_this_point, filter)) {
1462 // Heuristic: If we go at least ten seconds without the possession changing
1463 // or the operator specifying some other formation, we probably play the
1464 // same formation as the last point.
1465 function should_reuse_last_formation(events, t) {
1466 for (const e of events) {
1470 if (e.t > t + 10000) {
1473 const type = e.type;
1474 if (type === 'their_goal' || type === 'goal' ||
1475 type === 'set_defense' || type === 'set_offense' ||
1476 type === 'throwaway' || type === 'their_throwaway' ||
1477 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1478 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1479 type === 'formation_offense' || type === 'formation_defense') {
1486 function possibly_close_menu(e) {
1487 if (e.target.closest('#filter-click-to-add') === null &&
1488 e.target.closest('#filter-add-menu') === null &&
1489 e.target.closest('#filter-submenu') === null &&
1490 e.target.closest('.filter-pill') === null) {
1491 let add_menu = document.getElementById('filter-add-menu');
1492 let add_submenu = document.getElementById('filter-submenu');
1493 add_menu.style.display = 'none';
1494 add_submenu.style.display = 'none';
1498 let global_sort = {};
1500 function sort_by(th) {
1501 let tr = th.parentElement;
1503 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1504 let element = tr.children[column_idx];
1505 if (element === th) {
1506 ++child_idx; // Pad.
1509 if (element.hasAttribute('colspan')) {
1510 child_idx += parseInt(element.getAttribute('colspan'));
1517 let table = tr.parentElement;
1518 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
1519 let row = table.children[row_idx];
1520 let player = parseInt(row.dataset.player);
1521 let value = row.children[child_idx].textContent;
1522 global_sort[player] = value;
1526 function get_sorted_players(players)
1528 let p = Object.entries(players);
1529 if (global_sort.length !== 0) {
1531 let ai = parseFloat(global_sort[a[0]]);
1532 let bi = parseFloat(global_sort[b[0]]);
1533 if (ai == ai && bi == bi) {
1534 return bi - ai; // Reverse numeric.
1535 } else if (global_sort[a[0]] < global_sort[b[0]]) {
1537 } else if (global_sort[a[0]] > global_sort[b[0]]) {