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) + '%';
119 } else if (ci.decimals !== undefined) {
120 text = ci.val.toFixed(ci.decimals);
122 text = ci.val.toFixed(2);
124 if (ci.unit !== undefined) {
125 text += ' '+ ci.unit;
127 let element = add_3cell(tr, text);
128 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
131 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
132 if (ci.inverted === true) {
133 svg.classList.add('invertedci');
135 svg.classList.add('ci');
137 svg.setAttribute('width', ci_width);
138 svg.setAttribute('height', ci_height);
140 // The good (green) and red (bad) ranges.
141 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
142 s0.classList.add('range');
143 s0.classList.add('s0');
144 s0.setAttribute('width', to_x(ci.desired));
145 s0.setAttribute('height', ci_height);
146 s0.setAttribute('x', '0');
148 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
149 s1.classList.add('range');
150 s1.classList.add('s1');
151 s1.setAttribute('width', ci_width - to_x(ci.desired));
152 s1.setAttribute('height', ci_height);
153 s1.setAttribute('x', to_x(ci.desired));
156 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
157 bar.classList.add('bar');
158 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
159 bar.setAttribute('height', ci_height / 3);
160 bar.setAttribute('x', to_x(ci.lower_ci));
161 bar.setAttribute('y', ci_height / 3);
163 // Marker line for average.
164 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
165 marker.classList.add('marker');
166 marker.setAttribute('x1', to_x(ci.val));
167 marker.setAttribute('x2', to_x(ci.val));
168 marker.setAttribute('y1', ci_height / 6);
169 marker.setAttribute('y2', ci_height * 5 / 6);
173 svg.appendChild(bar);
174 svg.appendChild(marker);
176 element.appendChild(svg);
179 function calc_stats(json, filters) {
181 for (const player of json['players']) {
182 players[player['player_id']] = {
183 'name': player['name'],
184 'gender': player['gender'],
185 'number': player['number'],
201 'playing_time_ms': 0,
202 'offensive_playing_time_ms': 0,
203 'defensive_playing_time_ms': 0,
207 'offensive_points_completed': 0,
208 'offensive_points_won': 0,
209 'defensive_points_completed': 0,
210 'defensive_points_won': 0,
212 'offensive_soft_plus': 0,
213 'offensive_soft_minus': 0,
214 'defensive_soft_plus': 0,
215 'defensive_soft_minus': 0,
222 'last_point_seen': null,
223 'on_field_since': null,
228 players['globals'] = {
230 'playing_time_ms': 0,
231 'offensive_playing_time_ms': 0,
232 'defensive_playing_time_ms': 0,
235 'offensive_points_completed': 0,
236 'offensive_points_won': 0,
239 'defensive_points_completed': 0,
240 'defensive_points_won': 0,
245 'their_clean_holds': 0,
246 'their_clean_breaks': 0,
248 'touches_for_turnover': 0,
249 'touches_for_goal': 0,
250 'time_for_turnover': [],
252 'their_time_for_turnover': [],
253 'their_time_for_goal': [],
255 let globals = players['globals'];
257 for (const match of json['matches']) {
258 if (!keep_match(match['match_id'], filters)) {
264 let between_points = true;
266 let handler_got_by_interception = false; // Only relevant if handler !== null.
267 let prev_handler = null;
268 let live_since = null;
269 let offense = null; // True/false/null (unknown).
271 let pull_started = null;
272 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
274 let game_started = null;
275 let last_goal = null;
276 let current_predominant_gender = null;
277 let current_num_players_on_field = null;
279 let we_lost_disc = false;
280 let they_lost_disc = false;
281 let touches_this_possession = 0;
282 let possession_started = null;
283 let extra_ms_this_possession = 0; // Used at stoppages.
285 // The last used formations of the given kind, if any; they may be reused
286 // when the point starts, if nothing else is set.
287 let last_offensive_formation = null;
288 let last_defensive_formation = null;
290 // Formations we've set, but haven't really had the chance to use yet
291 // (e.g., we get a “use zone defense” event while we're still on offense).
292 let pending_offensive_formation = null;
293 let pending_defensive_formation = null;
295 // Formations that we have played at least once this point, after all
296 // heuristics and similar.
297 let formations_used_this_point = new Set();
299 for (const [q,p] of Object.entries(players)) {
300 p.on_field_since = null;
301 p.last_point_seen = null;
303 for (const e of match['events']) {
305 let type = e['type'];
306 let p = players[e['player']];
309 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
310 if (type === 'in' && p.on_field_since === null) {
311 p.on_field_since = t;
312 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
313 // A player needed for the filters went onto the field,
314 // so pretend people walked on right now (to start their
316 for (const [q,p2] of Object.entries(players)) {
317 if (p2.on_field_since !== null) {
318 p2.on_field_since = t;
322 } else if (type === 'out') {
323 take_off_field(p, t, live_since, offense, keep);
324 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
325 // A player needed for the filters went off the field,
326 // so we need to attribute time for all the others.
327 // Pretend they walked off and then immediately on again.
329 // TODO: We also need to take care of this to get the globals right.
330 for (const [q,p2] of Object.entries(players)) {
331 if (p2.on_field_since !== null) {
332 take_off_field(p2, t, live_since, offense, keep);
333 p2.on_field_since = t;
339 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
341 if (match['gender_rule_a']) {
342 if (type === 'restart' && !between_points) {
343 let predominant_gender = find_predominant_gender(players);
344 let num_players_on_field = find_num_players_on_field(players);
345 if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
346 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
348 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
349 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);
351 current_predominant_gender = predominant_gender;
352 current_num_players_on_field = num_players_on_field;
353 } else if (type === 'pull' || type === 'their_pull') {
354 let predominant_gender = find_predominant_gender(players);
355 let num_players_on_field = find_num_players_on_field(players);
356 let changed = (predominant_gender !== current_predominant_gender);
357 if (point_num !== 0) {
358 let should_change = (point_num % 4 == 1 || point_num % 4 == 3); // ABBA changes on 1 and 3.
359 if (changed && !should_change) {
360 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
361 } else if (!changed && should_change) {
362 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
364 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
365 console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
368 current_predominant_gender = predominant_gender;
369 current_num_players_on_field = num_players_on_field;
372 if (match['gender_pull_rule']) {
373 if (type === 'pull') {
374 if (current_predominant_gender !== null &&
375 p.gender !== current_predominant_gender) {
376 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
381 // Liveness management
382 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
384 if (type !== 'restart') {
385 between_points = false;
387 } else if (type === 'catch' && last_pull_was_ours === null) {
388 // Someone forgot to add the pull, so we'll need to wing it.
389 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
391 last_pull_was_ours = !offense;
392 between_points = false;
393 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
394 if (type === 'goal') {
395 if (keep) ++p.touches;
396 ++touches_this_possession;
398 for (const [q,p] of Object.entries(players)) {
399 if (p.on_field_since === null) {
402 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
404 // In case the player did nothing this point,
405 // not even subbing in.
406 p.last_point_seen = point_num;
410 if (keep) attribute_player_time(p, t, live_since, offense);
412 if (type !== 'stoppage') {
414 if (last_pull_was_ours === true) { // D point.
415 ++p.defensive_points_completed;
416 if (type === 'goal') {
417 ++p.defensive_points_won;
419 } else if (last_pull_was_ours === false) { // O point.
420 ++p.offensive_points_completed;
421 if (type === 'goal') {
422 ++p.offensive_points_won;
430 if (type !== 'stoppage') {
432 ++globals.points_played;
433 if (last_pull_was_ours === true) { // D point.
434 ++globals.defensive_points_completed;
435 if (type === 'goal') {
436 ++globals.defensive_points_won;
438 } else if (last_pull_was_ours === false) { // O point.
439 ++globals.offensive_points_completed;
440 if (type === 'goal') {
441 ++globals.offensive_points_won;
445 if (live_since !== null) {
446 globals.playing_time_ms += t - live_since;
447 if (offense === true) {
448 globals.offensive_playing_time_ms += t - live_since;
449 } else if (offense === false) {
450 globals.defensive_playing_time_ms += t - live_since;
459 if (type === 'goal') {
461 } else if (type === 'their_goal') {
465 // Point count management
466 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
468 p.last_point_seen = point_num;
472 if (type === 'goal' || type === 'their_goal') {
476 if (type !== 'out' && game_started === null) {
481 if (type === 'pull') {
482 puller = e['player'];
485 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
486 // No effect on pull.
487 } else if (type === 'pull_landed' && puller !== null) {
488 if (keep) players[puller].pull_times.push(t - pull_started);
489 } else if (type === 'pull_oob' && puller !== null) {
490 if (keep) ++players[puller].oob_pulls;
492 // Not pulling (if there was one, we never recorded its outcome, but still count it).
493 puller = pull_started = null;
496 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
498 if (type === 'goal' && !we_lost_disc) {
499 if (last_pull_was_ours === false) { // O point.
500 ++globals.clean_holds;
501 } else if (last_pull_was_ours === true) {
502 ++globals.clean_breaks;
504 } else if (type === 'their_goal' && !they_lost_disc) {
505 if (last_pull_was_ours === true) { // O point for them.
506 ++globals.their_clean_holds;
507 } else if (last_pull_was_ours === false) {
508 ++globals.their_clean_breaks;
513 // Offense/defense management
514 let last_offense = offense;
515 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
518 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
519 ++globals.turnovers_lost;
520 globals.touches_for_turnover += touches_this_possession;
521 if (possession_started != null) globals.time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
522 } else if (keep && type === 'goal') {
523 globals.touches_for_goal += touches_this_possession;
524 if (possession_started != null) globals.time_for_goal.push((t - possession_started) + extra_ms_this_possession);
526 touches_this_possession = 0;
527 possession_started = null;
528 extra_ms_this_possession = 0;
529 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
531 they_lost_disc = true;
532 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
533 ++globals.turnovers_won;
534 if (possession_started != null) globals.their_time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
535 } else if (keep && type === 'their_goal') {
536 if (possession_started != null) globals.their_time_for_goal.push((t - possession_started) + extra_ms_this_possession);
538 touches_this_possession = 0;
539 possession_started = null;
540 extra_ms_this_possession = 0;
542 if (type === 'goal' || type === 'their_goal') {
543 between_points = true;
544 we_lost_disc = false;
545 they_lost_disc = false;
546 touches_this_possession = 0;
548 if (last_offense !== offense && live_since !== null) {
549 // Switched offense/defense status, so attribute this drive as needed,
550 // and update live_since to take that into account.
552 for (const [q,p] of Object.entries(players)) {
553 if (p.on_field_since === null) {
556 attribute_player_time(p, t, live_since, last_offense);
558 globals.playing_time_ms += t - live_since;
559 if (offense === true) {
560 globals.offensive_playing_time_ms += t - live_since;
561 } else if (offense === false) {
562 globals.defensive_playing_time_ms += t - live_since;
567 // The rules for possessions are slightly different; we want to start at pulls,
568 // not previous goals.
569 if ((last_offense !== offense && type !== 'goal' && type !== 'their_goal' && live_since !== null) ||
570 type === 'pull' || type === 'their_pull') {
571 possession_started = t;
572 } else if (type === 'stoppage') {
573 if (possession_started !== null) {
574 extra_ms_this_possession = t - possession_started;
575 possession_started = null;
577 } else if (type === 'restart' && live_since !== null && !between_points) {
578 possession_started = t;
581 if (type === 'pull') {
582 last_pull_was_ours = true;
583 } else if (type === 'their_pull') {
584 last_pull_was_ours = false;
585 } else if (type === 'set_offense' && last_pull_was_ours === null) {
586 // set_offense could either be “changed to offense for some reason
587 // we could not express”, or “we started in the middle of a point,
588 // and we are offense”. We assume that if we already saw the pull,
589 // it's the former, and if not, it's the latter; thus, the === null
590 // test above. (It could also be “we set offense before the pull,
591 // so that we get the right button enabled”, in which case it will
592 // be overwritten by the next pull/their_pull event anyway.)
593 last_pull_was_ours = false;
594 } else if (type === 'set_defense' && last_pull_was_ours === null) {
596 last_pull_was_ours = true;
597 } else if (type === 'goal' || type === 'their_goal') {
598 last_pull_was_ours = null;
601 // Formation management
602 if (type === 'formation_offense' || type === 'formation_defense') {
603 let id = e.formation === null ? 0 : e.formation;
604 let for_offense = (type === 'formation_offense');
605 if (offense === for_offense) {
606 formations_used_this_point.add(id);
607 } else if (for_offense) {
608 pending_offensive_formation = id;
610 pending_defensive_formation = id;
613 last_offensive_formation = id;
615 last_defensive_formation = id;
617 } else if (last_offense !== offense) {
618 if (offense === true && pending_offensive_formation !== null) {
619 formations_used_this_point.add(pending_offensive_formation);
620 pending_offensive_formation = null;
621 } else if (offense === false && pending_defensive_formation !== null) {
622 formations_used_this_point.add(pending_defensive_formation);
623 pending_defensive_formation = null;
624 } else if (offense === true && last_defensive_formation !== null) {
625 if (should_reuse_last_formation(match['events'], t)) {
626 formations_used_this_point.add(last_defensive_formation);
628 } else if (offense === false && last_offensive_formation !== null) {
629 if (should_reuse_last_formation(match['events'], t)) {
630 formations_used_this_point.add(last_offensive_formation);
635 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
636 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
638 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
639 // The handler subbed out and was replaced with another handler,
640 // so this wasn't a pass.
645 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
646 // Self-pass to goal after an interception; this is not a real pass,
647 // just how we represent a Callahan right now -- so don't
648 // count the throw, any assists or similar.
650 // It's an open question how we should handle a self-pass that is
651 // _not_ after an interception, or a self-pass that's not a goal.
652 // (It must mean we tipped off someone.) We'll count it as a regular one
653 // for the time being, although it will make hockey assists weird.
658 handler = prev_handler = null;
659 } else if (type === 'catch' || type === 'goal') {
660 if (handler !== null) {
662 ++players[handler].num_throws;
667 if (keep) ++p.touches;
668 ++touches_this_possession;
669 if (type === 'goal') {
671 if (prev_handler !== null) {
672 ++players[prev_handler].hockey_assists;
674 if (handler !== null) {
675 ++players[handler].assists;
679 handler = prev_handler = null;
681 // Update hold history.
682 prev_handler = handler;
683 handler = e['player'];
684 handler_got_by_interception = false;
686 } else if (type === 'throwaway') {
691 handler = prev_handler = null;
692 } else if (type === 'drop') {
694 handler = prev_handler = null;
695 } else if (type === 'stallout') {
696 if (keep) ++p.stallouts;
697 handler = prev_handler = null;
698 } else if (type === 'was_d') {
699 if (keep) ++p.was_ds;
700 handler = prev_handler = null;
701 } else if (type === 'defense') {
702 if (keep) ++p.defenses;
703 } else if (type === 'interception') {
708 ++touches_this_possession;
711 handler = e['player'];
712 handler_got_by_interception = true;
713 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
715 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
716 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
717 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
718 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
719 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
720 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
721 type !== 'formation_offense' && type !== 'formation_defense') {
722 console.log(format_time(t) + ": Unknown event “" + e + "”");
725 if (type === 'goal' || type === 'their_goal') {
726 formations_used_this_point.clear();
730 // Add field time for all players still left at match end.
731 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
733 for (const [q,p] of Object.entries(players)) {
734 if (p.on_field_since !== null && last_goal !== null) {
735 p.field_time_ms += last_goal - p.on_field_since;
738 if (game_started !== null && last_goal !== null) {
739 globals.field_time_ms += last_goal - game_started;
741 if (live_since !== null && last_goal !== null) {
742 globals.playing_time_ms += last_goal - live_since;
743 if (offense === true) {
744 globals.offensive_playing_time_ms += last_goal - live_since;
745 } else if (offense === false) {
746 globals.defensive_playing_time_ms += last_goal - live_since;
754 function process_matches(json, filtersets) {
755 let chosen_category = get_chosen_category();
756 write_main_menu(chosen_category);
758 let filterset_values = Object.values(filtersets);
759 if (filterset_values.length === 0) {
760 filterset_values = [[]];
764 for (const filter of filterset_values) {
765 let players = calc_stats(json, filter);
767 if (chosen_category === 'general') {
768 rows = make_table_general(players);
769 } else if (chosen_category === 'offense') {
770 rows = make_table_offense(players);
771 } else if (chosen_category === 'defense') {
772 rows = make_table_defense(players);
773 } else if (chosen_category === 'playing_time') {
774 rows = make_table_playing_time(players);
775 } else if (chosen_category === 'per_point') {
776 rows = make_table_per_point(players);
777 } else if (chosen_category === 'team_wide') {
778 rows = make_table_team_wide(players);
783 let merged_rows = [];
784 if (filterset_values.length > 1) {
785 for (let i = 0; i < rowsets.length; ++i) {
786 let marker = make_filter_marker(filterset_values[i]);
788 // Make filter header.
789 let tr = rowsets[i][0];
790 let th = document.createElement('th');
792 tr.insertBefore(th, tr.firstChild);
794 for (let j = 1; j < rowsets[i].length; ++j) {
795 let tr = rowsets[i][j];
797 // Remove the name for cleanness.
799 tr.firstChild.nextSibling.textContent = '';
803 tr.style.borderTop = '0px';
805 if (i != rowsets.length - 1) {
806 tr.style.borderBottom = '0px';
809 // Make filter marker.
810 let td = document.createElement('td');
811 td.textContent = marker;
812 td.classList.add('filtermarker');
813 tr.insertBefore(td, tr.firstChild);
817 for (let i = 0; i < rowsets[0].length; ++i) {
818 for (let j = 0; j < rowsets.length; ++j) {
819 merged_rows.push(rowsets[j][i]);
820 if (i === 0) break; // Don't merge the headings.
824 merged_rows = rowsets[0];
826 document.getElementById('stats').replaceChildren(...merged_rows);
829 function get_chosen_category() {
830 if (window.location.hash === '#offense') {
832 } else if (window.location.hash === '#defense') {
834 } else if (window.location.hash === '#playing_time') {
835 return 'playing_time';
836 } else if (window.location.hash === '#per_point') {
838 } else if (window.location.hash === '#team_wide') {
845 function write_main_menu(chosen_category) {
848 ['general', 'General'],
849 ['offense', 'Offense'],
850 ['defense', 'Defense'],
851 ['playing_time', 'Playing time'],
852 ['per_point', 'Per point'],
853 ['team_wide', 'Team-wide'],
855 for (const [id, title] of categories) {
856 if (chosen_category === id) {
857 let span = document.createElement('span');
858 span.innerText = title;
861 let a = document.createElement('a');
862 a.appendChild(document.createTextNode(title));
863 a.setAttribute('href', '#' + id);
868 document.getElementById('mainmenu').replaceChildren(...elems);
871 // https://en.wikipedia.org/wiki/1.96#History
874 const ci_width = 100;
875 const ci_height = 20;
877 function make_binomial_ci(val, num, z) {
880 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
881 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
882 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
884 // Fix the signs so that we don't get -0.00.
885 low = Math.max(low, 0.0);
895 // These can only happen once per point, but you get -1 and +1
896 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
897 // and then we can rewrite back.
898 function make_efficiency_ci(points_won, points_completed, z)
900 let ci = make_binomial_ci(points_won, points_completed, z);
901 ci.val = 2.0 * ci.val - 1.0;
902 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
903 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
906 ci.desired = 0.0; // Desired = positive efficiency.
910 // Ds, throwaways and drops can happen multiple times per point,
911 // so they are Poisson distributed.
913 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
914 // since our rates are definitely below 2 per point).
916 // FIXME: z is ignored.
917 function make_poisson_ci(val, num, z, inverted)
919 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
920 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
922 // Fix the signs so that we don't get -0.00.
923 low = Math.max(low, 0.0);
925 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
934 'inverted': inverted,
938 // Wilson and Hilferty, again recommended for general use in the PDF above
939 // (anything from their group “G1” works).
940 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
941 function make_poisson_ci_large(val, num, z)
943 let low = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
944 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;
946 // Fix the signs so that we don't get -0.00.
947 low = Math.max(low, 0.0);
949 // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
950 // (this is used for number of touches).
963 // We don't really know what to expect for possessions; it appears roughly
964 // lognormal, but my head doesn't work well enough to extract the CI for
965 // the estimated sample mean, and now my head spins around whether we do
966 // this correctly even for Poisson :-) But we do a simple (non-BCa) bootstrap
967 // here, which should give us what we want.
969 // FIXME: z is ignored.
970 function make_ci_duration(vals, z)
973 let sample_means = [];
974 for (let i = 0; i < 300; ++i) {
976 for (let j = 0; j < vals.length; ++j) {
977 sum += vals[Math.floor(Math.random() * vals.length)];
979 sample_means.push(sum / vals.length);
983 // Interpolating here would probably be better, but OK.
984 let low = sample_means[Math.floor(0.025 * sample_means.length)];
985 let high = sample_means[Math.floor(0.975 * sample_means.length)];
987 // Find the point estimate of the mean.
989 for (const v of vals) {
992 let avg = sum / vals.length;
996 'lower_ci': low / 1000.0,
997 'upper_ci': high / 1000.0,
1007 function make_table_general(players) {
1010 let header = document.createElement('tr');
1011 add_th(header, 'Player');
1012 add_th(header, '+/-');
1013 add_th(header, 'Soft +/-');
1014 add_th(header, 'O efficiency');
1015 add_th(header, 'D efficiency');
1016 add_th(header, 'Points played');
1020 for (const [q,p] of get_sorted_players(players)) {
1021 if (q === 'globals') continue;
1022 let row = document.createElement('tr');
1023 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
1024 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
1025 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
1026 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
1027 let name = add_3cell(row, p.name, 'name'); // TODO: number?
1028 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
1029 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
1030 add_3cell_ci(row, o_efficiency);
1031 add_3cell_ci(row, d_efficiency);
1032 add_3cell(row, p.points_played);
1033 row.dataset.player = q;
1038 let globals = players['globals'];
1039 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
1040 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
1041 let row = document.createElement('tr');
1045 add_3cell_ci(row, o_efficiency);
1046 add_3cell_ci(row, d_efficiency);
1047 add_3cell(row, globals.points_played);
1053 function make_table_team_wide(players) {
1054 let globals = players['globals'];
1058 let header = document.createElement('tr');
1060 add_th(header, 'Our team', 6);
1061 add_th(header, 'Opponents', 6);
1067 let row = document.createElement('tr');
1068 let name = add_3cell(row, 'Turnovers generated', 'name');
1069 add_3cell(row, globals.turnovers_won);
1071 add_3cell(row, globals.turnovers_lost);
1078 let row = document.createElement('tr');
1079 let name = add_3cell(row, 'Clean holds', 'name');
1080 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1081 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1082 our_clean_holds.desired = 0.3; // Arbitrary.
1083 our_clean_holds.format = 'percentage';
1084 their_clean_holds.desired = 0.3;
1085 their_clean_holds.format = 'percentage';
1086 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1087 add_3cell_ci(row, our_clean_holds);
1088 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1089 add_3cell_ci(row, their_clean_holds);
1095 let row = document.createElement('tr');
1096 let name = add_3cell(row, 'Clean breaks', 'name');
1097 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1098 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1099 our_clean_breaks.desired = 0.3; // Arbitrary.
1100 our_clean_breaks.format = 'percentage';
1101 their_clean_breaks.desired = 0.3;
1102 their_clean_breaks.format = 'percentage';
1103 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1104 add_3cell_ci(row, our_clean_breaks);
1105 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1106 add_3cell_ci(row, their_clean_breaks);
1110 // Touches. We only have information for our team here.
1113 for (const [q,p] of get_sorted_players(players)) {
1114 if (q === 'globals') continue;
1117 let row = document.createElement('tr');
1118 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1119 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1120 let possessions = goals + globals.turnovers_lost;
1122 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1127 row = document.createElement('tr');
1128 add_3cell(row, 'Touches per possession (goals)', 'name');
1130 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1135 row = document.createElement('tr');
1136 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1138 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1144 // Time. Here we have (roughly) for both.
1146 let row = document.createElement('tr');
1147 let name = add_3cell(row, 'Time per possession (all)', 'name');
1148 let time = globals.time_for_turnover.concat(globals.time_for_goal);
1149 let their_time = globals.their_time_for_turnover.concat(globals.their_time_for_goal);
1151 add_3cell_ci(row, make_ci_duration(time, z));
1153 add_3cell_ci(row, make_ci_duration(their_time, z));
1156 row = document.createElement('tr');
1157 add_3cell(row, 'Time per possession (goals)', 'name');
1159 add_3cell_ci(row, make_ci_duration(globals.time_for_goal, z));
1161 add_3cell_ci(row, make_ci_duration(globals.their_time_for_goal, z));
1164 row = document.createElement('tr');
1165 add_3cell(row, 'Time per possession (turnovers)', 'name');
1167 add_3cell_ci(row, make_ci_duration(globals.time_for_turnover, z));
1169 add_3cell_ci(row, make_ci_duration(globals.their_time_for_turnover, z));
1176 function make_table_offense(players) {
1179 let header = document.createElement('tr');
1180 add_th(header, 'Player');
1181 add_th(header, 'Goals');
1182 add_th(header, 'Assists');
1183 add_th(header, 'Hockey assists');
1184 add_th(header, 'Throws');
1185 add_th(header, 'Throwaways');
1186 add_th(header, '%OK');
1187 add_th(header, 'Catches');
1188 add_th(header, 'Drops');
1189 add_th(header, 'D-ed');
1190 add_th(header, '%OK');
1191 add_th(header, 'Stalls');
1192 add_th(header, 'Soft +/-', 6);
1203 for (const [q,p] of get_sorted_players(players)) {
1204 if (q === 'globals') continue;
1205 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1206 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1208 throw_ok.format = 'percentage';
1209 catch_ok.format = 'percentage';
1211 // Desire at least 90% percentage. Fairly arbitrary.
1212 throw_ok.desired = 0.9;
1213 catch_ok.desired = 0.9;
1215 let row = document.createElement('tr');
1216 add_3cell(row, p.name, 'name'); // TODO: number?
1217 add_3cell(row, p.goals);
1218 add_3cell(row, p.assists);
1219 add_3cell(row, p.hockey_assists);
1220 add_3cell(row, p.num_throws);
1221 add_3cell(row, p.throwaways);
1222 add_3cell_ci(row, throw_ok);
1223 add_3cell(row, p.catches);
1224 add_3cell(row, p.drops);
1225 add_3cell(row, p.was_ds);
1226 add_3cell_ci(row, catch_ok);
1227 add_3cell(row, p.stallouts);
1228 add_3cell(row, '+' + p.offensive_soft_plus);
1229 add_3cell(row, '-' + p.offensive_soft_minus);
1230 row.dataset.player = q;
1234 num_throws += p.num_throws;
1235 throwaways += p.throwaways;
1236 catches += p.catches;
1239 stallouts += p.stallouts;
1243 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1244 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1245 throw_ok.format = 'percentage';
1246 catch_ok.format = 'percentage';
1247 throw_ok.desired = 0.9;
1248 catch_ok.desired = 0.9;
1250 let row = document.createElement('tr');
1252 add_3cell(row, goals);
1255 add_3cell(row, num_throws);
1256 add_3cell(row, throwaways);
1257 add_3cell_ci(row, throw_ok);
1258 add_3cell(row, catches);
1259 add_3cell(row, drops);
1260 add_3cell(row, was_ds);
1261 add_3cell_ci(row, catch_ok);
1262 add_3cell(row, stallouts);
1270 function make_table_defense(players) {
1273 let header = document.createElement('tr');
1274 add_th(header, 'Player');
1275 add_th(header, 'Ds');
1276 add_th(header, 'Pulls');
1277 add_th(header, 'OOB pulls');
1278 add_th(header, 'OOB%');
1279 add_th(header, 'Avg. hang time (IB)');
1280 add_th(header, 'Callahans');
1281 add_th(header, 'Soft +/-', 6);
1288 let sum_sum_time = 0;
1291 for (const [q,p] of get_sorted_players(players)) {
1292 if (q === 'globals') continue;
1294 for (const t of p.pull_times) {
1297 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1298 let oob_pct = 100 * p.oob_pulls / p.pulls;
1300 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1301 ci_oob.format = 'percentage';
1302 ci_oob.desired = 0.2; // Arbitrary.
1303 ci_oob.inverted = true;
1305 let row = document.createElement('tr');
1306 add_3cell(row, p.name, 'name'); // TODO: number?
1307 add_3cell(row, p.defenses);
1308 add_3cell(row, p.pulls);
1309 add_3cell(row, p.oob_pulls);
1310 add_3cell_ci(row, ci_oob);
1311 if (p.pulls > p.oob_pulls) {
1312 add_3cell(row, avg_time.toFixed(1) + ' sec');
1314 add_3cell(row, 'N/A');
1316 add_3cell(row, p.callahans);
1317 add_3cell(row, '+' + p.defensive_soft_plus);
1318 add_3cell(row, '-' + p.defensive_soft_minus);
1319 row.dataset.player = q;
1322 defenses += p.defenses;
1324 oob_pulls += p.oob_pulls;
1325 sum_sum_time += sum_time;
1326 callahans += p.callahans;
1330 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1331 ci_oob.format = 'percentage';
1332 ci_oob.desired = 0.2; // Arbitrary.
1333 ci_oob.inverted = true;
1335 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1336 let oob_pct = 100 * oob_pulls / pulls;
1338 let row = document.createElement('tr');
1340 add_3cell(row, defenses);
1341 add_3cell(row, pulls);
1342 add_3cell(row, oob_pulls);
1343 add_3cell_ci(row, ci_oob);
1344 if (pulls > oob_pulls) {
1345 add_3cell(row, avg_time.toFixed(1) + ' sec');
1347 add_3cell(row, 'N/A');
1349 add_3cell(row, callahans);
1357 function make_table_playing_time(players) {
1360 let header = document.createElement('tr');
1361 add_th(header, 'Player');
1362 add_th(header, 'Points played');
1363 add_th(header, 'Time played');
1364 add_th(header, 'O time');
1365 add_th(header, 'D time');
1366 add_th(header, 'Time on field');
1367 add_th(header, 'O points');
1368 add_th(header, 'D points');
1372 for (const [q,p] of get_sorted_players(players)) {
1373 if (q === 'globals') continue;
1374 let row = document.createElement('tr');
1375 add_3cell(row, p.name, 'name'); // TODO: number?
1376 add_3cell(row, p.points_played);
1377 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1378 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1379 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1380 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1381 add_3cell(row, p.offensive_points_completed);
1382 add_3cell(row, p.defensive_points_completed);
1383 row.dataset.player = q;
1388 let globals = players['globals'];
1389 let row = document.createElement('tr');
1391 add_3cell(row, globals.points_played);
1392 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1393 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1394 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1395 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1396 add_3cell(row, globals.offensive_points_completed);
1397 add_3cell(row, globals.defensive_points_completed);
1403 function make_table_per_point(players) {
1406 let header = document.createElement('tr');
1407 add_th(header, 'Player');
1408 add_th(header, 'Goals');
1409 add_th(header, 'Assists');
1410 add_th(header, 'Hockey assists');
1411 add_th(header, 'Ds');
1412 add_th(header, 'Throwaways');
1413 add_th(header, 'Recv. errors');
1414 add_th(header, 'Touches');
1420 let hockey_assists = 0;
1423 let receiver_errors = 0;
1425 for (const [q,p] of get_sorted_players(players)) {
1426 if (q === 'globals') continue;
1428 // Can only happen once per point, so these are binomials.
1429 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1430 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1431 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1432 // Arbitrarily desire at least 10% (not everybody can score or assist).
1433 ci_goals.desired = 0.1;
1434 ci_assists.desired = 0.1;
1435 ci_hockey_assists.desired = 0.1;
1437 let row = document.createElement('tr');
1438 add_3cell(row, p.name, 'name'); // TODO: number?
1439 add_3cell_ci(row, ci_goals);
1440 add_3cell_ci(row, ci_assists);
1441 add_3cell_ci(row, ci_hockey_assists);
1442 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1443 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1444 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1445 if (p.points_played > 0) {
1446 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1448 add_3cell(row, 'N/A');
1450 row.dataset.player = q;
1454 assists += p.assists;
1455 hockey_assists += p.hockey_assists;
1456 defenses += p.defenses;
1457 throwaways += p.throwaways;
1458 receiver_errors += p.drops + p.was_ds;
1459 touches += p.touches;
1463 let globals = players['globals'];
1464 let row = document.createElement('tr');
1466 if (globals.points_played > 0) {
1467 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1468 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1469 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1470 ci_goals.desired = 0.5;
1471 ci_assists.desired = 0.5;
1472 ci_hockey_assists.desired = 0.5;
1474 add_3cell_ci(row, ci_goals);
1475 add_3cell_ci(row, ci_assists);
1476 add_3cell_ci(row, ci_hockey_assists);
1478 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1479 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1480 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1482 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1484 add_3cell_with_filler_ci(row, 'N/A');
1485 add_3cell_with_filler_ci(row, 'N/A');
1486 add_3cell_with_filler_ci(row, 'N/A');
1487 add_3cell_with_filler_ci(row, 'N/A');
1488 add_3cell_with_filler_ci(row, 'N/A');
1489 add_3cell_with_filler_ci(row, 'N/A');
1490 add_3cell(row, 'N/A');
1497 function open_filter_menu(click_to_add_div) {
1498 document.getElementById('filter-submenu').style.display = 'none';
1499 let filter_div = click_to_add_div.parentElement;
1500 let filter_id = filter_div.dataset.filterId;
1502 let menu = document.getElementById('filter-add-menu');
1503 menu.parentElement.removeChild(menu);
1504 filter_div.appendChild(menu);
1505 menu.style.display = 'block';
1506 menu.replaceChildren();
1508 // Place the menu directly under the “click to add” label;
1509 // we don't anchor it since that label will move around
1510 // and the menu shouldn't.
1511 let rect = click_to_add_div.getBoundingClientRect();
1512 menu.style.left = rect.left + 'px';
1513 menu.style.top = (rect.bottom + 10) + 'px';
1515 let filterset = global_filters[filter_id];
1516 if (filterset === undefined) {
1517 global_filters[filter_id] = filterset = [];
1520 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1521 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1522 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1523 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1524 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1525 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1526 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1529 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1530 let item = document.createElement('div');
1531 item.classList.add('option');
1532 item.appendChild(document.createTextNode(title));
1534 let arrow = document.createElement('div');
1535 arrow.classList.add('arrow');
1536 arrow.textContent = '▸';
1537 item.appendChild(arrow);
1539 menu.appendChild(item);
1541 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1544 function find_all_ratios(json)
1548 for (const player of json['players']) {
1549 players[player['player_id']] = {
1550 'gender': player['gender'],
1551 'last_point_seen': null,
1554 for (const match of json['matches']) {
1555 for (const [q,p] of Object.entries(players)) {
1556 p.on_field_since = null;
1558 for (const e of match['events']) {
1559 let p = players[e['player']];
1560 let type = e['type'];
1561 if (type === 'in') {
1562 p.on_field_since = 1;
1563 } else if (type === 'out') {
1564 p.on_field_since = null;
1565 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1566 let code = find_gender_ratio_code(players);
1567 if (ratios[code] === undefined) {
1568 ratios[code] = code;
1569 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1570 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1571 match['description'] + ', ' + format_time(e['t']));
1580 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1581 let submenu = document.getElementById('filter-submenu');
1583 // Move to the same place as the top-level menu.
1584 submenu.parentElement.removeChild(submenu);
1585 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1588 const filter = find_filter(filterset, filter_type);
1591 if (filter_type === 'match') {
1592 for (const match of global_json['matches']) {
1594 'title': match['description'],
1595 'id': match['match_id']
1598 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1599 for (const player of global_json['players']) {
1601 'title': player['name'],
1602 'id': player['player_id']
1605 } else if (filter_type === 'formation_offense') {
1607 'title': '(None/unknown)',
1610 for (const formation of global_json['formations']) {
1611 if (formation['offense']) {
1613 'title': formation['name'],
1614 'id': formation['formation_id']
1618 } else if (filter_type === 'formation_defense') {
1620 'title': '(None/unknown)',
1623 for (const formation of global_json['formations']) {
1624 if (!formation['offense']) {
1626 'title': formation['name'],
1627 'id': formation['formation_id']
1631 } else if (filter_type === 'starting_on') {
1634 'id': false, // last_pull_was_ours
1638 'id': true, // last_pull_was_ours
1640 } else if (filter_type === 'gender_ratio') {
1641 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1649 for (const choice of choices) {
1650 let label = document.createElement('label');
1652 let subitem = document.createElement('div');
1653 subitem.classList.add('option');
1655 let check = document.createElement('input');
1656 check.setAttribute('type', 'checkbox');
1657 check.setAttribute('id', 'choice' + choice.id);
1658 if (filter !== null && filter.elements.has(choice.id)) {
1659 check.setAttribute('checked', 'checked');
1661 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1663 subitem.appendChild(check);
1664 subitem.appendChild(document.createTextNode(choice.title));
1666 label.appendChild(subitem);
1667 subitems.push(label);
1669 submenu.replaceChildren(...subitems);
1670 submenu.style.display = 'block';
1672 if (pill !== null) {
1673 let rect = pill.getBoundingClientRect();
1674 submenu.style.top = (rect.bottom + 10) + 'px';
1675 submenu.style.left = rect.left + 'px';
1677 // Position just outside the selected menu.
1678 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1679 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1680 submenu.style.left = (rect.right - 1) + 'px';
1684 // Find the right filter, if it exists.
1685 function find_filter(filterset, filter_type) {
1686 for (let f of filterset) {
1687 if (f.type === filter_type) {
1694 // Equivalent to Array.prototype.filter, but in-place.
1695 function inplace_filter(arr, cond) {
1697 for (let i = 0; i < arr.length; ++i) {
1705 function add_new_filterset() {
1706 let template = document.querySelector('.filter'); // First one is fine.
1707 let div = template.cloneNode(true);
1708 let add_menu = div.querySelector('#filter-add-menu');
1709 if (add_menu !== null) {
1710 div.removeChild(add_menu);
1712 let submenu = div.querySelector('#filter-submenu');
1713 if (submenu !== null) {
1714 div.removeChild(submenu);
1716 div.querySelector('.filters').replaceChildren();
1717 div.dataset.filterId = next_filterset_id++;
1718 template.parentElement.appendChild(div);
1721 function try_gc_filter_menus(cheap) {
1724 for (const filter_div of document.querySelectorAll('.filter')) {
1725 let id = filter_div.dataset.filterId;
1726 divs.push(filter_div);
1727 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1729 let last_div = divs[empties.length - 1];
1731 // See if we have two empty filter lists at the bottom of the list;
1732 // if so, we can remove one without it looking funny in the UI.
1733 // If not, we'll have to wait until closing the menu.
1734 // (The menu is positioned at the second-last one, so we can
1735 // remove the last one without issue.)
1736 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1737 delete global_filters[last_div.dataset.filterId];
1738 last_div.parentElement.removeChild(last_div);
1741 // This is a different situation from try_cheap_gc(), where we should
1742 // remove the one _not_ last. We might need to move the menu to the last one,
1743 // though, so it doesn't get lost.
1744 for (let i = 0; i < empties.length - 1; ++i) {
1749 delete global_filters[div.dataset.filterId];
1750 let add_menu = div.querySelector('#filter-add-menu');
1751 if (add_menu !== null) {
1752 div.removeChild(add_menu);
1753 last_div.appendChild(add_menu);
1755 let submenu = div.querySelector('#filter-submenu');
1756 if (submenu !== null) {
1757 div.removeChild(submenu);
1758 last_div.appendChild(submenu);
1760 div.parentElement.removeChild(div);
1765 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1766 let filter = find_filter(filterset, filter_type);
1767 let pills_div = filter_div.querySelector('.filters');
1768 if (e.target.checked) {
1769 // See if we must create a new empty filterset (since this went from
1770 // empty to non-empty).
1771 if (filterset.length === 0) {
1772 add_new_filterset();
1775 // See if we must add a new filter to the list.
1776 if (filter === null) {
1778 'type': filter_type,
1779 'elements': new Set([ id ]),
1781 filter.pill = make_filter_pill(filter_div, filterset, filter);
1782 filterset.push(filter);
1783 pills_div.appendChild(filter.pill);
1785 filter.elements.add(id);
1786 let new_pill = make_filter_pill(filter_div, filterset, filter);
1787 pills_div.replaceChild(new_pill, filter.pill);
1788 filter.pill = new_pill;
1791 filter.elements.delete(id);
1792 if (filter.elements.size === 0) {
1793 pills_div.removeChild(filter.pill);
1794 inplace_filter(filterset, f => f !== filter);
1796 if (filterset.length == 0) {
1797 try_gc_filter_menus(true);
1800 let new_pill = make_filter_pill(filter_div, filterset, filter);
1801 pills_div.replaceChild(new_pill, filter.pill);
1802 filter.pill = new_pill;
1806 process_matches(global_json, global_filters);
1809 function make_filter_pill(filter_div, filterset, filter) {
1810 let pill = document.createElement('div');
1811 pill.classList.add('filter-pill');
1813 if (filter.type === 'match') {
1817 for (const match_id of filter.elements) {
1818 all_names.push(find_match(match_id)['description']);
1820 let common_prefix = find_common_prefix_of_all(all_names);
1821 if (common_prefix !== null) {
1822 text += common_prefix + '(';
1826 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1827 for (const match_id of sorted_match_id) {
1831 let desc = find_match(match_id)['description'];
1832 if (common_prefix === null) {
1835 text += desc.substr(common_prefix.length);
1840 if (common_prefix !== null) {
1843 } else if (filter.type === 'player_any') {
1844 text = 'Player (any): ';
1845 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1847 for (const player_id of sorted_players) {
1851 text += find_player(player_id)['name'];
1854 } else if (filter.type === 'player_all') {
1856 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1858 for (const player_id of sorted_players) {
1862 text += find_player(player_id)['name'];
1865 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1866 const offense = (filter.type === 'formation_offense');
1874 for (const formation_id of filter.elements) {
1875 all_names.push(find_formation(formation_id)['name']);
1877 let common_prefix = find_common_prefix_of_all(all_names);
1878 if (common_prefix !== null) {
1879 text += common_prefix + '(';
1883 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1884 for (const formation_id of sorted_formation_id) {
1888 let desc = find_formation(formation_id)['name'];
1889 if (common_prefix === null) {
1892 text += desc.substr(common_prefix.length);
1897 if (common_prefix !== null) {
1900 } else if (filter.type === 'starting_on') {
1901 text = 'Starting on: ';
1903 if (filter.elements.has(false) && filter.elements.has(true)) {
1905 } else if (filter.elements.has(false)) {
1910 } else if (filter.type === 'gender_ratio') {
1914 for (const name of Array.from(filter.elements).sort()) {
1918 text += name; // FIXME
1923 let text_node = document.createElement('span');
1924 text_node.innerText = text;
1925 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1926 pill.appendChild(text_node);
1928 pill.appendChild(document.createTextNode(' '));
1930 let delete_node = document.createElement('span');
1931 delete_node.innerText = '✖';
1932 delete_node.addEventListener('click', (e) => {
1933 // Delete this filter entirely.
1934 pill.parentElement.removeChild(pill);
1935 inplace_filter(filterset, f => f !== filter);
1936 if (filterset.length == 0) {
1937 try_gc_filter_menus(false);
1939 process_matches(global_json, global_filters);
1941 let add_menu = document.getElementById('filter-add-menu');
1942 let add_submenu = document.getElementById('filter-submenu');
1943 add_menu.style.display = 'none';
1944 add_submenu.style.display = 'none';
1946 pill.appendChild(delete_node);
1947 pill.style.cursor = 'pointer';
1952 function make_filter_marker(filterset) {
1954 for (const filter of filterset) {
1958 if (filter.type === 'match') {
1960 for (const match of global_json['matches']) {
1961 all_names.push(match['description']);
1963 let common_prefix = find_common_prefix_of_all(all_names);
1965 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1966 for (const match_id of sorted_match_id) {
1967 let desc = find_match(match_id)['description'];
1968 if (common_prefix === null) {
1969 text += desc.substr(0, 3);
1971 text += desc.substr(common_prefix.length, 3);
1974 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1975 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1976 for (const player_id of sorted_players) {
1977 text += find_player(player_id)['name'].substr(0, 3);
1979 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1980 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1981 for (const formation_id of sorted_formation_id) {
1982 text += find_formation(formation_id)['name'].substr(0, 3);
1984 } else if (filter.type === 'starting_on') {
1985 if (filter.elements.has(false) && filter.elements.has(true)) {
1987 } else if (filter.elements.has(false)) {
1992 } else if (filter.type === 'gender_ratio') {
1994 for (const name of Array.from(filter.elements).sort()) {
1998 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
2006 function find_common_prefix(a, b) {
2008 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
2009 if (a[i] === b[i]) {
2018 function find_common_prefix_of_all(values) {
2019 if (values.length < 2) {
2022 let common_prefix = null;
2023 for (const desc of values) {
2024 if (common_prefix === null) {
2025 common_prefix = desc;
2027 common_prefix = find_common_prefix(common_prefix, desc);
2030 if (common_prefix.length >= 3) {
2031 return common_prefix;
2037 function find_match(match_id) {
2038 for (const match of global_json['matches']) {
2039 if (match['match_id'] === match_id) {
2046 function find_formation(formation_id) {
2047 for (const formation of global_json['formations']) {
2048 if (formation['formation_id'] === formation_id) {
2055 function find_player(player_id) {
2056 for (const player of global_json['players']) {
2057 if (player['player_id'] === player_id) {
2064 function player_pos(player_id) {
2066 for (const player of global_json['players']) {
2067 if (player['player_id'] === player_id) {
2075 function keep_match(match_id, filters) {
2076 for (const filter of filters) {
2077 if (filter.type === 'match') {
2078 return filter.elements.has(match_id);
2084 // Returns a map of e.g. F => 4, M => 3.
2085 function find_gender_ratio(players) {
2087 for (const [q,p] of Object.entries(players)) {
2088 if (p.on_field_since === null) {
2091 let gender = p.gender;
2092 if (gender === '' || gender === undefined || gender === null) {
2095 if (map[gender] === undefined) {
2104 function find_gender_ratio_code(players) {
2105 let map = find_gender_ratio(players);
2106 let all_genders = Array.from(Object.keys(map)).sort(
2108 if (map[a] !== map[b]) {
2109 return map[b] - map[a]; // Reverse numeric.
2119 for (const g of all_genders) {
2130 // null if none (e.g., if playing 3–3).
2131 function find_predominant_gender(players) {
2133 let predominant_gender = null;
2134 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2137 predominant_gender = gender;
2138 } else if (num == max) {
2139 predominant_gender = null; // At least two have the same.
2142 return predominant_gender;
2145 function find_num_players_on_field(players) {
2147 for (const [q,p] of Object.entries(players)) {
2148 if (p.on_field_since !== null) {
2155 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2156 if (filter.type === 'player_any') {
2157 for (const p of Array.from(filter.elements)) {
2158 if (players[p].on_field_since !== null) {
2163 } else if (filter.type === 'player_all') {
2164 for (const p of Array.from(filter.elements)) {
2165 if (players[p].on_field_since === null) {
2170 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2171 for (const f of Array.from(filter.elements)) {
2172 if (formations_used_this_point.has(f)) {
2177 } else if (filter.type === 'starting_on') {
2178 return filter.elements.has(last_pull_was_ours);
2179 } else if (filter.type === 'gender_ratio') {
2180 return filter.elements.has(find_gender_ratio_code(players));
2185 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2186 for (const filter of filters) {
2187 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2194 // Heuristic: If we go at least ten seconds without the possession changing
2195 // or the operator specifying some other formation, we probably play the
2196 // same formation as the last point.
2197 function should_reuse_last_formation(events, t) {
2198 for (const e of events) {
2202 if (e.t > t + 10000) {
2205 const type = e.type;
2206 if (type === 'their_goal' || type === 'goal' ||
2207 type === 'set_defense' || type === 'set_offense' ||
2208 type === 'throwaway' || type === 'their_throwaway' ||
2209 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2210 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2211 type === 'formation_offense' || type === 'formation_defense') {
2218 function possibly_close_menu(e) {
2219 if (e.target.closest('.filter-click-to-add') === null &&
2220 e.target.closest('#filter-add-menu') === null &&
2221 e.target.closest('#filter-submenu') === null &&
2222 e.target.closest('.filter-pill') === null) {
2223 let add_menu = document.getElementById('filter-add-menu');
2224 let add_submenu = document.getElementById('filter-submenu');
2225 add_menu.style.display = 'none';
2226 add_submenu.style.display = 'none';
2227 try_gc_filter_menus(false);
2231 let global_sort = {};
2233 function sort_by(th) {
2234 let tr = th.parentElement;
2236 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2237 let element = tr.children[column_idx];
2238 if (element === th) {
2239 ++child_idx; // Pad.
2242 if (element.hasAttribute('colspan')) {
2243 child_idx += parseInt(element.getAttribute('colspan'));
2250 let table = tr.parentElement;
2251 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2252 let row = table.children[row_idx];
2253 let player = parseInt(row.dataset.player);
2254 let value = row.children[child_idx].textContent;
2255 global_sort[player] = value;
2259 function get_sorted_players(players)
2261 let p = Object.entries(players);
2262 if (global_sort.length !== 0) {
2264 let ai = parseFloat(global_sort[a[0]]);
2265 let bi = parseFloat(global_sort[b[0]]);
2266 if (ai == ai && bi == bi) {
2267 return bi - ai; // Reverse numeric.
2268 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2270 } else if (global_sort[a[0]] > global_sort[b[0]]) {