3 // No frameworks, no compilers, no npm, just JavaScript. :-)
6 let global_filters = {};
7 let next_filterset_id = 2; // Arbitrary IDs are fine as long as they never collide.
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12 .then(response => response.json())
13 .then(response => { global_json = response; process_matches(global_json, global_filters); });
15 function format_time(t)
17 const ms = t % 1000 + '';
18 t = Math.floor(t / 1000);
19 const sec = t % 60 + '';
20 t = Math.floor(t / 60);
21 const min = t % 60 + '';
22 const hour = Math.floor(t / 60) + '';
23 return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
26 function attribute_player_time(player, to, from, offense) {
28 if (player.on_field_since > from) {
29 // Player came in while play happened (without a stoppage!?).
30 delta_time = to - player.on_field_since;
32 delta_time = to - from;
34 player.playing_time_ms += delta_time;
35 if (offense === true) {
36 player.offensive_playing_time_ms += delta_time;
37 } else if (offense === false) {
38 player.defensive_playing_time_ms += delta_time;
42 function take_off_field(player, t, live_since, offense, keep) {
44 if (live_since === null) {
45 // Play isn't live, so nothing to do.
47 attribute_player_time(player, t, live_since, offense);
49 if (player.on_field_since !== null) { // Just a safeguard; out without in should never happen.
50 player.field_time_ms += t - player.on_field_since;
53 player.on_field_since = null;
56 function add_cell(tr, element_type, text) {
57 let element = document.createElement(element_type);
58 element.textContent = text;
59 tr.appendChild(element);
63 function add_th(tr, text, colspan) {
64 let element = document.createElement('th');
65 let link = document.createElement('a');
66 link.style.cursor = 'pointer';
67 link.addEventListener('click', (e) => {
69 process_matches(global_json, global_filters);
71 link.textContent = text;
72 element.appendChild(link);
73 tr.appendChild(element);
76 element.setAttribute('colspan', colspan);
78 element.setAttribute('colspan', '3');
83 function add_3cell(tr, text, cls) {
84 let p1 = add_cell(tr, 'td', '');
85 let element = add_cell(tr, 'td', text);
86 let p2 = add_cell(tr, 'td', '');
88 p1.classList.add('pad');
89 p2.classList.add('pad');
90 if (cls === undefined) {
91 element.classList.add('num');
93 element.classList.add(cls);
98 function add_3cell_with_filler_ci(tr, text, cls) {
99 let element = add_3cell(tr, text, cls);
101 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102 svg.classList.add('fillerci');
103 svg.setAttribute('width', ci_width);
104 svg.setAttribute('height', ci_height);
105 element.appendChild(svg);
110 function add_3cell_ci(tr, ci) {
112 add_3cell_with_filler_ci(tr, 'N/A');
117 if (ci.format === 'percentage') {
118 text = (100 * ci.val).toFixed(0) + '%';
120 text = ci.val.toFixed(2);
122 let element = add_3cell(tr, text);
123 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
126 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
127 if (ci.inverted === true) {
128 svg.classList.add('invertedci');
130 svg.classList.add('ci');
132 svg.setAttribute('width', ci_width);
133 svg.setAttribute('height', ci_height);
135 // The good (green) and red (bad) ranges.
136 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
137 s0.classList.add('range');
138 s0.classList.add('s0');
139 s0.setAttribute('width', to_x(ci.desired));
140 s0.setAttribute('height', ci_height);
141 s0.setAttribute('x', '0');
143 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
144 s1.classList.add('range');
145 s1.classList.add('s1');
146 s1.setAttribute('width', ci_width - to_x(ci.desired));
147 s1.setAttribute('height', ci_height);
148 s1.setAttribute('x', to_x(ci.desired));
151 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
152 bar.classList.add('bar');
153 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
154 bar.setAttribute('height', ci_height / 3);
155 bar.setAttribute('x', to_x(ci.lower_ci));
156 bar.setAttribute('y', ci_height / 3);
158 // Marker line for average.
159 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
160 marker.classList.add('marker');
161 marker.setAttribute('x1', to_x(ci.val));
162 marker.setAttribute('x2', to_x(ci.val));
163 marker.setAttribute('y1', ci_height / 6);
164 marker.setAttribute('y2', ci_height * 5 / 6);
168 svg.appendChild(bar);
169 svg.appendChild(marker);
171 element.appendChild(svg);
174 function calc_stats(json, filters) {
176 for (const player of json['players']) {
177 players[player['player_id']] = {
178 'name': player['name'],
179 'gender': player['gender'],
180 'number': player['number'],
196 'playing_time_ms': 0,
197 'offensive_playing_time_ms': 0,
198 'defensive_playing_time_ms': 0,
202 'offensive_points_completed': 0,
203 'offensive_points_won': 0,
204 'defensive_points_completed': 0,
205 'defensive_points_won': 0,
207 'offensive_soft_plus': 0,
208 'offensive_soft_minus': 0,
209 'defensive_soft_plus': 0,
210 'defensive_soft_minus': 0,
217 'last_point_seen': null,
218 'on_field_since': null,
223 players['globals'] = {
225 'playing_time_ms': 0,
226 'offensive_playing_time_ms': 0,
227 'defensive_playing_time_ms': 0,
230 'offensive_points_completed': 0,
231 'offensive_points_won': 0,
232 'defensive_points_completed': 0,
233 'defensive_points_won': 0,
235 let globals = players['globals'];
237 for (const match of json['matches']) {
238 if (!keep_match(match['match_id'], filters)) {
244 let between_points = true;
246 let handler_got_by_interception = false; // Only relevant if handler !== null.
247 let prev_handler = null;
248 let live_since = null;
249 let offense = null; // True/false/null (unknown).
251 let pull_started = null;
252 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
254 let game_started = null;
255 let last_goal = null;
256 let current_predominant_gender = null;
257 let current_num_players_on_field = null;
259 // The last used formations of the given kind, if any; they may be reused
260 // when the point starts, if nothing else is set.
261 let last_offensive_formation = null;
262 let last_defensive_formation = null;
264 // Formations we've set, but haven't really had the chance to use yet
265 // (e.g., we get a “use zone defense” event while we're still on offense).
266 let pending_offensive_formation = null;
267 let pending_defensive_formation = null;
269 // Formations that we have played at least once this point, after all
270 // heuristics and similar.
271 let formations_used_this_point = new Set();
273 for (const [q,p] of Object.entries(players)) {
274 p.on_field_since = null;
275 p.last_point_seen = null;
277 for (const e of match['events']) {
279 let type = e['type'];
280 let p = players[e['player']];
283 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
284 if (type === 'in' && p.on_field_since === null) {
285 p.on_field_since = t;
286 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
287 // A player needed for the filters went onto the field,
288 // so pretend people walked on right now (to start their
290 for (const [q,p2] of Object.entries(players)) {
291 if (p2.on_field_since !== null) {
292 p2.on_field_since = t;
296 } else if (type === 'out') {
297 take_off_field(p, t, live_since, offense, keep);
298 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
299 // A player needed for the filters went off the field,
300 // so we need to attribute time for all the others.
301 // Pretend they walked off and then immediately on again.
303 // TODO: We also need to take care of this to get the globals right.
304 for (const [q,p2] of Object.entries(players)) {
305 if (p2.on_field_since !== null) {
306 take_off_field(p2, t, live_since, offense, keep);
307 p2.on_field_since = t;
313 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
315 if (match['gender_rule_a']) {
316 if (type === 'restart' && !between_points) {
317 let predominant_gender = find_predominant_gender(players);
318 let num_players_on_field = find_num_players_on_field(players);
319 if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
320 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
322 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
323 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);
325 current_predominant_gender = predominant_gender;
326 current_num_players_on_field = num_players_on_field;
327 } else if (type === 'pull' || type === 'their_pull') {
328 let predominant_gender = find_predominant_gender(players);
329 let num_players_on_field = find_num_players_on_field(players);
330 let changed = (predominant_gender !== current_predominant_gender);
331 if (point_num !== 0) {
332 let should_change = (point_num % 4 == 1 || point_num % 4 == 3); // ABBA changes on 1 and 3.
333 if (changed && !should_change) {
334 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
335 } else if (!changed && should_change) {
336 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
338 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
339 console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
342 current_predominant_gender = predominant_gender;
343 current_num_players_on_field = num_players_on_field;
346 if (match['gender_pull_rule']) {
347 if (type === 'pull') {
348 if (current_predominant_gender !== null &&
349 p.gender !== current_predominant_gender) {
350 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
355 // Liveness management
356 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
358 between_points = false;
359 } else if (type === 'catch' && last_pull_was_ours === null) {
360 // Someone forgot to add the pull, so we'll need to wing it.
361 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
363 last_pull_was_ours = !offense;
364 between_points = false;
365 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
366 for (const [q,p] of Object.entries(players)) {
367 if (p.on_field_since === null) {
370 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
372 // In case the player did nothing this point,
373 // not even subbing in.
374 p.last_point_seen = point_num;
378 if (keep) attribute_player_time(p, t, live_since, offense);
380 if (type !== 'stoppage') {
382 if (last_pull_was_ours === true) { // D point.
383 ++p.defensive_points_completed;
384 if (type === 'goal') {
385 ++p.defensive_points_won;
387 } else if (last_pull_was_ours === false) { // O point.
388 ++p.offensive_points_completed;
389 if (type === 'goal') {
390 ++p.offensive_points_won;
398 if (type !== 'stoppage') {
400 ++globals.points_played;
401 if (last_pull_was_ours === true) { // D point.
402 ++globals.defensive_points_completed;
403 if (type === 'goal') {
404 ++globals.defensive_points_won;
406 } else if (last_pull_was_ours === false) { // O point.
407 ++globals.offensive_points_completed;
408 if (type === 'goal') {
409 ++globals.offensive_points_won;
413 if (live_since !== null) {
414 globals.playing_time_ms += t - live_since;
415 if (offense === true) {
416 globals.offensive_playing_time_ms += t - live_since;
417 } else if (offense === false) {
418 globals.defensive_playing_time_ms += t - live_since;
427 if (type === 'goal') {
429 between_points = true;
430 } else if (type === 'their_goal') {
432 between_points = true;
435 // Point count management
436 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
438 p.last_point_seen = point_num;
442 if (type === 'goal' || type === 'their_goal') {
446 if (type !== 'out' && game_started === null) {
451 if (type === 'pull') {
452 puller = e['player'];
455 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
456 // No effect on pull.
457 } else if (type === 'pull_landed' && puller !== null) {
458 if (keep) players[puller].pull_times.push(t - pull_started);
459 } else if (type === 'pull_oob' && puller !== null) {
460 if (keep) ++players[puller].oob_pulls;
462 // Not pulling (if there was one, we never recorded its outcome, but still count it).
463 puller = pull_started = null;
466 // Offense/defense management
467 let last_offense = offense;
468 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
470 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
473 if (last_offense !== offense && live_since !== null) {
474 // Switched offense/defense status, so attribute this drive as needed,
475 // and update live_since to take that into account.
477 for (const [q,p] of Object.entries(players)) {
478 if (p.on_field_since === null) {
481 attribute_player_time(p, t, live_since, last_offense);
483 globals.playing_time_ms += t - live_since;
484 if (offense === true) {
485 globals.offensive_playing_time_ms += t - live_since;
486 } else if (offense === false) {
487 globals.defensive_playing_time_ms += t - live_since;
493 if (type === 'pull') {
494 last_pull_was_ours = true;
495 } else if (type === 'their_pull') {
496 last_pull_was_ours = false;
497 } else if (type === 'set_offense' && last_pull_was_ours === null) {
498 // set_offense could either be “changed to offense for some reason
499 // we could not express”, or “we started in the middle of a point,
500 // and we are offense”. We assume that if we already saw the pull,
501 // it's the former, and if not, it's the latter; thus, the === null
502 // test above. (It could also be “we set offense before the pull,
503 // so that we get the right button enabled”, in which case it will
504 // be overwritten by the next pull/their_pull event anyway.)
505 last_pull_was_ours = false;
506 } else if (type === 'set_defense' && last_pull_was_ours === null) {
508 last_pull_was_ours = true;
509 } else if (type === 'goal' || type === 'their_goal') {
510 last_pull_was_ours = null;
513 // Formation management
514 if (type === 'formation_offense' || type === 'formation_defense') {
515 let id = e.formation === null ? 0 : e.formation;
516 let for_offense = (type === 'formation_offense');
517 if (offense === for_offense) {
518 formations_used_this_point.add(id);
519 } else if (for_offense) {
520 pending_offensive_formation = id;
522 pending_defensive_formation = id;
525 last_offensive_formation = id;
527 last_defensive_formation = id;
529 } else if (last_offense !== offense) {
530 if (offense === true && pending_offensive_formation !== null) {
531 formations_used_this_point.add(pending_offensive_formation);
532 pending_offensive_formation = null;
533 } else if (offense === false && pending_defensive_formation !== null) {
534 formations_used_this_point.add(pending_defensive_formation);
535 pending_defensive_formation = null;
536 } else if (offense === true && last_defensive_formation !== null) {
537 if (should_reuse_last_formation(match['events'], t)) {
538 formations_used_this_point.add(last_defensive_formation);
540 } else if (offense === false && last_offensive_formation !== null) {
541 if (should_reuse_last_formation(match['events'], t)) {
542 formations_used_this_point.add(last_offensive_formation);
547 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
548 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
550 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
551 // The handler subbed out and was replaced with another handler,
552 // so this wasn't a pass.
557 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
558 // Self-pass to goal after an interception; this is not a real pass,
559 // just how we represent a Callahan right now -- so don't
560 // count the throw, any assists or similar.
562 // It's an open question how we should handle a self-pass that is
563 // _not_ after an interception, or a self-pass that's not a goal.
564 // (It must mean we tipped off someone.) We'll count it as a regular one
565 // for the time being, although it will make hockey assists weird.
570 handler = prev_handler = null;
571 } else if (type === 'catch' || type === 'goal') {
572 if (handler !== null) {
574 ++players[handler].num_throws;
579 if (keep) ++p.touches;
580 if (type === 'goal') {
582 if (prev_handler !== null) {
583 ++players[prev_handler].hockey_assists;
585 if (handler !== null) {
586 ++players[handler].assists;
590 handler = prev_handler = null;
592 // Update hold history.
593 prev_handler = handler;
594 handler = e['player'];
595 handler_got_by_interception = false;
597 } else if (type === 'throwaway') {
602 handler = prev_handler = null;
603 } else if (type === 'drop') {
605 handler = prev_handler = null;
606 } else if (type === 'stallout') {
607 if (keep) ++p.stallouts;
608 handler = prev_handler = null;
609 } else if (type === 'was_d') {
610 if (keep) ++p.was_ds;
611 handler = prev_handler = null;
612 } else if (type === 'defense') {
613 if (keep) ++p.defenses;
614 } else if (type === 'interception') {
621 handler = e['player'];
622 handler_got_by_interception = true;
623 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
625 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
626 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
627 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
628 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
629 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
630 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
631 type !== 'formation_offense' && type !== 'formation_defense') {
632 console.log(format_time(t) + ": Unknown event “" + e + "”");
635 if (type === 'goal' || type === 'their_goal') {
636 formations_used_this_point.clear();
640 // Add field time for all players still left at match end.
641 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
643 for (const [q,p] of Object.entries(players)) {
644 if (p.on_field_since !== null && last_goal !== null) {
645 p.field_time_ms += last_goal - p.on_field_since;
648 if (game_started !== null && last_goal !== null) {
649 globals.field_time_ms += last_goal - game_started;
651 if (live_since !== null && last_goal !== null) {
652 globals.playing_time_ms += last_goal - live_since;
653 if (offense === true) {
654 globals.offensive_playing_time_ms += last_goal - live_since;
655 } else if (offense === false) {
656 globals.defensive_playing_time_ms += last_goal - live_since;
664 function process_matches(json, filtersets) {
665 let chosen_category = get_chosen_category();
666 write_main_menu(chosen_category);
668 let filterset_values = Object.values(filtersets);
669 if (filterset_values.length === 0) {
670 filterset_values = [[]];
674 for (const filter of filterset_values) {
675 let players = calc_stats(json, filter);
677 if (chosen_category === 'general') {
678 rows = make_table_general(players);
679 } else if (chosen_category === 'offense') {
680 rows = make_table_offense(players);
681 } else if (chosen_category === 'defense') {
682 rows = make_table_defense(players);
683 } else if (chosen_category === 'playing_time') {
684 rows = make_table_playing_time(players);
685 } else if (chosen_category === 'per_point') {
686 rows = make_table_per_point(players);
691 let merged_rows = [];
692 if (filterset_values.length > 1) {
693 for (let i = 0; i < rowsets.length; ++i) {
694 let marker = make_filter_marker(filterset_values[i]);
696 // Make filter header.
697 let tr = rowsets[i][0];
698 let th = document.createElement('th');
700 tr.insertBefore(th, tr.firstChild);
702 for (let j = 1; j < rowsets[i].length; ++j) {
703 let tr = rowsets[i][j];
705 // Remove the name for cleanness.
707 tr.firstChild.nextSibling.textContent = '';
711 tr.style.borderTop = '0px';
713 if (i != rowsets.length - 1) {
714 tr.style.borderBottom = '0px';
717 // Make filter marker.
718 let td = document.createElement('td');
719 td.textContent = marker;
720 td.classList.add('filtermarker');
721 tr.insertBefore(td, tr.firstChild);
725 for (let i = 0; i < rowsets[0].length; ++i) {
726 for (let j = 0; j < rowsets.length; ++j) {
727 merged_rows.push(rowsets[j][i]);
728 if (i === 0) break; // Don't merge the headings.
732 merged_rows = rowsets[0];
734 document.getElementById('stats').replaceChildren(...merged_rows);
737 function get_chosen_category() {
738 if (window.location.hash === '#offense') {
740 } else if (window.location.hash === '#defense') {
742 } else if (window.location.hash === '#playing_time') {
743 return 'playing_time';
744 } else if (window.location.hash === '#per_point') {
751 function write_main_menu(chosen_category) {
753 if (chosen_category === 'general') {
754 let span = document.createElement('span');
755 span.innerText = 'General';
758 let a = document.createElement('a');
759 a.appendChild(document.createTextNode('General'));
760 a.setAttribute('href', '#general');
764 if (chosen_category === 'offense') {
765 let span = document.createElement('span');
766 span.innerText = 'Offense';
769 let a = document.createElement('a');
770 a.appendChild(document.createTextNode('Offense'));
771 a.setAttribute('href', '#offense');
775 if (chosen_category === 'defense') {
776 let span = document.createElement('span');
777 span.innerText = 'Defense';
780 let a = document.createElement('a');
781 a.appendChild(document.createTextNode('Defense'));
782 a.setAttribute('href', '#defense');
786 if (chosen_category === 'playing_time') {
787 let span = document.createElement('span');
788 span.innerText = 'Playing time';
791 let a = document.createElement('a');
792 a.appendChild(document.createTextNode('Playing time'));
793 a.setAttribute('href', '#playing_time');
797 if (chosen_category === 'per_point') {
798 let span = document.createElement('span');
799 span.innerText = 'Per point';
802 let a = document.createElement('a');
803 a.appendChild(document.createTextNode('Per point'));
804 a.setAttribute('href', '#per_point');
808 document.getElementById('mainmenu').replaceChildren(...elems);
811 // https://en.wikipedia.org/wiki/1.96#History
814 const ci_width = 100;
815 const ci_height = 20;
817 function make_binomial_ci(val, num, z) {
820 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
821 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
822 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
824 // Fix the signs so that we don't get -0.00.
825 low = Math.max(low, 0.0);
835 // These can only happen once per point, but you get -1 and +1
836 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
837 // and then we can rewrite back.
838 function make_efficiency_ci(points_won, points_completed, z)
840 let ci = make_binomial_ci(points_won, points_completed, z);
841 ci.val = 2.0 * ci.val - 1.0;
842 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
843 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
846 ci.desired = 0.0; // Desired = positive efficiency.
850 // Ds, throwaways and drops can happen multiple times per point,
851 // so they are Poisson distributed.
853 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
854 // since our rates are definitely below 2 per point).
855 function make_poisson_ci(val, num, z, inverted)
857 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
858 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
860 // Fix the signs so that we don't get -0.00.
861 low = Math.max(low, 0.0);
863 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
872 'inverted': inverted,
876 function make_table_general(players) {
879 let header = document.createElement('tr');
880 add_th(header, 'Player');
881 add_th(header, '+/-');
882 add_th(header, 'Soft +/-');
883 add_th(header, 'O efficiency');
884 add_th(header, 'D efficiency');
885 add_th(header, 'Points played');
889 for (const [q,p] of get_sorted_players(players)) {
890 if (q === 'globals') continue;
891 let row = document.createElement('tr');
892 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
893 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
894 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
895 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
896 let name = add_3cell(row, p.name, 'name'); // TODO: number?
897 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
898 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
899 add_3cell_ci(row, o_efficiency);
900 add_3cell_ci(row, d_efficiency);
901 add_3cell(row, p.points_played);
902 row.dataset.player = q;
907 let globals = players['globals'];
908 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
909 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
910 let row = document.createElement('tr');
914 add_3cell_ci(row, o_efficiency);
915 add_3cell_ci(row, d_efficiency);
916 add_3cell(row, globals.points_played);
922 function make_table_offense(players) {
925 let header = document.createElement('tr');
926 add_th(header, 'Player');
927 add_th(header, 'Goals');
928 add_th(header, 'Assists');
929 add_th(header, 'Hockey assists');
930 add_th(header, 'Throws');
931 add_th(header, 'Throwaways');
932 add_th(header, '%OK');
933 add_th(header, 'Catches');
934 add_th(header, 'Drops');
935 add_th(header, 'D-ed');
936 add_th(header, '%OK');
937 add_th(header, 'Stalls');
938 add_th(header, 'Soft +/-', 6);
949 for (const [q,p] of get_sorted_players(players)) {
950 if (q === 'globals') continue;
951 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
952 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
954 throw_ok.format = 'percentage';
955 catch_ok.format = 'percentage';
957 // Desire at least 90% percentage. Fairly arbitrary.
958 throw_ok.desired = 0.9;
959 catch_ok.desired = 0.9;
961 let row = document.createElement('tr');
962 add_3cell(row, p.name, 'name'); // TODO: number?
963 add_3cell(row, p.goals);
964 add_3cell(row, p.assists);
965 add_3cell(row, p.hockey_assists);
966 add_3cell(row, p.num_throws);
967 add_3cell(row, p.throwaways);
968 add_3cell_ci(row, throw_ok);
969 add_3cell(row, p.catches);
970 add_3cell(row, p.drops);
971 add_3cell(row, p.was_ds);
972 add_3cell_ci(row, catch_ok);
973 add_3cell(row, p.stallouts);
974 add_3cell(row, '+' + p.offensive_soft_plus);
975 add_3cell(row, '-' + p.offensive_soft_minus);
976 row.dataset.player = q;
980 num_throws += p.num_throws;
981 throwaways += p.throwaways;
982 catches += p.catches;
985 stallouts += p.stallouts;
989 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
990 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
991 throw_ok.format = 'percentage';
992 catch_ok.format = 'percentage';
993 throw_ok.desired = 0.9;
994 catch_ok.desired = 0.9;
996 let row = document.createElement('tr');
998 add_3cell(row, goals);
1001 add_3cell(row, num_throws);
1002 add_3cell(row, throwaways);
1003 add_3cell_ci(row, throw_ok);
1004 add_3cell(row, catches);
1005 add_3cell(row, drops);
1006 add_3cell(row, was_ds);
1007 add_3cell_ci(row, catch_ok);
1008 add_3cell(row, stallouts);
1016 function make_table_defense(players) {
1019 let header = document.createElement('tr');
1020 add_th(header, 'Player');
1021 add_th(header, 'Ds');
1022 add_th(header, 'Pulls');
1023 add_th(header, 'OOB pulls');
1024 add_th(header, 'OOB%');
1025 add_th(header, 'Avg. hang time (IB)');
1026 add_th(header, 'Callahans');
1027 add_th(header, 'Soft +/-', 6);
1034 let sum_sum_time = 0;
1037 for (const [q,p] of get_sorted_players(players)) {
1038 if (q === 'globals') continue;
1040 for (const t of p.pull_times) {
1043 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1044 let oob_pct = 100 * p.oob_pulls / p.pulls;
1046 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1047 ci_oob.format = 'percentage';
1048 ci_oob.desired = 0.2; // Arbitrary.
1049 ci_oob.inverted = true;
1051 let row = document.createElement('tr');
1052 add_3cell(row, p.name, 'name'); // TODO: number?
1053 add_3cell(row, p.defenses);
1054 add_3cell(row, p.pulls);
1055 add_3cell(row, p.oob_pulls);
1056 add_3cell_ci(row, ci_oob);
1057 if (p.pulls > p.oob_pulls) {
1058 add_3cell(row, avg_time.toFixed(1) + ' sec');
1060 add_3cell(row, 'N/A');
1062 add_3cell(row, p.callahans);
1063 add_3cell(row, '+' + p.defensive_soft_plus);
1064 add_3cell(row, '-' + p.defensive_soft_minus);
1065 row.dataset.player = q;
1068 defenses += p.defenses;
1070 oob_pulls += p.oob_pulls;
1071 sum_sum_time += sum_time;
1072 callahans += p.callahans;
1076 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1077 ci_oob.format = 'percentage';
1078 ci_oob.desired = 0.2; // Arbitrary.
1079 ci_oob.inverted = true;
1081 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1082 let oob_pct = 100 * oob_pulls / pulls;
1084 let row = document.createElement('tr');
1086 add_3cell(row, defenses);
1087 add_3cell(row, pulls);
1088 add_3cell(row, oob_pulls);
1089 add_3cell_ci(row, ci_oob);
1090 if (pulls > oob_pulls) {
1091 add_3cell(row, avg_time.toFixed(1) + ' sec');
1093 add_3cell(row, 'N/A');
1095 add_3cell(row, callahans);
1103 function make_table_playing_time(players) {
1106 let header = document.createElement('tr');
1107 add_th(header, 'Player');
1108 add_th(header, 'Points played');
1109 add_th(header, 'Time played');
1110 add_th(header, 'O time');
1111 add_th(header, 'D time');
1112 add_th(header, 'Time on field');
1113 add_th(header, 'O points');
1114 add_th(header, 'D points');
1118 for (const [q,p] of get_sorted_players(players)) {
1119 if (q === 'globals') continue;
1120 let row = document.createElement('tr');
1121 add_3cell(row, p.name, 'name'); // TODO: number?
1122 add_3cell(row, p.points_played);
1123 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1124 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1125 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1126 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1127 add_3cell(row, p.offensive_points_completed);
1128 add_3cell(row, p.defensive_points_completed);
1129 row.dataset.player = q;
1134 let globals = players['globals'];
1135 let row = document.createElement('tr');
1137 add_3cell(row, globals.points_played);
1138 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1139 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1140 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1141 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1142 add_3cell(row, globals.offensive_points_completed);
1143 add_3cell(row, globals.defensive_points_completed);
1149 function make_table_per_point(players) {
1152 let header = document.createElement('tr');
1153 add_th(header, 'Player');
1154 add_th(header, 'Goals');
1155 add_th(header, 'Assists');
1156 add_th(header, 'Hockey assists');
1157 add_th(header, 'Ds');
1158 add_th(header, 'Throwaways');
1159 add_th(header, 'Recv. errors');
1160 add_th(header, 'Touches');
1166 let hockey_assists = 0;
1169 let receiver_errors = 0;
1171 for (const [q,p] of get_sorted_players(players)) {
1172 if (q === 'globals') continue;
1174 // Can only happen once per point, so these are binomials.
1175 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1176 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1177 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1178 // Arbitrarily desire at least 10% (not everybody can score or assist).
1179 ci_goals.desired = 0.1;
1180 ci_assists.desired = 0.1;
1181 ci_hockey_assists.desired = 0.1;
1183 let row = document.createElement('tr');
1184 add_3cell(row, p.name, 'name'); // TODO: number?
1185 add_3cell_ci(row, ci_goals);
1186 add_3cell_ci(row, ci_assists);
1187 add_3cell_ci(row, ci_hockey_assists);
1188 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1189 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1190 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1191 if (p.points_played > 0) {
1192 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1194 add_3cell(row, 'N/A');
1196 row.dataset.player = q;
1200 assists += p.assists;
1201 hockey_assists += p.hockey_assists;
1202 defenses += p.defenses;
1203 throwaways += p.throwaways;
1204 receiver_errors += p.drops + p.was_ds;
1205 touches += p.touches;
1209 let globals = players['globals'];
1210 let row = document.createElement('tr');
1212 if (globals.points_played > 0) {
1213 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1214 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1215 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1216 ci_goals.desired = 0.5;
1217 ci_assists.desired = 0.5;
1218 ci_hockey_assists.desired = 0.5;
1220 add_3cell_ci(row, ci_goals);
1221 add_3cell_ci(row, ci_assists);
1222 add_3cell_ci(row, ci_hockey_assists);
1224 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1225 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1226 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1228 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1230 add_3cell_with_filler_ci(row, 'N/A');
1231 add_3cell_with_filler_ci(row, 'N/A');
1232 add_3cell_with_filler_ci(row, 'N/A');
1233 add_3cell_with_filler_ci(row, 'N/A');
1234 add_3cell_with_filler_ci(row, 'N/A');
1235 add_3cell_with_filler_ci(row, 'N/A');
1236 add_3cell(row, 'N/A');
1243 function open_filter_menu(click_to_add_div) {
1244 document.getElementById('filter-submenu').style.display = 'none';
1245 let filter_div = click_to_add_div.parentElement;
1246 let filter_id = filter_div.dataset.filterId;
1248 let menu = document.getElementById('filter-add-menu');
1249 menu.parentElement.removeChild(menu);
1250 filter_div.appendChild(menu);
1251 menu.style.display = 'block';
1252 menu.replaceChildren();
1254 // Place the menu directly under the “click to add” label;
1255 // we don't anchor it since that label will move around
1256 // and the menu shouldn't.
1257 let rect = click_to_add_div.getBoundingClientRect();
1258 menu.style.left = rect.left + 'px';
1259 menu.style.top = (rect.bottom + 10) + 'px';
1261 let filterset = global_filters[filter_id];
1262 if (filterset === undefined) {
1263 global_filters[filter_id] = filterset = [];
1266 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1267 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1268 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1269 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1270 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1271 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1272 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1275 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1276 let item = document.createElement('div');
1277 item.classList.add('option');
1278 item.appendChild(document.createTextNode(title));
1280 let arrow = document.createElement('div');
1281 arrow.classList.add('arrow');
1282 arrow.textContent = '▸';
1283 item.appendChild(arrow);
1285 menu.appendChild(item);
1287 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1290 function find_all_ratios(json)
1294 for (const player of json['players']) {
1295 players[player['player_id']] = {
1296 'gender': player['gender'],
1297 'last_point_seen': null,
1300 for (const match of json['matches']) {
1301 for (const [q,p] of Object.entries(players)) {
1302 p.on_field_since = null;
1304 for (const e of match['events']) {
1305 let p = players[e['player']];
1306 let type = e['type'];
1307 if (type === 'in') {
1308 p.on_field_since = 1;
1309 } else if (type === 'out') {
1310 p.on_field_since = null;
1311 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1312 let code = find_gender_ratio_code(players);
1313 if (ratios[code] === undefined) {
1314 ratios[code] = code;
1315 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1316 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1317 match['description'] + ', ' + format_time(e['t']));
1326 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1327 let submenu = document.getElementById('filter-submenu');
1329 // Move to the same place as the top-level menu.
1330 submenu.parentElement.removeChild(submenu);
1331 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1334 const filter = find_filter(filterset, filter_type);
1337 if (filter_type === 'match') {
1338 for (const match of global_json['matches']) {
1340 'title': match['description'],
1341 'id': match['match_id']
1344 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1345 for (const player of global_json['players']) {
1347 'title': player['name'],
1348 'id': player['player_id']
1351 } else if (filter_type === 'formation_offense') {
1353 'title': '(None/unknown)',
1356 for (const formation of global_json['formations']) {
1357 if (formation['offense']) {
1359 'title': formation['name'],
1360 'id': formation['formation_id']
1364 } else if (filter_type === 'formation_defense') {
1366 'title': '(None/unknown)',
1369 for (const formation of global_json['formations']) {
1370 if (!formation['offense']) {
1372 'title': formation['name'],
1373 'id': formation['formation_id']
1377 } else if (filter_type === 'starting_on') {
1380 'id': false, // last_pull_was_ours
1384 'id': true, // last_pull_was_ours
1386 } else if (filter_type === 'gender_ratio') {
1387 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1395 for (const choice of choices) {
1396 let label = document.createElement('label');
1398 let subitem = document.createElement('div');
1399 subitem.classList.add('option');
1401 let check = document.createElement('input');
1402 check.setAttribute('type', 'checkbox');
1403 check.setAttribute('id', 'choice' + choice.id);
1404 if (filter !== null && filter.elements.has(choice.id)) {
1405 check.setAttribute('checked', 'checked');
1407 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1409 subitem.appendChild(check);
1410 subitem.appendChild(document.createTextNode(choice.title));
1412 label.appendChild(subitem);
1413 subitems.push(label);
1415 submenu.replaceChildren(...subitems);
1416 submenu.style.display = 'block';
1418 if (pill !== null) {
1419 let rect = pill.getBoundingClientRect();
1420 submenu.style.top = (rect.bottom + 10) + 'px';
1421 submenu.style.left = rect.left + 'px';
1423 // Position just outside the selected menu.
1424 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1425 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1426 submenu.style.left = (rect.right - 1) + 'px';
1430 // Find the right filter, if it exists.
1431 function find_filter(filterset, filter_type) {
1432 for (let f of filterset) {
1433 if (f.type === filter_type) {
1440 // Equivalent to Array.prototype.filter, but in-place.
1441 function inplace_filter(arr, cond) {
1443 for (let i = 0; i < arr.length; ++i) {
1451 function add_new_filterset() {
1452 let template = document.querySelector('.filter'); // First one is fine.
1453 let div = template.cloneNode(true);
1454 let add_menu = div.querySelector('#filter-add-menu');
1455 if (add_menu !== null) {
1456 div.removeChild(add_menu);
1458 let submenu = div.querySelector('#filter-submenu');
1459 if (submenu !== null) {
1460 div.removeChild(submenu);
1462 div.querySelector('.filters').replaceChildren();
1463 div.dataset.filterId = next_filterset_id++;
1464 template.parentElement.appendChild(div);
1467 function try_gc_filter_menus(cheap) {
1470 for (const filter_div of document.querySelectorAll('.filter')) {
1471 let id = filter_div.dataset.filterId;
1472 divs.push(filter_div);
1473 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1475 let last_div = divs[empties.length - 1];
1477 // See if we have two empty filter lists at the bottom of the list;
1478 // if so, we can remove one without it looking funny in the UI.
1479 // If not, we'll have to wait until closing the menu.
1480 // (The menu is positioned at the second-last one, so we can
1481 // remove the last one without issue.)
1482 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1483 delete global_filters[last_div.dataset.filterId];
1484 last_div.parentElement.removeChild(last_div);
1487 // This is a different situation from try_cheap_gc(), where we should
1488 // remove the one _not_ last. We might need to move the menu to the last one,
1489 // though, so it doesn't get lost.
1490 for (let i = 0; i < empties.length - 1; ++i) {
1495 delete global_filters[div.dataset.filterId];
1496 let add_menu = div.querySelector('#filter-add-menu');
1497 if (add_menu !== null) {
1498 div.removeChild(add_menu);
1499 last_div.appendChild(add_menu);
1501 let submenu = div.querySelector('#filter-submenu');
1502 if (submenu !== null) {
1503 div.removeChild(submenu);
1504 last_div.appendChild(submenu);
1506 div.parentElement.removeChild(div);
1511 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1512 let filter = find_filter(filterset, filter_type);
1513 let pills_div = filter_div.querySelector('.filters');
1514 if (e.target.checked) {
1515 // See if we must create a new empty filterset (since this went from
1516 // empty to non-empty).
1517 if (filterset.length === 0) {
1518 add_new_filterset();
1521 // See if we must add a new filter to the list.
1522 if (filter === null) {
1524 'type': filter_type,
1525 'elements': new Set([ id ]),
1527 filter.pill = make_filter_pill(filter_div, filterset, filter);
1528 filterset.push(filter);
1529 pills_div.appendChild(filter.pill);
1531 filter.elements.add(id);
1532 let new_pill = make_filter_pill(filter_div, filterset, filter);
1533 pills_div.replaceChild(new_pill, filter.pill);
1534 filter.pill = new_pill;
1537 filter.elements.delete(id);
1538 if (filter.elements.size === 0) {
1539 pills_div.removeChild(filter.pill);
1540 inplace_filter(filterset, f => f !== filter);
1542 if (filterset.length == 0) {
1543 try_gc_filter_menus(true);
1546 let new_pill = make_filter_pill(filter_div, filterset, filter);
1547 pills_div.replaceChild(new_pill, filter.pill);
1548 filter.pill = new_pill;
1552 process_matches(global_json, global_filters);
1555 function make_filter_pill(filter_div, filterset, filter) {
1556 let pill = document.createElement('div');
1557 pill.classList.add('filter-pill');
1559 if (filter.type === 'match') {
1563 for (const match_id of filter.elements) {
1564 all_names.push(find_match(match_id)['description']);
1566 let common_prefix = find_common_prefix_of_all(all_names);
1567 if (common_prefix !== null) {
1568 text += common_prefix + '(';
1572 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1573 for (const match_id of sorted_match_id) {
1577 let desc = find_match(match_id)['description'];
1578 if (common_prefix === null) {
1581 text += desc.substr(common_prefix.length);
1586 if (common_prefix !== null) {
1589 } else if (filter.type === 'player_any') {
1590 text = 'Player (any): ';
1591 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1593 for (const player_id of sorted_players) {
1597 text += find_player(player_id)['name'];
1600 } else if (filter.type === 'player_all') {
1602 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1604 for (const player_id of sorted_players) {
1608 text += find_player(player_id)['name'];
1611 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1612 const offense = (filter.type === 'formation_offense');
1620 for (const formation_id of filter.elements) {
1621 all_names.push(find_formation(formation_id)['name']);
1623 let common_prefix = find_common_prefix_of_all(all_names);
1624 if (common_prefix !== null) {
1625 text += common_prefix + '(';
1629 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1630 for (const formation_id of sorted_formation_id) {
1634 let desc = find_formation(formation_id)['name'];
1635 if (common_prefix === null) {
1638 text += desc.substr(common_prefix.length);
1643 if (common_prefix !== null) {
1646 } else if (filter.type === 'starting_on') {
1647 text = 'Starting on: ';
1649 if (filter.elements.has(false) && filter.elements.has(true)) {
1651 } else if (filter.elements.has(false)) {
1656 } else if (filter.type === 'gender_ratio') {
1660 for (const name of Array.from(filter.elements).sort()) {
1664 text += name; // FIXME
1669 let text_node = document.createElement('span');
1670 text_node.innerText = text;
1671 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1672 pill.appendChild(text_node);
1674 pill.appendChild(document.createTextNode(' '));
1676 let delete_node = document.createElement('span');
1677 delete_node.innerText = '✖';
1678 delete_node.addEventListener('click', (e) => {
1679 // Delete this filter entirely.
1680 pill.parentElement.removeChild(pill);
1681 inplace_filter(filterset, f => f !== filter);
1682 if (filterset.length == 0) {
1683 try_gc_filter_menus(false);
1685 process_matches(global_json, global_filters);
1687 let add_menu = document.getElementById('filter-add-menu');
1688 let add_submenu = document.getElementById('filter-submenu');
1689 add_menu.style.display = 'none';
1690 add_submenu.style.display = 'none';
1692 pill.appendChild(delete_node);
1693 pill.style.cursor = 'pointer';
1698 function make_filter_marker(filterset) {
1700 for (const filter of filterset) {
1704 if (filter.type === 'match') {
1706 for (const match of global_json['matches']) {
1707 all_names.push(match['description']);
1709 let common_prefix = find_common_prefix_of_all(all_names);
1711 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1712 for (const match_id of sorted_match_id) {
1713 let desc = find_match(match_id)['description'];
1714 if (common_prefix === null) {
1715 text += desc.substr(0, 3);
1717 text += desc.substr(common_prefix.length, 3);
1720 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1721 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1722 for (const player_id of sorted_players) {
1723 text += find_player(player_id)['name'].substr(0, 3);
1725 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1726 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1727 for (const formation_id of sorted_formation_id) {
1728 text += find_formation(formation_id)['name'].substr(0, 3);
1730 } else if (filter.type === 'starting_on') {
1731 if (filter.elements.has(false) && filter.elements.has(true)) {
1733 } else if (filter.elements.has(false)) {
1738 } else if (filter.type === 'gender_ratio') {
1740 for (const name of Array.from(filter.elements).sort()) {
1744 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
1752 function find_common_prefix(a, b) {
1754 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1755 if (a[i] === b[i]) {
1764 function find_common_prefix_of_all(values) {
1765 if (values.length < 2) {
1768 let common_prefix = null;
1769 for (const desc of values) {
1770 if (common_prefix === null) {
1771 common_prefix = desc;
1773 common_prefix = find_common_prefix(common_prefix, desc);
1776 if (common_prefix.length >= 3) {
1777 return common_prefix;
1783 function find_match(match_id) {
1784 for (const match of global_json['matches']) {
1785 if (match['match_id'] === match_id) {
1792 function find_formation(formation_id) {
1793 for (const formation of global_json['formations']) {
1794 if (formation['formation_id'] === formation_id) {
1801 function find_player(player_id) {
1802 for (const player of global_json['players']) {
1803 if (player['player_id'] === player_id) {
1810 function player_pos(player_id) {
1812 for (const player of global_json['players']) {
1813 if (player['player_id'] === player_id) {
1821 function keep_match(match_id, filters) {
1822 for (const filter of filters) {
1823 if (filter.type === 'match') {
1824 return filter.elements.has(match_id);
1830 // Returns a map of e.g. F => 4, M => 3.
1831 function find_gender_ratio(players) {
1833 for (const [q,p] of Object.entries(players)) {
1834 if (p.on_field_since === null) {
1837 let gender = p.gender;
1838 if (gender === '' || gender === undefined || gender === null) {
1841 if (map[gender] === undefined) {
1850 function find_gender_ratio_code(players) {
1851 let map = find_gender_ratio(players);
1852 let all_genders = Array.from(Object.keys(map)).sort(
1854 if (map[a] !== map[b]) {
1855 return map[b] - map[a]; // Reverse numeric.
1865 for (const g of all_genders) {
1876 // null if none (e.g., if playing 3–3).
1877 function find_predominant_gender(players) {
1879 let predominant_gender = null;
1880 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
1883 predominant_gender = gender;
1884 } else if (num == max) {
1885 predominant_gender = null; // At least two have the same.
1888 return predominant_gender;
1891 function find_num_players_on_field(players) {
1893 for (const [q,p] of Object.entries(players)) {
1894 if (p.on_field_since !== null) {
1901 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1902 if (filter.type === 'player_any') {
1903 for (const p of Array.from(filter.elements)) {
1904 if (players[p].on_field_since !== null) {
1909 } else if (filter.type === 'player_all') {
1910 for (const p of Array.from(filter.elements)) {
1911 if (players[p].on_field_since === null) {
1916 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1917 for (const f of Array.from(filter.elements)) {
1918 if (formations_used_this_point.has(f)) {
1923 } else if (filter.type === 'starting_on') {
1924 return filter.elements.has(last_pull_was_ours);
1925 } else if (filter.type === 'gender_ratio') {
1926 return filter.elements.has(find_gender_ratio_code(players));
1931 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
1932 for (const filter of filters) {
1933 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
1940 // Heuristic: If we go at least ten seconds without the possession changing
1941 // or the operator specifying some other formation, we probably play the
1942 // same formation as the last point.
1943 function should_reuse_last_formation(events, t) {
1944 for (const e of events) {
1948 if (e.t > t + 10000) {
1951 const type = e.type;
1952 if (type === 'their_goal' || type === 'goal' ||
1953 type === 'set_defense' || type === 'set_offense' ||
1954 type === 'throwaway' || type === 'their_throwaway' ||
1955 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1956 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1957 type === 'formation_offense' || type === 'formation_defense') {
1964 function possibly_close_menu(e) {
1965 if (e.target.closest('.filter-click-to-add') === null &&
1966 e.target.closest('#filter-add-menu') === null &&
1967 e.target.closest('#filter-submenu') === null &&
1968 e.target.closest('.filter-pill') === null) {
1969 let add_menu = document.getElementById('filter-add-menu');
1970 let add_submenu = document.getElementById('filter-submenu');
1971 add_menu.style.display = 'none';
1972 add_submenu.style.display = 'none';
1973 try_gc_filter_menus(false);
1977 let global_sort = {};
1979 function sort_by(th) {
1980 let tr = th.parentElement;
1982 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1983 let element = tr.children[column_idx];
1984 if (element === th) {
1985 ++child_idx; // Pad.
1988 if (element.hasAttribute('colspan')) {
1989 child_idx += parseInt(element.getAttribute('colspan'));
1996 let table = tr.parentElement;
1997 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
1998 let row = table.children[row_idx];
1999 let player = parseInt(row.dataset.player);
2000 let value = row.children[child_idx].textContent;
2001 global_sort[player] = value;
2005 function get_sorted_players(players)
2007 let p = Object.entries(players);
2008 if (global_sort.length !== 0) {
2010 let ai = parseFloat(global_sort[a[0]]);
2011 let bi = parseFloat(global_sort[b[0]]);
2012 if (ai == ai && bi == bi) {
2013 return bi - ai; // Reverse numeric.
2014 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2016 } else if (global_sort[a[0]] > global_sort[b[0]]) {