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 if (ci.unit !== undefined) {
123 text += ' '+ ci.unit;
125 let element = add_3cell(tr, text);
126 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
129 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
130 if (ci.inverted === true) {
131 svg.classList.add('invertedci');
133 svg.classList.add('ci');
135 svg.setAttribute('width', ci_width);
136 svg.setAttribute('height', ci_height);
138 // The good (green) and red (bad) ranges.
139 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
140 s0.classList.add('range');
141 s0.classList.add('s0');
142 s0.setAttribute('width', to_x(ci.desired));
143 s0.setAttribute('height', ci_height);
144 s0.setAttribute('x', '0');
146 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
147 s1.classList.add('range');
148 s1.classList.add('s1');
149 s1.setAttribute('width', ci_width - to_x(ci.desired));
150 s1.setAttribute('height', ci_height);
151 s1.setAttribute('x', to_x(ci.desired));
154 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
155 bar.classList.add('bar');
156 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
157 bar.setAttribute('height', ci_height / 3);
158 bar.setAttribute('x', to_x(ci.lower_ci));
159 bar.setAttribute('y', ci_height / 3);
161 // Marker line for average.
162 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
163 marker.classList.add('marker');
164 marker.setAttribute('x1', to_x(ci.val));
165 marker.setAttribute('x2', to_x(ci.val));
166 marker.setAttribute('y1', ci_height / 6);
167 marker.setAttribute('y2', ci_height * 5 / 6);
171 svg.appendChild(bar);
172 svg.appendChild(marker);
174 element.appendChild(svg);
177 function calc_stats(json, filters) {
179 for (const player of json['players']) {
180 players[player['player_id']] = {
181 'name': player['name'],
182 'gender': player['gender'],
183 'number': player['number'],
199 'playing_time_ms': 0,
200 'offensive_playing_time_ms': 0,
201 'defensive_playing_time_ms': 0,
205 'offensive_points_completed': 0,
206 'offensive_points_won': 0,
207 'defensive_points_completed': 0,
208 'defensive_points_won': 0,
210 'offensive_soft_plus': 0,
211 'offensive_soft_minus': 0,
212 'defensive_soft_plus': 0,
213 'defensive_soft_minus': 0,
220 'last_point_seen': null,
221 'on_field_since': null,
226 players['globals'] = {
228 'playing_time_ms': 0,
229 'offensive_playing_time_ms': 0,
230 'defensive_playing_time_ms': 0,
233 'offensive_points_completed': 0,
234 'offensive_points_won': 0,
237 'defensive_points_completed': 0,
238 'defensive_points_won': 0,
243 'their_clean_holds': 0,
244 'their_clean_breaks': 0,
246 'touches_for_turnover': 0,
247 'touches_for_goal': 0,
248 'time_for_turnover': [],
250 'their_time_for_turnover': [],
251 'their_time_for_goal': [],
253 let globals = players['globals'];
255 for (const match of json['matches']) {
256 if (!keep_match(match['match_id'], filters)) {
262 let between_points = true;
264 let handler_got_by_interception = false; // Only relevant if handler !== null.
265 let prev_handler = null;
266 let live_since = null;
267 let offense = null; // True/false/null (unknown).
269 let pull_started = null;
270 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
272 let game_started = null;
273 let last_goal = null;
274 let current_predominant_gender = null;
275 let current_num_players_on_field = null;
277 let we_lost_disc = false;
278 let they_lost_disc = false;
279 let touches_this_possession = 0;
280 let possession_started = null;
281 let extra_ms_this_possession = 0; // Used at stoppages.
283 // The last used formations of the given kind, if any; they may be reused
284 // when the point starts, if nothing else is set.
285 let last_offensive_formation = null;
286 let last_defensive_formation = null;
288 // Formations we've set, but haven't really had the chance to use yet
289 // (e.g., we get a “use zone defense” event while we're still on offense).
290 let pending_offensive_formation = null;
291 let pending_defensive_formation = null;
293 // Formations that we have played at least once this point, after all
294 // heuristics and similar.
295 let formations_used_this_point = new Set();
297 for (const [q,p] of Object.entries(players)) {
298 p.on_field_since = null;
299 p.last_point_seen = null;
301 for (const e of match['events']) {
303 let type = e['type'];
304 let p = players[e['player']];
307 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
308 if (type === 'in' && p.on_field_since === null) {
309 p.on_field_since = t;
310 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
311 // A player needed for the filters went onto the field,
312 // so pretend people walked on right now (to start their
314 for (const [q,p2] of Object.entries(players)) {
315 if (p2.on_field_since !== null) {
316 p2.on_field_since = t;
320 } else if (type === 'out') {
321 take_off_field(p, t, live_since, offense, keep);
322 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
323 // A player needed for the filters went off the field,
324 // so we need to attribute time for all the others.
325 // Pretend they walked off and then immediately on again.
327 // TODO: We also need to take care of this to get the globals right.
328 for (const [q,p2] of Object.entries(players)) {
329 if (p2.on_field_since !== null) {
330 take_off_field(p2, t, live_since, offense, keep);
331 p2.on_field_since = t;
337 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
339 if (match['gender_rule_a']) {
340 if (type === 'restart' && !between_points) {
341 let predominant_gender = find_predominant_gender(players);
342 let num_players_on_field = find_num_players_on_field(players);
343 if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
344 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
346 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
347 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);
349 current_predominant_gender = predominant_gender;
350 current_num_players_on_field = num_players_on_field;
351 } else if (type === 'pull' || type === 'their_pull') {
352 let predominant_gender = find_predominant_gender(players);
353 let num_players_on_field = find_num_players_on_field(players);
354 let changed = (predominant_gender !== current_predominant_gender);
355 if (point_num !== 0) {
356 let should_change = (point_num % 4 == 1 || point_num % 4 == 3); // ABBA changes on 1 and 3.
357 if (changed && !should_change) {
358 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
359 } else if (!changed && should_change) {
360 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
362 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
363 console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
366 current_predominant_gender = predominant_gender;
367 current_num_players_on_field = num_players_on_field;
370 if (match['gender_pull_rule']) {
371 if (type === 'pull') {
372 if (current_predominant_gender !== null &&
373 p.gender !== current_predominant_gender) {
374 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
379 // Liveness management
380 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
382 if (type !== 'restart') {
383 between_points = false;
385 } else if (type === 'catch' && last_pull_was_ours === null) {
386 // Someone forgot to add the pull, so we'll need to wing it.
387 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
389 last_pull_was_ours = !offense;
390 between_points = false;
391 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
392 if (type === 'goal') {
393 if (keep) ++p.touches;
394 ++touches_this_possession;
396 for (const [q,p] of Object.entries(players)) {
397 if (p.on_field_since === null) {
400 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
402 // In case the player did nothing this point,
403 // not even subbing in.
404 p.last_point_seen = point_num;
408 if (keep) attribute_player_time(p, t, live_since, offense);
410 if (type !== 'stoppage') {
412 if (last_pull_was_ours === true) { // D point.
413 ++p.defensive_points_completed;
414 if (type === 'goal') {
415 ++p.defensive_points_won;
417 } else if (last_pull_was_ours === false) { // O point.
418 ++p.offensive_points_completed;
419 if (type === 'goal') {
420 ++p.offensive_points_won;
428 if (type !== 'stoppage') {
430 ++globals.points_played;
431 if (last_pull_was_ours === true) { // D point.
432 ++globals.defensive_points_completed;
433 if (type === 'goal') {
434 ++globals.defensive_points_won;
436 } else if (last_pull_was_ours === false) { // O point.
437 ++globals.offensive_points_completed;
438 if (type === 'goal') {
439 ++globals.offensive_points_won;
443 if (live_since !== null) {
444 globals.playing_time_ms += t - live_since;
445 if (offense === true) {
446 globals.offensive_playing_time_ms += t - live_since;
447 } else if (offense === false) {
448 globals.defensive_playing_time_ms += t - live_since;
457 if (type === 'goal') {
459 } else if (type === 'their_goal') {
463 // Point count management
464 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
466 p.last_point_seen = point_num;
470 if (type === 'goal' || type === 'their_goal') {
474 if (type !== 'out' && game_started === null) {
479 if (type === 'pull') {
480 puller = e['player'];
483 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
484 // No effect on pull.
485 } else if (type === 'pull_landed' && puller !== null) {
486 if (keep) players[puller].pull_times.push(t - pull_started);
487 } else if (type === 'pull_oob' && puller !== null) {
488 if (keep) ++players[puller].oob_pulls;
490 // Not pulling (if there was one, we never recorded its outcome, but still count it).
491 puller = pull_started = null;
494 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
496 if (type === 'goal' && !we_lost_disc) {
497 if (last_pull_was_ours === false) { // O point.
498 ++globals.clean_holds;
499 } else if (last_pull_was_ours === true) {
500 ++globals.clean_breaks;
502 } else if (type === 'their_goal' && !they_lost_disc) {
503 if (last_pull_was_ours === true) { // O point for them.
504 ++globals.their_clean_holds;
505 } else if (last_pull_was_ours === false) {
506 ++globals.their_clean_breaks;
511 // Offense/defense management
512 let last_offense = offense;
513 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
516 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
517 ++globals.turnovers_lost;
518 globals.touches_for_turnover += touches_this_possession;
519 if (possession_started != null) globals.time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
520 } else if (keep && type === 'goal') {
521 globals.touches_for_goal += touches_this_possession;
522 if (possession_started != null) globals.time_for_goal.push((t - possession_started) + extra_ms_this_possession);
524 touches_this_possession = 0;
525 possession_started = null;
526 extra_ms_this_possession = 0;
527 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
529 they_lost_disc = true;
530 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
531 ++globals.turnovers_won;
532 if (possession_started != null) globals.their_time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
533 } else if (keep && type === 'their_goal') {
534 if (possession_started != null) globals.their_time_for_goal.push((t - possession_started) + extra_ms_this_possession);
536 touches_this_possession = 0;
537 possession_started = null;
538 extra_ms_this_possession = 0;
540 if (type === 'goal' || type === 'their_goal') {
541 between_points = true;
542 we_lost_disc = false;
543 they_lost_disc = false;
544 touches_this_possession = 0;
546 if (last_offense !== offense && live_since !== null) {
547 // Switched offense/defense status, so attribute this drive as needed,
548 // and update live_since to take that into account.
550 for (const [q,p] of Object.entries(players)) {
551 if (p.on_field_since === null) {
554 attribute_player_time(p, t, live_since, last_offense);
556 globals.playing_time_ms += t - live_since;
557 if (offense === true) {
558 globals.offensive_playing_time_ms += t - live_since;
559 } else if (offense === false) {
560 globals.defensive_playing_time_ms += t - live_since;
565 // The rules for possessions are slightly different; we want to start at pulls,
566 // not previous goals.
567 if ((last_offense !== offense && type !== 'goal' && type !== 'their_goal' && live_since !== null) ||
568 type === 'pull' || type === 'their_pull') {
569 possession_started = t;
570 } else if (type === 'stoppage') {
571 if (possession_started !== null) {
572 extra_ms_this_possession = t - possession_started;
573 possession_started = null;
575 } else if (type === 'restart' && live_since !== null && !between_points) {
576 possession_started = t;
579 if (type === 'pull') {
580 last_pull_was_ours = true;
581 } else if (type === 'their_pull') {
582 last_pull_was_ours = false;
583 } else if (type === 'set_offense' && last_pull_was_ours === null) {
584 // set_offense could either be “changed to offense for some reason
585 // we could not express”, or “we started in the middle of a point,
586 // and we are offense”. We assume that if we already saw the pull,
587 // it's the former, and if not, it's the latter; thus, the === null
588 // test above. (It could also be “we set offense before the pull,
589 // so that we get the right button enabled”, in which case it will
590 // be overwritten by the next pull/their_pull event anyway.)
591 last_pull_was_ours = false;
592 } else if (type === 'set_defense' && last_pull_was_ours === null) {
594 last_pull_was_ours = true;
595 } else if (type === 'goal' || type === 'their_goal') {
596 last_pull_was_ours = null;
599 // Formation management
600 if (type === 'formation_offense' || type === 'formation_defense') {
601 let id = e.formation === null ? 0 : e.formation;
602 let for_offense = (type === 'formation_offense');
603 if (offense === for_offense) {
604 formations_used_this_point.add(id);
605 } else if (for_offense) {
606 pending_offensive_formation = id;
608 pending_defensive_formation = id;
611 last_offensive_formation = id;
613 last_defensive_formation = id;
615 } else if (last_offense !== offense) {
616 if (offense === true && pending_offensive_formation !== null) {
617 formations_used_this_point.add(pending_offensive_formation);
618 pending_offensive_formation = null;
619 } else if (offense === false && pending_defensive_formation !== null) {
620 formations_used_this_point.add(pending_defensive_formation);
621 pending_defensive_formation = null;
622 } else if (offense === true && last_defensive_formation !== null) {
623 if (should_reuse_last_formation(match['events'], t)) {
624 formations_used_this_point.add(last_defensive_formation);
626 } else if (offense === false && last_offensive_formation !== null) {
627 if (should_reuse_last_formation(match['events'], t)) {
628 formations_used_this_point.add(last_offensive_formation);
633 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
634 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
636 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
637 // The handler subbed out and was replaced with another handler,
638 // so this wasn't a pass.
643 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
644 // Self-pass to goal after an interception; this is not a real pass,
645 // just how we represent a Callahan right now -- so don't
646 // count the throw, any assists or similar.
648 // It's an open question how we should handle a self-pass that is
649 // _not_ after an interception, or a self-pass that's not a goal.
650 // (It must mean we tipped off someone.) We'll count it as a regular one
651 // for the time being, although it will make hockey assists weird.
656 handler = prev_handler = null;
657 } else if (type === 'catch' || type === 'goal') {
658 if (handler !== null) {
660 ++players[handler].num_throws;
665 if (keep) ++p.touches;
666 ++touches_this_possession;
667 if (type === 'goal') {
669 if (prev_handler !== null) {
670 ++players[prev_handler].hockey_assists;
672 if (handler !== null) {
673 ++players[handler].assists;
677 handler = prev_handler = null;
679 // Update hold history.
680 prev_handler = handler;
681 handler = e['player'];
682 handler_got_by_interception = false;
684 } else if (type === 'throwaway') {
689 handler = prev_handler = null;
690 } else if (type === 'drop') {
692 handler = prev_handler = null;
693 } else if (type === 'stallout') {
694 if (keep) ++p.stallouts;
695 handler = prev_handler = null;
696 } else if (type === 'was_d') {
697 if (keep) ++p.was_ds;
698 handler = prev_handler = null;
699 } else if (type === 'defense') {
700 if (keep) ++p.defenses;
701 } else if (type === 'interception') {
706 ++touches_this_possession;
709 handler = e['player'];
710 handler_got_by_interception = true;
711 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
713 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
714 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
715 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
716 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
717 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
718 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
719 type !== 'formation_offense' && type !== 'formation_defense') {
720 console.log(format_time(t) + ": Unknown event “" + e + "”");
723 if (type === 'goal' || type === 'their_goal') {
724 formations_used_this_point.clear();
728 // Add field time for all players still left at match end.
729 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
731 for (const [q,p] of Object.entries(players)) {
732 if (p.on_field_since !== null && last_goal !== null) {
733 p.field_time_ms += last_goal - p.on_field_since;
736 if (game_started !== null && last_goal !== null) {
737 globals.field_time_ms += last_goal - game_started;
739 if (live_since !== null && last_goal !== null) {
740 globals.playing_time_ms += last_goal - live_since;
741 if (offense === true) {
742 globals.offensive_playing_time_ms += last_goal - live_since;
743 } else if (offense === false) {
744 globals.defensive_playing_time_ms += last_goal - live_since;
752 function process_matches(json, filtersets) {
753 let chosen_category = get_chosen_category();
754 write_main_menu(chosen_category);
756 let filterset_values = Object.values(filtersets);
757 if (filterset_values.length === 0) {
758 filterset_values = [[]];
762 for (const filter of filterset_values) {
763 let players = calc_stats(json, filter);
765 if (chosen_category === 'general') {
766 rows = make_table_general(players);
767 } else if (chosen_category === 'offense') {
768 rows = make_table_offense(players);
769 } else if (chosen_category === 'defense') {
770 rows = make_table_defense(players);
771 } else if (chosen_category === 'playing_time') {
772 rows = make_table_playing_time(players);
773 } else if (chosen_category === 'per_point') {
774 rows = make_table_per_point(players);
775 } else if (chosen_category === 'team_wide') {
776 rows = make_table_team_wide(players);
781 let merged_rows = [];
782 if (filterset_values.length > 1) {
783 for (let i = 0; i < rowsets.length; ++i) {
784 let marker = make_filter_marker(filterset_values[i]);
786 // Make filter header.
787 let tr = rowsets[i][0];
788 let th = document.createElement('th');
790 tr.insertBefore(th, tr.firstChild);
792 for (let j = 1; j < rowsets[i].length; ++j) {
793 let tr = rowsets[i][j];
795 // Remove the name for cleanness.
797 tr.firstChild.nextSibling.textContent = '';
801 tr.style.borderTop = '0px';
803 if (i != rowsets.length - 1) {
804 tr.style.borderBottom = '0px';
807 // Make filter marker.
808 let td = document.createElement('td');
809 td.textContent = marker;
810 td.classList.add('filtermarker');
811 tr.insertBefore(td, tr.firstChild);
815 for (let i = 0; i < rowsets[0].length; ++i) {
816 for (let j = 0; j < rowsets.length; ++j) {
817 merged_rows.push(rowsets[j][i]);
818 if (i === 0) break; // Don't merge the headings.
822 merged_rows = rowsets[0];
824 document.getElementById('stats').replaceChildren(...merged_rows);
827 function get_chosen_category() {
828 if (window.location.hash === '#offense') {
830 } else if (window.location.hash === '#defense') {
832 } else if (window.location.hash === '#playing_time') {
833 return 'playing_time';
834 } else if (window.location.hash === '#per_point') {
836 } else if (window.location.hash === '#team_wide') {
843 function write_main_menu(chosen_category) {
846 ['general', 'General'],
847 ['offense', 'Offense'],
848 ['defense', 'Defense'],
849 ['playing_time', 'Playing time'],
850 ['per_point', 'Per point'],
851 ['team_wide', 'Team-wide'],
853 for (const [id, title] of categories) {
854 if (chosen_category === id) {
855 let span = document.createElement('span');
856 span.innerText = title;
859 let a = document.createElement('a');
860 a.appendChild(document.createTextNode(title));
861 a.setAttribute('href', '#' + id);
866 document.getElementById('mainmenu').replaceChildren(...elems);
869 // https://en.wikipedia.org/wiki/1.96#History
872 const ci_width = 100;
873 const ci_height = 20;
875 function make_binomial_ci(val, num, z) {
878 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
879 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
880 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
882 // Fix the signs so that we don't get -0.00.
883 low = Math.max(low, 0.0);
893 // These can only happen once per point, but you get -1 and +1
894 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
895 // and then we can rewrite back.
896 function make_efficiency_ci(points_won, points_completed, z)
898 let ci = make_binomial_ci(points_won, points_completed, z);
899 ci.val = 2.0 * ci.val - 1.0;
900 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
901 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
904 ci.desired = 0.0; // Desired = positive efficiency.
908 // Ds, throwaways and drops can happen multiple times per point,
909 // so they are Poisson distributed.
911 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
912 // since our rates are definitely below 2 per point).
914 // FIXME: z is ignored.
915 function make_poisson_ci(val, num, z, inverted)
917 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
918 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
920 // Fix the signs so that we don't get -0.00.
921 low = Math.max(low, 0.0);
923 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
932 'inverted': inverted,
936 // Wilson and Hilferty, again recommended for general use in the PDF above
937 // (anything from their group “G1” works).
938 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
939 function make_poisson_ci_large(val, num, z)
941 let low = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
942 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;
944 // Fix the signs so that we don't get -0.00.
945 low = Math.max(low, 0.0);
947 // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
948 // (this is used for number of touches).
961 // We don't really know what to expect for possessions; it appears roughly
962 // lognormal, but my head doesn't work well enough to extract the CI for
963 // the estimated sample mean, and now my head spins around whether we do
964 // this correctly even for Poisson :-) But we do a simple (non-BCa) bootstrap
965 // here, which should give us what we want.
967 // FIXME: z is ignored.
968 function make_ci_duration(vals, z)
971 let sample_means = [];
972 for (let i = 0; i < 300; ++i) {
974 for (let j = 0; j < vals.length; ++j) {
975 sum += vals[Math.floor(Math.random() * vals.length)];
977 sample_means.push(sum / vals.length);
981 // Interpolating here would probably be better, but OK.
982 let low = sample_means[Math.floor(0.025 * sample_means.length)];
983 let high = sample_means[Math.floor(0.975 * sample_means.length)];
985 // Find the point estimate of the mean.
987 for (const v of vals) {
990 let avg = sum / vals.length;
994 'lower_ci': low / 1000.0,
995 'upper_ci': high / 1000.0,
1004 function make_table_general(players) {
1007 let header = document.createElement('tr');
1008 add_th(header, 'Player');
1009 add_th(header, '+/-');
1010 add_th(header, 'Soft +/-');
1011 add_th(header, 'O efficiency');
1012 add_th(header, 'D efficiency');
1013 add_th(header, 'Points played');
1017 for (const [q,p] of get_sorted_players(players)) {
1018 if (q === 'globals') continue;
1019 let row = document.createElement('tr');
1020 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
1021 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
1022 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
1023 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
1024 let name = add_3cell(row, p.name, 'name'); // TODO: number?
1025 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
1026 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
1027 add_3cell_ci(row, o_efficiency);
1028 add_3cell_ci(row, d_efficiency);
1029 add_3cell(row, p.points_played);
1030 row.dataset.player = q;
1035 let globals = players['globals'];
1036 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
1037 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
1038 let row = document.createElement('tr');
1042 add_3cell_ci(row, o_efficiency);
1043 add_3cell_ci(row, d_efficiency);
1044 add_3cell(row, globals.points_played);
1050 function make_table_team_wide(players) {
1051 let globals = players['globals'];
1055 let header = document.createElement('tr');
1057 add_th(header, 'Our team', 6);
1058 add_th(header, 'Opponents', 6);
1064 let row = document.createElement('tr');
1065 let name = add_3cell(row, 'Turnovers generated', 'name');
1066 add_3cell(row, globals.turnovers_won);
1068 add_3cell(row, globals.turnovers_lost);
1075 let row = document.createElement('tr');
1076 let name = add_3cell(row, 'Clean holds', 'name');
1077 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1078 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1079 our_clean_holds.desired = 0.3; // Arbitrary.
1080 our_clean_holds.format = 'percentage';
1081 their_clean_holds.desired = 0.3;
1082 their_clean_holds.format = 'percentage';
1083 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1084 add_3cell_ci(row, our_clean_holds);
1085 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1086 add_3cell_ci(row, their_clean_holds);
1092 let row = document.createElement('tr');
1093 let name = add_3cell(row, 'Clean breaks', 'name');
1094 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1095 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1096 our_clean_breaks.desired = 0.3; // Arbitrary.
1097 our_clean_breaks.format = 'percentage';
1098 their_clean_breaks.desired = 0.3;
1099 their_clean_breaks.format = 'percentage';
1100 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1101 add_3cell_ci(row, our_clean_breaks);
1102 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1103 add_3cell_ci(row, their_clean_breaks);
1107 // Touches. We only have information for our team here.
1110 for (const [q,p] of get_sorted_players(players)) {
1111 if (q === 'globals') continue;
1114 let row = document.createElement('tr');
1115 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1116 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1117 let possessions = goals + globals.turnovers_lost;
1119 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1124 row = document.createElement('tr');
1125 add_3cell(row, 'Touches per possession (goals)', 'name');
1127 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1132 row = document.createElement('tr');
1133 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1135 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1141 // Time. Here we have (roughly) for both.
1143 let row = document.createElement('tr');
1144 let name = add_3cell(row, 'Time per possession (all)', 'name');
1145 let time = globals.time_for_turnover.concat(globals.time_for_goal);
1146 let their_time = globals.their_time_for_turnover.concat(globals.their_time_for_goal);
1148 add_3cell_ci(row, make_ci_duration(time, z));
1150 add_3cell_ci(row, make_ci_duration(their_time, z));
1153 row = document.createElement('tr');
1154 add_3cell(row, 'Time per possession (goals)', 'name');
1156 add_3cell_ci(row, make_ci_duration(globals.time_for_goal, z));
1158 add_3cell_ci(row, make_ci_duration(globals.their_time_for_goal, z));
1161 row = document.createElement('tr');
1162 add_3cell(row, 'Time per possession (turnovers)', 'name');
1164 add_3cell_ci(row, make_ci_duration(globals.time_for_turnover, z));
1166 add_3cell_ci(row, make_ci_duration(globals.their_time_for_turnover, z));
1173 function make_table_offense(players) {
1176 let header = document.createElement('tr');
1177 add_th(header, 'Player');
1178 add_th(header, 'Goals');
1179 add_th(header, 'Assists');
1180 add_th(header, 'Hockey assists');
1181 add_th(header, 'Throws');
1182 add_th(header, 'Throwaways');
1183 add_th(header, '%OK');
1184 add_th(header, 'Catches');
1185 add_th(header, 'Drops');
1186 add_th(header, 'D-ed');
1187 add_th(header, '%OK');
1188 add_th(header, 'Stalls');
1189 add_th(header, 'Soft +/-', 6);
1200 for (const [q,p] of get_sorted_players(players)) {
1201 if (q === 'globals') continue;
1202 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1203 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1205 throw_ok.format = 'percentage';
1206 catch_ok.format = 'percentage';
1208 // Desire at least 90% percentage. Fairly arbitrary.
1209 throw_ok.desired = 0.9;
1210 catch_ok.desired = 0.9;
1212 let row = document.createElement('tr');
1213 add_3cell(row, p.name, 'name'); // TODO: number?
1214 add_3cell(row, p.goals);
1215 add_3cell(row, p.assists);
1216 add_3cell(row, p.hockey_assists);
1217 add_3cell(row, p.num_throws);
1218 add_3cell(row, p.throwaways);
1219 add_3cell_ci(row, throw_ok);
1220 add_3cell(row, p.catches);
1221 add_3cell(row, p.drops);
1222 add_3cell(row, p.was_ds);
1223 add_3cell_ci(row, catch_ok);
1224 add_3cell(row, p.stallouts);
1225 add_3cell(row, '+' + p.offensive_soft_plus);
1226 add_3cell(row, '-' + p.offensive_soft_minus);
1227 row.dataset.player = q;
1231 num_throws += p.num_throws;
1232 throwaways += p.throwaways;
1233 catches += p.catches;
1236 stallouts += p.stallouts;
1240 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1241 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1242 throw_ok.format = 'percentage';
1243 catch_ok.format = 'percentage';
1244 throw_ok.desired = 0.9;
1245 catch_ok.desired = 0.9;
1247 let row = document.createElement('tr');
1249 add_3cell(row, goals);
1252 add_3cell(row, num_throws);
1253 add_3cell(row, throwaways);
1254 add_3cell_ci(row, throw_ok);
1255 add_3cell(row, catches);
1256 add_3cell(row, drops);
1257 add_3cell(row, was_ds);
1258 add_3cell_ci(row, catch_ok);
1259 add_3cell(row, stallouts);
1267 function make_table_defense(players) {
1270 let header = document.createElement('tr');
1271 add_th(header, 'Player');
1272 add_th(header, 'Ds');
1273 add_th(header, 'Pulls');
1274 add_th(header, 'OOB pulls');
1275 add_th(header, 'OOB%');
1276 add_th(header, 'Avg. hang time (IB)');
1277 add_th(header, 'Callahans');
1278 add_th(header, 'Soft +/-', 6);
1285 let sum_sum_time = 0;
1288 for (const [q,p] of get_sorted_players(players)) {
1289 if (q === 'globals') continue;
1291 for (const t of p.pull_times) {
1294 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1295 let oob_pct = 100 * p.oob_pulls / p.pulls;
1297 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1298 ci_oob.format = 'percentage';
1299 ci_oob.desired = 0.2; // Arbitrary.
1300 ci_oob.inverted = true;
1302 let row = document.createElement('tr');
1303 add_3cell(row, p.name, 'name'); // TODO: number?
1304 add_3cell(row, p.defenses);
1305 add_3cell(row, p.pulls);
1306 add_3cell(row, p.oob_pulls);
1307 add_3cell_ci(row, ci_oob);
1308 if (p.pulls > p.oob_pulls) {
1309 add_3cell(row, avg_time.toFixed(1) + ' sec');
1311 add_3cell(row, 'N/A');
1313 add_3cell(row, p.callahans);
1314 add_3cell(row, '+' + p.defensive_soft_plus);
1315 add_3cell(row, '-' + p.defensive_soft_minus);
1316 row.dataset.player = q;
1319 defenses += p.defenses;
1321 oob_pulls += p.oob_pulls;
1322 sum_sum_time += sum_time;
1323 callahans += p.callahans;
1327 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1328 ci_oob.format = 'percentage';
1329 ci_oob.desired = 0.2; // Arbitrary.
1330 ci_oob.inverted = true;
1332 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1333 let oob_pct = 100 * oob_pulls / pulls;
1335 let row = document.createElement('tr');
1337 add_3cell(row, defenses);
1338 add_3cell(row, pulls);
1339 add_3cell(row, oob_pulls);
1340 add_3cell_ci(row, ci_oob);
1341 if (pulls > oob_pulls) {
1342 add_3cell(row, avg_time.toFixed(1) + ' sec');
1344 add_3cell(row, 'N/A');
1346 add_3cell(row, callahans);
1354 function make_table_playing_time(players) {
1357 let header = document.createElement('tr');
1358 add_th(header, 'Player');
1359 add_th(header, 'Points played');
1360 add_th(header, 'Time played');
1361 add_th(header, 'O time');
1362 add_th(header, 'D time');
1363 add_th(header, 'Time on field');
1364 add_th(header, 'O points');
1365 add_th(header, 'D points');
1369 for (const [q,p] of get_sorted_players(players)) {
1370 if (q === 'globals') continue;
1371 let row = document.createElement('tr');
1372 add_3cell(row, p.name, 'name'); // TODO: number?
1373 add_3cell(row, p.points_played);
1374 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1375 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1376 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1377 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1378 add_3cell(row, p.offensive_points_completed);
1379 add_3cell(row, p.defensive_points_completed);
1380 row.dataset.player = q;
1385 let globals = players['globals'];
1386 let row = document.createElement('tr');
1388 add_3cell(row, globals.points_played);
1389 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1390 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1391 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1392 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1393 add_3cell(row, globals.offensive_points_completed);
1394 add_3cell(row, globals.defensive_points_completed);
1400 function make_table_per_point(players) {
1403 let header = document.createElement('tr');
1404 add_th(header, 'Player');
1405 add_th(header, 'Goals');
1406 add_th(header, 'Assists');
1407 add_th(header, 'Hockey assists');
1408 add_th(header, 'Ds');
1409 add_th(header, 'Throwaways');
1410 add_th(header, 'Recv. errors');
1411 add_th(header, 'Touches');
1417 let hockey_assists = 0;
1420 let receiver_errors = 0;
1422 for (const [q,p] of get_sorted_players(players)) {
1423 if (q === 'globals') continue;
1425 // Can only happen once per point, so these are binomials.
1426 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1427 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1428 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1429 // Arbitrarily desire at least 10% (not everybody can score or assist).
1430 ci_goals.desired = 0.1;
1431 ci_assists.desired = 0.1;
1432 ci_hockey_assists.desired = 0.1;
1434 let row = document.createElement('tr');
1435 add_3cell(row, p.name, 'name'); // TODO: number?
1436 add_3cell_ci(row, ci_goals);
1437 add_3cell_ci(row, ci_assists);
1438 add_3cell_ci(row, ci_hockey_assists);
1439 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1440 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1441 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1442 if (p.points_played > 0) {
1443 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1445 add_3cell(row, 'N/A');
1447 row.dataset.player = q;
1451 assists += p.assists;
1452 hockey_assists += p.hockey_assists;
1453 defenses += p.defenses;
1454 throwaways += p.throwaways;
1455 receiver_errors += p.drops + p.was_ds;
1456 touches += p.touches;
1460 let globals = players['globals'];
1461 let row = document.createElement('tr');
1463 if (globals.points_played > 0) {
1464 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1465 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1466 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1467 ci_goals.desired = 0.5;
1468 ci_assists.desired = 0.5;
1469 ci_hockey_assists.desired = 0.5;
1471 add_3cell_ci(row, ci_goals);
1472 add_3cell_ci(row, ci_assists);
1473 add_3cell_ci(row, ci_hockey_assists);
1475 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1476 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1477 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1479 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1481 add_3cell_with_filler_ci(row, 'N/A');
1482 add_3cell_with_filler_ci(row, 'N/A');
1483 add_3cell_with_filler_ci(row, 'N/A');
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(row, 'N/A');
1494 function open_filter_menu(click_to_add_div) {
1495 document.getElementById('filter-submenu').style.display = 'none';
1496 let filter_div = click_to_add_div.parentElement;
1497 let filter_id = filter_div.dataset.filterId;
1499 let menu = document.getElementById('filter-add-menu');
1500 menu.parentElement.removeChild(menu);
1501 filter_div.appendChild(menu);
1502 menu.style.display = 'block';
1503 menu.replaceChildren();
1505 // Place the menu directly under the “click to add” label;
1506 // we don't anchor it since that label will move around
1507 // and the menu shouldn't.
1508 let rect = click_to_add_div.getBoundingClientRect();
1509 menu.style.left = rect.left + 'px';
1510 menu.style.top = (rect.bottom + 10) + 'px';
1512 let filterset = global_filters[filter_id];
1513 if (filterset === undefined) {
1514 global_filters[filter_id] = filterset = [];
1517 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1518 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1519 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1520 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1521 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1522 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1523 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1526 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1527 let item = document.createElement('div');
1528 item.classList.add('option');
1529 item.appendChild(document.createTextNode(title));
1531 let arrow = document.createElement('div');
1532 arrow.classList.add('arrow');
1533 arrow.textContent = '▸';
1534 item.appendChild(arrow);
1536 menu.appendChild(item);
1538 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1541 function find_all_ratios(json)
1545 for (const player of json['players']) {
1546 players[player['player_id']] = {
1547 'gender': player['gender'],
1548 'last_point_seen': null,
1551 for (const match of json['matches']) {
1552 for (const [q,p] of Object.entries(players)) {
1553 p.on_field_since = null;
1555 for (const e of match['events']) {
1556 let p = players[e['player']];
1557 let type = e['type'];
1558 if (type === 'in') {
1559 p.on_field_since = 1;
1560 } else if (type === 'out') {
1561 p.on_field_since = null;
1562 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1563 let code = find_gender_ratio_code(players);
1564 if (ratios[code] === undefined) {
1565 ratios[code] = code;
1566 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1567 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1568 match['description'] + ', ' + format_time(e['t']));
1577 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1578 let submenu = document.getElementById('filter-submenu');
1580 // Move to the same place as the top-level menu.
1581 submenu.parentElement.removeChild(submenu);
1582 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1585 const filter = find_filter(filterset, filter_type);
1588 if (filter_type === 'match') {
1589 for (const match of global_json['matches']) {
1591 'title': match['description'],
1592 'id': match['match_id']
1595 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1596 for (const player of global_json['players']) {
1598 'title': player['name'],
1599 'id': player['player_id']
1602 } else if (filter_type === 'formation_offense') {
1604 'title': '(None/unknown)',
1607 for (const formation of global_json['formations']) {
1608 if (formation['offense']) {
1610 'title': formation['name'],
1611 'id': formation['formation_id']
1615 } else if (filter_type === 'formation_defense') {
1617 'title': '(None/unknown)',
1620 for (const formation of global_json['formations']) {
1621 if (!formation['offense']) {
1623 'title': formation['name'],
1624 'id': formation['formation_id']
1628 } else if (filter_type === 'starting_on') {
1631 'id': false, // last_pull_was_ours
1635 'id': true, // last_pull_was_ours
1637 } else if (filter_type === 'gender_ratio') {
1638 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1646 for (const choice of choices) {
1647 let label = document.createElement('label');
1649 let subitem = document.createElement('div');
1650 subitem.classList.add('option');
1652 let check = document.createElement('input');
1653 check.setAttribute('type', 'checkbox');
1654 check.setAttribute('id', 'choice' + choice.id);
1655 if (filter !== null && filter.elements.has(choice.id)) {
1656 check.setAttribute('checked', 'checked');
1658 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1660 subitem.appendChild(check);
1661 subitem.appendChild(document.createTextNode(choice.title));
1663 label.appendChild(subitem);
1664 subitems.push(label);
1666 submenu.replaceChildren(...subitems);
1667 submenu.style.display = 'block';
1669 if (pill !== null) {
1670 let rect = pill.getBoundingClientRect();
1671 submenu.style.top = (rect.bottom + 10) + 'px';
1672 submenu.style.left = rect.left + 'px';
1674 // Position just outside the selected menu.
1675 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1676 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1677 submenu.style.left = (rect.right - 1) + 'px';
1681 // Find the right filter, if it exists.
1682 function find_filter(filterset, filter_type) {
1683 for (let f of filterset) {
1684 if (f.type === filter_type) {
1691 // Equivalent to Array.prototype.filter, but in-place.
1692 function inplace_filter(arr, cond) {
1694 for (let i = 0; i < arr.length; ++i) {
1702 function add_new_filterset() {
1703 let template = document.querySelector('.filter'); // First one is fine.
1704 let div = template.cloneNode(true);
1705 let add_menu = div.querySelector('#filter-add-menu');
1706 if (add_menu !== null) {
1707 div.removeChild(add_menu);
1709 let submenu = div.querySelector('#filter-submenu');
1710 if (submenu !== null) {
1711 div.removeChild(submenu);
1713 div.querySelector('.filters').replaceChildren();
1714 div.dataset.filterId = next_filterset_id++;
1715 template.parentElement.appendChild(div);
1718 function try_gc_filter_menus(cheap) {
1721 for (const filter_div of document.querySelectorAll('.filter')) {
1722 let id = filter_div.dataset.filterId;
1723 divs.push(filter_div);
1724 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1726 let last_div = divs[empties.length - 1];
1728 // See if we have two empty filter lists at the bottom of the list;
1729 // if so, we can remove one without it looking funny in the UI.
1730 // If not, we'll have to wait until closing the menu.
1731 // (The menu is positioned at the second-last one, so we can
1732 // remove the last one without issue.)
1733 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1734 delete global_filters[last_div.dataset.filterId];
1735 last_div.parentElement.removeChild(last_div);
1738 // This is a different situation from try_cheap_gc(), where we should
1739 // remove the one _not_ last. We might need to move the menu to the last one,
1740 // though, so it doesn't get lost.
1741 for (let i = 0; i < empties.length - 1; ++i) {
1746 delete global_filters[div.dataset.filterId];
1747 let add_menu = div.querySelector('#filter-add-menu');
1748 if (add_menu !== null) {
1749 div.removeChild(add_menu);
1750 last_div.appendChild(add_menu);
1752 let submenu = div.querySelector('#filter-submenu');
1753 if (submenu !== null) {
1754 div.removeChild(submenu);
1755 last_div.appendChild(submenu);
1757 div.parentElement.removeChild(div);
1762 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1763 let filter = find_filter(filterset, filter_type);
1764 let pills_div = filter_div.querySelector('.filters');
1765 if (e.target.checked) {
1766 // See if we must create a new empty filterset (since this went from
1767 // empty to non-empty).
1768 if (filterset.length === 0) {
1769 add_new_filterset();
1772 // See if we must add a new filter to the list.
1773 if (filter === null) {
1775 'type': filter_type,
1776 'elements': new Set([ id ]),
1778 filter.pill = make_filter_pill(filter_div, filterset, filter);
1779 filterset.push(filter);
1780 pills_div.appendChild(filter.pill);
1782 filter.elements.add(id);
1783 let new_pill = make_filter_pill(filter_div, filterset, filter);
1784 pills_div.replaceChild(new_pill, filter.pill);
1785 filter.pill = new_pill;
1788 filter.elements.delete(id);
1789 if (filter.elements.size === 0) {
1790 pills_div.removeChild(filter.pill);
1791 inplace_filter(filterset, f => f !== filter);
1793 if (filterset.length == 0) {
1794 try_gc_filter_menus(true);
1797 let new_pill = make_filter_pill(filter_div, filterset, filter);
1798 pills_div.replaceChild(new_pill, filter.pill);
1799 filter.pill = new_pill;
1803 process_matches(global_json, global_filters);
1806 function make_filter_pill(filter_div, filterset, filter) {
1807 let pill = document.createElement('div');
1808 pill.classList.add('filter-pill');
1810 if (filter.type === 'match') {
1814 for (const match_id of filter.elements) {
1815 all_names.push(find_match(match_id)['description']);
1817 let common_prefix = find_common_prefix_of_all(all_names);
1818 if (common_prefix !== null) {
1819 text += common_prefix + '(';
1823 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1824 for (const match_id of sorted_match_id) {
1828 let desc = find_match(match_id)['description'];
1829 if (common_prefix === null) {
1832 text += desc.substr(common_prefix.length);
1837 if (common_prefix !== null) {
1840 } else if (filter.type === 'player_any') {
1841 text = 'Player (any): ';
1842 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1844 for (const player_id of sorted_players) {
1848 text += find_player(player_id)['name'];
1851 } else if (filter.type === 'player_all') {
1853 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1855 for (const player_id of sorted_players) {
1859 text += find_player(player_id)['name'];
1862 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1863 const offense = (filter.type === 'formation_offense');
1871 for (const formation_id of filter.elements) {
1872 all_names.push(find_formation(formation_id)['name']);
1874 let common_prefix = find_common_prefix_of_all(all_names);
1875 if (common_prefix !== null) {
1876 text += common_prefix + '(';
1880 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1881 for (const formation_id of sorted_formation_id) {
1885 let desc = find_formation(formation_id)['name'];
1886 if (common_prefix === null) {
1889 text += desc.substr(common_prefix.length);
1894 if (common_prefix !== null) {
1897 } else if (filter.type === 'starting_on') {
1898 text = 'Starting on: ';
1900 if (filter.elements.has(false) && filter.elements.has(true)) {
1902 } else if (filter.elements.has(false)) {
1907 } else if (filter.type === 'gender_ratio') {
1911 for (const name of Array.from(filter.elements).sort()) {
1915 text += name; // FIXME
1920 let text_node = document.createElement('span');
1921 text_node.innerText = text;
1922 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1923 pill.appendChild(text_node);
1925 pill.appendChild(document.createTextNode(' '));
1927 let delete_node = document.createElement('span');
1928 delete_node.innerText = '✖';
1929 delete_node.addEventListener('click', (e) => {
1930 // Delete this filter entirely.
1931 pill.parentElement.removeChild(pill);
1932 inplace_filter(filterset, f => f !== filter);
1933 if (filterset.length == 0) {
1934 try_gc_filter_menus(false);
1936 process_matches(global_json, global_filters);
1938 let add_menu = document.getElementById('filter-add-menu');
1939 let add_submenu = document.getElementById('filter-submenu');
1940 add_menu.style.display = 'none';
1941 add_submenu.style.display = 'none';
1943 pill.appendChild(delete_node);
1944 pill.style.cursor = 'pointer';
1949 function make_filter_marker(filterset) {
1951 for (const filter of filterset) {
1955 if (filter.type === 'match') {
1957 for (const match of global_json['matches']) {
1958 all_names.push(match['description']);
1960 let common_prefix = find_common_prefix_of_all(all_names);
1962 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1963 for (const match_id of sorted_match_id) {
1964 let desc = find_match(match_id)['description'];
1965 if (common_prefix === null) {
1966 text += desc.substr(0, 3);
1968 text += desc.substr(common_prefix.length, 3);
1971 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1972 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1973 for (const player_id of sorted_players) {
1974 text += find_player(player_id)['name'].substr(0, 3);
1976 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1977 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1978 for (const formation_id of sorted_formation_id) {
1979 text += find_formation(formation_id)['name'].substr(0, 3);
1981 } else if (filter.type === 'starting_on') {
1982 if (filter.elements.has(false) && filter.elements.has(true)) {
1984 } else if (filter.elements.has(false)) {
1989 } else if (filter.type === 'gender_ratio') {
1991 for (const name of Array.from(filter.elements).sort()) {
1995 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
2003 function find_common_prefix(a, b) {
2005 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
2006 if (a[i] === b[i]) {
2015 function find_common_prefix_of_all(values) {
2016 if (values.length < 2) {
2019 let common_prefix = null;
2020 for (const desc of values) {
2021 if (common_prefix === null) {
2022 common_prefix = desc;
2024 common_prefix = find_common_prefix(common_prefix, desc);
2027 if (common_prefix.length >= 3) {
2028 return common_prefix;
2034 function find_match(match_id) {
2035 for (const match of global_json['matches']) {
2036 if (match['match_id'] === match_id) {
2043 function find_formation(formation_id) {
2044 for (const formation of global_json['formations']) {
2045 if (formation['formation_id'] === formation_id) {
2052 function find_player(player_id) {
2053 for (const player of global_json['players']) {
2054 if (player['player_id'] === player_id) {
2061 function player_pos(player_id) {
2063 for (const player of global_json['players']) {
2064 if (player['player_id'] === player_id) {
2072 function keep_match(match_id, filters) {
2073 for (const filter of filters) {
2074 if (filter.type === 'match') {
2075 return filter.elements.has(match_id);
2081 // Returns a map of e.g. F => 4, M => 3.
2082 function find_gender_ratio(players) {
2084 for (const [q,p] of Object.entries(players)) {
2085 if (p.on_field_since === null) {
2088 let gender = p.gender;
2089 if (gender === '' || gender === undefined || gender === null) {
2092 if (map[gender] === undefined) {
2101 function find_gender_ratio_code(players) {
2102 let map = find_gender_ratio(players);
2103 let all_genders = Array.from(Object.keys(map)).sort(
2105 if (map[a] !== map[b]) {
2106 return map[b] - map[a]; // Reverse numeric.
2116 for (const g of all_genders) {
2127 // null if none (e.g., if playing 3–3).
2128 function find_predominant_gender(players) {
2130 let predominant_gender = null;
2131 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2134 predominant_gender = gender;
2135 } else if (num == max) {
2136 predominant_gender = null; // At least two have the same.
2139 return predominant_gender;
2142 function find_num_players_on_field(players) {
2144 for (const [q,p] of Object.entries(players)) {
2145 if (p.on_field_since !== null) {
2152 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2153 if (filter.type === 'player_any') {
2154 for (const p of Array.from(filter.elements)) {
2155 if (players[p].on_field_since !== null) {
2160 } else if (filter.type === 'player_all') {
2161 for (const p of Array.from(filter.elements)) {
2162 if (players[p].on_field_since === null) {
2167 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2168 for (const f of Array.from(filter.elements)) {
2169 if (formations_used_this_point.has(f)) {
2174 } else if (filter.type === 'starting_on') {
2175 return filter.elements.has(last_pull_was_ours);
2176 } else if (filter.type === 'gender_ratio') {
2177 return filter.elements.has(find_gender_ratio_code(players));
2182 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2183 for (const filter of filters) {
2184 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2191 // Heuristic: If we go at least ten seconds without the possession changing
2192 // or the operator specifying some other formation, we probably play the
2193 // same formation as the last point.
2194 function should_reuse_last_formation(events, t) {
2195 for (const e of events) {
2199 if (e.t > t + 10000) {
2202 const type = e.type;
2203 if (type === 'their_goal' || type === 'goal' ||
2204 type === 'set_defense' || type === 'set_offense' ||
2205 type === 'throwaway' || type === 'their_throwaway' ||
2206 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2207 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2208 type === 'formation_offense' || type === 'formation_defense') {
2215 function possibly_close_menu(e) {
2216 if (e.target.closest('.filter-click-to-add') === null &&
2217 e.target.closest('#filter-add-menu') === null &&
2218 e.target.closest('#filter-submenu') === null &&
2219 e.target.closest('.filter-pill') === null) {
2220 let add_menu = document.getElementById('filter-add-menu');
2221 let add_submenu = document.getElementById('filter-submenu');
2222 add_menu.style.display = 'none';
2223 add_submenu.style.display = 'none';
2224 try_gc_filter_menus(false);
2228 let global_sort = {};
2230 function sort_by(th) {
2231 let tr = th.parentElement;
2233 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2234 let element = tr.children[column_idx];
2235 if (element === th) {
2236 ++child_idx; // Pad.
2239 if (element.hasAttribute('colspan')) {
2240 child_idx += parseInt(element.getAttribute('colspan'));
2247 let table = tr.parentElement;
2248 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2249 let row = table.children[row_idx];
2250 let player = parseInt(row.dataset.player);
2251 let value = row.children[child_idx].textContent;
2252 global_sort[player] = value;
2256 function get_sorted_players(players)
2258 let p = Object.entries(players);
2259 if (global_sort.length !== 0) {
2261 let ai = parseFloat(global_sort[a[0]]);
2262 let bi = parseFloat(global_sort[b[0]]);
2263 if (ai == ai && bi == bi) {
2264 return bi - ai; // Reverse numeric.
2265 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2267 } else if (global_sort[a[0]] > global_sort[b[0]]) {