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 recursively_expand_filterset(filterset, base, result)
756 if (result.length >= 100) {
759 if (base.length == filterset.length) {
763 let filter = filterset[base.length];
765 let elements = filter.elements;
766 if (elements.size === 0) {
767 elements = filter.choices;
769 for (const element of elements) {
772 'elements': new Set([ element ]),
773 'split': false, // Not used.
775 recursively_expand_filterset(filterset, [...base, split_filter], result);
778 recursively_expand_filterset(filterset, [...base, filter], result);
782 function expand_filtersets(filtersets) {
783 if (filtersets.length === 0) {
788 for (const filterset of filtersets) {
789 recursively_expand_filterset(filterset, [], expanded);
794 function process_matches(json, unexpanded_filtersets) {
795 let chosen_category = get_chosen_category();
796 write_main_menu(chosen_category);
798 let filtersets = expand_filtersets(Object.values(unexpanded_filtersets));
801 for (const filter of filtersets) {
802 let players = calc_stats(json, filter);
804 if (chosen_category === 'general') {
805 rows = make_table_general(players);
806 } else if (chosen_category === 'offense') {
807 rows = make_table_offense(players);
808 } else if (chosen_category === 'defense') {
809 rows = make_table_defense(players);
810 } else if (chosen_category === 'playing_time') {
811 rows = make_table_playing_time(players);
812 } else if (chosen_category === 'per_point') {
813 rows = make_table_per_point(players);
814 } else if (chosen_category === 'team_wide') {
815 rows = make_table_team_wide(players);
820 let merged_rows = [];
821 if (filtersets.length > 1) {
822 for (let i = 0; i < rowsets.length; ++i) {
823 let marker = make_filter_marker(filtersets[i]);
825 // Make filter header.
826 let tr = rowsets[i][0];
827 let th = document.createElement('th');
829 tr.insertBefore(th, tr.firstChild);
831 for (let j = 1; j < rowsets[i].length; ++j) {
832 let tr = rowsets[i][j];
834 // Remove the name for cleanness.
836 tr.firstChild.nextSibling.textContent = '';
840 tr.style.borderTop = '0px';
842 if (i != rowsets.length - 1) {
843 tr.style.borderBottom = '0px';
846 // Make filter marker.
847 let td = document.createElement('td');
848 td.textContent = marker;
849 td.classList.add('filtermarker');
850 tr.insertBefore(td, tr.firstChild);
854 for (let i = 0; i < rowsets[0].length; ++i) {
855 for (let j = 0; j < rowsets.length; ++j) {
856 merged_rows.push(rowsets[j][i]);
857 if (i === 0) break; // Don't merge the headings.
861 merged_rows = rowsets[0];
863 document.getElementById('stats').replaceChildren(...merged_rows);
866 function get_chosen_category() {
867 if (window.location.hash === '#offense') {
869 } else if (window.location.hash === '#defense') {
871 } else if (window.location.hash === '#playing_time') {
872 return 'playing_time';
873 } else if (window.location.hash === '#per_point') {
875 } else if (window.location.hash === '#team_wide') {
882 function write_main_menu(chosen_category) {
885 ['general', 'General'],
886 ['offense', 'Offense'],
887 ['defense', 'Defense'],
888 ['playing_time', 'Playing time'],
889 ['per_point', 'Per point'],
890 ['team_wide', 'Team-wide'],
892 for (const [id, title] of categories) {
893 if (chosen_category === id) {
894 let span = document.createElement('span');
895 span.innerText = title;
898 let a = document.createElement('a');
899 a.appendChild(document.createTextNode(title));
900 a.setAttribute('href', '#' + id);
905 document.getElementById('mainmenu').replaceChildren(...elems);
908 // https://en.wikipedia.org/wiki/1.96#History
911 const ci_width = 100;
912 const ci_height = 20;
914 function make_binomial_ci(val, num, z) {
917 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
918 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
919 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
921 // Fix the signs so that we don't get -0.00.
922 low = Math.max(low, 0.0);
932 // These can only happen once per point, but you get -1 and +1
933 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
934 // and then we can rewrite back.
935 function make_efficiency_ci(points_won, points_completed, z)
937 let ci = make_binomial_ci(points_won, points_completed, z);
938 ci.val = 2.0 * ci.val - 1.0;
939 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
940 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
943 ci.desired = 0.0; // Desired = positive efficiency.
947 // Ds, throwaways and drops can happen multiple times per point,
948 // so they are Poisson distributed.
950 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
951 // since our rates are definitely below 2 per point).
953 // FIXME: z is ignored.
954 function make_poisson_ci(val, num, z, inverted)
956 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
957 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
959 // Fix the signs so that we don't get -0.00.
960 low = Math.max(low, 0.0);
962 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
971 'inverted': inverted,
975 // Wilson and Hilferty, again recommended for general use in the PDF above
976 // (anything from their group “G1” works).
977 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
978 function make_poisson_ci_large(val, num, z)
980 let low = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
981 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;
983 // Fix the signs so that we don't get -0.00.
984 low = Math.max(low, 0.0);
986 // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
987 // (this is used for number of touches).
1000 // We don't really know what to expect for possessions; it appears roughly
1001 // lognormal, but my head doesn't work well enough to extract the CI for
1002 // the estimated sample mean, and now my head spins around whether we do
1003 // this correctly even for Poisson :-) But we do a simple (non-BCa) bootstrap
1004 // here, which should give us what we want.
1006 // FIXME: z is ignored.
1007 function make_ci_duration(vals, z)
1010 let sample_means = [];
1011 for (let i = 0; i < 300; ++i) {
1013 for (let j = 0; j < vals.length; ++j) {
1014 sum += vals[Math.floor(Math.random() * vals.length)];
1016 sample_means.push(sum / vals.length);
1018 sample_means.sort();
1020 // Interpolating here would probably be better, but OK.
1021 let low = sample_means[Math.floor(0.025 * sample_means.length)];
1022 let high = sample_means[Math.floor(0.975 * sample_means.length)];
1024 // Find the point estimate of the mean.
1026 for (const v of vals) {
1029 let avg = sum / vals.length;
1032 'val': avg / 1000.0,
1033 'lower_ci': low / 1000.0,
1034 'upper_ci': high / 1000.0,
1044 function make_table_general(players) {
1047 let header = document.createElement('tr');
1048 add_th(header, 'Player');
1049 add_th(header, '+/-');
1050 add_th(header, 'Soft +/-');
1051 add_th(header, 'O efficiency');
1052 add_th(header, 'D efficiency');
1053 add_th(header, 'Points played');
1057 for (const [q,p] of get_sorted_players(players)) {
1058 if (q === 'globals') continue;
1059 let row = document.createElement('tr');
1060 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
1061 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
1062 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
1063 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
1064 let name = add_3cell(row, p.name, 'name'); // TODO: number?
1065 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
1066 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
1067 add_3cell_ci(row, o_efficiency);
1068 add_3cell_ci(row, d_efficiency);
1069 add_3cell(row, p.points_played);
1070 row.dataset.player = q;
1075 let globals = players['globals'];
1076 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
1077 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
1078 let row = document.createElement('tr');
1082 add_3cell_ci(row, o_efficiency);
1083 add_3cell_ci(row, d_efficiency);
1084 add_3cell(row, globals.points_played);
1090 function make_table_team_wide(players) {
1091 let globals = players['globals'];
1095 let header = document.createElement('tr');
1097 add_th(header, 'Our team', 6);
1098 add_th(header, 'Opponents', 6);
1104 let row = document.createElement('tr');
1105 let name = add_3cell(row, 'Turnovers generated', 'name');
1106 add_3cell(row, globals.turnovers_won);
1108 add_3cell(row, globals.turnovers_lost);
1115 let row = document.createElement('tr');
1116 let name = add_3cell(row, 'Clean holds', 'name');
1117 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1118 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1119 our_clean_holds.desired = 0.3; // Arbitrary.
1120 our_clean_holds.format = 'percentage';
1121 their_clean_holds.desired = 0.3;
1122 their_clean_holds.format = 'percentage';
1123 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1124 add_3cell_ci(row, our_clean_holds);
1125 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1126 add_3cell_ci(row, their_clean_holds);
1132 let row = document.createElement('tr');
1133 let name = add_3cell(row, 'Clean breaks', 'name');
1134 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1135 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1136 our_clean_breaks.desired = 0.3; // Arbitrary.
1137 our_clean_breaks.format = 'percentage';
1138 their_clean_breaks.desired = 0.3;
1139 their_clean_breaks.format = 'percentage';
1140 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1141 add_3cell_ci(row, our_clean_breaks);
1142 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1143 add_3cell_ci(row, their_clean_breaks);
1147 // Touches. We only have information for our team here.
1150 for (const [q,p] of get_sorted_players(players)) {
1151 if (q === 'globals') continue;
1154 let row = document.createElement('tr');
1155 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1156 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1157 let possessions = goals + globals.turnovers_lost;
1159 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1164 row = document.createElement('tr');
1165 add_3cell(row, 'Touches per possession (goals)', 'name');
1167 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1172 row = document.createElement('tr');
1173 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1175 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1181 // Time. Here we have (roughly) for both.
1183 let row = document.createElement('tr');
1184 let name = add_3cell(row, 'Time per possession (all)', 'name');
1185 let time = globals.time_for_turnover.concat(globals.time_for_goal);
1186 let their_time = globals.their_time_for_turnover.concat(globals.their_time_for_goal);
1188 add_3cell_ci(row, make_ci_duration(time, z));
1190 add_3cell_ci(row, make_ci_duration(their_time, z));
1193 row = document.createElement('tr');
1194 add_3cell(row, 'Time per possession (goals)', 'name');
1196 add_3cell_ci(row, make_ci_duration(globals.time_for_goal, z));
1198 add_3cell_ci(row, make_ci_duration(globals.their_time_for_goal, z));
1201 row = document.createElement('tr');
1202 add_3cell(row, 'Time per possession (turnovers)', 'name');
1204 add_3cell_ci(row, make_ci_duration(globals.time_for_turnover, z));
1206 add_3cell_ci(row, make_ci_duration(globals.their_time_for_turnover, z));
1213 function make_table_offense(players) {
1216 let header = document.createElement('tr');
1217 add_th(header, 'Player');
1218 add_th(header, 'Goals');
1219 add_th(header, 'Assists');
1220 add_th(header, 'Hockey assists');
1221 add_th(header, 'Throws');
1222 add_th(header, 'Throwaways');
1223 add_th(header, '%OK');
1224 add_th(header, 'Catches');
1225 add_th(header, 'Drops');
1226 add_th(header, 'D-ed');
1227 add_th(header, '%OK');
1228 add_th(header, 'Stalls');
1229 add_th(header, 'Soft +/-', 6);
1240 for (const [q,p] of get_sorted_players(players)) {
1241 if (q === 'globals') continue;
1242 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1243 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1245 throw_ok.format = 'percentage';
1246 catch_ok.format = 'percentage';
1248 // Desire at least 90% percentage. Fairly arbitrary.
1249 throw_ok.desired = 0.9;
1250 catch_ok.desired = 0.9;
1252 let row = document.createElement('tr');
1253 add_3cell(row, p.name, 'name'); // TODO: number?
1254 add_3cell(row, p.goals);
1255 add_3cell(row, p.assists);
1256 add_3cell(row, p.hockey_assists);
1257 add_3cell(row, p.num_throws);
1258 add_3cell(row, p.throwaways);
1259 add_3cell_ci(row, throw_ok);
1260 add_3cell(row, p.catches);
1261 add_3cell(row, p.drops);
1262 add_3cell(row, p.was_ds);
1263 add_3cell_ci(row, catch_ok);
1264 add_3cell(row, p.stallouts);
1265 add_3cell(row, '+' + p.offensive_soft_plus);
1266 add_3cell(row, '-' + p.offensive_soft_minus);
1267 row.dataset.player = q;
1271 num_throws += p.num_throws;
1272 throwaways += p.throwaways;
1273 catches += p.catches;
1276 stallouts += p.stallouts;
1280 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1281 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1282 throw_ok.format = 'percentage';
1283 catch_ok.format = 'percentage';
1284 throw_ok.desired = 0.9;
1285 catch_ok.desired = 0.9;
1287 let row = document.createElement('tr');
1289 add_3cell(row, goals);
1292 add_3cell(row, num_throws);
1293 add_3cell(row, throwaways);
1294 add_3cell_ci(row, throw_ok);
1295 add_3cell(row, catches);
1296 add_3cell(row, drops);
1297 add_3cell(row, was_ds);
1298 add_3cell_ci(row, catch_ok);
1299 add_3cell(row, stallouts);
1307 function make_table_defense(players) {
1310 let header = document.createElement('tr');
1311 add_th(header, 'Player');
1312 add_th(header, 'Ds');
1313 add_th(header, 'Pulls');
1314 add_th(header, 'OOB pulls');
1315 add_th(header, 'OOB%');
1316 add_th(header, 'Avg. hang time (IB)');
1317 add_th(header, 'Callahans');
1318 add_th(header, 'Soft +/-', 6);
1325 let sum_sum_time = 0;
1328 for (const [q,p] of get_sorted_players(players)) {
1329 if (q === 'globals') continue;
1331 for (const t of p.pull_times) {
1334 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1335 let oob_pct = 100 * p.oob_pulls / p.pulls;
1337 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1338 ci_oob.format = 'percentage';
1339 ci_oob.desired = 0.2; // Arbitrary.
1340 ci_oob.inverted = true;
1342 let row = document.createElement('tr');
1343 add_3cell(row, p.name, 'name'); // TODO: number?
1344 add_3cell(row, p.defenses);
1345 add_3cell(row, p.pulls);
1346 add_3cell(row, p.oob_pulls);
1347 add_3cell_ci(row, ci_oob);
1348 if (p.pulls > p.oob_pulls) {
1349 add_3cell(row, avg_time.toFixed(1) + ' sec');
1351 add_3cell(row, 'N/A');
1353 add_3cell(row, p.callahans);
1354 add_3cell(row, '+' + p.defensive_soft_plus);
1355 add_3cell(row, '-' + p.defensive_soft_minus);
1356 row.dataset.player = q;
1359 defenses += p.defenses;
1361 oob_pulls += p.oob_pulls;
1362 sum_sum_time += sum_time;
1363 callahans += p.callahans;
1367 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1368 ci_oob.format = 'percentage';
1369 ci_oob.desired = 0.2; // Arbitrary.
1370 ci_oob.inverted = true;
1372 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1373 let oob_pct = 100 * oob_pulls / pulls;
1375 let row = document.createElement('tr');
1377 add_3cell(row, defenses);
1378 add_3cell(row, pulls);
1379 add_3cell(row, oob_pulls);
1380 add_3cell_ci(row, ci_oob);
1381 if (pulls > oob_pulls) {
1382 add_3cell(row, avg_time.toFixed(1) + ' sec');
1384 add_3cell(row, 'N/A');
1386 add_3cell(row, callahans);
1394 function make_table_playing_time(players) {
1397 let header = document.createElement('tr');
1398 add_th(header, 'Player');
1399 add_th(header, 'Points played');
1400 add_th(header, 'Time played');
1401 add_th(header, 'O time');
1402 add_th(header, 'D time');
1403 add_th(header, 'Time on field');
1404 add_th(header, 'O points');
1405 add_th(header, 'D points');
1409 for (const [q,p] of get_sorted_players(players)) {
1410 if (q === 'globals') continue;
1411 let row = document.createElement('tr');
1412 add_3cell(row, p.name, 'name'); // TODO: number?
1413 add_3cell(row, p.points_played);
1414 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1415 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1416 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1417 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1418 add_3cell(row, p.offensive_points_completed);
1419 add_3cell(row, p.defensive_points_completed);
1420 row.dataset.player = q;
1425 let globals = players['globals'];
1426 let row = document.createElement('tr');
1428 add_3cell(row, globals.points_played);
1429 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1430 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1431 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1432 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1433 add_3cell(row, globals.offensive_points_completed);
1434 add_3cell(row, globals.defensive_points_completed);
1440 function make_table_per_point(players) {
1443 let header = document.createElement('tr');
1444 add_th(header, 'Player');
1445 add_th(header, 'Goals');
1446 add_th(header, 'Assists');
1447 add_th(header, 'Hockey assists');
1448 add_th(header, 'Ds');
1449 add_th(header, 'Throwaways');
1450 add_th(header, 'Recv. errors');
1451 add_th(header, 'Touches');
1457 let hockey_assists = 0;
1460 let receiver_errors = 0;
1462 for (const [q,p] of get_sorted_players(players)) {
1463 if (q === 'globals') continue;
1465 // Can only happen once per point, so these are binomials.
1466 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1467 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1468 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1469 // Arbitrarily desire at least 10% (not everybody can score or assist).
1470 ci_goals.desired = 0.1;
1471 ci_assists.desired = 0.1;
1472 ci_hockey_assists.desired = 0.1;
1474 let row = document.createElement('tr');
1475 add_3cell(row, p.name, 'name'); // TODO: number?
1476 add_3cell_ci(row, ci_goals);
1477 add_3cell_ci(row, ci_assists);
1478 add_3cell_ci(row, ci_hockey_assists);
1479 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1480 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1481 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1482 if (p.points_played > 0) {
1483 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1485 add_3cell(row, 'N/A');
1487 row.dataset.player = q;
1491 assists += p.assists;
1492 hockey_assists += p.hockey_assists;
1493 defenses += p.defenses;
1494 throwaways += p.throwaways;
1495 receiver_errors += p.drops + p.was_ds;
1496 touches += p.touches;
1500 let globals = players['globals'];
1501 let row = document.createElement('tr');
1503 if (globals.points_played > 0) {
1504 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1505 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1506 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1507 ci_goals.desired = 0.5;
1508 ci_assists.desired = 0.5;
1509 ci_hockey_assists.desired = 0.5;
1511 add_3cell_ci(row, ci_goals);
1512 add_3cell_ci(row, ci_assists);
1513 add_3cell_ci(row, ci_hockey_assists);
1515 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1516 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1517 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1519 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1521 add_3cell_with_filler_ci(row, 'N/A');
1522 add_3cell_with_filler_ci(row, 'N/A');
1523 add_3cell_with_filler_ci(row, 'N/A');
1524 add_3cell_with_filler_ci(row, 'N/A');
1525 add_3cell_with_filler_ci(row, 'N/A');
1526 add_3cell_with_filler_ci(row, 'N/A');
1527 add_3cell(row, 'N/A');
1534 function open_filter_menu(click_to_add_div) {
1535 document.getElementById('filter-submenu').style.display = 'none';
1536 let filter_div = click_to_add_div.parentElement;
1537 let filter_id = filter_div.dataset.filterId;
1539 let menu = document.getElementById('filter-add-menu');
1540 menu.parentElement.removeChild(menu);
1541 filter_div.appendChild(menu);
1542 menu.style.display = 'block';
1543 menu.replaceChildren();
1545 // Place the menu directly under the “click to add” label;
1546 // we don't anchor it since that label will move around
1547 // and the menu shouldn't.
1548 let rect = click_to_add_div.getBoundingClientRect();
1549 menu.style.left = rect.left + 'px';
1550 menu.style.top = (rect.bottom + 10) + 'px';
1552 let filterset = global_filters[filter_id];
1553 if (filterset === undefined) {
1554 global_filters[filter_id] = filterset = [];
1557 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1558 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1559 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1560 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1561 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1562 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1563 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1566 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1567 let item = document.createElement('div');
1568 item.classList.add('option');
1569 item.appendChild(document.createTextNode(title));
1571 let arrow = document.createElement('div');
1572 arrow.classList.add('arrow');
1573 arrow.textContent = '▸';
1574 item.appendChild(arrow);
1576 menu.appendChild(item);
1578 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1581 function find_all_ratios(json)
1585 for (const player of json['players']) {
1586 players[player['player_id']] = {
1587 'gender': player['gender'],
1588 'last_point_seen': null,
1591 for (const match of json['matches']) {
1592 for (const [q,p] of Object.entries(players)) {
1593 p.on_field_since = null;
1595 for (const e of match['events']) {
1596 let p = players[e['player']];
1597 let type = e['type'];
1598 if (type === 'in') {
1599 p.on_field_since = 1;
1600 } else if (type === 'out') {
1601 p.on_field_since = null;
1602 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1603 let code = find_gender_ratio_code(players);
1604 if (ratios[code] === undefined) {
1605 ratios[code] = code;
1606 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1607 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1608 match['description'] + ', ' + format_time(e['t']));
1617 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1618 let submenu = document.getElementById('filter-submenu');
1620 // Move to the same place as the top-level menu.
1621 submenu.parentElement.removeChild(submenu);
1622 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1625 const filter = find_filter(filterset, filter_type);
1628 if (filter_type === 'match') {
1629 for (const match of global_json['matches']) {
1631 'title': match['description'],
1632 'id': match['match_id']
1635 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1636 for (const player of global_json['players']) {
1638 'title': player['name'],
1639 'id': player['player_id']
1642 } else if (filter_type === 'formation_offense') {
1644 'title': '(None/unknown)',
1647 for (const formation of global_json['formations']) {
1648 if (formation['offense']) {
1650 'title': formation['name'],
1651 'id': formation['formation_id']
1655 } else if (filter_type === 'formation_defense') {
1657 'title': '(None/unknown)',
1660 for (const formation of global_json['formations']) {
1661 if (!formation['offense']) {
1663 'title': formation['name'],
1664 'id': formation['formation_id']
1668 } else if (filter_type === 'starting_on') {
1671 'id': false, // last_pull_was_ours
1675 'id': true, // last_pull_was_ours
1677 } else if (filter_type === 'gender_ratio') {
1678 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1686 let choice_set = new Set();
1687 for (const choice of choices) {
1688 choice_set.add(choice.id);
1691 for (const choice of choices) {
1692 let label = document.createElement('label');
1694 let subitem = document.createElement('div');
1695 subitem.classList.add('option');
1697 let check = document.createElement('input');
1698 check.setAttribute('type', 'checkbox');
1699 check.setAttribute('id', 'choice' + choice.id);
1700 if (filter !== null && filter.elements.has(choice.id)) {
1701 check.setAttribute('checked', 'checked');
1703 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id, choice_set); });
1705 subitem.appendChild(check);
1706 subitem.appendChild(document.createTextNode(choice.title));
1708 label.appendChild(subitem);
1709 subitems.push(label);
1712 // If meaningful (it's not for player_all, since all data for that would be
1713 // the same anyway), show the split checkbox.
1714 if (choices.length > 1 && filter_type !== 'player_all') {
1715 let label = document.createElement('label');
1717 let subitem = document.createElement('div');
1718 subitem.classList.add('option');
1720 let check = document.createElement('input');
1721 check.setAttribute('type', 'checkbox');
1722 check.setAttribute('id', 'choice_split');
1723 if (filter !== null && filter.split) {
1724 check.setAttribute('checked', 'checked');
1726 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, 'split', choice_set); });
1728 subitem.appendChild(check);
1729 let text_span = document.createElement('span'); // So that we can style its disabling later.
1730 text_span.appendChild(document.createTextNode('Split'));
1731 subitem.appendChild(text_span);
1732 subitem.style.borderTop = '1px solid #ddd';
1734 label.appendChild(subitem);
1735 subitems.push(label);
1738 submenu.replaceChildren(...subitems);
1739 submenu.style.display = 'block';
1741 if (pill !== null) {
1742 let rect = pill.getBoundingClientRect();
1743 submenu.style.top = (rect.bottom + 10) + 'px';
1744 submenu.style.left = rect.left + 'px';
1746 // Position just outside the selected menu.
1747 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1748 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1749 submenu.style.left = (rect.right - 1) + 'px';
1753 // Find the right filter, if it exists.
1754 function find_filter(filterset, filter_type) {
1755 for (let f of filterset) {
1756 if (f.type === filter_type) {
1763 // Equivalent to Array.prototype.filter, but in-place.
1764 function inplace_filter(arr, cond) {
1766 for (let i = 0; i < arr.length; ++i) {
1774 function add_new_filterset() {
1775 let template = document.querySelector('.filter'); // First one is fine.
1776 let div = template.cloneNode(true);
1777 let add_menu = div.querySelector('#filter-add-menu');
1778 if (add_menu !== null) {
1779 div.removeChild(add_menu);
1781 let submenu = div.querySelector('#filter-submenu');
1782 if (submenu !== null) {
1783 div.removeChild(submenu);
1785 div.querySelector('.filters').replaceChildren();
1786 div.dataset.filterId = next_filterset_id++;
1787 template.parentElement.appendChild(div);
1790 function try_gc_filter_menus(cheap) {
1793 for (const filter_div of document.querySelectorAll('.filter')) {
1794 let id = filter_div.dataset.filterId;
1795 divs.push(filter_div);
1796 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1798 let last_div = divs[empties.length - 1];
1800 // See if we have two empty filter lists at the bottom of the list;
1801 // if so, we can remove one without it looking funny in the UI.
1802 // If not, we'll have to wait until closing the menu.
1803 // (The menu is positioned at the second-last one, so we can
1804 // remove the last one without issue.)
1805 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1806 delete global_filters[last_div.dataset.filterId];
1807 last_div.parentElement.removeChild(last_div);
1810 // This is a different situation from try_cheap_gc(), where we should
1811 // remove the one _not_ last. We might need to move the menu to the last one,
1812 // though, so it doesn't get lost.
1813 for (let i = 0; i < empties.length - 1; ++i) {
1818 delete global_filters[div.dataset.filterId];
1819 let add_menu = div.querySelector('#filter-add-menu');
1820 if (add_menu !== null) {
1821 div.removeChild(add_menu);
1822 last_div.appendChild(add_menu);
1824 let submenu = div.querySelector('#filter-submenu');
1825 if (submenu !== null) {
1826 div.removeChild(submenu);
1827 last_div.appendChild(submenu);
1829 div.parentElement.removeChild(div);
1834 function checkbox_changed(filter_div, filterset, e, filter_type, id, choices) {
1835 let filter = find_filter(filterset, filter_type);
1836 let pills_div = filter_div.querySelector('.filters');
1837 if (e.target.checked) {
1838 // See if we must create a new empty filterset (since this went from
1839 // empty to non-empty).
1840 if (filterset.length === 0) {
1841 add_new_filterset();
1844 // See if we must add a new filter to the list.
1845 if (filter === null) {
1847 'type': filter_type,
1848 'elements': new Set(),
1852 if (id === 'split') {
1853 filter.split = true;
1855 filter.elements.add(id);
1857 filter.pill = make_filter_pill(filter_div, filterset, filter);
1858 filterset.push(filter);
1859 pills_div.appendChild(filter.pill);
1861 if (id === 'split') {
1862 filter.split = true;
1864 filter.elements.add(id);
1866 let new_pill = make_filter_pill(filter_div, filterset, filter);
1867 pills_div.replaceChild(new_pill, filter.pill);
1868 filter.pill = new_pill;
1871 if (id === 'split') {
1872 filter.split = false;
1874 filter.elements.delete(id);
1876 if (filter.elements.size === 0) {
1877 pills_div.removeChild(filter.pill);
1878 inplace_filter(filterset, f => f !== filter);
1880 if (filterset.length == 0) {
1881 try_gc_filter_menus(true);
1884 let new_pill = make_filter_pill(filter_div, filterset, filter);
1885 pills_div.replaceChild(new_pill, filter.pill);
1886 filter.pill = new_pill;
1889 let choice_split = document.getElementById('choice_split');
1890 if (filter.elements.size === 1) {
1891 choice_split.nextSibling.style.opacity = 0.2;
1892 choice_split.setAttribute('disabled', 'disabled');
1894 choice_split.nextSibling.style.opacity = 1.0;
1895 choice_split.removeAttribute('disabled');
1898 process_matches(global_json, global_filters);
1901 function make_filter_pill(filter_div, filterset, filter) {
1902 let pill = document.createElement('div');
1903 pill.classList.add('filter-pill');
1905 if (filter.type === 'match') {
1909 for (const match_id of filter.elements) {
1910 all_names.push(find_match(match_id)['description']);
1912 let common_prefix = find_common_prefix_of_all(all_names);
1913 if (common_prefix !== null) {
1914 text += common_prefix + '(';
1918 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1919 for (const match_id of sorted_match_id) {
1923 let desc = find_match(match_id)['description'];
1924 if (common_prefix === null) {
1927 text += desc.substr(common_prefix.length);
1932 if (common_prefix !== null) {
1935 } else if (filter.type === 'player_any') {
1936 text = 'Player (any): ';
1937 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1939 for (const player_id of sorted_players) {
1943 text += find_player(player_id)['name'];
1946 } else if (filter.type === 'player_all') {
1948 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1950 for (const player_id of sorted_players) {
1954 text += find_player(player_id)['name'];
1957 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1958 const offense = (filter.type === 'formation_offense');
1966 for (const formation_id of filter.elements) {
1967 all_names.push(find_formation(formation_id)['name']);
1969 let common_prefix = find_common_prefix_of_all(all_names);
1970 if (common_prefix !== null) {
1971 text += common_prefix + '(';
1975 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1976 for (const formation_id of sorted_formation_id) {
1980 let desc = find_formation(formation_id)['name'];
1981 if (common_prefix === null) {
1984 text += desc.substr(common_prefix.length);
1989 if (common_prefix !== null) {
1992 } else if (filter.type === 'starting_on') {
1993 text = 'Starting on: ';
1995 if (filter.elements.has(false) && filter.elements.has(true)) {
1997 } else if (filter.elements.has(false)) {
2002 } else if (filter.type === 'gender_ratio') {
2006 for (const name of Array.from(filter.elements).sort()) {
2010 text += name; // FIXME
2014 if (filter.split && filter.elements.size !== 1) {
2018 let text_node = document.createElement('span');
2019 text_node.innerText = text;
2020 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
2021 pill.appendChild(text_node);
2023 pill.appendChild(document.createTextNode(' '));
2025 let delete_node = document.createElement('span');
2026 delete_node.innerText = '✖';
2027 delete_node.addEventListener('click', (e) => {
2028 // Delete this filter entirely.
2029 pill.parentElement.removeChild(pill);
2030 inplace_filter(filterset, f => f !== filter);
2031 if (filterset.length == 0) {
2032 try_gc_filter_menus(false);
2034 process_matches(global_json, global_filters);
2036 let add_menu = document.getElementById('filter-add-menu');
2037 let add_submenu = document.getElementById('filter-submenu');
2038 add_menu.style.display = 'none';
2039 add_submenu.style.display = 'none';
2041 pill.appendChild(delete_node);
2042 pill.style.cursor = 'pointer';
2047 function make_filter_marker(filterset) {
2049 for (const filter of filterset) {
2053 if (filter.type === 'match') {
2055 for (const match of global_json['matches']) {
2056 all_names.push(match['description']);
2058 let common_prefix = find_common_prefix_of_all(all_names);
2060 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
2061 for (const match_id of sorted_match_id) {
2062 let desc = find_match(match_id)['description'];
2063 if (common_prefix === null) {
2064 text += desc.substr(0, 3);
2066 text += desc.substr(common_prefix.length, 3);
2069 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
2070 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
2071 for (const player_id of sorted_players) {
2072 text += find_player(player_id)['name'].substr(0, 3);
2074 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2075 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
2076 for (const formation_id of sorted_formation_id) {
2077 text += find_formation(formation_id)['name'].substr(0, 3);
2079 } else if (filter.type === 'starting_on') {
2080 if (filter.elements.has(false) && filter.elements.has(true)) {
2082 } else if (filter.elements.has(false)) {
2087 } else if (filter.type === 'gender_ratio') {
2089 for (const name of Array.from(filter.elements).sort()) {
2093 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
2101 function find_common_prefix(a, b) {
2103 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
2104 if (a[i] === b[i]) {
2113 function find_common_prefix_of_all(values) {
2114 if (values.length < 2) {
2117 let common_prefix = null;
2118 for (const desc of values) {
2119 if (common_prefix === null) {
2120 common_prefix = desc;
2122 common_prefix = find_common_prefix(common_prefix, desc);
2125 if (common_prefix.length >= 3) {
2126 return common_prefix;
2132 function find_match(match_id) {
2133 for (const match of global_json['matches']) {
2134 if (match['match_id'] === match_id) {
2141 function find_formation(formation_id) {
2142 for (const formation of global_json['formations']) {
2143 if (formation['formation_id'] === formation_id) {
2150 function find_player(player_id) {
2151 for (const player of global_json['players']) {
2152 if (player['player_id'] === player_id) {
2159 function player_pos(player_id) {
2161 for (const player of global_json['players']) {
2162 if (player['player_id'] === player_id) {
2170 function keep_match(match_id, filters) {
2171 for (const filter of filters) {
2172 if (filter.type === 'match') {
2173 return filter.elements.has(match_id);
2179 // Returns a map of e.g. F => 4, M => 3.
2180 function find_gender_ratio(players) {
2182 for (const [q,p] of Object.entries(players)) {
2183 if (p.on_field_since === null) {
2186 let gender = p.gender;
2187 if (gender === '' || gender === undefined || gender === null) {
2190 if (map[gender] === undefined) {
2199 function find_gender_ratio_code(players) {
2200 let map = find_gender_ratio(players);
2201 let all_genders = Array.from(Object.keys(map)).sort(
2203 if (map[a] !== map[b]) {
2204 return map[b] - map[a]; // Reverse numeric.
2214 for (const g of all_genders) {
2225 // null if none (e.g., if playing 3–3).
2226 function find_predominant_gender(players) {
2228 let predominant_gender = null;
2229 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2232 predominant_gender = gender;
2233 } else if (num == max) {
2234 predominant_gender = null; // At least two have the same.
2237 return predominant_gender;
2240 function find_num_players_on_field(players) {
2242 for (const [q,p] of Object.entries(players)) {
2243 if (p.on_field_since !== null) {
2250 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2251 if (filter.type === 'player_any') {
2252 for (const p of Array.from(filter.elements)) {
2253 if (players[p].on_field_since !== null) {
2258 } else if (filter.type === 'player_all') {
2259 for (const p of Array.from(filter.elements)) {
2260 if (players[p].on_field_since === null) {
2265 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2266 for (const f of Array.from(filter.elements)) {
2267 if (formations_used_this_point.has(f)) {
2272 } else if (filter.type === 'starting_on') {
2273 return filter.elements.has(last_pull_was_ours);
2274 } else if (filter.type === 'gender_ratio') {
2275 return filter.elements.has(find_gender_ratio_code(players));
2280 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2281 for (const filter of filters) {
2282 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2289 // Heuristic: If we go at least ten seconds without the possession changing
2290 // or the operator specifying some other formation, we probably play the
2291 // same formation as the last point.
2292 function should_reuse_last_formation(events, t) {
2293 for (const e of events) {
2297 if (e.t > t + 10000) {
2300 const type = e.type;
2301 if (type === 'their_goal' || type === 'goal' ||
2302 type === 'set_defense' || type === 'set_offense' ||
2303 type === 'throwaway' || type === 'their_throwaway' ||
2304 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2305 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2306 type === 'formation_offense' || type === 'formation_defense') {
2313 function possibly_close_menu(e) {
2314 if (e.target.closest('.filter-click-to-add') === null &&
2315 e.target.closest('#filter-add-menu') === null &&
2316 e.target.closest('#filter-submenu') === null &&
2317 e.target.closest('.filter-pill') === null) {
2318 let add_menu = document.getElementById('filter-add-menu');
2319 let add_submenu = document.getElementById('filter-submenu');
2320 add_menu.style.display = 'none';
2321 add_submenu.style.display = 'none';
2322 try_gc_filter_menus(false);
2326 let global_sort = {};
2328 function sort_by(th) {
2329 let tr = th.parentElement;
2331 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2332 let element = tr.children[column_idx];
2333 if (element === th) {
2334 ++child_idx; // Pad.
2337 if (element.hasAttribute('colspan')) {
2338 child_idx += parseInt(element.getAttribute('colspan'));
2345 let table = tr.parentElement;
2346 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2347 let row = table.children[row_idx];
2348 let player = parseInt(row.dataset.player);
2349 let value = row.children[child_idx].textContent;
2350 global_sort[player] = value;
2354 function get_sorted_players(players)
2356 let p = Object.entries(players);
2357 if (global_sort.length !== 0) {
2359 let ai = parseFloat(global_sort[a[0]]);
2360 let bi = parseFloat(global_sort[b[0]]);
2361 if (ai == ai && bi == bi) {
2362 return bi - ai; // Reverse numeric.
2363 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2365 } else if (global_sort[a[0]] > global_sort[b[0]]) {