3 // No frameworks, no compilers, no npm, just JavaScript. :-)
6 let global_filters = {};
7 let next_filterset_id = 2; // Arbitrary IDs are fine as long as they never collide.
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12 .then(response => response.json())
13 .then(response => { global_json = response; process_matches(global_json, global_filters); });
15 function format_time(t)
17 const ms = t % 1000 + '';
18 t = Math.floor(t / 1000);
19 const sec = t % 60 + '';
20 t = Math.floor(t / 60);
21 const min = t % 60 + '';
22 const hour = Math.floor(t / 60) + '';
23 return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
26 function attribute_player_time(player, to, from, offense) {
28 if (player.on_field_since > from) {
29 // Player came in while play happened (without a stoppage!?).
30 delta_time = to - player.on_field_since;
32 delta_time = to - from;
34 player.playing_time_ms += delta_time;
35 if (offense === true) {
36 player.offensive_playing_time_ms += delta_time;
37 } else if (offense === false) {
38 player.defensive_playing_time_ms += delta_time;
42 function take_off_field(player, t, live_since, offense, keep) {
44 if (live_since === null) {
45 // Play isn't live, so nothing to do.
47 attribute_player_time(player, t, live_since, offense);
49 if (player.on_field_since !== null) { // Just a safeguard; out without in should never happen.
50 player.field_time_ms += t - player.on_field_since;
53 player.on_field_since = null;
56 function add_cell(tr, element_type, text) {
57 let element = document.createElement(element_type);
58 element.textContent = text;
59 tr.appendChild(element);
63 function add_th(tr, text, colspan) {
64 let element = document.createElement('th');
65 let link = document.createElement('a');
66 link.style.cursor = 'pointer';
67 link.addEventListener('click', (e) => {
69 process_matches(global_json, global_filters);
71 link.textContent = text;
72 element.appendChild(link);
73 tr.appendChild(element);
76 element.setAttribute('colspan', colspan);
78 element.setAttribute('colspan', '3');
83 function add_3cell(tr, text, cls) {
84 let p1 = add_cell(tr, 'td', '');
85 let element = add_cell(tr, 'td', text);
86 let p2 = add_cell(tr, 'td', '');
88 p1.classList.add('pad');
89 p2.classList.add('pad');
90 if (cls === undefined) {
91 element.classList.add('num');
93 element.classList.add(cls);
98 function add_3cell_with_filler_ci(tr, text, cls) {
99 let element = add_3cell(tr, text, cls);
101 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102 svg.classList.add('fillerci');
103 svg.setAttribute('width', ci_width);
104 svg.setAttribute('height', ci_height);
105 element.appendChild(svg);
110 function add_3cell_ci(tr, ci) {
112 add_3cell_with_filler_ci(tr, 'N/A');
117 if (ci.format === 'percentage') {
118 text = (100 * ci.val).toFixed(0) + '%';
120 text = ci.val.toFixed(2);
122 let element = add_3cell(tr, text);
123 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
126 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
127 if (ci.inverted === true) {
128 svg.classList.add('invertedci');
130 svg.classList.add('ci');
132 svg.setAttribute('width', ci_width);
133 svg.setAttribute('height', ci_height);
135 // The good (green) and red (bad) ranges.
136 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
137 s0.classList.add('range');
138 s0.classList.add('s0');
139 s0.setAttribute('width', to_x(ci.desired));
140 s0.setAttribute('height', ci_height);
141 s0.setAttribute('x', '0');
143 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
144 s1.classList.add('range');
145 s1.classList.add('s1');
146 s1.setAttribute('width', ci_width - to_x(ci.desired));
147 s1.setAttribute('height', ci_height);
148 s1.setAttribute('x', to_x(ci.desired));
151 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
152 bar.classList.add('bar');
153 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
154 bar.setAttribute('height', ci_height / 3);
155 bar.setAttribute('x', to_x(ci.lower_ci));
156 bar.setAttribute('y', ci_height / 3);
158 // Marker line for average.
159 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
160 marker.classList.add('marker');
161 marker.setAttribute('x1', to_x(ci.val));
162 marker.setAttribute('x2', to_x(ci.val));
163 marker.setAttribute('y1', ci_height / 6);
164 marker.setAttribute('y2', ci_height * 5 / 6);
168 svg.appendChild(bar);
169 svg.appendChild(marker);
171 element.appendChild(svg);
174 function calc_stats(json, filters) {
176 for (const player of json['players']) {
177 players[player['player_id']] = {
178 'name': player['name'],
179 'gender': player['gender'],
180 'number': player['number'],
196 'playing_time_ms': 0,
197 'offensive_playing_time_ms': 0,
198 'defensive_playing_time_ms': 0,
202 'offensive_points_completed': 0,
203 'offensive_points_won': 0,
204 'defensive_points_completed': 0,
205 'defensive_points_won': 0,
207 'offensive_soft_plus': 0,
208 'offensive_soft_minus': 0,
209 'defensive_soft_plus': 0,
210 'defensive_soft_minus': 0,
217 'last_point_seen': null,
218 'on_field_since': null,
223 players['globals'] = {
225 'playing_time_ms': 0,
226 'offensive_playing_time_ms': 0,
227 'defensive_playing_time_ms': 0,
230 'offensive_points_completed': 0,
231 'offensive_points_won': 0,
234 'defensive_points_completed': 0,
235 'defensive_points_won': 0,
240 'their_clean_holds': 0,
241 'their_clean_breaks': 0,
243 'touches_for_turnover': 0,
244 'touches_for_goal': 0,
246 let globals = players['globals'];
248 for (const match of json['matches']) {
249 if (!keep_match(match['match_id'], filters)) {
255 let between_points = true;
257 let handler_got_by_interception = false; // Only relevant if handler !== null.
258 let prev_handler = null;
259 let live_since = null;
260 let offense = null; // True/false/null (unknown).
262 let pull_started = null;
263 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
265 let game_started = null;
266 let last_goal = null;
267 let current_predominant_gender = null;
268 let current_num_players_on_field = null;
270 let we_lost_disc = false;
271 let they_lost_disc = false;
272 let touches_this_possession = 0;
274 // The last used formations of the given kind, if any; they may be reused
275 // when the point starts, if nothing else is set.
276 let last_offensive_formation = null;
277 let last_defensive_formation = null;
279 // Formations we've set, but haven't really had the chance to use yet
280 // (e.g., we get a “use zone defense” event while we're still on offense).
281 let pending_offensive_formation = null;
282 let pending_defensive_formation = null;
284 // Formations that we have played at least once this point, after all
285 // heuristics and similar.
286 let formations_used_this_point = new Set();
288 for (const [q,p] of Object.entries(players)) {
289 p.on_field_since = null;
290 p.last_point_seen = null;
292 for (const e of match['events']) {
294 let type = e['type'];
295 let p = players[e['player']];
298 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
299 if (type === 'in' && p.on_field_since === null) {
300 p.on_field_since = t;
301 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
302 // A player needed for the filters went onto the field,
303 // so pretend people walked on right now (to start their
305 for (const [q,p2] of Object.entries(players)) {
306 if (p2.on_field_since !== null) {
307 p2.on_field_since = t;
311 } else if (type === 'out') {
312 take_off_field(p, t, live_since, offense, keep);
313 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
314 // A player needed for the filters went off the field,
315 // so we need to attribute time for all the others.
316 // Pretend they walked off and then immediately on again.
318 // TODO: We also need to take care of this to get the globals right.
319 for (const [q,p2] of Object.entries(players)) {
320 if (p2.on_field_since !== null) {
321 take_off_field(p2, t, live_since, offense, keep);
322 p2.on_field_since = t;
328 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
330 if (match['gender_rule_a']) {
331 if (type === 'restart' && !between_points) {
332 let predominant_gender = find_predominant_gender(players);
333 let num_players_on_field = find_num_players_on_field(players);
334 if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
335 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
337 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
338 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed number of players on field from ' + current_num_players_on_field + ' to ' + num_players_on_field);
340 current_predominant_gender = predominant_gender;
341 current_num_players_on_field = num_players_on_field;
342 } else if (type === 'pull' || type === 'their_pull') {
343 let predominant_gender = find_predominant_gender(players);
344 let num_players_on_field = find_num_players_on_field(players);
345 let changed = (predominant_gender !== current_predominant_gender);
346 if (point_num !== 0) {
347 let should_change = (point_num % 4 == 1 || point_num % 4 == 3); // ABBA changes on 1 and 3.
348 if (changed && !should_change) {
349 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
350 } else if (!changed && should_change) {
351 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
353 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
354 console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
357 current_predominant_gender = predominant_gender;
358 current_num_players_on_field = num_players_on_field;
361 if (match['gender_pull_rule']) {
362 if (type === 'pull') {
363 if (current_predominant_gender !== null &&
364 p.gender !== current_predominant_gender) {
365 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
370 // Liveness management
371 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
373 if (type !== 'restart') {
374 between_points = false;
376 } else if (type === 'catch' && last_pull_was_ours === null) {
377 // Someone forgot to add the pull, so we'll need to wing it.
378 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
380 last_pull_was_ours = !offense;
381 between_points = false;
382 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
383 if (type === 'goal') {
384 if (keep) ++p.touches;
385 ++touches_this_possession;
387 for (const [q,p] of Object.entries(players)) {
388 if (p.on_field_since === null) {
391 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
393 // In case the player did nothing this point,
394 // not even subbing in.
395 p.last_point_seen = point_num;
399 if (keep) attribute_player_time(p, t, live_since, offense);
401 if (type !== 'stoppage') {
403 if (last_pull_was_ours === true) { // D point.
404 ++p.defensive_points_completed;
405 if (type === 'goal') {
406 ++p.defensive_points_won;
408 } else if (last_pull_was_ours === false) { // O point.
409 ++p.offensive_points_completed;
410 if (type === 'goal') {
411 ++p.offensive_points_won;
419 if (type !== 'stoppage') {
421 ++globals.points_played;
422 if (last_pull_was_ours === true) { // D point.
423 ++globals.defensive_points_completed;
424 if (type === 'goal') {
425 ++globals.defensive_points_won;
427 } else if (last_pull_was_ours === false) { // O point.
428 ++globals.offensive_points_completed;
429 if (type === 'goal') {
430 ++globals.offensive_points_won;
434 if (live_since !== null) {
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;
448 if (type === 'goal') {
450 } else if (type === 'their_goal') {
454 // Point count management
455 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
457 p.last_point_seen = point_num;
461 if (type === 'goal' || type === 'their_goal') {
465 if (type !== 'out' && game_started === null) {
470 if (type === 'pull') {
471 puller = e['player'];
474 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
475 // No effect on pull.
476 } else if (type === 'pull_landed' && puller !== null) {
477 if (keep) players[puller].pull_times.push(t - pull_started);
478 } else if (type === 'pull_oob' && puller !== null) {
479 if (keep) ++players[puller].oob_pulls;
481 // Not pulling (if there was one, we never recorded its outcome, but still count it).
482 puller = pull_started = null;
485 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
487 if (type === 'goal' && !we_lost_disc) {
488 if (last_pull_was_ours === false) { // O point.
489 ++globals.clean_holds;
490 } else if (last_pull_was_ours === true) {
491 ++globals.clean_breaks;
493 } else if (type === 'their_goal' && !they_lost_disc) {
494 if (last_pull_was_ours === true) { // O point for them.
495 ++globals.their_clean_holds;
496 } else if (last_pull_was_ours === false) {
497 ++globals.their_clean_breaks;
502 // Offense/defense management
503 let last_offense = offense;
504 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
507 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
508 ++globals.turnovers_lost;
509 globals.touches_for_turnover += touches_this_possession;
510 } else if (keep && type === 'goal') {
511 globals.touches_for_goal += touches_this_possession;
513 touches_this_possession = 0;
514 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
516 they_lost_disc = true;
517 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
518 ++globals.turnovers_won;
520 touches_this_possession = 0;
522 if (type === 'goal' || type === 'their_goal') {
523 between_points = true;
524 we_lost_disc = false;
525 they_lost_disc = false;
526 touches_this_possession = 0;
528 if (last_offense !== offense && live_since !== null) {
529 // Switched offense/defense status, so attribute this drive as needed,
530 // and update live_since to take that into account.
532 for (const [q,p] of Object.entries(players)) {
533 if (p.on_field_since === null) {
536 attribute_player_time(p, t, live_since, last_offense);
538 globals.playing_time_ms += t - live_since;
539 if (offense === true) {
540 globals.offensive_playing_time_ms += t - live_since;
541 } else if (offense === false) {
542 globals.defensive_playing_time_ms += t - live_since;
548 if (type === 'pull') {
549 last_pull_was_ours = true;
550 } else if (type === 'their_pull') {
551 last_pull_was_ours = false;
552 } else if (type === 'set_offense' && last_pull_was_ours === null) {
553 // set_offense could either be “changed to offense for some reason
554 // we could not express”, or “we started in the middle of a point,
555 // and we are offense”. We assume that if we already saw the pull,
556 // it's the former, and if not, it's the latter; thus, the === null
557 // test above. (It could also be “we set offense before the pull,
558 // so that we get the right button enabled”, in which case it will
559 // be overwritten by the next pull/their_pull event anyway.)
560 last_pull_was_ours = false;
561 } else if (type === 'set_defense' && last_pull_was_ours === null) {
563 last_pull_was_ours = true;
564 } else if (type === 'goal' || type === 'their_goal') {
565 last_pull_was_ours = null;
568 // Formation management
569 if (type === 'formation_offense' || type === 'formation_defense') {
570 let id = e.formation === null ? 0 : e.formation;
571 let for_offense = (type === 'formation_offense');
572 if (offense === for_offense) {
573 formations_used_this_point.add(id);
574 } else if (for_offense) {
575 pending_offensive_formation = id;
577 pending_defensive_formation = id;
580 last_offensive_formation = id;
582 last_defensive_formation = id;
584 } else if (last_offense !== offense) {
585 if (offense === true && pending_offensive_formation !== null) {
586 formations_used_this_point.add(pending_offensive_formation);
587 pending_offensive_formation = null;
588 } else if (offense === false && pending_defensive_formation !== null) {
589 formations_used_this_point.add(pending_defensive_formation);
590 pending_defensive_formation = null;
591 } else if (offense === true && last_defensive_formation !== null) {
592 if (should_reuse_last_formation(match['events'], t)) {
593 formations_used_this_point.add(last_defensive_formation);
595 } else if (offense === false && last_offensive_formation !== null) {
596 if (should_reuse_last_formation(match['events'], t)) {
597 formations_used_this_point.add(last_offensive_formation);
602 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
603 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
605 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
606 // The handler subbed out and was replaced with another handler,
607 // so this wasn't a pass.
612 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
613 // Self-pass to goal after an interception; this is not a real pass,
614 // just how we represent a Callahan right now -- so don't
615 // count the throw, any assists or similar.
617 // It's an open question how we should handle a self-pass that is
618 // _not_ after an interception, or a self-pass that's not a goal.
619 // (It must mean we tipped off someone.) We'll count it as a regular one
620 // for the time being, although it will make hockey assists weird.
625 handler = prev_handler = null;
626 } else if (type === 'catch' || type === 'goal') {
627 if (handler !== null) {
629 ++players[handler].num_throws;
634 if (keep) ++p.touches;
635 ++touches_this_possession;
636 if (type === 'goal') {
638 if (prev_handler !== null) {
639 ++players[prev_handler].hockey_assists;
641 if (handler !== null) {
642 ++players[handler].assists;
646 handler = prev_handler = null;
648 // Update hold history.
649 prev_handler = handler;
650 handler = e['player'];
651 handler_got_by_interception = false;
653 } else if (type === 'throwaway') {
658 handler = prev_handler = null;
659 } else if (type === 'drop') {
661 handler = prev_handler = null;
662 } else if (type === 'stallout') {
663 if (keep) ++p.stallouts;
664 handler = prev_handler = null;
665 } else if (type === 'was_d') {
666 if (keep) ++p.was_ds;
667 handler = prev_handler = null;
668 } else if (type === 'defense') {
669 if (keep) ++p.defenses;
670 } else if (type === 'interception') {
675 ++touches_this_possession;
678 handler = e['player'];
679 handler_got_by_interception = true;
680 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
682 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
683 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
684 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
685 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
686 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
687 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
688 type !== 'formation_offense' && type !== 'formation_defense') {
689 console.log(format_time(t) + ": Unknown event “" + e + "”");
692 if (type === 'goal' || type === 'their_goal') {
693 formations_used_this_point.clear();
697 // Add field time for all players still left at match end.
698 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
700 for (const [q,p] of Object.entries(players)) {
701 if (p.on_field_since !== null && last_goal !== null) {
702 p.field_time_ms += last_goal - p.on_field_since;
705 if (game_started !== null && last_goal !== null) {
706 globals.field_time_ms += last_goal - game_started;
708 if (live_since !== null && last_goal !== null) {
709 globals.playing_time_ms += last_goal - live_since;
710 if (offense === true) {
711 globals.offensive_playing_time_ms += last_goal - live_since;
712 } else if (offense === false) {
713 globals.defensive_playing_time_ms += last_goal - live_since;
721 function process_matches(json, filtersets) {
722 let chosen_category = get_chosen_category();
723 write_main_menu(chosen_category);
725 let filterset_values = Object.values(filtersets);
726 if (filterset_values.length === 0) {
727 filterset_values = [[]];
731 for (const filter of filterset_values) {
732 let players = calc_stats(json, filter);
734 if (chosen_category === 'general') {
735 rows = make_table_general(players);
736 } else if (chosen_category === 'offense') {
737 rows = make_table_offense(players);
738 } else if (chosen_category === 'defense') {
739 rows = make_table_defense(players);
740 } else if (chosen_category === 'playing_time') {
741 rows = make_table_playing_time(players);
742 } else if (chosen_category === 'per_point') {
743 rows = make_table_per_point(players);
744 } else if (chosen_category === 'team_wide') {
745 rows = make_table_team_wide(players);
750 let merged_rows = [];
751 if (filterset_values.length > 1) {
752 for (let i = 0; i < rowsets.length; ++i) {
753 let marker = make_filter_marker(filterset_values[i]);
755 // Make filter header.
756 let tr = rowsets[i][0];
757 let th = document.createElement('th');
759 tr.insertBefore(th, tr.firstChild);
761 for (let j = 1; j < rowsets[i].length; ++j) {
762 let tr = rowsets[i][j];
764 // Remove the name for cleanness.
766 tr.firstChild.nextSibling.textContent = '';
770 tr.style.borderTop = '0px';
772 if (i != rowsets.length - 1) {
773 tr.style.borderBottom = '0px';
776 // Make filter marker.
777 let td = document.createElement('td');
778 td.textContent = marker;
779 td.classList.add('filtermarker');
780 tr.insertBefore(td, tr.firstChild);
784 for (let i = 0; i < rowsets[0].length; ++i) {
785 for (let j = 0; j < rowsets.length; ++j) {
786 merged_rows.push(rowsets[j][i]);
787 if (i === 0) break; // Don't merge the headings.
791 merged_rows = rowsets[0];
793 document.getElementById('stats').replaceChildren(...merged_rows);
796 function get_chosen_category() {
797 if (window.location.hash === '#offense') {
799 } else if (window.location.hash === '#defense') {
801 } else if (window.location.hash === '#playing_time') {
802 return 'playing_time';
803 } else if (window.location.hash === '#per_point') {
805 } else if (window.location.hash === '#team_wide') {
812 function write_main_menu(chosen_category) {
815 ['general', 'General'],
816 ['offense', 'Offense'],
817 ['defense', 'Defense'],
818 ['playing_time', 'Playing time'],
819 ['per_point', 'Per point'],
820 ['team_wide', 'Team-wide'],
822 for (const [id, title] of categories) {
823 if (chosen_category === id) {
824 let span = document.createElement('span');
825 span.innerText = title;
828 let a = document.createElement('a');
829 a.appendChild(document.createTextNode(title));
830 a.setAttribute('href', '#' + id);
835 document.getElementById('mainmenu').replaceChildren(...elems);
838 // https://en.wikipedia.org/wiki/1.96#History
841 const ci_width = 100;
842 const ci_height = 20;
844 function make_binomial_ci(val, num, z) {
847 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
848 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
849 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
851 // Fix the signs so that we don't get -0.00.
852 low = Math.max(low, 0.0);
862 // These can only happen once per point, but you get -1 and +1
863 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
864 // and then we can rewrite back.
865 function make_efficiency_ci(points_won, points_completed, z)
867 let ci = make_binomial_ci(points_won, points_completed, z);
868 ci.val = 2.0 * ci.val - 1.0;
869 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
870 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
873 ci.desired = 0.0; // Desired = positive efficiency.
877 // Ds, throwaways and drops can happen multiple times per point,
878 // so they are Poisson distributed.
880 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
881 // since our rates are definitely below 2 per point).
883 // FIXME: z is ignored.
884 function make_poisson_ci(val, num, z, inverted)
886 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
887 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
889 // Fix the signs so that we don't get -0.00.
890 low = Math.max(low, 0.0);
892 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
901 'inverted': inverted,
905 // Wilson and Hilferty, again recommended for general use in the PDF above
906 // (anything from their group “G1” works).
907 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
908 function make_poisson_ci_large(val, num, z, inverted)
910 let low = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
911 let high = (val + 1.0) * Math.pow(1.0 - 1.0 / (9.0 * (val + 1.0)) + z / (3.0 * Math.sqrt(val + 1.0)), 3.0) / num;
913 // Fix the signs so that we don't get -0.00.
914 low = Math.max(low, 0.0);
916 // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
917 // (this is used for number of touches).
926 'inverted': inverted,
930 function make_table_general(players) {
933 let header = document.createElement('tr');
934 add_th(header, 'Player');
935 add_th(header, '+/-');
936 add_th(header, 'Soft +/-');
937 add_th(header, 'O efficiency');
938 add_th(header, 'D efficiency');
939 add_th(header, 'Points played');
943 for (const [q,p] of get_sorted_players(players)) {
944 if (q === 'globals') continue;
945 let row = document.createElement('tr');
946 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
947 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
948 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
949 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
950 let name = add_3cell(row, p.name, 'name'); // TODO: number?
951 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
952 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
953 add_3cell_ci(row, o_efficiency);
954 add_3cell_ci(row, d_efficiency);
955 add_3cell(row, p.points_played);
956 row.dataset.player = q;
961 let globals = players['globals'];
962 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
963 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
964 let row = document.createElement('tr');
968 add_3cell_ci(row, o_efficiency);
969 add_3cell_ci(row, d_efficiency);
970 add_3cell(row, globals.points_played);
976 function make_table_team_wide(players) {
977 let globals = players['globals'];
981 let header = document.createElement('tr');
983 add_th(header, 'Our team', 6);
984 add_th(header, 'Opponents', 6);
990 let row = document.createElement('tr');
991 let name = add_3cell(row, 'Turnovers generated', 'name');
992 add_3cell(row, globals.turnovers_won);
994 add_3cell(row, globals.turnovers_lost);
1001 let row = document.createElement('tr');
1002 let name = add_3cell(row, 'Clean holds', 'name');
1003 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1004 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1005 our_clean_holds.desired = 0.3; // Arbitrary.
1006 our_clean_holds.format = 'percentage';
1007 their_clean_holds.desired = 0.3;
1008 their_clean_holds.format = 'percentage';
1009 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1010 add_3cell_ci(row, our_clean_holds);
1011 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1012 add_3cell_ci(row, their_clean_holds);
1018 let row = document.createElement('tr');
1019 let name = add_3cell(row, 'Clean breaks', 'name');
1020 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1021 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1022 our_clean_breaks.desired = 0.3; // Arbitrary.
1023 our_clean_breaks.format = 'percentage';
1024 their_clean_breaks.desired = 0.3;
1025 their_clean_breaks.format = 'percentage';
1026 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1027 add_3cell_ci(row, our_clean_breaks);
1028 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1029 add_3cell_ci(row, their_clean_breaks);
1033 // Touches. We only have information for our team here.
1036 for (const [q,p] of get_sorted_players(players)) {
1037 if (q === 'globals') continue;
1041 let row = document.createElement('tr');
1042 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1043 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1044 let possessions = goals + globals.turnovers_lost;
1046 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1051 row = document.createElement('tr');
1052 add_3cell(row, 'Touches per possession (goals)', 'name');
1054 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1059 row = document.createElement('tr');
1060 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1062 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1071 function make_table_offense(players) {
1074 let header = document.createElement('tr');
1075 add_th(header, 'Player');
1076 add_th(header, 'Goals');
1077 add_th(header, 'Assists');
1078 add_th(header, 'Hockey assists');
1079 add_th(header, 'Throws');
1080 add_th(header, 'Throwaways');
1081 add_th(header, '%OK');
1082 add_th(header, 'Catches');
1083 add_th(header, 'Drops');
1084 add_th(header, 'D-ed');
1085 add_th(header, '%OK');
1086 add_th(header, 'Stalls');
1087 add_th(header, 'Soft +/-', 6);
1098 for (const [q,p] of get_sorted_players(players)) {
1099 if (q === 'globals') continue;
1100 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1101 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1103 throw_ok.format = 'percentage';
1104 catch_ok.format = 'percentage';
1106 // Desire at least 90% percentage. Fairly arbitrary.
1107 throw_ok.desired = 0.9;
1108 catch_ok.desired = 0.9;
1110 let row = document.createElement('tr');
1111 add_3cell(row, p.name, 'name'); // TODO: number?
1112 add_3cell(row, p.goals);
1113 add_3cell(row, p.assists);
1114 add_3cell(row, p.hockey_assists);
1115 add_3cell(row, p.num_throws);
1116 add_3cell(row, p.throwaways);
1117 add_3cell_ci(row, throw_ok);
1118 add_3cell(row, p.catches);
1119 add_3cell(row, p.drops);
1120 add_3cell(row, p.was_ds);
1121 add_3cell_ci(row, catch_ok);
1122 add_3cell(row, p.stallouts);
1123 add_3cell(row, '+' + p.offensive_soft_plus);
1124 add_3cell(row, '-' + p.offensive_soft_minus);
1125 row.dataset.player = q;
1129 num_throws += p.num_throws;
1130 throwaways += p.throwaways;
1131 catches += p.catches;
1134 stallouts += p.stallouts;
1138 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1139 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1140 throw_ok.format = 'percentage';
1141 catch_ok.format = 'percentage';
1142 throw_ok.desired = 0.9;
1143 catch_ok.desired = 0.9;
1145 let row = document.createElement('tr');
1147 add_3cell(row, goals);
1150 add_3cell(row, num_throws);
1151 add_3cell(row, throwaways);
1152 add_3cell_ci(row, throw_ok);
1153 add_3cell(row, catches);
1154 add_3cell(row, drops);
1155 add_3cell(row, was_ds);
1156 add_3cell_ci(row, catch_ok);
1157 add_3cell(row, stallouts);
1165 function make_table_defense(players) {
1168 let header = document.createElement('tr');
1169 add_th(header, 'Player');
1170 add_th(header, 'Ds');
1171 add_th(header, 'Pulls');
1172 add_th(header, 'OOB pulls');
1173 add_th(header, 'OOB%');
1174 add_th(header, 'Avg. hang time (IB)');
1175 add_th(header, 'Callahans');
1176 add_th(header, 'Soft +/-', 6);
1183 let sum_sum_time = 0;
1186 for (const [q,p] of get_sorted_players(players)) {
1187 if (q === 'globals') continue;
1189 for (const t of p.pull_times) {
1192 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1193 let oob_pct = 100 * p.oob_pulls / p.pulls;
1195 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1196 ci_oob.format = 'percentage';
1197 ci_oob.desired = 0.2; // Arbitrary.
1198 ci_oob.inverted = true;
1200 let row = document.createElement('tr');
1201 add_3cell(row, p.name, 'name'); // TODO: number?
1202 add_3cell(row, p.defenses);
1203 add_3cell(row, p.pulls);
1204 add_3cell(row, p.oob_pulls);
1205 add_3cell_ci(row, ci_oob);
1206 if (p.pulls > p.oob_pulls) {
1207 add_3cell(row, avg_time.toFixed(1) + ' sec');
1209 add_3cell(row, 'N/A');
1211 add_3cell(row, p.callahans);
1212 add_3cell(row, '+' + p.defensive_soft_plus);
1213 add_3cell(row, '-' + p.defensive_soft_minus);
1214 row.dataset.player = q;
1217 defenses += p.defenses;
1219 oob_pulls += p.oob_pulls;
1220 sum_sum_time += sum_time;
1221 callahans += p.callahans;
1225 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1226 ci_oob.format = 'percentage';
1227 ci_oob.desired = 0.2; // Arbitrary.
1228 ci_oob.inverted = true;
1230 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1231 let oob_pct = 100 * oob_pulls / pulls;
1233 let row = document.createElement('tr');
1235 add_3cell(row, defenses);
1236 add_3cell(row, pulls);
1237 add_3cell(row, oob_pulls);
1238 add_3cell_ci(row, ci_oob);
1239 if (pulls > oob_pulls) {
1240 add_3cell(row, avg_time.toFixed(1) + ' sec');
1242 add_3cell(row, 'N/A');
1244 add_3cell(row, callahans);
1252 function make_table_playing_time(players) {
1255 let header = document.createElement('tr');
1256 add_th(header, 'Player');
1257 add_th(header, 'Points played');
1258 add_th(header, 'Time played');
1259 add_th(header, 'O time');
1260 add_th(header, 'D time');
1261 add_th(header, 'Time on field');
1262 add_th(header, 'O points');
1263 add_th(header, 'D points');
1267 for (const [q,p] of get_sorted_players(players)) {
1268 if (q === 'globals') continue;
1269 let row = document.createElement('tr');
1270 add_3cell(row, p.name, 'name'); // TODO: number?
1271 add_3cell(row, p.points_played);
1272 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1273 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1274 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1275 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1276 add_3cell(row, p.offensive_points_completed);
1277 add_3cell(row, p.defensive_points_completed);
1278 row.dataset.player = q;
1283 let globals = players['globals'];
1284 let row = document.createElement('tr');
1286 add_3cell(row, globals.points_played);
1287 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1288 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1289 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1290 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1291 add_3cell(row, globals.offensive_points_completed);
1292 add_3cell(row, globals.defensive_points_completed);
1298 function make_table_per_point(players) {
1301 let header = document.createElement('tr');
1302 add_th(header, 'Player');
1303 add_th(header, 'Goals');
1304 add_th(header, 'Assists');
1305 add_th(header, 'Hockey assists');
1306 add_th(header, 'Ds');
1307 add_th(header, 'Throwaways');
1308 add_th(header, 'Recv. errors');
1309 add_th(header, 'Touches');
1315 let hockey_assists = 0;
1318 let receiver_errors = 0;
1320 for (const [q,p] of get_sorted_players(players)) {
1321 if (q === 'globals') continue;
1323 // Can only happen once per point, so these are binomials.
1324 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1325 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1326 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1327 // Arbitrarily desire at least 10% (not everybody can score or assist).
1328 ci_goals.desired = 0.1;
1329 ci_assists.desired = 0.1;
1330 ci_hockey_assists.desired = 0.1;
1332 let row = document.createElement('tr');
1333 add_3cell(row, p.name, 'name'); // TODO: number?
1334 add_3cell_ci(row, ci_goals);
1335 add_3cell_ci(row, ci_assists);
1336 add_3cell_ci(row, ci_hockey_assists);
1337 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1338 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1339 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1340 if (p.points_played > 0) {
1341 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1343 add_3cell(row, 'N/A');
1345 row.dataset.player = q;
1349 assists += p.assists;
1350 hockey_assists += p.hockey_assists;
1351 defenses += p.defenses;
1352 throwaways += p.throwaways;
1353 receiver_errors += p.drops + p.was_ds;
1354 touches += p.touches;
1358 let globals = players['globals'];
1359 let row = document.createElement('tr');
1361 if (globals.points_played > 0) {
1362 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1363 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1364 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1365 ci_goals.desired = 0.5;
1366 ci_assists.desired = 0.5;
1367 ci_hockey_assists.desired = 0.5;
1369 add_3cell_ci(row, ci_goals);
1370 add_3cell_ci(row, ci_assists);
1371 add_3cell_ci(row, ci_hockey_assists);
1373 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1374 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1375 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1377 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1379 add_3cell_with_filler_ci(row, 'N/A');
1380 add_3cell_with_filler_ci(row, 'N/A');
1381 add_3cell_with_filler_ci(row, 'N/A');
1382 add_3cell_with_filler_ci(row, 'N/A');
1383 add_3cell_with_filler_ci(row, 'N/A');
1384 add_3cell_with_filler_ci(row, 'N/A');
1385 add_3cell(row, 'N/A');
1392 function open_filter_menu(click_to_add_div) {
1393 document.getElementById('filter-submenu').style.display = 'none';
1394 let filter_div = click_to_add_div.parentElement;
1395 let filter_id = filter_div.dataset.filterId;
1397 let menu = document.getElementById('filter-add-menu');
1398 menu.parentElement.removeChild(menu);
1399 filter_div.appendChild(menu);
1400 menu.style.display = 'block';
1401 menu.replaceChildren();
1403 // Place the menu directly under the “click to add” label;
1404 // we don't anchor it since that label will move around
1405 // and the menu shouldn't.
1406 let rect = click_to_add_div.getBoundingClientRect();
1407 menu.style.left = rect.left + 'px';
1408 menu.style.top = (rect.bottom + 10) + 'px';
1410 let filterset = global_filters[filter_id];
1411 if (filterset === undefined) {
1412 global_filters[filter_id] = filterset = [];
1415 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1416 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1417 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1418 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1419 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1420 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1421 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1424 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1425 let item = document.createElement('div');
1426 item.classList.add('option');
1427 item.appendChild(document.createTextNode(title));
1429 let arrow = document.createElement('div');
1430 arrow.classList.add('arrow');
1431 arrow.textContent = '▸';
1432 item.appendChild(arrow);
1434 menu.appendChild(item);
1436 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1439 function find_all_ratios(json)
1443 for (const player of json['players']) {
1444 players[player['player_id']] = {
1445 'gender': player['gender'],
1446 'last_point_seen': null,
1449 for (const match of json['matches']) {
1450 for (const [q,p] of Object.entries(players)) {
1451 p.on_field_since = null;
1453 for (const e of match['events']) {
1454 let p = players[e['player']];
1455 let type = e['type'];
1456 if (type === 'in') {
1457 p.on_field_since = 1;
1458 } else if (type === 'out') {
1459 p.on_field_since = null;
1460 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1461 let code = find_gender_ratio_code(players);
1462 if (ratios[code] === undefined) {
1463 ratios[code] = code;
1464 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1465 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1466 match['description'] + ', ' + format_time(e['t']));
1475 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1476 let submenu = document.getElementById('filter-submenu');
1478 // Move to the same place as the top-level menu.
1479 submenu.parentElement.removeChild(submenu);
1480 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1483 const filter = find_filter(filterset, filter_type);
1486 if (filter_type === 'match') {
1487 for (const match of global_json['matches']) {
1489 'title': match['description'],
1490 'id': match['match_id']
1493 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1494 for (const player of global_json['players']) {
1496 'title': player['name'],
1497 'id': player['player_id']
1500 } else if (filter_type === 'formation_offense') {
1502 'title': '(None/unknown)',
1505 for (const formation of global_json['formations']) {
1506 if (formation['offense']) {
1508 'title': formation['name'],
1509 'id': formation['formation_id']
1513 } else if (filter_type === 'formation_defense') {
1515 'title': '(None/unknown)',
1518 for (const formation of global_json['formations']) {
1519 if (!formation['offense']) {
1521 'title': formation['name'],
1522 'id': formation['formation_id']
1526 } else if (filter_type === 'starting_on') {
1529 'id': false, // last_pull_was_ours
1533 'id': true, // last_pull_was_ours
1535 } else if (filter_type === 'gender_ratio') {
1536 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1544 for (const choice of choices) {
1545 let label = document.createElement('label');
1547 let subitem = document.createElement('div');
1548 subitem.classList.add('option');
1550 let check = document.createElement('input');
1551 check.setAttribute('type', 'checkbox');
1552 check.setAttribute('id', 'choice' + choice.id);
1553 if (filter !== null && filter.elements.has(choice.id)) {
1554 check.setAttribute('checked', 'checked');
1556 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1558 subitem.appendChild(check);
1559 subitem.appendChild(document.createTextNode(choice.title));
1561 label.appendChild(subitem);
1562 subitems.push(label);
1564 submenu.replaceChildren(...subitems);
1565 submenu.style.display = 'block';
1567 if (pill !== null) {
1568 let rect = pill.getBoundingClientRect();
1569 submenu.style.top = (rect.bottom + 10) + 'px';
1570 submenu.style.left = rect.left + 'px';
1572 // Position just outside the selected menu.
1573 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1574 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1575 submenu.style.left = (rect.right - 1) + 'px';
1579 // Find the right filter, if it exists.
1580 function find_filter(filterset, filter_type) {
1581 for (let f of filterset) {
1582 if (f.type === filter_type) {
1589 // Equivalent to Array.prototype.filter, but in-place.
1590 function inplace_filter(arr, cond) {
1592 for (let i = 0; i < arr.length; ++i) {
1600 function add_new_filterset() {
1601 let template = document.querySelector('.filter'); // First one is fine.
1602 let div = template.cloneNode(true);
1603 let add_menu = div.querySelector('#filter-add-menu');
1604 if (add_menu !== null) {
1605 div.removeChild(add_menu);
1607 let submenu = div.querySelector('#filter-submenu');
1608 if (submenu !== null) {
1609 div.removeChild(submenu);
1611 div.querySelector('.filters').replaceChildren();
1612 div.dataset.filterId = next_filterset_id++;
1613 template.parentElement.appendChild(div);
1616 function try_gc_filter_menus(cheap) {
1619 for (const filter_div of document.querySelectorAll('.filter')) {
1620 let id = filter_div.dataset.filterId;
1621 divs.push(filter_div);
1622 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1624 let last_div = divs[empties.length - 1];
1626 // See if we have two empty filter lists at the bottom of the list;
1627 // if so, we can remove one without it looking funny in the UI.
1628 // If not, we'll have to wait until closing the menu.
1629 // (The menu is positioned at the second-last one, so we can
1630 // remove the last one without issue.)
1631 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1632 delete global_filters[last_div.dataset.filterId];
1633 last_div.parentElement.removeChild(last_div);
1636 // This is a different situation from try_cheap_gc(), where we should
1637 // remove the one _not_ last. We might need to move the menu to the last one,
1638 // though, so it doesn't get lost.
1639 for (let i = 0; i < empties.length - 1; ++i) {
1644 delete global_filters[div.dataset.filterId];
1645 let add_menu = div.querySelector('#filter-add-menu');
1646 if (add_menu !== null) {
1647 div.removeChild(add_menu);
1648 last_div.appendChild(add_menu);
1650 let submenu = div.querySelector('#filter-submenu');
1651 if (submenu !== null) {
1652 div.removeChild(submenu);
1653 last_div.appendChild(submenu);
1655 div.parentElement.removeChild(div);
1660 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1661 let filter = find_filter(filterset, filter_type);
1662 let pills_div = filter_div.querySelector('.filters');
1663 if (e.target.checked) {
1664 // See if we must create a new empty filterset (since this went from
1665 // empty to non-empty).
1666 if (filterset.length === 0) {
1667 add_new_filterset();
1670 // See if we must add a new filter to the list.
1671 if (filter === null) {
1673 'type': filter_type,
1674 'elements': new Set([ id ]),
1676 filter.pill = make_filter_pill(filter_div, filterset, filter);
1677 filterset.push(filter);
1678 pills_div.appendChild(filter.pill);
1680 filter.elements.add(id);
1681 let new_pill = make_filter_pill(filter_div, filterset, filter);
1682 pills_div.replaceChild(new_pill, filter.pill);
1683 filter.pill = new_pill;
1686 filter.elements.delete(id);
1687 if (filter.elements.size === 0) {
1688 pills_div.removeChild(filter.pill);
1689 inplace_filter(filterset, f => f !== filter);
1691 if (filterset.length == 0) {
1692 try_gc_filter_menus(true);
1695 let new_pill = make_filter_pill(filter_div, filterset, filter);
1696 pills_div.replaceChild(new_pill, filter.pill);
1697 filter.pill = new_pill;
1701 process_matches(global_json, global_filters);
1704 function make_filter_pill(filter_div, filterset, filter) {
1705 let pill = document.createElement('div');
1706 pill.classList.add('filter-pill');
1708 if (filter.type === 'match') {
1712 for (const match_id of filter.elements) {
1713 all_names.push(find_match(match_id)['description']);
1715 let common_prefix = find_common_prefix_of_all(all_names);
1716 if (common_prefix !== null) {
1717 text += common_prefix + '(';
1721 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1722 for (const match_id of sorted_match_id) {
1726 let desc = find_match(match_id)['description'];
1727 if (common_prefix === null) {
1730 text += desc.substr(common_prefix.length);
1735 if (common_prefix !== null) {
1738 } else if (filter.type === 'player_any') {
1739 text = 'Player (any): ';
1740 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1742 for (const player_id of sorted_players) {
1746 text += find_player(player_id)['name'];
1749 } else if (filter.type === 'player_all') {
1751 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1753 for (const player_id of sorted_players) {
1757 text += find_player(player_id)['name'];
1760 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1761 const offense = (filter.type === 'formation_offense');
1769 for (const formation_id of filter.elements) {
1770 all_names.push(find_formation(formation_id)['name']);
1772 let common_prefix = find_common_prefix_of_all(all_names);
1773 if (common_prefix !== null) {
1774 text += common_prefix + '(';
1778 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1779 for (const formation_id of sorted_formation_id) {
1783 let desc = find_formation(formation_id)['name'];
1784 if (common_prefix === null) {
1787 text += desc.substr(common_prefix.length);
1792 if (common_prefix !== null) {
1795 } else if (filter.type === 'starting_on') {
1796 text = 'Starting on: ';
1798 if (filter.elements.has(false) && filter.elements.has(true)) {
1800 } else if (filter.elements.has(false)) {
1805 } else if (filter.type === 'gender_ratio') {
1809 for (const name of Array.from(filter.elements).sort()) {
1813 text += name; // FIXME
1818 let text_node = document.createElement('span');
1819 text_node.innerText = text;
1820 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1821 pill.appendChild(text_node);
1823 pill.appendChild(document.createTextNode(' '));
1825 let delete_node = document.createElement('span');
1826 delete_node.innerText = '✖';
1827 delete_node.addEventListener('click', (e) => {
1828 // Delete this filter entirely.
1829 pill.parentElement.removeChild(pill);
1830 inplace_filter(filterset, f => f !== filter);
1831 if (filterset.length == 0) {
1832 try_gc_filter_menus(false);
1834 process_matches(global_json, global_filters);
1836 let add_menu = document.getElementById('filter-add-menu');
1837 let add_submenu = document.getElementById('filter-submenu');
1838 add_menu.style.display = 'none';
1839 add_submenu.style.display = 'none';
1841 pill.appendChild(delete_node);
1842 pill.style.cursor = 'pointer';
1847 function make_filter_marker(filterset) {
1849 for (const filter of filterset) {
1853 if (filter.type === 'match') {
1855 for (const match of global_json['matches']) {
1856 all_names.push(match['description']);
1858 let common_prefix = find_common_prefix_of_all(all_names);
1860 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1861 for (const match_id of sorted_match_id) {
1862 let desc = find_match(match_id)['description'];
1863 if (common_prefix === null) {
1864 text += desc.substr(0, 3);
1866 text += desc.substr(common_prefix.length, 3);
1869 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1870 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1871 for (const player_id of sorted_players) {
1872 text += find_player(player_id)['name'].substr(0, 3);
1874 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1875 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1876 for (const formation_id of sorted_formation_id) {
1877 text += find_formation(formation_id)['name'].substr(0, 3);
1879 } else if (filter.type === 'starting_on') {
1880 if (filter.elements.has(false) && filter.elements.has(true)) {
1882 } else if (filter.elements.has(false)) {
1887 } else if (filter.type === 'gender_ratio') {
1889 for (const name of Array.from(filter.elements).sort()) {
1893 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
1901 function find_common_prefix(a, b) {
1903 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1904 if (a[i] === b[i]) {
1913 function find_common_prefix_of_all(values) {
1914 if (values.length < 2) {
1917 let common_prefix = null;
1918 for (const desc of values) {
1919 if (common_prefix === null) {
1920 common_prefix = desc;
1922 common_prefix = find_common_prefix(common_prefix, desc);
1925 if (common_prefix.length >= 3) {
1926 return common_prefix;
1932 function find_match(match_id) {
1933 for (const match of global_json['matches']) {
1934 if (match['match_id'] === match_id) {
1941 function find_formation(formation_id) {
1942 for (const formation of global_json['formations']) {
1943 if (formation['formation_id'] === formation_id) {
1950 function find_player(player_id) {
1951 for (const player of global_json['players']) {
1952 if (player['player_id'] === player_id) {
1959 function player_pos(player_id) {
1961 for (const player of global_json['players']) {
1962 if (player['player_id'] === player_id) {
1970 function keep_match(match_id, filters) {
1971 for (const filter of filters) {
1972 if (filter.type === 'match') {
1973 return filter.elements.has(match_id);
1979 // Returns a map of e.g. F => 4, M => 3.
1980 function find_gender_ratio(players) {
1982 for (const [q,p] of Object.entries(players)) {
1983 if (p.on_field_since === null) {
1986 let gender = p.gender;
1987 if (gender === '' || gender === undefined || gender === null) {
1990 if (map[gender] === undefined) {
1999 function find_gender_ratio_code(players) {
2000 let map = find_gender_ratio(players);
2001 let all_genders = Array.from(Object.keys(map)).sort(
2003 if (map[a] !== map[b]) {
2004 return map[b] - map[a]; // Reverse numeric.
2014 for (const g of all_genders) {
2025 // null if none (e.g., if playing 3–3).
2026 function find_predominant_gender(players) {
2028 let predominant_gender = null;
2029 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2032 predominant_gender = gender;
2033 } else if (num == max) {
2034 predominant_gender = null; // At least two have the same.
2037 return predominant_gender;
2040 function find_num_players_on_field(players) {
2042 for (const [q,p] of Object.entries(players)) {
2043 if (p.on_field_since !== null) {
2050 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2051 if (filter.type === 'player_any') {
2052 for (const p of Array.from(filter.elements)) {
2053 if (players[p].on_field_since !== null) {
2058 } else if (filter.type === 'player_all') {
2059 for (const p of Array.from(filter.elements)) {
2060 if (players[p].on_field_since === null) {
2065 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2066 for (const f of Array.from(filter.elements)) {
2067 if (formations_used_this_point.has(f)) {
2072 } else if (filter.type === 'starting_on') {
2073 return filter.elements.has(last_pull_was_ours);
2074 } else if (filter.type === 'gender_ratio') {
2075 return filter.elements.has(find_gender_ratio_code(players));
2080 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2081 for (const filter of filters) {
2082 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2089 // Heuristic: If we go at least ten seconds without the possession changing
2090 // or the operator specifying some other formation, we probably play the
2091 // same formation as the last point.
2092 function should_reuse_last_formation(events, t) {
2093 for (const e of events) {
2097 if (e.t > t + 10000) {
2100 const type = e.type;
2101 if (type === 'their_goal' || type === 'goal' ||
2102 type === 'set_defense' || type === 'set_offense' ||
2103 type === 'throwaway' || type === 'their_throwaway' ||
2104 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2105 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2106 type === 'formation_offense' || type === 'formation_defense') {
2113 function possibly_close_menu(e) {
2114 if (e.target.closest('.filter-click-to-add') === null &&
2115 e.target.closest('#filter-add-menu') === null &&
2116 e.target.closest('#filter-submenu') === null &&
2117 e.target.closest('.filter-pill') === null) {
2118 let add_menu = document.getElementById('filter-add-menu');
2119 let add_submenu = document.getElementById('filter-submenu');
2120 add_menu.style.display = 'none';
2121 add_submenu.style.display = 'none';
2122 try_gc_filter_menus(false);
2126 let global_sort = {};
2128 function sort_by(th) {
2129 let tr = th.parentElement;
2131 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2132 let element = tr.children[column_idx];
2133 if (element === th) {
2134 ++child_idx; // Pad.
2137 if (element.hasAttribute('colspan')) {
2138 child_idx += parseInt(element.getAttribute('colspan'));
2145 let table = tr.parentElement;
2146 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2147 let row = table.children[row_idx];
2148 let player = parseInt(row.dataset.player);
2149 let value = row.children[child_idx].textContent;
2150 global_sort[player] = value;
2154 function get_sorted_players(players)
2156 let p = Object.entries(players);
2157 if (global_sort.length !== 0) {
2159 let ai = parseFloat(global_sort[a[0]]);
2160 let bi = parseFloat(global_sort[b[0]]);
2161 if (ai == ai && bi == bi) {
2162 return bi - ai; // Reverse numeric.
2163 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2165 } else if (global_sort[a[0]] > global_sort[b[0]]) {