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 let globals = players['globals'];
245 for (const match of json['matches']) {
246 if (!keep_match(match['match_id'], filters)) {
252 let between_points = true;
254 let handler_got_by_interception = false; // Only relevant if handler !== null.
255 let prev_handler = null;
256 let live_since = null;
257 let offense = null; // True/false/null (unknown).
259 let pull_started = null;
260 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
262 let game_started = null;
263 let last_goal = null;
264 let current_predominant_gender = null;
265 let current_num_players_on_field = null;
267 let we_lost_disc = false;
268 let they_lost_disc = false;
270 // The last used formations of the given kind, if any; they may be reused
271 // when the point starts, if nothing else is set.
272 let last_offensive_formation = null;
273 let last_defensive_formation = null;
275 // Formations we've set, but haven't really had the chance to use yet
276 // (e.g., we get a “use zone defense” event while we're still on offense).
277 let pending_offensive_formation = null;
278 let pending_defensive_formation = null;
280 // Formations that we have played at least once this point, after all
281 // heuristics and similar.
282 let formations_used_this_point = new Set();
284 for (const [q,p] of Object.entries(players)) {
285 p.on_field_since = null;
286 p.last_point_seen = null;
288 for (const e of match['events']) {
290 let type = e['type'];
291 let p = players[e['player']];
294 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
295 if (type === 'in' && p.on_field_since === null) {
296 p.on_field_since = t;
297 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
298 // A player needed for the filters went onto the field,
299 // so pretend people walked on right now (to start their
301 for (const [q,p2] of Object.entries(players)) {
302 if (p2.on_field_since !== null) {
303 p2.on_field_since = t;
307 } else if (type === 'out') {
308 take_off_field(p, t, live_since, offense, keep);
309 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
310 // A player needed for the filters went off the field,
311 // so we need to attribute time for all the others.
312 // Pretend they walked off and then immediately on again.
314 // TODO: We also need to take care of this to get the globals right.
315 for (const [q,p2] of Object.entries(players)) {
316 if (p2.on_field_since !== null) {
317 take_off_field(p2, t, live_since, offense, keep);
318 p2.on_field_since = t;
324 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
326 if (match['gender_rule_a']) {
327 if (type === 'restart' && !between_points) {
328 let predominant_gender = find_predominant_gender(players);
329 let num_players_on_field = find_num_players_on_field(players);
330 if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
331 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
333 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
334 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);
336 current_predominant_gender = predominant_gender;
337 current_num_players_on_field = num_players_on_field;
338 } else if (type === 'pull' || type === 'their_pull') {
339 let predominant_gender = find_predominant_gender(players);
340 let num_players_on_field = find_num_players_on_field(players);
341 let changed = (predominant_gender !== current_predominant_gender);
342 if (point_num !== 0) {
343 let should_change = (point_num % 4 == 1 || point_num % 4 == 3); // ABBA changes on 1 and 3.
344 if (changed && !should_change) {
345 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
346 } else if (!changed && should_change) {
347 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
349 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
350 console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
353 current_predominant_gender = predominant_gender;
354 current_num_players_on_field = num_players_on_field;
357 if (match['gender_pull_rule']) {
358 if (type === 'pull') {
359 if (current_predominant_gender !== null &&
360 p.gender !== current_predominant_gender) {
361 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
366 // Liveness management
367 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
369 between_points = false;
370 } else if (type === 'catch' && last_pull_was_ours === null) {
371 // Someone forgot to add the pull, so we'll need to wing it.
372 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
374 last_pull_was_ours = !offense;
375 between_points = false;
376 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
377 for (const [q,p] of Object.entries(players)) {
378 if (p.on_field_since === null) {
381 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
383 // In case the player did nothing this point,
384 // not even subbing in.
385 p.last_point_seen = point_num;
389 if (keep) attribute_player_time(p, t, live_since, offense);
391 if (type !== 'stoppage') {
393 if (last_pull_was_ours === true) { // D point.
394 ++p.defensive_points_completed;
395 if (type === 'goal') {
396 ++p.defensive_points_won;
398 } else if (last_pull_was_ours === false) { // O point.
399 ++p.offensive_points_completed;
400 if (type === 'goal') {
401 ++p.offensive_points_won;
409 if (type !== 'stoppage') {
411 ++globals.points_played;
412 if (last_pull_was_ours === true) { // D point.
413 ++globals.defensive_points_completed;
414 if (type === 'goal') {
415 ++globals.defensive_points_won;
417 } else if (last_pull_was_ours === false) { // O point.
418 ++globals.offensive_points_completed;
419 if (type === 'goal') {
420 ++globals.offensive_points_won;
424 if (live_since !== null) {
425 globals.playing_time_ms += t - live_since;
426 if (offense === true) {
427 globals.offensive_playing_time_ms += t - live_since;
428 } else if (offense === false) {
429 globals.defensive_playing_time_ms += t - live_since;
438 if (type === 'goal') {
440 } else if (type === 'their_goal') {
444 // Point count management
445 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
447 p.last_point_seen = point_num;
451 if (type === 'goal' || type === 'their_goal') {
455 if (type !== 'out' && game_started === null) {
460 if (type === 'pull') {
461 puller = e['player'];
464 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
465 // No effect on pull.
466 } else if (type === 'pull_landed' && puller !== null) {
467 if (keep) players[puller].pull_times.push(t - pull_started);
468 } else if (type === 'pull_oob' && puller !== null) {
469 if (keep) ++players[puller].oob_pulls;
471 // Not pulling (if there was one, we never recorded its outcome, but still count it).
472 puller = pull_started = null;
475 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
477 if (type === 'goal' && !we_lost_disc) {
478 if (last_pull_was_ours === false) { // O point.
479 ++globals.clean_holds;
480 } else if (last_pull_was_ours === true) {
481 ++globals.clean_breaks;
483 } else if (type === 'their_goal' && !they_lost_disc) {
484 if (last_pull_was_ours === true) { // O point for them.
485 ++globals.their_clean_holds;
486 } else if (last_pull_was_ours === false) {
487 ++globals.their_clean_breaks;
492 // Offense/defense management
493 let last_offense = offense;
494 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
497 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
498 ++globals.turnovers_lost;
500 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
502 they_lost_disc = true;
503 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
504 ++globals.turnovers_won;
507 if (type === 'goal' || type === 'their_goal') {
508 between_points = true;
509 we_lost_disc = false;
510 they_lost_disc = false;
512 if (last_offense !== offense && live_since !== null) {
513 // Switched offense/defense status, so attribute this drive as needed,
514 // and update live_since to take that into account.
516 for (const [q,p] of Object.entries(players)) {
517 if (p.on_field_since === null) {
520 attribute_player_time(p, t, live_since, last_offense);
522 globals.playing_time_ms += t - live_since;
523 if (offense === true) {
524 globals.offensive_playing_time_ms += t - live_since;
525 } else if (offense === false) {
526 globals.defensive_playing_time_ms += t - live_since;
532 if (type === 'pull') {
533 last_pull_was_ours = true;
534 } else if (type === 'their_pull') {
535 last_pull_was_ours = false;
536 } else if (type === 'set_offense' && last_pull_was_ours === null) {
537 // set_offense could either be “changed to offense for some reason
538 // we could not express”, or “we started in the middle of a point,
539 // and we are offense”. We assume that if we already saw the pull,
540 // it's the former, and if not, it's the latter; thus, the === null
541 // test above. (It could also be “we set offense before the pull,
542 // so that we get the right button enabled”, in which case it will
543 // be overwritten by the next pull/their_pull event anyway.)
544 last_pull_was_ours = false;
545 } else if (type === 'set_defense' && last_pull_was_ours === null) {
547 last_pull_was_ours = true;
548 } else if (type === 'goal' || type === 'their_goal') {
549 last_pull_was_ours = null;
552 // Formation management
553 if (type === 'formation_offense' || type === 'formation_defense') {
554 let id = e.formation === null ? 0 : e.formation;
555 let for_offense = (type === 'formation_offense');
556 if (offense === for_offense) {
557 formations_used_this_point.add(id);
558 } else if (for_offense) {
559 pending_offensive_formation = id;
561 pending_defensive_formation = id;
564 last_offensive_formation = id;
566 last_defensive_formation = id;
568 } else if (last_offense !== offense) {
569 if (offense === true && pending_offensive_formation !== null) {
570 formations_used_this_point.add(pending_offensive_formation);
571 pending_offensive_formation = null;
572 } else if (offense === false && pending_defensive_formation !== null) {
573 formations_used_this_point.add(pending_defensive_formation);
574 pending_defensive_formation = null;
575 } else if (offense === true && last_defensive_formation !== null) {
576 if (should_reuse_last_formation(match['events'], t)) {
577 formations_used_this_point.add(last_defensive_formation);
579 } else if (offense === false && last_offensive_formation !== null) {
580 if (should_reuse_last_formation(match['events'], t)) {
581 formations_used_this_point.add(last_offensive_formation);
586 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
587 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
589 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
590 // The handler subbed out and was replaced with another handler,
591 // so this wasn't a pass.
596 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
597 // Self-pass to goal after an interception; this is not a real pass,
598 // just how we represent a Callahan right now -- so don't
599 // count the throw, any assists or similar.
601 // It's an open question how we should handle a self-pass that is
602 // _not_ after an interception, or a self-pass that's not a goal.
603 // (It must mean we tipped off someone.) We'll count it as a regular one
604 // for the time being, although it will make hockey assists weird.
609 handler = prev_handler = null;
610 } else if (type === 'catch' || type === 'goal') {
611 if (handler !== null) {
613 ++players[handler].num_throws;
618 if (keep) ++p.touches;
619 if (type === 'goal') {
621 if (prev_handler !== null) {
622 ++players[prev_handler].hockey_assists;
624 if (handler !== null) {
625 ++players[handler].assists;
629 handler = prev_handler = null;
631 // Update hold history.
632 prev_handler = handler;
633 handler = e['player'];
634 handler_got_by_interception = false;
636 } else if (type === 'throwaway') {
641 handler = prev_handler = null;
642 } else if (type === 'drop') {
644 handler = prev_handler = null;
645 } else if (type === 'stallout') {
646 if (keep) ++p.stallouts;
647 handler = prev_handler = null;
648 } else if (type === 'was_d') {
649 if (keep) ++p.was_ds;
650 handler = prev_handler = null;
651 } else if (type === 'defense') {
652 if (keep) ++p.defenses;
653 } else if (type === 'interception') {
660 handler = e['player'];
661 handler_got_by_interception = true;
662 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
664 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
665 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
666 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
667 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
668 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
669 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
670 type !== 'formation_offense' && type !== 'formation_defense') {
671 console.log(format_time(t) + ": Unknown event “" + e + "”");
674 if (type === 'goal' || type === 'their_goal') {
675 formations_used_this_point.clear();
679 // Add field time for all players still left at match end.
680 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
682 for (const [q,p] of Object.entries(players)) {
683 if (p.on_field_since !== null && last_goal !== null) {
684 p.field_time_ms += last_goal - p.on_field_since;
687 if (game_started !== null && last_goal !== null) {
688 globals.field_time_ms += last_goal - game_started;
690 if (live_since !== null && last_goal !== null) {
691 globals.playing_time_ms += last_goal - live_since;
692 if (offense === true) {
693 globals.offensive_playing_time_ms += last_goal - live_since;
694 } else if (offense === false) {
695 globals.defensive_playing_time_ms += last_goal - live_since;
703 function process_matches(json, filtersets) {
704 let chosen_category = get_chosen_category();
705 write_main_menu(chosen_category);
707 let filterset_values = Object.values(filtersets);
708 if (filterset_values.length === 0) {
709 filterset_values = [[]];
713 for (const filter of filterset_values) {
714 let players = calc_stats(json, filter);
716 if (chosen_category === 'general') {
717 rows = make_table_general(players);
718 } else if (chosen_category === 'offense') {
719 rows = make_table_offense(players);
720 } else if (chosen_category === 'defense') {
721 rows = make_table_defense(players);
722 } else if (chosen_category === 'playing_time') {
723 rows = make_table_playing_time(players);
724 } else if (chosen_category === 'per_point') {
725 rows = make_table_per_point(players);
726 } else if (chosen_category === 'team_wide') {
727 rows = make_table_team_wide(players);
732 let merged_rows = [];
733 if (filterset_values.length > 1) {
734 for (let i = 0; i < rowsets.length; ++i) {
735 let marker = make_filter_marker(filterset_values[i]);
737 // Make filter header.
738 let tr = rowsets[i][0];
739 let th = document.createElement('th');
741 tr.insertBefore(th, tr.firstChild);
743 for (let j = 1; j < rowsets[i].length; ++j) {
744 let tr = rowsets[i][j];
746 // Remove the name for cleanness.
748 tr.firstChild.nextSibling.textContent = '';
752 tr.style.borderTop = '0px';
754 if (i != rowsets.length - 1) {
755 tr.style.borderBottom = '0px';
758 // Make filter marker.
759 let td = document.createElement('td');
760 td.textContent = marker;
761 td.classList.add('filtermarker');
762 tr.insertBefore(td, tr.firstChild);
766 for (let i = 0; i < rowsets[0].length; ++i) {
767 for (let j = 0; j < rowsets.length; ++j) {
768 merged_rows.push(rowsets[j][i]);
769 if (i === 0) break; // Don't merge the headings.
773 merged_rows = rowsets[0];
775 document.getElementById('stats').replaceChildren(...merged_rows);
778 function get_chosen_category() {
779 if (window.location.hash === '#offense') {
781 } else if (window.location.hash === '#defense') {
783 } else if (window.location.hash === '#playing_time') {
784 return 'playing_time';
785 } else if (window.location.hash === '#per_point') {
787 } else if (window.location.hash === '#team_wide') {
794 function write_main_menu(chosen_category) {
797 ['general', 'General'],
798 ['offense', 'Offense'],
799 ['defense', 'Defense'],
800 ['playing_time', 'Playing time'],
801 ['per_point', 'Per point'],
802 ['team_wide', 'Team-wide'],
804 for (const [id, title] of categories) {
805 if (chosen_category === id) {
806 let span = document.createElement('span');
807 span.innerText = title;
810 let a = document.createElement('a');
811 a.appendChild(document.createTextNode(title));
812 a.setAttribute('href', '#' + id);
817 document.getElementById('mainmenu').replaceChildren(...elems);
820 // https://en.wikipedia.org/wiki/1.96#History
823 const ci_width = 100;
824 const ci_height = 20;
826 function make_binomial_ci(val, num, z) {
829 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
830 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
831 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
833 // Fix the signs so that we don't get -0.00.
834 low = Math.max(low, 0.0);
844 // These can only happen once per point, but you get -1 and +1
845 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
846 // and then we can rewrite back.
847 function make_efficiency_ci(points_won, points_completed, z)
849 let ci = make_binomial_ci(points_won, points_completed, z);
850 ci.val = 2.0 * ci.val - 1.0;
851 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
852 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
855 ci.desired = 0.0; // Desired = positive efficiency.
859 // Ds, throwaways and drops can happen multiple times per point,
860 // so they are Poisson distributed.
862 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
863 // since our rates are definitely below 2 per point).
864 function make_poisson_ci(val, num, z, inverted)
866 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
867 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
869 // Fix the signs so that we don't get -0.00.
870 low = Math.max(low, 0.0);
872 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
881 'inverted': inverted,
885 function make_table_general(players) {
888 let header = document.createElement('tr');
889 add_th(header, 'Player');
890 add_th(header, '+/-');
891 add_th(header, 'Soft +/-');
892 add_th(header, 'O efficiency');
893 add_th(header, 'D efficiency');
894 add_th(header, 'Points played');
898 for (const [q,p] of get_sorted_players(players)) {
899 if (q === 'globals') continue;
900 let row = document.createElement('tr');
901 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
902 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
903 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
904 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
905 let name = add_3cell(row, p.name, 'name'); // TODO: number?
906 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
907 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
908 add_3cell_ci(row, o_efficiency);
909 add_3cell_ci(row, d_efficiency);
910 add_3cell(row, p.points_played);
911 row.dataset.player = q;
916 let globals = players['globals'];
917 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
918 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
919 let row = document.createElement('tr');
923 add_3cell_ci(row, o_efficiency);
924 add_3cell_ci(row, d_efficiency);
925 add_3cell(row, globals.points_played);
931 function make_table_team_wide(players) {
932 let globals = players['globals'];
936 let header = document.createElement('tr');
938 add_th(header, 'Our team', 6);
939 add_th(header, 'Their team', 6);
945 let row = document.createElement('tr');
946 let name = add_3cell(row, 'Turnovers generated', 'name');
948 add_3cell(row, globals.turnovers_won);
950 add_3cell(row, globals.turnovers_lost);
956 let row = document.createElement('tr');
957 let name = add_3cell(row, 'Clean holds', 'name');
958 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
959 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
960 our_clean_holds.desired = 0.3; // Arbitrary.
961 our_clean_holds.format = 'percentage';
962 their_clean_holds.desired = 0.3;
963 their_clean_holds.format = 'percentage';
964 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
965 add_3cell_ci(row, our_clean_holds);
966 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
967 add_3cell_ci(row, their_clean_holds);
973 let row = document.createElement('tr');
974 let name = add_3cell(row, 'Clean breaks', 'name');
975 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
976 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
977 our_clean_breaks.desired = 0.3; // Arbitrary.
978 our_clean_breaks.format = 'percentage';
979 their_clean_breaks.desired = 0.3;
980 their_clean_breaks.format = 'percentage';
981 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
982 add_3cell_ci(row, our_clean_breaks);
983 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
984 add_3cell_ci(row, their_clean_breaks);
991 function make_table_offense(players) {
994 let header = document.createElement('tr');
995 add_th(header, 'Player');
996 add_th(header, 'Goals');
997 add_th(header, 'Assists');
998 add_th(header, 'Hockey assists');
999 add_th(header, 'Throws');
1000 add_th(header, 'Throwaways');
1001 add_th(header, '%OK');
1002 add_th(header, 'Catches');
1003 add_th(header, 'Drops');
1004 add_th(header, 'D-ed');
1005 add_th(header, '%OK');
1006 add_th(header, 'Stalls');
1007 add_th(header, 'Soft +/-', 6);
1018 for (const [q,p] of get_sorted_players(players)) {
1019 if (q === 'globals') continue;
1020 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1021 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1023 throw_ok.format = 'percentage';
1024 catch_ok.format = 'percentage';
1026 // Desire at least 90% percentage. Fairly arbitrary.
1027 throw_ok.desired = 0.9;
1028 catch_ok.desired = 0.9;
1030 let row = document.createElement('tr');
1031 add_3cell(row, p.name, 'name'); // TODO: number?
1032 add_3cell(row, p.goals);
1033 add_3cell(row, p.assists);
1034 add_3cell(row, p.hockey_assists);
1035 add_3cell(row, p.num_throws);
1036 add_3cell(row, p.throwaways);
1037 add_3cell_ci(row, throw_ok);
1038 add_3cell(row, p.catches);
1039 add_3cell(row, p.drops);
1040 add_3cell(row, p.was_ds);
1041 add_3cell_ci(row, catch_ok);
1042 add_3cell(row, p.stallouts);
1043 add_3cell(row, '+' + p.offensive_soft_plus);
1044 add_3cell(row, '-' + p.offensive_soft_minus);
1045 row.dataset.player = q;
1049 num_throws += p.num_throws;
1050 throwaways += p.throwaways;
1051 catches += p.catches;
1054 stallouts += p.stallouts;
1058 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1059 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1060 throw_ok.format = 'percentage';
1061 catch_ok.format = 'percentage';
1062 throw_ok.desired = 0.9;
1063 catch_ok.desired = 0.9;
1065 let row = document.createElement('tr');
1067 add_3cell(row, goals);
1070 add_3cell(row, num_throws);
1071 add_3cell(row, throwaways);
1072 add_3cell_ci(row, throw_ok);
1073 add_3cell(row, catches);
1074 add_3cell(row, drops);
1075 add_3cell(row, was_ds);
1076 add_3cell_ci(row, catch_ok);
1077 add_3cell(row, stallouts);
1085 function make_table_defense(players) {
1088 let header = document.createElement('tr');
1089 add_th(header, 'Player');
1090 add_th(header, 'Ds');
1091 add_th(header, 'Pulls');
1092 add_th(header, 'OOB pulls');
1093 add_th(header, 'OOB%');
1094 add_th(header, 'Avg. hang time (IB)');
1095 add_th(header, 'Callahans');
1096 add_th(header, 'Soft +/-', 6);
1103 let sum_sum_time = 0;
1106 for (const [q,p] of get_sorted_players(players)) {
1107 if (q === 'globals') continue;
1109 for (const t of p.pull_times) {
1112 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1113 let oob_pct = 100 * p.oob_pulls / p.pulls;
1115 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1116 ci_oob.format = 'percentage';
1117 ci_oob.desired = 0.2; // Arbitrary.
1118 ci_oob.inverted = true;
1120 let row = document.createElement('tr');
1121 add_3cell(row, p.name, 'name'); // TODO: number?
1122 add_3cell(row, p.defenses);
1123 add_3cell(row, p.pulls);
1124 add_3cell(row, p.oob_pulls);
1125 add_3cell_ci(row, ci_oob);
1126 if (p.pulls > p.oob_pulls) {
1127 add_3cell(row, avg_time.toFixed(1) + ' sec');
1129 add_3cell(row, 'N/A');
1131 add_3cell(row, p.callahans);
1132 add_3cell(row, '+' + p.defensive_soft_plus);
1133 add_3cell(row, '-' + p.defensive_soft_minus);
1134 row.dataset.player = q;
1137 defenses += p.defenses;
1139 oob_pulls += p.oob_pulls;
1140 sum_sum_time += sum_time;
1141 callahans += p.callahans;
1145 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1146 ci_oob.format = 'percentage';
1147 ci_oob.desired = 0.2; // Arbitrary.
1148 ci_oob.inverted = true;
1150 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1151 let oob_pct = 100 * oob_pulls / pulls;
1153 let row = document.createElement('tr');
1155 add_3cell(row, defenses);
1156 add_3cell(row, pulls);
1157 add_3cell(row, oob_pulls);
1158 add_3cell_ci(row, ci_oob);
1159 if (pulls > oob_pulls) {
1160 add_3cell(row, avg_time.toFixed(1) + ' sec');
1162 add_3cell(row, 'N/A');
1164 add_3cell(row, callahans);
1172 function make_table_playing_time(players) {
1175 let header = document.createElement('tr');
1176 add_th(header, 'Player');
1177 add_th(header, 'Points played');
1178 add_th(header, 'Time played');
1179 add_th(header, 'O time');
1180 add_th(header, 'D time');
1181 add_th(header, 'Time on field');
1182 add_th(header, 'O points');
1183 add_th(header, 'D points');
1187 for (const [q,p] of get_sorted_players(players)) {
1188 if (q === 'globals') continue;
1189 let row = document.createElement('tr');
1190 add_3cell(row, p.name, 'name'); // TODO: number?
1191 add_3cell(row, p.points_played);
1192 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1193 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1194 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1195 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1196 add_3cell(row, p.offensive_points_completed);
1197 add_3cell(row, p.defensive_points_completed);
1198 row.dataset.player = q;
1203 let globals = players['globals'];
1204 let row = document.createElement('tr');
1206 add_3cell(row, globals.points_played);
1207 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1208 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1209 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1210 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1211 add_3cell(row, globals.offensive_points_completed);
1212 add_3cell(row, globals.defensive_points_completed);
1218 function make_table_per_point(players) {
1221 let header = document.createElement('tr');
1222 add_th(header, 'Player');
1223 add_th(header, 'Goals');
1224 add_th(header, 'Assists');
1225 add_th(header, 'Hockey assists');
1226 add_th(header, 'Ds');
1227 add_th(header, 'Throwaways');
1228 add_th(header, 'Recv. errors');
1229 add_th(header, 'Touches');
1235 let hockey_assists = 0;
1238 let receiver_errors = 0;
1240 for (const [q,p] of get_sorted_players(players)) {
1241 if (q === 'globals') continue;
1243 // Can only happen once per point, so these are binomials.
1244 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1245 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1246 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1247 // Arbitrarily desire at least 10% (not everybody can score or assist).
1248 ci_goals.desired = 0.1;
1249 ci_assists.desired = 0.1;
1250 ci_hockey_assists.desired = 0.1;
1252 let row = document.createElement('tr');
1253 add_3cell(row, p.name, 'name'); // TODO: number?
1254 add_3cell_ci(row, ci_goals);
1255 add_3cell_ci(row, ci_assists);
1256 add_3cell_ci(row, ci_hockey_assists);
1257 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1258 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1259 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1260 if (p.points_played > 0) {
1261 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1263 add_3cell(row, 'N/A');
1265 row.dataset.player = q;
1269 assists += p.assists;
1270 hockey_assists += p.hockey_assists;
1271 defenses += p.defenses;
1272 throwaways += p.throwaways;
1273 receiver_errors += p.drops + p.was_ds;
1274 touches += p.touches;
1278 let globals = players['globals'];
1279 let row = document.createElement('tr');
1281 if (globals.points_played > 0) {
1282 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1283 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1284 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1285 ci_goals.desired = 0.5;
1286 ci_assists.desired = 0.5;
1287 ci_hockey_assists.desired = 0.5;
1289 add_3cell_ci(row, ci_goals);
1290 add_3cell_ci(row, ci_assists);
1291 add_3cell_ci(row, ci_hockey_assists);
1293 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1294 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1295 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1297 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1299 add_3cell_with_filler_ci(row, 'N/A');
1300 add_3cell_with_filler_ci(row, 'N/A');
1301 add_3cell_with_filler_ci(row, 'N/A');
1302 add_3cell_with_filler_ci(row, 'N/A');
1303 add_3cell_with_filler_ci(row, 'N/A');
1304 add_3cell_with_filler_ci(row, 'N/A');
1305 add_3cell(row, 'N/A');
1312 function open_filter_menu(click_to_add_div) {
1313 document.getElementById('filter-submenu').style.display = 'none';
1314 let filter_div = click_to_add_div.parentElement;
1315 let filter_id = filter_div.dataset.filterId;
1317 let menu = document.getElementById('filter-add-menu');
1318 menu.parentElement.removeChild(menu);
1319 filter_div.appendChild(menu);
1320 menu.style.display = 'block';
1321 menu.replaceChildren();
1323 // Place the menu directly under the “click to add” label;
1324 // we don't anchor it since that label will move around
1325 // and the menu shouldn't.
1326 let rect = click_to_add_div.getBoundingClientRect();
1327 menu.style.left = rect.left + 'px';
1328 menu.style.top = (rect.bottom + 10) + 'px';
1330 let filterset = global_filters[filter_id];
1331 if (filterset === undefined) {
1332 global_filters[filter_id] = filterset = [];
1335 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1336 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1337 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1338 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1339 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1340 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1341 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1344 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1345 let item = document.createElement('div');
1346 item.classList.add('option');
1347 item.appendChild(document.createTextNode(title));
1349 let arrow = document.createElement('div');
1350 arrow.classList.add('arrow');
1351 arrow.textContent = '▸';
1352 item.appendChild(arrow);
1354 menu.appendChild(item);
1356 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1359 function find_all_ratios(json)
1363 for (const player of json['players']) {
1364 players[player['player_id']] = {
1365 'gender': player['gender'],
1366 'last_point_seen': null,
1369 for (const match of json['matches']) {
1370 for (const [q,p] of Object.entries(players)) {
1371 p.on_field_since = null;
1373 for (const e of match['events']) {
1374 let p = players[e['player']];
1375 let type = e['type'];
1376 if (type === 'in') {
1377 p.on_field_since = 1;
1378 } else if (type === 'out') {
1379 p.on_field_since = null;
1380 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1381 let code = find_gender_ratio_code(players);
1382 if (ratios[code] === undefined) {
1383 ratios[code] = code;
1384 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1385 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1386 match['description'] + ', ' + format_time(e['t']));
1395 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1396 let submenu = document.getElementById('filter-submenu');
1398 // Move to the same place as the top-level menu.
1399 submenu.parentElement.removeChild(submenu);
1400 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1403 const filter = find_filter(filterset, filter_type);
1406 if (filter_type === 'match') {
1407 for (const match of global_json['matches']) {
1409 'title': match['description'],
1410 'id': match['match_id']
1413 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1414 for (const player of global_json['players']) {
1416 'title': player['name'],
1417 'id': player['player_id']
1420 } else if (filter_type === 'formation_offense') {
1422 'title': '(None/unknown)',
1425 for (const formation of global_json['formations']) {
1426 if (formation['offense']) {
1428 'title': formation['name'],
1429 'id': formation['formation_id']
1433 } else if (filter_type === 'formation_defense') {
1435 'title': '(None/unknown)',
1438 for (const formation of global_json['formations']) {
1439 if (!formation['offense']) {
1441 'title': formation['name'],
1442 'id': formation['formation_id']
1446 } else if (filter_type === 'starting_on') {
1449 'id': false, // last_pull_was_ours
1453 'id': true, // last_pull_was_ours
1455 } else if (filter_type === 'gender_ratio') {
1456 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1464 for (const choice of choices) {
1465 let label = document.createElement('label');
1467 let subitem = document.createElement('div');
1468 subitem.classList.add('option');
1470 let check = document.createElement('input');
1471 check.setAttribute('type', 'checkbox');
1472 check.setAttribute('id', 'choice' + choice.id);
1473 if (filter !== null && filter.elements.has(choice.id)) {
1474 check.setAttribute('checked', 'checked');
1476 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1478 subitem.appendChild(check);
1479 subitem.appendChild(document.createTextNode(choice.title));
1481 label.appendChild(subitem);
1482 subitems.push(label);
1484 submenu.replaceChildren(...subitems);
1485 submenu.style.display = 'block';
1487 if (pill !== null) {
1488 let rect = pill.getBoundingClientRect();
1489 submenu.style.top = (rect.bottom + 10) + 'px';
1490 submenu.style.left = rect.left + 'px';
1492 // Position just outside the selected menu.
1493 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1494 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1495 submenu.style.left = (rect.right - 1) + 'px';
1499 // Find the right filter, if it exists.
1500 function find_filter(filterset, filter_type) {
1501 for (let f of filterset) {
1502 if (f.type === filter_type) {
1509 // Equivalent to Array.prototype.filter, but in-place.
1510 function inplace_filter(arr, cond) {
1512 for (let i = 0; i < arr.length; ++i) {
1520 function add_new_filterset() {
1521 let template = document.querySelector('.filter'); // First one is fine.
1522 let div = template.cloneNode(true);
1523 let add_menu = div.querySelector('#filter-add-menu');
1524 if (add_menu !== null) {
1525 div.removeChild(add_menu);
1527 let submenu = div.querySelector('#filter-submenu');
1528 if (submenu !== null) {
1529 div.removeChild(submenu);
1531 div.querySelector('.filters').replaceChildren();
1532 div.dataset.filterId = next_filterset_id++;
1533 template.parentElement.appendChild(div);
1536 function try_gc_filter_menus(cheap) {
1539 for (const filter_div of document.querySelectorAll('.filter')) {
1540 let id = filter_div.dataset.filterId;
1541 divs.push(filter_div);
1542 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1544 let last_div = divs[empties.length - 1];
1546 // See if we have two empty filter lists at the bottom of the list;
1547 // if so, we can remove one without it looking funny in the UI.
1548 // If not, we'll have to wait until closing the menu.
1549 // (The menu is positioned at the second-last one, so we can
1550 // remove the last one without issue.)
1551 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1552 delete global_filters[last_div.dataset.filterId];
1553 last_div.parentElement.removeChild(last_div);
1556 // This is a different situation from try_cheap_gc(), where we should
1557 // remove the one _not_ last. We might need to move the menu to the last one,
1558 // though, so it doesn't get lost.
1559 for (let i = 0; i < empties.length - 1; ++i) {
1564 delete global_filters[div.dataset.filterId];
1565 let add_menu = div.querySelector('#filter-add-menu');
1566 if (add_menu !== null) {
1567 div.removeChild(add_menu);
1568 last_div.appendChild(add_menu);
1570 let submenu = div.querySelector('#filter-submenu');
1571 if (submenu !== null) {
1572 div.removeChild(submenu);
1573 last_div.appendChild(submenu);
1575 div.parentElement.removeChild(div);
1580 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1581 let filter = find_filter(filterset, filter_type);
1582 let pills_div = filter_div.querySelector('.filters');
1583 if (e.target.checked) {
1584 // See if we must create a new empty filterset (since this went from
1585 // empty to non-empty).
1586 if (filterset.length === 0) {
1587 add_new_filterset();
1590 // See if we must add a new filter to the list.
1591 if (filter === null) {
1593 'type': filter_type,
1594 'elements': new Set([ id ]),
1596 filter.pill = make_filter_pill(filter_div, filterset, filter);
1597 filterset.push(filter);
1598 pills_div.appendChild(filter.pill);
1600 filter.elements.add(id);
1601 let new_pill = make_filter_pill(filter_div, filterset, filter);
1602 pills_div.replaceChild(new_pill, filter.pill);
1603 filter.pill = new_pill;
1606 filter.elements.delete(id);
1607 if (filter.elements.size === 0) {
1608 pills_div.removeChild(filter.pill);
1609 inplace_filter(filterset, f => f !== filter);
1611 if (filterset.length == 0) {
1612 try_gc_filter_menus(true);
1615 let new_pill = make_filter_pill(filter_div, filterset, filter);
1616 pills_div.replaceChild(new_pill, filter.pill);
1617 filter.pill = new_pill;
1621 process_matches(global_json, global_filters);
1624 function make_filter_pill(filter_div, filterset, filter) {
1625 let pill = document.createElement('div');
1626 pill.classList.add('filter-pill');
1628 if (filter.type === 'match') {
1632 for (const match_id of filter.elements) {
1633 all_names.push(find_match(match_id)['description']);
1635 let common_prefix = find_common_prefix_of_all(all_names);
1636 if (common_prefix !== null) {
1637 text += common_prefix + '(';
1641 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1642 for (const match_id of sorted_match_id) {
1646 let desc = find_match(match_id)['description'];
1647 if (common_prefix === null) {
1650 text += desc.substr(common_prefix.length);
1655 if (common_prefix !== null) {
1658 } else if (filter.type === 'player_any') {
1659 text = 'Player (any): ';
1660 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1662 for (const player_id of sorted_players) {
1666 text += find_player(player_id)['name'];
1669 } else if (filter.type === 'player_all') {
1671 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1673 for (const player_id of sorted_players) {
1677 text += find_player(player_id)['name'];
1680 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1681 const offense = (filter.type === 'formation_offense');
1689 for (const formation_id of filter.elements) {
1690 all_names.push(find_formation(formation_id)['name']);
1692 let common_prefix = find_common_prefix_of_all(all_names);
1693 if (common_prefix !== null) {
1694 text += common_prefix + '(';
1698 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1699 for (const formation_id of sorted_formation_id) {
1703 let desc = find_formation(formation_id)['name'];
1704 if (common_prefix === null) {
1707 text += desc.substr(common_prefix.length);
1712 if (common_prefix !== null) {
1715 } else if (filter.type === 'starting_on') {
1716 text = 'Starting on: ';
1718 if (filter.elements.has(false) && filter.elements.has(true)) {
1720 } else if (filter.elements.has(false)) {
1725 } else if (filter.type === 'gender_ratio') {
1729 for (const name of Array.from(filter.elements).sort()) {
1733 text += name; // FIXME
1738 let text_node = document.createElement('span');
1739 text_node.innerText = text;
1740 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1741 pill.appendChild(text_node);
1743 pill.appendChild(document.createTextNode(' '));
1745 let delete_node = document.createElement('span');
1746 delete_node.innerText = '✖';
1747 delete_node.addEventListener('click', (e) => {
1748 // Delete this filter entirely.
1749 pill.parentElement.removeChild(pill);
1750 inplace_filter(filterset, f => f !== filter);
1751 if (filterset.length == 0) {
1752 try_gc_filter_menus(false);
1754 process_matches(global_json, global_filters);
1756 let add_menu = document.getElementById('filter-add-menu');
1757 let add_submenu = document.getElementById('filter-submenu');
1758 add_menu.style.display = 'none';
1759 add_submenu.style.display = 'none';
1761 pill.appendChild(delete_node);
1762 pill.style.cursor = 'pointer';
1767 function make_filter_marker(filterset) {
1769 for (const filter of filterset) {
1773 if (filter.type === 'match') {
1775 for (const match of global_json['matches']) {
1776 all_names.push(match['description']);
1778 let common_prefix = find_common_prefix_of_all(all_names);
1780 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1781 for (const match_id of sorted_match_id) {
1782 let desc = find_match(match_id)['description'];
1783 if (common_prefix === null) {
1784 text += desc.substr(0, 3);
1786 text += desc.substr(common_prefix.length, 3);
1789 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1790 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1791 for (const player_id of sorted_players) {
1792 text += find_player(player_id)['name'].substr(0, 3);
1794 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1795 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1796 for (const formation_id of sorted_formation_id) {
1797 text += find_formation(formation_id)['name'].substr(0, 3);
1799 } else if (filter.type === 'starting_on') {
1800 if (filter.elements.has(false) && filter.elements.has(true)) {
1802 } else if (filter.elements.has(false)) {
1807 } else if (filter.type === 'gender_ratio') {
1809 for (const name of Array.from(filter.elements).sort()) {
1813 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
1821 function find_common_prefix(a, b) {
1823 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1824 if (a[i] === b[i]) {
1833 function find_common_prefix_of_all(values) {
1834 if (values.length < 2) {
1837 let common_prefix = null;
1838 for (const desc of values) {
1839 if (common_prefix === null) {
1840 common_prefix = desc;
1842 common_prefix = find_common_prefix(common_prefix, desc);
1845 if (common_prefix.length >= 3) {
1846 return common_prefix;
1852 function find_match(match_id) {
1853 for (const match of global_json['matches']) {
1854 if (match['match_id'] === match_id) {
1861 function find_formation(formation_id) {
1862 for (const formation of global_json['formations']) {
1863 if (formation['formation_id'] === formation_id) {
1870 function find_player(player_id) {
1871 for (const player of global_json['players']) {
1872 if (player['player_id'] === player_id) {
1879 function player_pos(player_id) {
1881 for (const player of global_json['players']) {
1882 if (player['player_id'] === player_id) {
1890 function keep_match(match_id, filters) {
1891 for (const filter of filters) {
1892 if (filter.type === 'match') {
1893 return filter.elements.has(match_id);
1899 // Returns a map of e.g. F => 4, M => 3.
1900 function find_gender_ratio(players) {
1902 for (const [q,p] of Object.entries(players)) {
1903 if (p.on_field_since === null) {
1906 let gender = p.gender;
1907 if (gender === '' || gender === undefined || gender === null) {
1910 if (map[gender] === undefined) {
1919 function find_gender_ratio_code(players) {
1920 let map = find_gender_ratio(players);
1921 let all_genders = Array.from(Object.keys(map)).sort(
1923 if (map[a] !== map[b]) {
1924 return map[b] - map[a]; // Reverse numeric.
1934 for (const g of all_genders) {
1945 // null if none (e.g., if playing 3–3).
1946 function find_predominant_gender(players) {
1948 let predominant_gender = null;
1949 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
1952 predominant_gender = gender;
1953 } else if (num == max) {
1954 predominant_gender = null; // At least two have the same.
1957 return predominant_gender;
1960 function find_num_players_on_field(players) {
1962 for (const [q,p] of Object.entries(players)) {
1963 if (p.on_field_since !== null) {
1970 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1971 if (filter.type === 'player_any') {
1972 for (const p of Array.from(filter.elements)) {
1973 if (players[p].on_field_since !== null) {
1978 } else if (filter.type === 'player_all') {
1979 for (const p of Array.from(filter.elements)) {
1980 if (players[p].on_field_since === null) {
1985 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1986 for (const f of Array.from(filter.elements)) {
1987 if (formations_used_this_point.has(f)) {
1992 } else if (filter.type === 'starting_on') {
1993 return filter.elements.has(last_pull_was_ours);
1994 } else if (filter.type === 'gender_ratio') {
1995 return filter.elements.has(find_gender_ratio_code(players));
2000 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2001 for (const filter of filters) {
2002 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2009 // Heuristic: If we go at least ten seconds without the possession changing
2010 // or the operator specifying some other formation, we probably play the
2011 // same formation as the last point.
2012 function should_reuse_last_formation(events, t) {
2013 for (const e of events) {
2017 if (e.t > t + 10000) {
2020 const type = e.type;
2021 if (type === 'their_goal' || type === 'goal' ||
2022 type === 'set_defense' || type === 'set_offense' ||
2023 type === 'throwaway' || type === 'their_throwaway' ||
2024 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2025 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2026 type === 'formation_offense' || type === 'formation_defense') {
2033 function possibly_close_menu(e) {
2034 if (e.target.closest('.filter-click-to-add') === null &&
2035 e.target.closest('#filter-add-menu') === null &&
2036 e.target.closest('#filter-submenu') === null &&
2037 e.target.closest('.filter-pill') === null) {
2038 let add_menu = document.getElementById('filter-add-menu');
2039 let add_submenu = document.getElementById('filter-submenu');
2040 add_menu.style.display = 'none';
2041 add_submenu.style.display = 'none';
2042 try_gc_filter_menus(false);
2046 let global_sort = {};
2048 function sort_by(th) {
2049 let tr = th.parentElement;
2051 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2052 let element = tr.children[column_idx];
2053 if (element === th) {
2054 ++child_idx; // Pad.
2057 if (element.hasAttribute('colspan')) {
2058 child_idx += parseInt(element.getAttribute('colspan'));
2065 let table = tr.parentElement;
2066 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2067 let row = table.children[row_idx];
2068 let player = parseInt(row.dataset.player);
2069 let value = row.children[child_idx].textContent;
2070 global_sort[player] = value;
2074 function get_sorted_players(players)
2076 let p = Object.entries(players);
2077 if (global_sort.length !== 0) {
2079 let ai = parseFloat(global_sort[a[0]]);
2080 let bi = parseFloat(global_sort[b[0]]);
2081 if (ai == ai && bi == bi) {
2082 return bi - ai; // Reverse numeric.
2083 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2085 } else if (global_sort[a[0]] > global_sort[b[0]]) {