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 between_points = false;
374 } else if (type === 'catch' && last_pull_was_ours === null) {
375 // Someone forgot to add the pull, so we'll need to wing it.
376 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
378 last_pull_was_ours = !offense;
379 between_points = false;
380 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
381 if (type === 'goal') {
382 if (keep) ++p.touches;
383 ++touches_this_possession;
385 for (const [q,p] of Object.entries(players)) {
386 if (p.on_field_since === null) {
389 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
391 // In case the player did nothing this point,
392 // not even subbing in.
393 p.last_point_seen = point_num;
397 if (keep) attribute_player_time(p, t, live_since, offense);
399 if (type !== 'stoppage') {
401 if (last_pull_was_ours === true) { // D point.
402 ++p.defensive_points_completed;
403 if (type === 'goal') {
404 ++p.defensive_points_won;
406 } else if (last_pull_was_ours === false) { // O point.
407 ++p.offensive_points_completed;
408 if (type === 'goal') {
409 ++p.offensive_points_won;
417 if (type !== 'stoppage') {
419 ++globals.points_played;
420 if (last_pull_was_ours === true) { // D point.
421 ++globals.defensive_points_completed;
422 if (type === 'goal') {
423 ++globals.defensive_points_won;
425 } else if (last_pull_was_ours === false) { // O point.
426 ++globals.offensive_points_completed;
427 if (type === 'goal') {
428 ++globals.offensive_points_won;
432 if (live_since !== null) {
433 globals.playing_time_ms += t - live_since;
434 if (offense === true) {
435 globals.offensive_playing_time_ms += t - live_since;
436 } else if (offense === false) {
437 globals.defensive_playing_time_ms += t - live_since;
446 if (type === 'goal') {
448 } else if (type === 'their_goal') {
452 // Point count management
453 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
455 p.last_point_seen = point_num;
459 if (type === 'goal' || type === 'their_goal') {
463 if (type !== 'out' && game_started === null) {
468 if (type === 'pull') {
469 puller = e['player'];
472 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
473 // No effect on pull.
474 } else if (type === 'pull_landed' && puller !== null) {
475 if (keep) players[puller].pull_times.push(t - pull_started);
476 } else if (type === 'pull_oob' && puller !== null) {
477 if (keep) ++players[puller].oob_pulls;
479 // Not pulling (if there was one, we never recorded its outcome, but still count it).
480 puller = pull_started = null;
483 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
485 if (type === 'goal' && !we_lost_disc) {
486 if (last_pull_was_ours === false) { // O point.
487 ++globals.clean_holds;
488 } else if (last_pull_was_ours === true) {
489 ++globals.clean_breaks;
491 } else if (type === 'their_goal' && !they_lost_disc) {
492 if (last_pull_was_ours === true) { // O point for them.
493 ++globals.their_clean_holds;
494 } else if (last_pull_was_ours === false) {
495 ++globals.their_clean_breaks;
500 // Offense/defense management
501 let last_offense = offense;
502 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
505 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
506 ++globals.turnovers_lost;
507 globals.touches_for_turnover += touches_this_possession;
508 } else if (keep && type === 'goal') {
509 globals.touches_for_goal += touches_this_possession;
511 touches_this_possession = 0;
512 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
514 they_lost_disc = true;
515 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
516 ++globals.turnovers_won;
518 touches_this_possession = 0;
520 if (type === 'goal' || type === 'their_goal') {
521 between_points = true;
522 we_lost_disc = false;
523 they_lost_disc = false;
524 touches_this_possession = 0;
526 if (last_offense !== offense && live_since !== null) {
527 // Switched offense/defense status, so attribute this drive as needed,
528 // and update live_since to take that into account.
530 for (const [q,p] of Object.entries(players)) {
531 if (p.on_field_since === null) {
534 attribute_player_time(p, t, live_since, last_offense);
536 globals.playing_time_ms += t - live_since;
537 if (offense === true) {
538 globals.offensive_playing_time_ms += t - live_since;
539 } else if (offense === false) {
540 globals.defensive_playing_time_ms += t - live_since;
546 if (type === 'pull') {
547 last_pull_was_ours = true;
548 } else if (type === 'their_pull') {
549 last_pull_was_ours = false;
550 } else if (type === 'set_offense' && last_pull_was_ours === null) {
551 // set_offense could either be “changed to offense for some reason
552 // we could not express”, or “we started in the middle of a point,
553 // and we are offense”. We assume that if we already saw the pull,
554 // it's the former, and if not, it's the latter; thus, the === null
555 // test above. (It could also be “we set offense before the pull,
556 // so that we get the right button enabled”, in which case it will
557 // be overwritten by the next pull/their_pull event anyway.)
558 last_pull_was_ours = false;
559 } else if (type === 'set_defense' && last_pull_was_ours === null) {
561 last_pull_was_ours = true;
562 } else if (type === 'goal' || type === 'their_goal') {
563 last_pull_was_ours = null;
566 // Formation management
567 if (type === 'formation_offense' || type === 'formation_defense') {
568 let id = e.formation === null ? 0 : e.formation;
569 let for_offense = (type === 'formation_offense');
570 if (offense === for_offense) {
571 formations_used_this_point.add(id);
572 } else if (for_offense) {
573 pending_offensive_formation = id;
575 pending_defensive_formation = id;
578 last_offensive_formation = id;
580 last_defensive_formation = id;
582 } else if (last_offense !== offense) {
583 if (offense === true && pending_offensive_formation !== null) {
584 formations_used_this_point.add(pending_offensive_formation);
585 pending_offensive_formation = null;
586 } else if (offense === false && pending_defensive_formation !== null) {
587 formations_used_this_point.add(pending_defensive_formation);
588 pending_defensive_formation = null;
589 } else if (offense === true && last_defensive_formation !== null) {
590 if (should_reuse_last_formation(match['events'], t)) {
591 formations_used_this_point.add(last_defensive_formation);
593 } else if (offense === false && last_offensive_formation !== null) {
594 if (should_reuse_last_formation(match['events'], t)) {
595 formations_used_this_point.add(last_offensive_formation);
600 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
601 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
603 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
604 // The handler subbed out and was replaced with another handler,
605 // so this wasn't a pass.
610 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
611 // Self-pass to goal after an interception; this is not a real pass,
612 // just how we represent a Callahan right now -- so don't
613 // count the throw, any assists or similar.
615 // It's an open question how we should handle a self-pass that is
616 // _not_ after an interception, or a self-pass that's not a goal.
617 // (It must mean we tipped off someone.) We'll count it as a regular one
618 // for the time being, although it will make hockey assists weird.
623 handler = prev_handler = null;
624 } else if (type === 'catch' || type === 'goal') {
625 if (handler !== null) {
627 ++players[handler].num_throws;
632 if (keep) ++p.touches;
633 ++touches_this_possession;
634 if (type === 'goal') {
636 if (prev_handler !== null) {
637 ++players[prev_handler].hockey_assists;
639 if (handler !== null) {
640 ++players[handler].assists;
644 handler = prev_handler = null;
646 // Update hold history.
647 prev_handler = handler;
648 handler = e['player'];
649 handler_got_by_interception = false;
651 } else if (type === 'throwaway') {
656 handler = prev_handler = null;
657 } else if (type === 'drop') {
659 handler = prev_handler = null;
660 } else if (type === 'stallout') {
661 if (keep) ++p.stallouts;
662 handler = prev_handler = null;
663 } else if (type === 'was_d') {
664 if (keep) ++p.was_ds;
665 handler = prev_handler = null;
666 } else if (type === 'defense') {
667 if (keep) ++p.defenses;
668 } else if (type === 'interception') {
673 ++touches_this_possession;
676 handler = e['player'];
677 handler_got_by_interception = true;
678 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
680 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
681 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
682 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
683 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
684 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
685 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
686 type !== 'formation_offense' && type !== 'formation_defense') {
687 console.log(format_time(t) + ": Unknown event “" + e + "”");
690 if (type === 'goal' || type === 'their_goal') {
691 formations_used_this_point.clear();
695 // Add field time for all players still left at match end.
696 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
698 for (const [q,p] of Object.entries(players)) {
699 if (p.on_field_since !== null && last_goal !== null) {
700 p.field_time_ms += last_goal - p.on_field_since;
703 if (game_started !== null && last_goal !== null) {
704 globals.field_time_ms += last_goal - game_started;
706 if (live_since !== null && last_goal !== null) {
707 globals.playing_time_ms += last_goal - live_since;
708 if (offense === true) {
709 globals.offensive_playing_time_ms += last_goal - live_since;
710 } else if (offense === false) {
711 globals.defensive_playing_time_ms += last_goal - live_since;
719 function process_matches(json, filtersets) {
720 let chosen_category = get_chosen_category();
721 write_main_menu(chosen_category);
723 let filterset_values = Object.values(filtersets);
724 if (filterset_values.length === 0) {
725 filterset_values = [[]];
729 for (const filter of filterset_values) {
730 let players = calc_stats(json, filter);
732 if (chosen_category === 'general') {
733 rows = make_table_general(players);
734 } else if (chosen_category === 'offense') {
735 rows = make_table_offense(players);
736 } else if (chosen_category === 'defense') {
737 rows = make_table_defense(players);
738 } else if (chosen_category === 'playing_time') {
739 rows = make_table_playing_time(players);
740 } else if (chosen_category === 'per_point') {
741 rows = make_table_per_point(players);
742 } else if (chosen_category === 'team_wide') {
743 rows = make_table_team_wide(players);
748 let merged_rows = [];
749 if (filterset_values.length > 1) {
750 for (let i = 0; i < rowsets.length; ++i) {
751 let marker = make_filter_marker(filterset_values[i]);
753 // Make filter header.
754 let tr = rowsets[i][0];
755 let th = document.createElement('th');
757 tr.insertBefore(th, tr.firstChild);
759 for (let j = 1; j < rowsets[i].length; ++j) {
760 let tr = rowsets[i][j];
762 // Remove the name for cleanness.
764 tr.firstChild.nextSibling.textContent = '';
768 tr.style.borderTop = '0px';
770 if (i != rowsets.length - 1) {
771 tr.style.borderBottom = '0px';
774 // Make filter marker.
775 let td = document.createElement('td');
776 td.textContent = marker;
777 td.classList.add('filtermarker');
778 tr.insertBefore(td, tr.firstChild);
782 for (let i = 0; i < rowsets[0].length; ++i) {
783 for (let j = 0; j < rowsets.length; ++j) {
784 merged_rows.push(rowsets[j][i]);
785 if (i === 0) break; // Don't merge the headings.
789 merged_rows = rowsets[0];
791 document.getElementById('stats').replaceChildren(...merged_rows);
794 function get_chosen_category() {
795 if (window.location.hash === '#offense') {
797 } else if (window.location.hash === '#defense') {
799 } else if (window.location.hash === '#playing_time') {
800 return 'playing_time';
801 } else if (window.location.hash === '#per_point') {
803 } else if (window.location.hash === '#team_wide') {
810 function write_main_menu(chosen_category) {
813 ['general', 'General'],
814 ['offense', 'Offense'],
815 ['defense', 'Defense'],
816 ['playing_time', 'Playing time'],
817 ['per_point', 'Per point'],
818 ['team_wide', 'Team-wide'],
820 for (const [id, title] of categories) {
821 if (chosen_category === id) {
822 let span = document.createElement('span');
823 span.innerText = title;
826 let a = document.createElement('a');
827 a.appendChild(document.createTextNode(title));
828 a.setAttribute('href', '#' + id);
833 document.getElementById('mainmenu').replaceChildren(...elems);
836 // https://en.wikipedia.org/wiki/1.96#History
839 const ci_width = 100;
840 const ci_height = 20;
842 function make_binomial_ci(val, num, z) {
845 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
846 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
847 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
849 // Fix the signs so that we don't get -0.00.
850 low = Math.max(low, 0.0);
860 // These can only happen once per point, but you get -1 and +1
861 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
862 // and then we can rewrite back.
863 function make_efficiency_ci(points_won, points_completed, z)
865 let ci = make_binomial_ci(points_won, points_completed, z);
866 ci.val = 2.0 * ci.val - 1.0;
867 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
868 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
871 ci.desired = 0.0; // Desired = positive efficiency.
875 // Ds, throwaways and drops can happen multiple times per point,
876 // so they are Poisson distributed.
878 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
879 // since our rates are definitely below 2 per point).
881 // FIXME: z is ignored.
882 function make_poisson_ci(val, num, z, inverted)
884 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
885 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
887 // Fix the signs so that we don't get -0.00.
888 low = Math.max(low, 0.0);
890 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
899 'inverted': inverted,
903 // Wilson and Hilferty, again recommended for general use in the PDF above
904 // (anything from their group “G1” works).
905 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
906 function make_poisson_ci_large(val, num, z, inverted)
908 let low = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
909 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;
911 // Fix the signs so that we don't get -0.00.
912 low = Math.max(low, 0.0);
914 // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
915 // (this is used for number of touches).
924 'inverted': inverted,
928 function make_table_general(players) {
931 let header = document.createElement('tr');
932 add_th(header, 'Player');
933 add_th(header, '+/-');
934 add_th(header, 'Soft +/-');
935 add_th(header, 'O efficiency');
936 add_th(header, 'D efficiency');
937 add_th(header, 'Points played');
941 for (const [q,p] of get_sorted_players(players)) {
942 if (q === 'globals') continue;
943 let row = document.createElement('tr');
944 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
945 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
946 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
947 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
948 let name = add_3cell(row, p.name, 'name'); // TODO: number?
949 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
950 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
951 add_3cell_ci(row, o_efficiency);
952 add_3cell_ci(row, d_efficiency);
953 add_3cell(row, p.points_played);
954 row.dataset.player = q;
959 let globals = players['globals'];
960 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
961 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
962 let row = document.createElement('tr');
966 add_3cell_ci(row, o_efficiency);
967 add_3cell_ci(row, d_efficiency);
968 add_3cell(row, globals.points_played);
974 function make_table_team_wide(players) {
975 let globals = players['globals'];
979 let header = document.createElement('tr');
981 add_th(header, 'Our team', 6);
982 add_th(header, 'Opponents', 6);
988 let row = document.createElement('tr');
989 let name = add_3cell(row, 'Turnovers generated', 'name');
990 add_3cell(row, globals.turnovers_won);
992 add_3cell(row, globals.turnovers_lost);
999 let row = document.createElement('tr');
1000 let name = add_3cell(row, 'Clean holds', 'name');
1001 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1002 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1003 our_clean_holds.desired = 0.3; // Arbitrary.
1004 our_clean_holds.format = 'percentage';
1005 their_clean_holds.desired = 0.3;
1006 their_clean_holds.format = 'percentage';
1007 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1008 add_3cell_ci(row, our_clean_holds);
1009 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1010 add_3cell_ci(row, their_clean_holds);
1016 let row = document.createElement('tr');
1017 let name = add_3cell(row, 'Clean breaks', 'name');
1018 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1019 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1020 our_clean_breaks.desired = 0.3; // Arbitrary.
1021 our_clean_breaks.format = 'percentage';
1022 their_clean_breaks.desired = 0.3;
1023 their_clean_breaks.format = 'percentage';
1024 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1025 add_3cell_ci(row, our_clean_breaks);
1026 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1027 add_3cell_ci(row, their_clean_breaks);
1031 // Touches. We only have information for our team here.
1034 for (const [q,p] of get_sorted_players(players)) {
1035 if (q === 'globals') continue;
1039 let row = document.createElement('tr');
1040 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1041 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1042 let possessions = goals + globals.turnovers_lost;
1044 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1049 row = document.createElement('tr');
1050 add_3cell(row, 'Touches per possession (goals)', 'name');
1052 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1057 row = document.createElement('tr');
1058 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1060 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1069 function make_table_offense(players) {
1072 let header = document.createElement('tr');
1073 add_th(header, 'Player');
1074 add_th(header, 'Goals');
1075 add_th(header, 'Assists');
1076 add_th(header, 'Hockey assists');
1077 add_th(header, 'Throws');
1078 add_th(header, 'Throwaways');
1079 add_th(header, '%OK');
1080 add_th(header, 'Catches');
1081 add_th(header, 'Drops');
1082 add_th(header, 'D-ed');
1083 add_th(header, '%OK');
1084 add_th(header, 'Stalls');
1085 add_th(header, 'Soft +/-', 6);
1096 for (const [q,p] of get_sorted_players(players)) {
1097 if (q === 'globals') continue;
1098 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1099 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1101 throw_ok.format = 'percentage';
1102 catch_ok.format = 'percentage';
1104 // Desire at least 90% percentage. Fairly arbitrary.
1105 throw_ok.desired = 0.9;
1106 catch_ok.desired = 0.9;
1108 let row = document.createElement('tr');
1109 add_3cell(row, p.name, 'name'); // TODO: number?
1110 add_3cell(row, p.goals);
1111 add_3cell(row, p.assists);
1112 add_3cell(row, p.hockey_assists);
1113 add_3cell(row, p.num_throws);
1114 add_3cell(row, p.throwaways);
1115 add_3cell_ci(row, throw_ok);
1116 add_3cell(row, p.catches);
1117 add_3cell(row, p.drops);
1118 add_3cell(row, p.was_ds);
1119 add_3cell_ci(row, catch_ok);
1120 add_3cell(row, p.stallouts);
1121 add_3cell(row, '+' + p.offensive_soft_plus);
1122 add_3cell(row, '-' + p.offensive_soft_minus);
1123 row.dataset.player = q;
1127 num_throws += p.num_throws;
1128 throwaways += p.throwaways;
1129 catches += p.catches;
1132 stallouts += p.stallouts;
1136 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1137 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1138 throw_ok.format = 'percentage';
1139 catch_ok.format = 'percentage';
1140 throw_ok.desired = 0.9;
1141 catch_ok.desired = 0.9;
1143 let row = document.createElement('tr');
1145 add_3cell(row, goals);
1148 add_3cell(row, num_throws);
1149 add_3cell(row, throwaways);
1150 add_3cell_ci(row, throw_ok);
1151 add_3cell(row, catches);
1152 add_3cell(row, drops);
1153 add_3cell(row, was_ds);
1154 add_3cell_ci(row, catch_ok);
1155 add_3cell(row, stallouts);
1163 function make_table_defense(players) {
1166 let header = document.createElement('tr');
1167 add_th(header, 'Player');
1168 add_th(header, 'Ds');
1169 add_th(header, 'Pulls');
1170 add_th(header, 'OOB pulls');
1171 add_th(header, 'OOB%');
1172 add_th(header, 'Avg. hang time (IB)');
1173 add_th(header, 'Callahans');
1174 add_th(header, 'Soft +/-', 6);
1181 let sum_sum_time = 0;
1184 for (const [q,p] of get_sorted_players(players)) {
1185 if (q === 'globals') continue;
1187 for (const t of p.pull_times) {
1190 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1191 let oob_pct = 100 * p.oob_pulls / p.pulls;
1193 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1194 ci_oob.format = 'percentage';
1195 ci_oob.desired = 0.2; // Arbitrary.
1196 ci_oob.inverted = true;
1198 let row = document.createElement('tr');
1199 add_3cell(row, p.name, 'name'); // TODO: number?
1200 add_3cell(row, p.defenses);
1201 add_3cell(row, p.pulls);
1202 add_3cell(row, p.oob_pulls);
1203 add_3cell_ci(row, ci_oob);
1204 if (p.pulls > p.oob_pulls) {
1205 add_3cell(row, avg_time.toFixed(1) + ' sec');
1207 add_3cell(row, 'N/A');
1209 add_3cell(row, p.callahans);
1210 add_3cell(row, '+' + p.defensive_soft_plus);
1211 add_3cell(row, '-' + p.defensive_soft_minus);
1212 row.dataset.player = q;
1215 defenses += p.defenses;
1217 oob_pulls += p.oob_pulls;
1218 sum_sum_time += sum_time;
1219 callahans += p.callahans;
1223 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1224 ci_oob.format = 'percentage';
1225 ci_oob.desired = 0.2; // Arbitrary.
1226 ci_oob.inverted = true;
1228 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1229 let oob_pct = 100 * oob_pulls / pulls;
1231 let row = document.createElement('tr');
1233 add_3cell(row, defenses);
1234 add_3cell(row, pulls);
1235 add_3cell(row, oob_pulls);
1236 add_3cell_ci(row, ci_oob);
1237 if (pulls > oob_pulls) {
1238 add_3cell(row, avg_time.toFixed(1) + ' sec');
1240 add_3cell(row, 'N/A');
1242 add_3cell(row, callahans);
1250 function make_table_playing_time(players) {
1253 let header = document.createElement('tr');
1254 add_th(header, 'Player');
1255 add_th(header, 'Points played');
1256 add_th(header, 'Time played');
1257 add_th(header, 'O time');
1258 add_th(header, 'D time');
1259 add_th(header, 'Time on field');
1260 add_th(header, 'O points');
1261 add_th(header, 'D points');
1265 for (const [q,p] of get_sorted_players(players)) {
1266 if (q === 'globals') continue;
1267 let row = document.createElement('tr');
1268 add_3cell(row, p.name, 'name'); // TODO: number?
1269 add_3cell(row, p.points_played);
1270 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1271 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1272 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1273 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1274 add_3cell(row, p.offensive_points_completed);
1275 add_3cell(row, p.defensive_points_completed);
1276 row.dataset.player = q;
1281 let globals = players['globals'];
1282 let row = document.createElement('tr');
1284 add_3cell(row, globals.points_played);
1285 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1286 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1287 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1288 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1289 add_3cell(row, globals.offensive_points_completed);
1290 add_3cell(row, globals.defensive_points_completed);
1296 function make_table_per_point(players) {
1299 let header = document.createElement('tr');
1300 add_th(header, 'Player');
1301 add_th(header, 'Goals');
1302 add_th(header, 'Assists');
1303 add_th(header, 'Hockey assists');
1304 add_th(header, 'Ds');
1305 add_th(header, 'Throwaways');
1306 add_th(header, 'Recv. errors');
1307 add_th(header, 'Touches');
1313 let hockey_assists = 0;
1316 let receiver_errors = 0;
1318 for (const [q,p] of get_sorted_players(players)) {
1319 if (q === 'globals') continue;
1321 // Can only happen once per point, so these are binomials.
1322 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1323 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1324 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1325 // Arbitrarily desire at least 10% (not everybody can score or assist).
1326 ci_goals.desired = 0.1;
1327 ci_assists.desired = 0.1;
1328 ci_hockey_assists.desired = 0.1;
1330 let row = document.createElement('tr');
1331 add_3cell(row, p.name, 'name'); // TODO: number?
1332 add_3cell_ci(row, ci_goals);
1333 add_3cell_ci(row, ci_assists);
1334 add_3cell_ci(row, ci_hockey_assists);
1335 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1336 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1337 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1338 if (p.points_played > 0) {
1339 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1341 add_3cell(row, 'N/A');
1343 row.dataset.player = q;
1347 assists += p.assists;
1348 hockey_assists += p.hockey_assists;
1349 defenses += p.defenses;
1350 throwaways += p.throwaways;
1351 receiver_errors += p.drops + p.was_ds;
1352 touches += p.touches;
1356 let globals = players['globals'];
1357 let row = document.createElement('tr');
1359 if (globals.points_played > 0) {
1360 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1361 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1362 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1363 ci_goals.desired = 0.5;
1364 ci_assists.desired = 0.5;
1365 ci_hockey_assists.desired = 0.5;
1367 add_3cell_ci(row, ci_goals);
1368 add_3cell_ci(row, ci_assists);
1369 add_3cell_ci(row, ci_hockey_assists);
1371 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1372 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1373 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1375 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1377 add_3cell_with_filler_ci(row, 'N/A');
1378 add_3cell_with_filler_ci(row, 'N/A');
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(row, 'N/A');
1390 function open_filter_menu(click_to_add_div) {
1391 document.getElementById('filter-submenu').style.display = 'none';
1392 let filter_div = click_to_add_div.parentElement;
1393 let filter_id = filter_div.dataset.filterId;
1395 let menu = document.getElementById('filter-add-menu');
1396 menu.parentElement.removeChild(menu);
1397 filter_div.appendChild(menu);
1398 menu.style.display = 'block';
1399 menu.replaceChildren();
1401 // Place the menu directly under the “click to add” label;
1402 // we don't anchor it since that label will move around
1403 // and the menu shouldn't.
1404 let rect = click_to_add_div.getBoundingClientRect();
1405 menu.style.left = rect.left + 'px';
1406 menu.style.top = (rect.bottom + 10) + 'px';
1408 let filterset = global_filters[filter_id];
1409 if (filterset === undefined) {
1410 global_filters[filter_id] = filterset = [];
1413 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1414 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1415 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1416 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1417 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1418 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1419 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1422 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1423 let item = document.createElement('div');
1424 item.classList.add('option');
1425 item.appendChild(document.createTextNode(title));
1427 let arrow = document.createElement('div');
1428 arrow.classList.add('arrow');
1429 arrow.textContent = '▸';
1430 item.appendChild(arrow);
1432 menu.appendChild(item);
1434 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1437 function find_all_ratios(json)
1441 for (const player of json['players']) {
1442 players[player['player_id']] = {
1443 'gender': player['gender'],
1444 'last_point_seen': null,
1447 for (const match of json['matches']) {
1448 for (const [q,p] of Object.entries(players)) {
1449 p.on_field_since = null;
1451 for (const e of match['events']) {
1452 let p = players[e['player']];
1453 let type = e['type'];
1454 if (type === 'in') {
1455 p.on_field_since = 1;
1456 } else if (type === 'out') {
1457 p.on_field_since = null;
1458 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1459 let code = find_gender_ratio_code(players);
1460 if (ratios[code] === undefined) {
1461 ratios[code] = code;
1462 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1463 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1464 match['description'] + ', ' + format_time(e['t']));
1473 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1474 let submenu = document.getElementById('filter-submenu');
1476 // Move to the same place as the top-level menu.
1477 submenu.parentElement.removeChild(submenu);
1478 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1481 const filter = find_filter(filterset, filter_type);
1484 if (filter_type === 'match') {
1485 for (const match of global_json['matches']) {
1487 'title': match['description'],
1488 'id': match['match_id']
1491 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1492 for (const player of global_json['players']) {
1494 'title': player['name'],
1495 'id': player['player_id']
1498 } else if (filter_type === 'formation_offense') {
1500 'title': '(None/unknown)',
1503 for (const formation of global_json['formations']) {
1504 if (formation['offense']) {
1506 'title': formation['name'],
1507 'id': formation['formation_id']
1511 } else if (filter_type === 'formation_defense') {
1513 'title': '(None/unknown)',
1516 for (const formation of global_json['formations']) {
1517 if (!formation['offense']) {
1519 'title': formation['name'],
1520 'id': formation['formation_id']
1524 } else if (filter_type === 'starting_on') {
1527 'id': false, // last_pull_was_ours
1531 'id': true, // last_pull_was_ours
1533 } else if (filter_type === 'gender_ratio') {
1534 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1542 for (const choice of choices) {
1543 let label = document.createElement('label');
1545 let subitem = document.createElement('div');
1546 subitem.classList.add('option');
1548 let check = document.createElement('input');
1549 check.setAttribute('type', 'checkbox');
1550 check.setAttribute('id', 'choice' + choice.id);
1551 if (filter !== null && filter.elements.has(choice.id)) {
1552 check.setAttribute('checked', 'checked');
1554 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1556 subitem.appendChild(check);
1557 subitem.appendChild(document.createTextNode(choice.title));
1559 label.appendChild(subitem);
1560 subitems.push(label);
1562 submenu.replaceChildren(...subitems);
1563 submenu.style.display = 'block';
1565 if (pill !== null) {
1566 let rect = pill.getBoundingClientRect();
1567 submenu.style.top = (rect.bottom + 10) + 'px';
1568 submenu.style.left = rect.left + 'px';
1570 // Position just outside the selected menu.
1571 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1572 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1573 submenu.style.left = (rect.right - 1) + 'px';
1577 // Find the right filter, if it exists.
1578 function find_filter(filterset, filter_type) {
1579 for (let f of filterset) {
1580 if (f.type === filter_type) {
1587 // Equivalent to Array.prototype.filter, but in-place.
1588 function inplace_filter(arr, cond) {
1590 for (let i = 0; i < arr.length; ++i) {
1598 function add_new_filterset() {
1599 let template = document.querySelector('.filter'); // First one is fine.
1600 let div = template.cloneNode(true);
1601 let add_menu = div.querySelector('#filter-add-menu');
1602 if (add_menu !== null) {
1603 div.removeChild(add_menu);
1605 let submenu = div.querySelector('#filter-submenu');
1606 if (submenu !== null) {
1607 div.removeChild(submenu);
1609 div.querySelector('.filters').replaceChildren();
1610 div.dataset.filterId = next_filterset_id++;
1611 template.parentElement.appendChild(div);
1614 function try_gc_filter_menus(cheap) {
1617 for (const filter_div of document.querySelectorAll('.filter')) {
1618 let id = filter_div.dataset.filterId;
1619 divs.push(filter_div);
1620 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1622 let last_div = divs[empties.length - 1];
1624 // See if we have two empty filter lists at the bottom of the list;
1625 // if so, we can remove one without it looking funny in the UI.
1626 // If not, we'll have to wait until closing the menu.
1627 // (The menu is positioned at the second-last one, so we can
1628 // remove the last one without issue.)
1629 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1630 delete global_filters[last_div.dataset.filterId];
1631 last_div.parentElement.removeChild(last_div);
1634 // This is a different situation from try_cheap_gc(), where we should
1635 // remove the one _not_ last. We might need to move the menu to the last one,
1636 // though, so it doesn't get lost.
1637 for (let i = 0; i < empties.length - 1; ++i) {
1642 delete global_filters[div.dataset.filterId];
1643 let add_menu = div.querySelector('#filter-add-menu');
1644 if (add_menu !== null) {
1645 div.removeChild(add_menu);
1646 last_div.appendChild(add_menu);
1648 let submenu = div.querySelector('#filter-submenu');
1649 if (submenu !== null) {
1650 div.removeChild(submenu);
1651 last_div.appendChild(submenu);
1653 div.parentElement.removeChild(div);
1658 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1659 let filter = find_filter(filterset, filter_type);
1660 let pills_div = filter_div.querySelector('.filters');
1661 if (e.target.checked) {
1662 // See if we must create a new empty filterset (since this went from
1663 // empty to non-empty).
1664 if (filterset.length === 0) {
1665 add_new_filterset();
1668 // See if we must add a new filter to the list.
1669 if (filter === null) {
1671 'type': filter_type,
1672 'elements': new Set([ id ]),
1674 filter.pill = make_filter_pill(filter_div, filterset, filter);
1675 filterset.push(filter);
1676 pills_div.appendChild(filter.pill);
1678 filter.elements.add(id);
1679 let new_pill = make_filter_pill(filter_div, filterset, filter);
1680 pills_div.replaceChild(new_pill, filter.pill);
1681 filter.pill = new_pill;
1684 filter.elements.delete(id);
1685 if (filter.elements.size === 0) {
1686 pills_div.removeChild(filter.pill);
1687 inplace_filter(filterset, f => f !== filter);
1689 if (filterset.length == 0) {
1690 try_gc_filter_menus(true);
1693 let new_pill = make_filter_pill(filter_div, filterset, filter);
1694 pills_div.replaceChild(new_pill, filter.pill);
1695 filter.pill = new_pill;
1699 process_matches(global_json, global_filters);
1702 function make_filter_pill(filter_div, filterset, filter) {
1703 let pill = document.createElement('div');
1704 pill.classList.add('filter-pill');
1706 if (filter.type === 'match') {
1710 for (const match_id of filter.elements) {
1711 all_names.push(find_match(match_id)['description']);
1713 let common_prefix = find_common_prefix_of_all(all_names);
1714 if (common_prefix !== null) {
1715 text += common_prefix + '(';
1719 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1720 for (const match_id of sorted_match_id) {
1724 let desc = find_match(match_id)['description'];
1725 if (common_prefix === null) {
1728 text += desc.substr(common_prefix.length);
1733 if (common_prefix !== null) {
1736 } else if (filter.type === 'player_any') {
1737 text = 'Player (any): ';
1738 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1740 for (const player_id of sorted_players) {
1744 text += find_player(player_id)['name'];
1747 } else if (filter.type === 'player_all') {
1749 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1751 for (const player_id of sorted_players) {
1755 text += find_player(player_id)['name'];
1758 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1759 const offense = (filter.type === 'formation_offense');
1767 for (const formation_id of filter.elements) {
1768 all_names.push(find_formation(formation_id)['name']);
1770 let common_prefix = find_common_prefix_of_all(all_names);
1771 if (common_prefix !== null) {
1772 text += common_prefix + '(';
1776 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1777 for (const formation_id of sorted_formation_id) {
1781 let desc = find_formation(formation_id)['name'];
1782 if (common_prefix === null) {
1785 text += desc.substr(common_prefix.length);
1790 if (common_prefix !== null) {
1793 } else if (filter.type === 'starting_on') {
1794 text = 'Starting on: ';
1796 if (filter.elements.has(false) && filter.elements.has(true)) {
1798 } else if (filter.elements.has(false)) {
1803 } else if (filter.type === 'gender_ratio') {
1807 for (const name of Array.from(filter.elements).sort()) {
1811 text += name; // FIXME
1816 let text_node = document.createElement('span');
1817 text_node.innerText = text;
1818 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1819 pill.appendChild(text_node);
1821 pill.appendChild(document.createTextNode(' '));
1823 let delete_node = document.createElement('span');
1824 delete_node.innerText = '✖';
1825 delete_node.addEventListener('click', (e) => {
1826 // Delete this filter entirely.
1827 pill.parentElement.removeChild(pill);
1828 inplace_filter(filterset, f => f !== filter);
1829 if (filterset.length == 0) {
1830 try_gc_filter_menus(false);
1832 process_matches(global_json, global_filters);
1834 let add_menu = document.getElementById('filter-add-menu');
1835 let add_submenu = document.getElementById('filter-submenu');
1836 add_menu.style.display = 'none';
1837 add_submenu.style.display = 'none';
1839 pill.appendChild(delete_node);
1840 pill.style.cursor = 'pointer';
1845 function make_filter_marker(filterset) {
1847 for (const filter of filterset) {
1851 if (filter.type === 'match') {
1853 for (const match of global_json['matches']) {
1854 all_names.push(match['description']);
1856 let common_prefix = find_common_prefix_of_all(all_names);
1858 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1859 for (const match_id of sorted_match_id) {
1860 let desc = find_match(match_id)['description'];
1861 if (common_prefix === null) {
1862 text += desc.substr(0, 3);
1864 text += desc.substr(common_prefix.length, 3);
1867 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1868 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1869 for (const player_id of sorted_players) {
1870 text += find_player(player_id)['name'].substr(0, 3);
1872 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1873 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1874 for (const formation_id of sorted_formation_id) {
1875 text += find_formation(formation_id)['name'].substr(0, 3);
1877 } else if (filter.type === 'starting_on') {
1878 if (filter.elements.has(false) && filter.elements.has(true)) {
1880 } else if (filter.elements.has(false)) {
1885 } else if (filter.type === 'gender_ratio') {
1887 for (const name of Array.from(filter.elements).sort()) {
1891 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
1899 function find_common_prefix(a, b) {
1901 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1902 if (a[i] === b[i]) {
1911 function find_common_prefix_of_all(values) {
1912 if (values.length < 2) {
1915 let common_prefix = null;
1916 for (const desc of values) {
1917 if (common_prefix === null) {
1918 common_prefix = desc;
1920 common_prefix = find_common_prefix(common_prefix, desc);
1923 if (common_prefix.length >= 3) {
1924 return common_prefix;
1930 function find_match(match_id) {
1931 for (const match of global_json['matches']) {
1932 if (match['match_id'] === match_id) {
1939 function find_formation(formation_id) {
1940 for (const formation of global_json['formations']) {
1941 if (formation['formation_id'] === formation_id) {
1948 function find_player(player_id) {
1949 for (const player of global_json['players']) {
1950 if (player['player_id'] === player_id) {
1957 function player_pos(player_id) {
1959 for (const player of global_json['players']) {
1960 if (player['player_id'] === player_id) {
1968 function keep_match(match_id, filters) {
1969 for (const filter of filters) {
1970 if (filter.type === 'match') {
1971 return filter.elements.has(match_id);
1977 // Returns a map of e.g. F => 4, M => 3.
1978 function find_gender_ratio(players) {
1980 for (const [q,p] of Object.entries(players)) {
1981 if (p.on_field_since === null) {
1984 let gender = p.gender;
1985 if (gender === '' || gender === undefined || gender === null) {
1988 if (map[gender] === undefined) {
1997 function find_gender_ratio_code(players) {
1998 let map = find_gender_ratio(players);
1999 let all_genders = Array.from(Object.keys(map)).sort(
2001 if (map[a] !== map[b]) {
2002 return map[b] - map[a]; // Reverse numeric.
2012 for (const g of all_genders) {
2023 // null if none (e.g., if playing 3–3).
2024 function find_predominant_gender(players) {
2026 let predominant_gender = null;
2027 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2030 predominant_gender = gender;
2031 } else if (num == max) {
2032 predominant_gender = null; // At least two have the same.
2035 return predominant_gender;
2038 function find_num_players_on_field(players) {
2040 for (const [q,p] of Object.entries(players)) {
2041 if (p.on_field_since !== null) {
2048 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2049 if (filter.type === 'player_any') {
2050 for (const p of Array.from(filter.elements)) {
2051 if (players[p].on_field_since !== null) {
2056 } else if (filter.type === 'player_all') {
2057 for (const p of Array.from(filter.elements)) {
2058 if (players[p].on_field_since === null) {
2063 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2064 for (const f of Array.from(filter.elements)) {
2065 if (formations_used_this_point.has(f)) {
2070 } else if (filter.type === 'starting_on') {
2071 return filter.elements.has(last_pull_was_ours);
2072 } else if (filter.type === 'gender_ratio') {
2073 return filter.elements.has(find_gender_ratio_code(players));
2078 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2079 for (const filter of filters) {
2080 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2087 // Heuristic: If we go at least ten seconds without the possession changing
2088 // or the operator specifying some other formation, we probably play the
2089 // same formation as the last point.
2090 function should_reuse_last_formation(events, t) {
2091 for (const e of events) {
2095 if (e.t > t + 10000) {
2098 const type = e.type;
2099 if (type === 'their_goal' || type === 'goal' ||
2100 type === 'set_defense' || type === 'set_offense' ||
2101 type === 'throwaway' || type === 'their_throwaway' ||
2102 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2103 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2104 type === 'formation_offense' || type === 'formation_defense') {
2111 function possibly_close_menu(e) {
2112 if (e.target.closest('.filter-click-to-add') === null &&
2113 e.target.closest('#filter-add-menu') === null &&
2114 e.target.closest('#filter-submenu') === null &&
2115 e.target.closest('.filter-pill') === null) {
2116 let add_menu = document.getElementById('filter-add-menu');
2117 let add_submenu = document.getElementById('filter-submenu');
2118 add_menu.style.display = 'none';
2119 add_submenu.style.display = 'none';
2120 try_gc_filter_menus(false);
2124 let global_sort = {};
2126 function sort_by(th) {
2127 let tr = th.parentElement;
2129 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2130 let element = tr.children[column_idx];
2131 if (element === th) {
2132 ++child_idx; // Pad.
2135 if (element.hasAttribute('colspan')) {
2136 child_idx += parseInt(element.getAttribute('colspan'));
2143 let table = tr.parentElement;
2144 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2145 let row = table.children[row_idx];
2146 let player = parseInt(row.dataset.player);
2147 let value = row.children[child_idx].textContent;
2148 global_sort[player] = value;
2152 function get_sorted_players(players)
2154 let p = Object.entries(players);
2155 if (global_sort.length !== 0) {
2157 let ai = parseFloat(global_sort[a[0]]);
2158 let bi = parseFloat(global_sort[b[0]]);
2159 if (ai == ai && bi == bi) {
2160 return bi - ai; // Reverse numeric.
2161 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2163 } else if (global_sort[a[0]] > global_sort[b[0]]) {