3 // No frameworks, no compilers, no npm, just JavaScript. :-)
6 let global_filters = {};
7 let next_filterset_id = 2; // Arbitrary IDs are fine as long as they never collide.
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12 .then(response => response.json())
13 .then(response => { global_json = response; process_matches(global_json, global_filters); });
15 function format_time(t)
17 const ms = t % 1000 + '';
18 t = Math.floor(t / 1000);
19 const sec = t % 60 + '';
20 t = Math.floor(t / 60);
21 const min = t % 60 + '';
22 const hour = Math.floor(t / 60) + '';
23 return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
26 function attribute_player_time(player, to, from, offense) {
28 if (player.on_field_since > from) {
29 // Player came in while play happened (without a stoppage!?).
30 delta_time = to - player.on_field_since;
32 delta_time = to - from;
34 player.playing_time_ms += delta_time;
35 if (offense === true) {
36 player.offensive_playing_time_ms += delta_time;
37 } else if (offense === false) {
38 player.defensive_playing_time_ms += delta_time;
42 function take_off_field(player, t, live_since, offense, keep) {
44 if (live_since === null) {
45 // Play isn't live, so nothing to do.
47 attribute_player_time(player, t, live_since, offense);
49 if (player.on_field_since !== null) { // Just a safeguard; out without in should never happen.
50 player.field_time_ms += t - player.on_field_since;
53 player.on_field_since = null;
56 function add_cell(tr, element_type, text) {
57 let element = document.createElement(element_type);
58 element.textContent = text;
59 tr.appendChild(element);
63 function add_th(tr, text, colspan) {
64 let element = document.createElement('th');
65 let link = document.createElement('a');
66 link.style.cursor = 'pointer';
67 link.addEventListener('click', (e) => {
69 process_matches(global_json, global_filters);
71 link.textContent = text;
72 element.appendChild(link);
73 tr.appendChild(element);
76 element.setAttribute('colspan', colspan);
78 element.setAttribute('colspan', '3');
83 function add_3cell(tr, text, cls) {
84 let p1 = add_cell(tr, 'td', '');
85 let element = add_cell(tr, 'td', text);
86 let p2 = add_cell(tr, 'td', '');
88 p1.classList.add('pad');
89 p2.classList.add('pad');
90 if (cls === undefined) {
91 element.classList.add('num');
93 element.classList.add(cls);
98 function add_3cell_with_filler_ci(tr, text, cls) {
99 let element = add_3cell(tr, text, cls);
101 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102 svg.classList.add('fillerci');
103 svg.setAttribute('width', ci_width);
104 svg.setAttribute('height', ci_height);
105 element.appendChild(svg);
110 function add_3cell_ci(tr, ci) {
112 add_3cell_with_filler_ci(tr, 'N/A');
117 if (ci.format === 'percentage') {
118 text = (100 * ci.val).toFixed(0) + '%';
120 text = ci.val.toFixed(2);
122 let element = add_3cell(tr, text);
123 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
126 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
127 if (ci.inverted === true) {
128 svg.classList.add('invertedci');
130 svg.classList.add('ci');
132 svg.setAttribute('width', ci_width);
133 svg.setAttribute('height', ci_height);
135 // The good (green) and red (bad) ranges.
136 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
137 s0.classList.add('range');
138 s0.classList.add('s0');
139 s0.setAttribute('width', to_x(ci.desired));
140 s0.setAttribute('height', ci_height);
141 s0.setAttribute('x', '0');
143 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
144 s1.classList.add('range');
145 s1.classList.add('s1');
146 s1.setAttribute('width', ci_width - to_x(ci.desired));
147 s1.setAttribute('height', ci_height);
148 s1.setAttribute('x', to_x(ci.desired));
151 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
152 bar.classList.add('bar');
153 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
154 bar.setAttribute('height', ci_height / 3);
155 bar.setAttribute('x', to_x(ci.lower_ci));
156 bar.setAttribute('y', ci_height / 3);
158 // Marker line for average.
159 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
160 marker.classList.add('marker');
161 marker.setAttribute('x1', to_x(ci.val));
162 marker.setAttribute('x2', to_x(ci.val));
163 marker.setAttribute('y1', ci_height / 6);
164 marker.setAttribute('y2', ci_height * 5 / 6);
168 svg.appendChild(bar);
169 svg.appendChild(marker);
171 element.appendChild(svg);
174 function calc_stats(json, filters) {
176 for (const player of json['players']) {
177 players[player['player_id']] = {
178 'name': player['name'],
179 'gender': player['gender'],
180 'number': player['number'],
196 'playing_time_ms': 0,
197 'offensive_playing_time_ms': 0,
198 'defensive_playing_time_ms': 0,
202 'offensive_points_completed': 0,
203 'offensive_points_won': 0,
204 'defensive_points_completed': 0,
205 'defensive_points_won': 0,
207 'offensive_soft_plus': 0,
208 'offensive_soft_minus': 0,
209 'defensive_soft_plus': 0,
210 'defensive_soft_minus': 0,
217 'last_point_seen': null,
218 'on_field_since': null,
223 players['globals'] = {
225 'playing_time_ms': 0,
226 'offensive_playing_time_ms': 0,
227 'defensive_playing_time_ms': 0,
230 'offensive_points_completed': 0,
231 'offensive_points_won': 0,
234 'defensive_points_completed': 0,
235 'defensive_points_won': 0,
240 'their_clean_holds': 0,
241 'their_clean_breaks': 0,
243 let globals = players['globals'];
245 for (const match of json['matches']) {
246 if (!keep_match(match['match_id'], filters)) {
252 let between_points = true;
254 let handler_got_by_interception = false; // Only relevant if handler !== null.
255 let prev_handler = null;
256 let live_since = null;
257 let offense = null; // True/false/null (unknown).
259 let pull_started = null;
260 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
262 let game_started = null;
263 let last_goal = null;
264 let current_predominant_gender = null;
265 let current_num_players_on_field = null;
267 let we_lost_disc = false;
268 let they_lost_disc = false;
270 // The last used formations of the given kind, if any; they may be reused
271 // when the point starts, if nothing else is set.
272 let last_offensive_formation = null;
273 let last_defensive_formation = null;
275 // Formations we've set, but haven't really had the chance to use yet
276 // (e.g., we get a “use zone defense” event while we're still on offense).
277 let pending_offensive_formation = null;
278 let pending_defensive_formation = null;
280 // Formations that we have played at least once this point, after all
281 // heuristics and similar.
282 let formations_used_this_point = new Set();
284 for (const [q,p] of Object.entries(players)) {
285 p.on_field_since = null;
286 p.last_point_seen = null;
288 for (const e of match['events']) {
290 let type = e['type'];
291 let p = players[e['player']];
294 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
295 if (type === 'in' && p.on_field_since === null) {
296 p.on_field_since = t;
297 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
298 // A player needed for the filters went onto the field,
299 // so pretend people walked on right now (to start their
301 for (const [q,p2] of Object.entries(players)) {
302 if (p2.on_field_since !== null) {
303 p2.on_field_since = t;
307 } else if (type === 'out') {
308 take_off_field(p, t, live_since, offense, keep);
309 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
310 // A player needed for the filters went off the field,
311 // so we need to attribute time for all the others.
312 // Pretend they walked off and then immediately on again.
314 // TODO: We also need to take care of this to get the globals right.
315 for (const [q,p2] of Object.entries(players)) {
316 if (p2.on_field_since !== null) {
317 take_off_field(p2, t, live_since, offense, keep);
318 p2.on_field_since = t;
324 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
326 if (match['gender_rule_a']) {
327 if (type === 'restart' && !between_points) {
328 let predominant_gender = find_predominant_gender(players);
329 let num_players_on_field = find_num_players_on_field(players);
330 if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
331 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
333 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
334 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed number of players on field from ' + current_num_players_on_field + ' to ' + num_players_on_field);
336 current_predominant_gender = predominant_gender;
337 current_num_players_on_field = num_players_on_field;
338 } else if (type === 'pull' || type === 'their_pull') {
339 let predominant_gender = find_predominant_gender(players);
340 let num_players_on_field = find_num_players_on_field(players);
341 let changed = (predominant_gender !== current_predominant_gender);
342 if (point_num !== 0) {
343 let should_change = (point_num % 4 == 1 || point_num % 4 == 3); // ABBA changes on 1 and 3.
344 if (changed && !should_change) {
345 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
346 } else if (!changed && should_change) {
347 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
349 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
350 console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
353 current_predominant_gender = predominant_gender;
354 current_num_players_on_field = num_players_on_field;
357 if (match['gender_pull_rule']) {
358 if (type === 'pull') {
359 if (current_predominant_gender !== null &&
360 p.gender !== current_predominant_gender) {
361 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
366 // Liveness management
367 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
369 between_points = false;
370 } else if (type === 'catch' && last_pull_was_ours === null) {
371 // Someone forgot to add the pull, so we'll need to wing it.
372 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
374 last_pull_was_ours = !offense;
375 between_points = false;
376 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
377 for (const [q,p] of Object.entries(players)) {
378 if (p.on_field_since === null) {
381 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
383 // In case the player did nothing this point,
384 // not even subbing in.
385 p.last_point_seen = point_num;
389 if (keep) attribute_player_time(p, t, live_since, offense);
391 if (type !== 'stoppage') {
393 if (last_pull_was_ours === true) { // D point.
394 ++p.defensive_points_completed;
395 if (type === 'goal') {
396 ++p.defensive_points_won;
398 } else if (last_pull_was_ours === false) { // O point.
399 ++p.offensive_points_completed;
400 if (type === 'goal') {
401 ++p.offensive_points_won;
409 if (type !== 'stoppage') {
411 ++globals.points_played;
412 if (last_pull_was_ours === true) { // D point.
413 ++globals.defensive_points_completed;
414 if (type === 'goal') {
415 ++globals.defensive_points_won;
417 } else if (last_pull_was_ours === false) { // O point.
418 ++globals.offensive_points_completed;
419 if (type === 'goal') {
420 ++globals.offensive_points_won;
424 if (live_since !== null) {
425 globals.playing_time_ms += t - live_since;
426 if (offense === true) {
427 globals.offensive_playing_time_ms += t - live_since;
428 } else if (offense === false) {
429 globals.defensive_playing_time_ms += t - live_since;
438 if (type === 'goal') {
440 } else if (type === 'their_goal') {
444 // Point count management
445 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
447 p.last_point_seen = point_num;
451 if (type === 'goal' || type === 'their_goal') {
455 if (type !== 'out' && game_started === null) {
460 if (type === 'pull') {
461 puller = e['player'];
464 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
465 // No effect on pull.
466 } else if (type === 'pull_landed' && puller !== null) {
467 if (keep) players[puller].pull_times.push(t - pull_started);
468 } else if (type === 'pull_oob' && puller !== null) {
469 if (keep) ++players[puller].oob_pulls;
471 // Not pulling (if there was one, we never recorded its outcome, but still count it).
472 puller = pull_started = null;
475 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
477 if (type === 'goal' && !we_lost_disc) {
478 if (last_pull_was_ours === false) { // O point.
479 ++globals.clean_holds;
480 } else if (last_pull_was_ours === true) {
481 ++globals.clean_breaks;
483 } else if (type === 'their_goal' && !they_lost_disc) {
484 if (last_pull_was_ours === true) { // O point for them.
485 ++globals.their_clean_holds;
486 } else if (last_pull_was_ours === false) {
487 ++globals.their_clean_breaks;
492 // Offense/defense management
493 let last_offense = offense;
494 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
497 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
498 ++globals.turnovers_lost;
500 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
502 they_lost_disc = true;
503 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
504 ++globals.turnovers_won;
507 if (type === 'goal' || type === 'their_goal') {
508 between_points = true;
509 we_lost_disc = false;
510 they_lost_disc = false;
512 if (last_offense !== offense && live_since !== null) {
513 // Switched offense/defense status, so attribute this drive as needed,
514 // and update live_since to take that into account.
516 for (const [q,p] of Object.entries(players)) {
517 if (p.on_field_since === null) {
520 attribute_player_time(p, t, live_since, last_offense);
522 globals.playing_time_ms += t - live_since;
523 if (offense === true) {
524 globals.offensive_playing_time_ms += t - live_since;
525 } else if (offense === false) {
526 globals.defensive_playing_time_ms += t - live_since;
532 if (type === 'pull') {
533 last_pull_was_ours = true;
534 } else if (type === 'their_pull') {
535 last_pull_was_ours = false;
536 } else if (type === 'set_offense' && last_pull_was_ours === null) {
537 // set_offense could either be “changed to offense for some reason
538 // we could not express”, or “we started in the middle of a point,
539 // and we are offense”. We assume that if we already saw the pull,
540 // it's the former, and if not, it's the latter; thus, the === null
541 // test above. (It could also be “we set offense before the pull,
542 // so that we get the right button enabled”, in which case it will
543 // be overwritten by the next pull/their_pull event anyway.)
544 last_pull_was_ours = false;
545 } else if (type === 'set_defense' && last_pull_was_ours === null) {
547 last_pull_was_ours = true;
548 } else if (type === 'goal' || type === 'their_goal') {
549 last_pull_was_ours = null;
552 // Formation management
553 if (type === 'formation_offense' || type === 'formation_defense') {
554 let id = e.formation === null ? 0 : e.formation;
555 let for_offense = (type === 'formation_offense');
556 if (offense === for_offense) {
557 formations_used_this_point.add(id);
558 } else if (for_offense) {
559 pending_offensive_formation = id;
561 pending_defensive_formation = id;
564 last_offensive_formation = id;
566 last_defensive_formation = id;
568 } else if (last_offense !== offense) {
569 if (offense === true && pending_offensive_formation !== null) {
570 formations_used_this_point.add(pending_offensive_formation);
571 pending_offensive_formation = null;
572 } else if (offense === false && pending_defensive_formation !== null) {
573 formations_used_this_point.add(pending_defensive_formation);
574 pending_defensive_formation = null;
575 } else if (offense === true && last_defensive_formation !== null) {
576 if (should_reuse_last_formation(match['events'], t)) {
577 formations_used_this_point.add(last_defensive_formation);
579 } else if (offense === false && last_offensive_formation !== null) {
580 if (should_reuse_last_formation(match['events'], t)) {
581 formations_used_this_point.add(last_offensive_formation);
586 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
587 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
589 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
590 // The handler subbed out and was replaced with another handler,
591 // so this wasn't a pass.
596 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
597 // Self-pass to goal after an interception; this is not a real pass,
598 // just how we represent a Callahan right now -- so don't
599 // count the throw, any assists or similar.
601 // It's an open question how we should handle a self-pass that is
602 // _not_ after an interception, or a self-pass that's not a goal.
603 // (It must mean we tipped off someone.) We'll count it as a regular one
604 // for the time being, although it will make hockey assists weird.
609 handler = prev_handler = null;
610 } else if (type === 'catch' || type === 'goal') {
611 if (handler !== null) {
613 ++players[handler].num_throws;
618 if (keep) ++p.touches;
619 if (type === 'goal') {
621 if (prev_handler !== null) {
622 ++players[prev_handler].hockey_assists;
624 if (handler !== null) {
625 ++players[handler].assists;
629 handler = prev_handler = null;
631 // Update hold history.
632 prev_handler = handler;
633 handler = e['player'];
634 handler_got_by_interception = false;
636 } else if (type === 'throwaway') {
641 handler = prev_handler = null;
642 } else if (type === 'drop') {
644 handler = prev_handler = null;
645 } else if (type === 'stallout') {
646 if (keep) ++p.stallouts;
647 handler = prev_handler = null;
648 } else if (type === 'was_d') {
649 if (keep) ++p.was_ds;
650 handler = prev_handler = null;
651 } else if (type === 'defense') {
652 if (keep) ++p.defenses;
653 } else if (type === 'interception') {
660 handler = e['player'];
661 handler_got_by_interception = true;
662 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
664 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
665 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
666 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
667 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
668 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
669 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
670 type !== 'formation_offense' && type !== 'formation_defense') {
671 console.log(format_time(t) + ": Unknown event “" + e + "”");
674 if (type === 'goal' || type === 'their_goal') {
675 formations_used_this_point.clear();
679 // Add field time for all players still left at match end.
680 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
682 for (const [q,p] of Object.entries(players)) {
683 if (p.on_field_since !== null && last_goal !== null) {
684 p.field_time_ms += last_goal - p.on_field_since;
687 if (game_started !== null && last_goal !== null) {
688 globals.field_time_ms += last_goal - game_started;
690 if (live_since !== null && last_goal !== null) {
691 globals.playing_time_ms += last_goal - live_since;
692 if (offense === true) {
693 globals.offensive_playing_time_ms += last_goal - live_since;
694 } else if (offense === false) {
695 globals.defensive_playing_time_ms += last_goal - live_since;
703 function process_matches(json, filtersets) {
704 let chosen_category = get_chosen_category();
705 write_main_menu(chosen_category);
707 let filterset_values = Object.values(filtersets);
708 if (filterset_values.length === 0) {
709 filterset_values = [[]];
713 for (const filter of filterset_values) {
714 let players = calc_stats(json, filter);
716 if (chosen_category === 'general') {
717 rows = make_table_general(players);
718 } else if (chosen_category === 'offense') {
719 rows = make_table_offense(players);
720 } else if (chosen_category === 'defense') {
721 rows = make_table_defense(players);
722 } else if (chosen_category === 'playing_time') {
723 rows = make_table_playing_time(players);
724 } else if (chosen_category === 'per_point') {
725 rows = make_table_per_point(players);
726 } else if (chosen_category === 'team_wide') {
727 rows = make_table_team_wide(players);
732 let merged_rows = [];
733 if (filterset_values.length > 1) {
734 for (let i = 0; i < rowsets.length; ++i) {
735 let marker = make_filter_marker(filterset_values[i]);
737 // Make filter header.
738 let tr = rowsets[i][0];
739 let th = document.createElement('th');
741 tr.insertBefore(th, tr.firstChild);
743 for (let j = 1; j < rowsets[i].length; ++j) {
744 let tr = rowsets[i][j];
746 // Remove the name for cleanness.
748 tr.firstChild.nextSibling.textContent = '';
752 tr.style.borderTop = '0px';
754 if (i != rowsets.length - 1) {
755 tr.style.borderBottom = '0px';
758 // Make filter marker.
759 let td = document.createElement('td');
760 td.textContent = marker;
761 td.classList.add('filtermarker');
762 tr.insertBefore(td, tr.firstChild);
766 for (let i = 0; i < rowsets[0].length; ++i) {
767 for (let j = 0; j < rowsets.length; ++j) {
768 merged_rows.push(rowsets[j][i]);
769 if (i === 0) break; // Don't merge the headings.
773 merged_rows = rowsets[0];
775 document.getElementById('stats').replaceChildren(...merged_rows);
778 function get_chosen_category() {
779 if (window.location.hash === '#offense') {
781 } else if (window.location.hash === '#defense') {
783 } else if (window.location.hash === '#playing_time') {
784 return 'playing_time';
785 } else if (window.location.hash === '#per_point') {
787 } else if (window.location.hash === '#team_wide') {
794 function write_main_menu(chosen_category) {
797 ['general', 'General'],
798 ['offense', 'Offense'],
799 ['defense', 'Defense'],
800 ['playing_time', 'Playing time'],
801 ['per_point', 'Per point'],
802 ['team_wide', 'Team-wide'],
804 for (const [id, title] of categories) {
805 if (chosen_category === id) {
806 let span = document.createElement('span');
807 span.innerText = title;
810 let a = document.createElement('a');
811 a.appendChild(document.createTextNode(title));
812 a.setAttribute('href', '#' + id);
817 document.getElementById('mainmenu').replaceChildren(...elems);
820 // https://en.wikipedia.org/wiki/1.96#History
823 const ci_width = 100;
824 const ci_height = 20;
826 function make_binomial_ci(val, num, z) {
829 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
830 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
831 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
833 // Fix the signs so that we don't get -0.00.
834 low = Math.max(low, 0.0);
844 // These can only happen once per point, but you get -1 and +1
845 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
846 // and then we can rewrite back.
847 function make_efficiency_ci(points_won, points_completed, z)
849 let ci = make_binomial_ci(points_won, points_completed, z);
850 ci.val = 2.0 * ci.val - 1.0;
851 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
852 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
855 ci.desired = 0.0; // Desired = positive efficiency.
859 // Ds, throwaways and drops can happen multiple times per point,
860 // so they are Poisson distributed.
862 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
863 // since our rates are definitely below 2 per point).
864 function make_poisson_ci(val, num, z, inverted)
866 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
867 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
869 // Fix the signs so that we don't get -0.00.
870 low = Math.max(low, 0.0);
872 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
881 'inverted': inverted,
885 function make_table_general(players) {
888 let header = document.createElement('tr');
889 add_th(header, 'Player');
890 add_th(header, '+/-');
891 add_th(header, 'Soft +/-');
892 add_th(header, 'O efficiency');
893 add_th(header, 'D efficiency');
894 add_th(header, 'Points played');
898 for (const [q,p] of get_sorted_players(players)) {
899 if (q === 'globals') continue;
900 let row = document.createElement('tr');
901 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
902 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
903 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
904 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
905 let name = add_3cell(row, p.name, 'name'); // TODO: number?
906 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
907 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
908 add_3cell_ci(row, o_efficiency);
909 add_3cell_ci(row, d_efficiency);
910 add_3cell(row, p.points_played);
911 row.dataset.player = q;
916 let globals = players['globals'];
917 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
918 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
919 let row = document.createElement('tr');
923 add_3cell_ci(row, o_efficiency);
924 add_3cell_ci(row, d_efficiency);
925 add_3cell(row, globals.points_played);
931 function make_table_team_wide(players) {
932 let globals = players['globals'];
936 let header = document.createElement('tr');
938 add_th(header, 'Our team');
939 add_th(header, 'Their team');
945 let row = document.createElement('tr');
946 let name = add_3cell(row, 'Turnovers generated', 'name');
947 add_3cell(row, globals.turnovers_won);
948 add_3cell(row, globals.turnovers_lost);
954 let row = document.createElement('tr');
955 let name = add_3cell(row, 'Clean holds', 'name');
956 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
957 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
958 our_clean_holds.desired = 0.3; // Arbitrary.
959 their_clean_holds.desired = 0.3;
960 add_3cell_ci(row, our_clean_holds);
961 add_3cell_ci(row, their_clean_holds);
967 let row = document.createElement('tr');
968 let name = add_3cell(row, 'Clean breaks', 'name');
969 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
970 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
971 our_clean_breaks.desired = 0.3; // Arbitrary.
972 their_clean_breaks.desired = 0.3;
973 add_3cell_ci(row, our_clean_breaks);
974 add_3cell_ci(row, their_clean_breaks);
981 function make_table_offense(players) {
984 let header = document.createElement('tr');
985 add_th(header, 'Player');
986 add_th(header, 'Goals');
987 add_th(header, 'Assists');
988 add_th(header, 'Hockey assists');
989 add_th(header, 'Throws');
990 add_th(header, 'Throwaways');
991 add_th(header, '%OK');
992 add_th(header, 'Catches');
993 add_th(header, 'Drops');
994 add_th(header, 'D-ed');
995 add_th(header, '%OK');
996 add_th(header, 'Stalls');
997 add_th(header, 'Soft +/-', 6);
1008 for (const [q,p] of get_sorted_players(players)) {
1009 if (q === 'globals') continue;
1010 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1011 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1013 throw_ok.format = 'percentage';
1014 catch_ok.format = 'percentage';
1016 // Desire at least 90% percentage. Fairly arbitrary.
1017 throw_ok.desired = 0.9;
1018 catch_ok.desired = 0.9;
1020 let row = document.createElement('tr');
1021 add_3cell(row, p.name, 'name'); // TODO: number?
1022 add_3cell(row, p.goals);
1023 add_3cell(row, p.assists);
1024 add_3cell(row, p.hockey_assists);
1025 add_3cell(row, p.num_throws);
1026 add_3cell(row, p.throwaways);
1027 add_3cell_ci(row, throw_ok);
1028 add_3cell(row, p.catches);
1029 add_3cell(row, p.drops);
1030 add_3cell(row, p.was_ds);
1031 add_3cell_ci(row, catch_ok);
1032 add_3cell(row, p.stallouts);
1033 add_3cell(row, '+' + p.offensive_soft_plus);
1034 add_3cell(row, '-' + p.offensive_soft_minus);
1035 row.dataset.player = q;
1039 num_throws += p.num_throws;
1040 throwaways += p.throwaways;
1041 catches += p.catches;
1044 stallouts += p.stallouts;
1048 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1049 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1050 throw_ok.format = 'percentage';
1051 catch_ok.format = 'percentage';
1052 throw_ok.desired = 0.9;
1053 catch_ok.desired = 0.9;
1055 let row = document.createElement('tr');
1057 add_3cell(row, goals);
1060 add_3cell(row, num_throws);
1061 add_3cell(row, throwaways);
1062 add_3cell_ci(row, throw_ok);
1063 add_3cell(row, catches);
1064 add_3cell(row, drops);
1065 add_3cell(row, was_ds);
1066 add_3cell_ci(row, catch_ok);
1067 add_3cell(row, stallouts);
1075 function make_table_defense(players) {
1078 let header = document.createElement('tr');
1079 add_th(header, 'Player');
1080 add_th(header, 'Ds');
1081 add_th(header, 'Pulls');
1082 add_th(header, 'OOB pulls');
1083 add_th(header, 'OOB%');
1084 add_th(header, 'Avg. hang time (IB)');
1085 add_th(header, 'Callahans');
1086 add_th(header, 'Soft +/-', 6);
1093 let sum_sum_time = 0;
1096 for (const [q,p] of get_sorted_players(players)) {
1097 if (q === 'globals') continue;
1099 for (const t of p.pull_times) {
1102 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1103 let oob_pct = 100 * p.oob_pulls / p.pulls;
1105 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1106 ci_oob.format = 'percentage';
1107 ci_oob.desired = 0.2; // Arbitrary.
1108 ci_oob.inverted = true;
1110 let row = document.createElement('tr');
1111 add_3cell(row, p.name, 'name'); // TODO: number?
1112 add_3cell(row, p.defenses);
1113 add_3cell(row, p.pulls);
1114 add_3cell(row, p.oob_pulls);
1115 add_3cell_ci(row, ci_oob);
1116 if (p.pulls > p.oob_pulls) {
1117 add_3cell(row, avg_time.toFixed(1) + ' sec');
1119 add_3cell(row, 'N/A');
1121 add_3cell(row, p.callahans);
1122 add_3cell(row, '+' + p.defensive_soft_plus);
1123 add_3cell(row, '-' + p.defensive_soft_minus);
1124 row.dataset.player = q;
1127 defenses += p.defenses;
1129 oob_pulls += p.oob_pulls;
1130 sum_sum_time += sum_time;
1131 callahans += p.callahans;
1135 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1136 ci_oob.format = 'percentage';
1137 ci_oob.desired = 0.2; // Arbitrary.
1138 ci_oob.inverted = true;
1140 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1141 let oob_pct = 100 * oob_pulls / pulls;
1143 let row = document.createElement('tr');
1145 add_3cell(row, defenses);
1146 add_3cell(row, pulls);
1147 add_3cell(row, oob_pulls);
1148 add_3cell_ci(row, ci_oob);
1149 if (pulls > oob_pulls) {
1150 add_3cell(row, avg_time.toFixed(1) + ' sec');
1152 add_3cell(row, 'N/A');
1154 add_3cell(row, callahans);
1162 function make_table_playing_time(players) {
1165 let header = document.createElement('tr');
1166 add_th(header, 'Player');
1167 add_th(header, 'Points played');
1168 add_th(header, 'Time played');
1169 add_th(header, 'O time');
1170 add_th(header, 'D time');
1171 add_th(header, 'Time on field');
1172 add_th(header, 'O points');
1173 add_th(header, 'D points');
1177 for (const [q,p] of get_sorted_players(players)) {
1178 if (q === 'globals') continue;
1179 let row = document.createElement('tr');
1180 add_3cell(row, p.name, 'name'); // TODO: number?
1181 add_3cell(row, p.points_played);
1182 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1183 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1184 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1185 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1186 add_3cell(row, p.offensive_points_completed);
1187 add_3cell(row, p.defensive_points_completed);
1188 row.dataset.player = q;
1193 let globals = players['globals'];
1194 let row = document.createElement('tr');
1196 add_3cell(row, globals.points_played);
1197 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1198 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1199 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1200 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1201 add_3cell(row, globals.offensive_points_completed);
1202 add_3cell(row, globals.defensive_points_completed);
1208 function make_table_per_point(players) {
1211 let header = document.createElement('tr');
1212 add_th(header, 'Player');
1213 add_th(header, 'Goals');
1214 add_th(header, 'Assists');
1215 add_th(header, 'Hockey assists');
1216 add_th(header, 'Ds');
1217 add_th(header, 'Throwaways');
1218 add_th(header, 'Recv. errors');
1219 add_th(header, 'Touches');
1225 let hockey_assists = 0;
1228 let receiver_errors = 0;
1230 for (const [q,p] of get_sorted_players(players)) {
1231 if (q === 'globals') continue;
1233 // Can only happen once per point, so these are binomials.
1234 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1235 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1236 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1237 // Arbitrarily desire at least 10% (not everybody can score or assist).
1238 ci_goals.desired = 0.1;
1239 ci_assists.desired = 0.1;
1240 ci_hockey_assists.desired = 0.1;
1242 let row = document.createElement('tr');
1243 add_3cell(row, p.name, 'name'); // TODO: number?
1244 add_3cell_ci(row, ci_goals);
1245 add_3cell_ci(row, ci_assists);
1246 add_3cell_ci(row, ci_hockey_assists);
1247 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1248 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1249 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1250 if (p.points_played > 0) {
1251 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1253 add_3cell(row, 'N/A');
1255 row.dataset.player = q;
1259 assists += p.assists;
1260 hockey_assists += p.hockey_assists;
1261 defenses += p.defenses;
1262 throwaways += p.throwaways;
1263 receiver_errors += p.drops + p.was_ds;
1264 touches += p.touches;
1268 let globals = players['globals'];
1269 let row = document.createElement('tr');
1271 if (globals.points_played > 0) {
1272 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1273 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1274 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1275 ci_goals.desired = 0.5;
1276 ci_assists.desired = 0.5;
1277 ci_hockey_assists.desired = 0.5;
1279 add_3cell_ci(row, ci_goals);
1280 add_3cell_ci(row, ci_assists);
1281 add_3cell_ci(row, ci_hockey_assists);
1283 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1284 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1285 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1287 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1289 add_3cell_with_filler_ci(row, 'N/A');
1290 add_3cell_with_filler_ci(row, 'N/A');
1291 add_3cell_with_filler_ci(row, 'N/A');
1292 add_3cell_with_filler_ci(row, 'N/A');
1293 add_3cell_with_filler_ci(row, 'N/A');
1294 add_3cell_with_filler_ci(row, 'N/A');
1295 add_3cell(row, 'N/A');
1302 function open_filter_menu(click_to_add_div) {
1303 document.getElementById('filter-submenu').style.display = 'none';
1304 let filter_div = click_to_add_div.parentElement;
1305 let filter_id = filter_div.dataset.filterId;
1307 let menu = document.getElementById('filter-add-menu');
1308 menu.parentElement.removeChild(menu);
1309 filter_div.appendChild(menu);
1310 menu.style.display = 'block';
1311 menu.replaceChildren();
1313 // Place the menu directly under the “click to add” label;
1314 // we don't anchor it since that label will move around
1315 // and the menu shouldn't.
1316 let rect = click_to_add_div.getBoundingClientRect();
1317 menu.style.left = rect.left + 'px';
1318 menu.style.top = (rect.bottom + 10) + 'px';
1320 let filterset = global_filters[filter_id];
1321 if (filterset === undefined) {
1322 global_filters[filter_id] = filterset = [];
1325 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1326 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1327 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1328 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1329 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1330 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1331 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1334 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1335 let item = document.createElement('div');
1336 item.classList.add('option');
1337 item.appendChild(document.createTextNode(title));
1339 let arrow = document.createElement('div');
1340 arrow.classList.add('arrow');
1341 arrow.textContent = '▸';
1342 item.appendChild(arrow);
1344 menu.appendChild(item);
1346 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1349 function find_all_ratios(json)
1353 for (const player of json['players']) {
1354 players[player['player_id']] = {
1355 'gender': player['gender'],
1356 'last_point_seen': null,
1359 for (const match of json['matches']) {
1360 for (const [q,p] of Object.entries(players)) {
1361 p.on_field_since = null;
1363 for (const e of match['events']) {
1364 let p = players[e['player']];
1365 let type = e['type'];
1366 if (type === 'in') {
1367 p.on_field_since = 1;
1368 } else if (type === 'out') {
1369 p.on_field_since = null;
1370 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1371 let code = find_gender_ratio_code(players);
1372 if (ratios[code] === undefined) {
1373 ratios[code] = code;
1374 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1375 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1376 match['description'] + ', ' + format_time(e['t']));
1385 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1386 let submenu = document.getElementById('filter-submenu');
1388 // Move to the same place as the top-level menu.
1389 submenu.parentElement.removeChild(submenu);
1390 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1393 const filter = find_filter(filterset, filter_type);
1396 if (filter_type === 'match') {
1397 for (const match of global_json['matches']) {
1399 'title': match['description'],
1400 'id': match['match_id']
1403 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1404 for (const player of global_json['players']) {
1406 'title': player['name'],
1407 'id': player['player_id']
1410 } else if (filter_type === 'formation_offense') {
1412 'title': '(None/unknown)',
1415 for (const formation of global_json['formations']) {
1416 if (formation['offense']) {
1418 'title': formation['name'],
1419 'id': formation['formation_id']
1423 } else if (filter_type === 'formation_defense') {
1425 'title': '(None/unknown)',
1428 for (const formation of global_json['formations']) {
1429 if (!formation['offense']) {
1431 'title': formation['name'],
1432 'id': formation['formation_id']
1436 } else if (filter_type === 'starting_on') {
1439 'id': false, // last_pull_was_ours
1443 'id': true, // last_pull_was_ours
1445 } else if (filter_type === 'gender_ratio') {
1446 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1454 for (const choice of choices) {
1455 let label = document.createElement('label');
1457 let subitem = document.createElement('div');
1458 subitem.classList.add('option');
1460 let check = document.createElement('input');
1461 check.setAttribute('type', 'checkbox');
1462 check.setAttribute('id', 'choice' + choice.id);
1463 if (filter !== null && filter.elements.has(choice.id)) {
1464 check.setAttribute('checked', 'checked');
1466 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1468 subitem.appendChild(check);
1469 subitem.appendChild(document.createTextNode(choice.title));
1471 label.appendChild(subitem);
1472 subitems.push(label);
1474 submenu.replaceChildren(...subitems);
1475 submenu.style.display = 'block';
1477 if (pill !== null) {
1478 let rect = pill.getBoundingClientRect();
1479 submenu.style.top = (rect.bottom + 10) + 'px';
1480 submenu.style.left = rect.left + 'px';
1482 // Position just outside the selected menu.
1483 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1484 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1485 submenu.style.left = (rect.right - 1) + 'px';
1489 // Find the right filter, if it exists.
1490 function find_filter(filterset, filter_type) {
1491 for (let f of filterset) {
1492 if (f.type === filter_type) {
1499 // Equivalent to Array.prototype.filter, but in-place.
1500 function inplace_filter(arr, cond) {
1502 for (let i = 0; i < arr.length; ++i) {
1510 function add_new_filterset() {
1511 let template = document.querySelector('.filter'); // First one is fine.
1512 let div = template.cloneNode(true);
1513 let add_menu = div.querySelector('#filter-add-menu');
1514 if (add_menu !== null) {
1515 div.removeChild(add_menu);
1517 let submenu = div.querySelector('#filter-submenu');
1518 if (submenu !== null) {
1519 div.removeChild(submenu);
1521 div.querySelector('.filters').replaceChildren();
1522 div.dataset.filterId = next_filterset_id++;
1523 template.parentElement.appendChild(div);
1526 function try_gc_filter_menus(cheap) {
1529 for (const filter_div of document.querySelectorAll('.filter')) {
1530 let id = filter_div.dataset.filterId;
1531 divs.push(filter_div);
1532 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1534 let last_div = divs[empties.length - 1];
1536 // See if we have two empty filter lists at the bottom of the list;
1537 // if so, we can remove one without it looking funny in the UI.
1538 // If not, we'll have to wait until closing the menu.
1539 // (The menu is positioned at the second-last one, so we can
1540 // remove the last one without issue.)
1541 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1542 delete global_filters[last_div.dataset.filterId];
1543 last_div.parentElement.removeChild(last_div);
1546 // This is a different situation from try_cheap_gc(), where we should
1547 // remove the one _not_ last. We might need to move the menu to the last one,
1548 // though, so it doesn't get lost.
1549 for (let i = 0; i < empties.length - 1; ++i) {
1554 delete global_filters[div.dataset.filterId];
1555 let add_menu = div.querySelector('#filter-add-menu');
1556 if (add_menu !== null) {
1557 div.removeChild(add_menu);
1558 last_div.appendChild(add_menu);
1560 let submenu = div.querySelector('#filter-submenu');
1561 if (submenu !== null) {
1562 div.removeChild(submenu);
1563 last_div.appendChild(submenu);
1565 div.parentElement.removeChild(div);
1570 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1571 let filter = find_filter(filterset, filter_type);
1572 let pills_div = filter_div.querySelector('.filters');
1573 if (e.target.checked) {
1574 // See if we must create a new empty filterset (since this went from
1575 // empty to non-empty).
1576 if (filterset.length === 0) {
1577 add_new_filterset();
1580 // See if we must add a new filter to the list.
1581 if (filter === null) {
1583 'type': filter_type,
1584 'elements': new Set([ id ]),
1586 filter.pill = make_filter_pill(filter_div, filterset, filter);
1587 filterset.push(filter);
1588 pills_div.appendChild(filter.pill);
1590 filter.elements.add(id);
1591 let new_pill = make_filter_pill(filter_div, filterset, filter);
1592 pills_div.replaceChild(new_pill, filter.pill);
1593 filter.pill = new_pill;
1596 filter.elements.delete(id);
1597 if (filter.elements.size === 0) {
1598 pills_div.removeChild(filter.pill);
1599 inplace_filter(filterset, f => f !== filter);
1601 if (filterset.length == 0) {
1602 try_gc_filter_menus(true);
1605 let new_pill = make_filter_pill(filter_div, filterset, filter);
1606 pills_div.replaceChild(new_pill, filter.pill);
1607 filter.pill = new_pill;
1611 process_matches(global_json, global_filters);
1614 function make_filter_pill(filter_div, filterset, filter) {
1615 let pill = document.createElement('div');
1616 pill.classList.add('filter-pill');
1618 if (filter.type === 'match') {
1622 for (const match_id of filter.elements) {
1623 all_names.push(find_match(match_id)['description']);
1625 let common_prefix = find_common_prefix_of_all(all_names);
1626 if (common_prefix !== null) {
1627 text += common_prefix + '(';
1631 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1632 for (const match_id of sorted_match_id) {
1636 let desc = find_match(match_id)['description'];
1637 if (common_prefix === null) {
1640 text += desc.substr(common_prefix.length);
1645 if (common_prefix !== null) {
1648 } else if (filter.type === 'player_any') {
1649 text = 'Player (any): ';
1650 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1652 for (const player_id of sorted_players) {
1656 text += find_player(player_id)['name'];
1659 } else if (filter.type === 'player_all') {
1661 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1663 for (const player_id of sorted_players) {
1667 text += find_player(player_id)['name'];
1670 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1671 const offense = (filter.type === 'formation_offense');
1679 for (const formation_id of filter.elements) {
1680 all_names.push(find_formation(formation_id)['name']);
1682 let common_prefix = find_common_prefix_of_all(all_names);
1683 if (common_prefix !== null) {
1684 text += common_prefix + '(';
1688 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1689 for (const formation_id of sorted_formation_id) {
1693 let desc = find_formation(formation_id)['name'];
1694 if (common_prefix === null) {
1697 text += desc.substr(common_prefix.length);
1702 if (common_prefix !== null) {
1705 } else if (filter.type === 'starting_on') {
1706 text = 'Starting on: ';
1708 if (filter.elements.has(false) && filter.elements.has(true)) {
1710 } else if (filter.elements.has(false)) {
1715 } else if (filter.type === 'gender_ratio') {
1719 for (const name of Array.from(filter.elements).sort()) {
1723 text += name; // FIXME
1728 let text_node = document.createElement('span');
1729 text_node.innerText = text;
1730 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1731 pill.appendChild(text_node);
1733 pill.appendChild(document.createTextNode(' '));
1735 let delete_node = document.createElement('span');
1736 delete_node.innerText = '✖';
1737 delete_node.addEventListener('click', (e) => {
1738 // Delete this filter entirely.
1739 pill.parentElement.removeChild(pill);
1740 inplace_filter(filterset, f => f !== filter);
1741 if (filterset.length == 0) {
1742 try_gc_filter_menus(false);
1744 process_matches(global_json, global_filters);
1746 let add_menu = document.getElementById('filter-add-menu');
1747 let add_submenu = document.getElementById('filter-submenu');
1748 add_menu.style.display = 'none';
1749 add_submenu.style.display = 'none';
1751 pill.appendChild(delete_node);
1752 pill.style.cursor = 'pointer';
1757 function make_filter_marker(filterset) {
1759 for (const filter of filterset) {
1763 if (filter.type === 'match') {
1765 for (const match of global_json['matches']) {
1766 all_names.push(match['description']);
1768 let common_prefix = find_common_prefix_of_all(all_names);
1770 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1771 for (const match_id of sorted_match_id) {
1772 let desc = find_match(match_id)['description'];
1773 if (common_prefix === null) {
1774 text += desc.substr(0, 3);
1776 text += desc.substr(common_prefix.length, 3);
1779 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1780 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1781 for (const player_id of sorted_players) {
1782 text += find_player(player_id)['name'].substr(0, 3);
1784 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1785 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1786 for (const formation_id of sorted_formation_id) {
1787 text += find_formation(formation_id)['name'].substr(0, 3);
1789 } else if (filter.type === 'starting_on') {
1790 if (filter.elements.has(false) && filter.elements.has(true)) {
1792 } else if (filter.elements.has(false)) {
1797 } else if (filter.type === 'gender_ratio') {
1799 for (const name of Array.from(filter.elements).sort()) {
1803 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
1811 function find_common_prefix(a, b) {
1813 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1814 if (a[i] === b[i]) {
1823 function find_common_prefix_of_all(values) {
1824 if (values.length < 2) {
1827 let common_prefix = null;
1828 for (const desc of values) {
1829 if (common_prefix === null) {
1830 common_prefix = desc;
1832 common_prefix = find_common_prefix(common_prefix, desc);
1835 if (common_prefix.length >= 3) {
1836 return common_prefix;
1842 function find_match(match_id) {
1843 for (const match of global_json['matches']) {
1844 if (match['match_id'] === match_id) {
1851 function find_formation(formation_id) {
1852 for (const formation of global_json['formations']) {
1853 if (formation['formation_id'] === formation_id) {
1860 function find_player(player_id) {
1861 for (const player of global_json['players']) {
1862 if (player['player_id'] === player_id) {
1869 function player_pos(player_id) {
1871 for (const player of global_json['players']) {
1872 if (player['player_id'] === player_id) {
1880 function keep_match(match_id, filters) {
1881 for (const filter of filters) {
1882 if (filter.type === 'match') {
1883 return filter.elements.has(match_id);
1889 // Returns a map of e.g. F => 4, M => 3.
1890 function find_gender_ratio(players) {
1892 for (const [q,p] of Object.entries(players)) {
1893 if (p.on_field_since === null) {
1896 let gender = p.gender;
1897 if (gender === '' || gender === undefined || gender === null) {
1900 if (map[gender] === undefined) {
1909 function find_gender_ratio_code(players) {
1910 let map = find_gender_ratio(players);
1911 let all_genders = Array.from(Object.keys(map)).sort(
1913 if (map[a] !== map[b]) {
1914 return map[b] - map[a]; // Reverse numeric.
1924 for (const g of all_genders) {
1935 // null if none (e.g., if playing 3–3).
1936 function find_predominant_gender(players) {
1938 let predominant_gender = null;
1939 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
1942 predominant_gender = gender;
1943 } else if (num == max) {
1944 predominant_gender = null; // At least two have the same.
1947 return predominant_gender;
1950 function find_num_players_on_field(players) {
1952 for (const [q,p] of Object.entries(players)) {
1953 if (p.on_field_since !== null) {
1960 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1961 if (filter.type === 'player_any') {
1962 for (const p of Array.from(filter.elements)) {
1963 if (players[p].on_field_since !== null) {
1968 } else if (filter.type === 'player_all') {
1969 for (const p of Array.from(filter.elements)) {
1970 if (players[p].on_field_since === null) {
1975 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1976 for (const f of Array.from(filter.elements)) {
1977 if (formations_used_this_point.has(f)) {
1982 } else if (filter.type === 'starting_on') {
1983 return filter.elements.has(last_pull_was_ours);
1984 } else if (filter.type === 'gender_ratio') {
1985 return filter.elements.has(find_gender_ratio_code(players));
1990 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
1991 for (const filter of filters) {
1992 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
1999 // Heuristic: If we go at least ten seconds without the possession changing
2000 // or the operator specifying some other formation, we probably play the
2001 // same formation as the last point.
2002 function should_reuse_last_formation(events, t) {
2003 for (const e of events) {
2007 if (e.t > t + 10000) {
2010 const type = e.type;
2011 if (type === 'their_goal' || type === 'goal' ||
2012 type === 'set_defense' || type === 'set_offense' ||
2013 type === 'throwaway' || type === 'their_throwaway' ||
2014 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2015 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2016 type === 'formation_offense' || type === 'formation_defense') {
2023 function possibly_close_menu(e) {
2024 if (e.target.closest('.filter-click-to-add') === null &&
2025 e.target.closest('#filter-add-menu') === null &&
2026 e.target.closest('#filter-submenu') === null &&
2027 e.target.closest('.filter-pill') === null) {
2028 let add_menu = document.getElementById('filter-add-menu');
2029 let add_submenu = document.getElementById('filter-submenu');
2030 add_menu.style.display = 'none';
2031 add_submenu.style.display = 'none';
2032 try_gc_filter_menus(false);
2036 let global_sort = {};
2038 function sort_by(th) {
2039 let tr = th.parentElement;
2041 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2042 let element = tr.children[column_idx];
2043 if (element === th) {
2044 ++child_idx; // Pad.
2047 if (element.hasAttribute('colspan')) {
2048 child_idx += parseInt(element.getAttribute('colspan'));
2055 let table = tr.parentElement;
2056 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2057 let row = table.children[row_idx];
2058 let player = parseInt(row.dataset.player);
2059 let value = row.children[child_idx].textContent;
2060 global_sort[player] = value;
2064 function get_sorted_players(players)
2066 let p = Object.entries(players);
2067 if (global_sort.length !== 0) {
2069 let ai = parseFloat(global_sort[a[0]]);
2070 let bi = parseFloat(global_sort[b[0]]);
2071 if (ai == ai && bi == bi) {
2072 return bi - ai; // Reverse numeric.
2073 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2075 } else if (global_sort[a[0]] > global_sort[b[0]]) {