%% ========================================================================= %% PLAYER LOAD EQUATION COMPARISON — FULL PROCESSING PIPELINE %% ========================================================================= % % Callaway, A.J., Ellis, S.A., & Williams, J. % "Not All Player Load Equations Are Equivalent: Formula Choice Alters % Load Magnitude and Interpretation in Elite Football" % % Open-source reproducibility code for the manuscript above; if you use it, % please cite the paper. The 2022 FIFA World Cup tracking and event data are % open access from PFF FC: % https://www.blog.fc.pff.com/blog/pff-fc-release-2022-world-cup-data % A compact per-player-match summary checkpoint is included in ../data so the % full analysis reproduces in minutes without downloading the raw data (MODE A % below). Add a LICENSE file of your choice before publishing. % % This script reproduces the complete analysis pipeline from raw PFF tracking % data files through to all statistical outputs used in the manuscript. % % WHAT THIS SCRIPT DOES (in order): % % Stage 1 — Extract player positions from event JSON files % Builds a player-position lookup table (game + team + jersey) % % Stage 2 — Parse tracking JSONL files % Extracts raw and Kalman-smoothed XY coordinates per frame % Saves one intermediate .mat file per game % % Stage 3 — Derive acceleration % Applies four signal-processing conditions (raw, Kalman, % Butterworth 2 Hz, Butterworth 4 Hz) and computes acceleration % using a central finite-difference scheme % % Stage 4 — Apply all 11 PlayerLoad equations % Accumulates per-player-match load under each condition % Saves summary table as both .mat and .csv % % Stage 5 — Statistical analysis % Descriptive statistics, Bland-Altman agreement and conversion % coefficients (both per-match absolute and per-90 bases), % rank-order / top-decile misclassification, and positional % per-90 spread with Kruskal-Wallis effect sizes. % Saves four Excel workbooks. Reproduces every result in the paper. % % Stage 6 — Winter residual analysis % Optimal Butterworth cutoff (elbow of the mean residual curve, % ~1.06 Hz) and a bootstrap 95% CI quantifying its uncertainty. % % Stage 7 — Figures (per-90 base, manuscript figures) % Figure 1 Winter residual (elbow + bootstrap CI), Figure 2 % Bland-Altman EQ3 vs EQ5 (single comparable-scale panel), Figure 3 % rank-order (two cross-family panels). One run reproduces all three. % % INPUT FILES REQUIRED: % - Tracking data: one .jsonl file per game (from PFF Sports) % - Event data: one .json file per game (from PFF Sports) % % OUTPUT FILES PRODUCED: % - player_positions.csv — player position lookup table % - intermediate/*.mat — one per game (can delete after Stage 4) % - PlayerLoad_Summary.mat/.csv — per-player-match load values, all equations % - PlayerLoad_Descriptive.xlsx — mean ± SD by position and condition (absolute + per-90) % - PlayerLoad_BlandAltman.xlsx — agreement + conversion for all equation pairs (both bases) % - PlayerLoad_RatioMatrix.xlsx — pairwise mean ratios (both bases) % - PlayerLoad_RankOrder.xlsx — rank-order/misclassification and positional per-90 spread % - PlayerLoad_WinterElbow.xlsx — Winter residual cutoff elbow and 95% CI % - figures/Figure1_WinterResidual, Figure2_BlandAltman, Figure3_RankOrder (tif + png) % % Supplementary numbers all reproduce from the sheets above: Table 2/S3 (Descriptive), % Table 3/S2a/S4 (BlandAltman, with RMSE and R2_LOO columns), S2b (ExactScalars_S2b), % S5 (RatioMatrix), S6 (SmoothingRatios_S6). Formatting into the paper layout is manual. % % REQUIREMENTS: % - MATLAB R2020b or later % - Signal Processing Toolbox (for butter, filtfilt) % - Statistics and Machine Learning Toolbox (for corr Spearman, kruskalwallis) % - exportgraphics (R2020a+) for saving figures % % USAGE: % 1. Set the five paths in SECTION 0 below % 2. Run the script (Ctrl+Enter runs section by section, or press Run for all) % 3. Each stage is independent — if a stage has already been run, set the % corresponding CONFIG.skip_* flag to true to resume from that point % % ESTIMATED RUN TIME (64-game World Cup dataset): % Stage 1: ~2 min % Stage 2: ~20-40 min (depends on hardware and file I/O speed) % Stage 3: ~30-60 min % Stage 4: ~5 min % Stage 5: ~10 min % % ========================================================================= clear; clc; close all; %% ========================================================================= %% SECTION 0: CONFIGURATION %% ========================================================================= % % Two modes: % MODE A - FAST reproduction from the included summary checkpoint (DEFAULT). % Regenerates every statistic and supplementary table from % data/PlayerLoad_Summary_CORRECTED.csv in ~2 min, no raw data. % Nothing to configure - just run this file. % MODE B - FULL reproduction from raw PFF tracking data: % 1. Download the 2022 FIFA World Cup data from PFF (open access): % https://www.blog.fc.pff.com/blog/pff-fc-release-2022-world-cup-data % 2. Decompress the tracking *.jsonl.bz2 files to plain *.jsonl. % 3. Set CONFIG.tracking_folder and CONFIG.event_folder below. % 4. Set CONFIG.summary_checkpoint_csv = '' to force a full run. % Repository root (this file lives in /code/); used for the default paths. thisFile = mfilename('fullpath'); if isempty(thisFile); thisFile = fullfile(pwd, 'code', 'PlayerLoad_Pipeline'); end repoRoot = fileparts(fileparts(thisFile)); % MODE A (default): included summary checkpoint. Set to '' for a full raw run (MODE B). CONFIG.summary_checkpoint_csv = fullfile(repoRoot, 'data', 'PlayerLoad_Summary_CORRECTED.csv'); % MODE B: raw-data folders (leave '' when using the checkpoint above). CONFIG.tracking_folder = ''; % folder of decompressed *.jsonl tracking files (one per game) CONFIG.event_folder = ''; % folder of *.json event files (one per game) % Output folder (subfolders created automatically). CONFIG.output_folder = fullfile(repoRoot, 'output'); % --- Resume flags (full-run only): set true to skip an already-completed stage --- CONFIG.skip_stage1 = false; CONFIG.skip_stage2 = false; CONFIG.skip_stage3 = false; CONFIG.skip_stage4 = false; CONFIG.skip_winter = false; % Checkpoint mode auto-skips the raw-processing (1-4), Winter (6) and figure (7) stages. if ~isempty(CONFIG.summary_checkpoint_csv) [CONFIG.skip_stage1, CONFIG.skip_stage2, CONFIG.skip_stage3, ... CONFIG.skip_stage4, CONFIG.skip_winter] = deal(true); end % --- Signal parameters (do not change unless you know why) ---------------- CONFIG.fps = 29.9697; % PFF tracking nominal frame rate (Hz) CONFIG.dt = 1 / CONFIG.fps; CONFIG.butter_order = 2; % filter order; zero-phase via filtfilt = effective 4th order CONFIG.butter_freqs = [2, 4]; % Hz — Butterworth conditions used in paper CONFIG.min_frames = 100; % minimum valid frames per player-period to retain CONFIG.stoppage_p1 = 2700; % clock threshold (s) for stoppage flagging, period 1 CONFIG.stoppage_p2 = 5400; % clock threshold (s) for stoppage flagging, period 2 CONFIG.top_frac = 0.10; % top-decile threshold for rank-order misclassification CONFIG.rank_cond = 'kalman'; % smoothing condition for the rank-order analysis (paper) % Stage 6 (Winter residual analysis) parameters CONFIG.winter_fc = [0.5 10.0 0.25]; % residual grid [min max step] (Hz) CONFIG.winter_ngames = 20; % games to sample x-position sequences from CONFIG.winter_nseq = 100; % target number of player-period sequences CONFIG.winter_minfrm = 150; % min frames per sequence (~5 s) CONFIG.winter_maxfrm = 900; % max frames per sequence (~30 s window) CONFIG.winter_seed = 42; % rng seed for reproducible sampling CONFIG.winter_nboot = 2000; % bootstrap resamples for the elbow CI CONFIG.winter_bootseed= 1; % bootstrap seed (reproducible CI) % ========================================================================= % Derived paths — do not edit % ========================================================================= CONFIG.positions_file = fullfile(CONFIG.output_folder, 'player_positions.csv'); CONFIG.intermediate_folder = fullfile(CONFIG.output_folder, 'intermediate'); CONFIG.summary_mat = fullfile(CONFIG.output_folder, 'PlayerLoad_Summary.mat'); CONFIG.summary_csv = fullfile(CONFIG.output_folder, 'PlayerLoad_Summary.csv'); CONFIG.out_descriptive = fullfile(CONFIG.output_folder, 'PlayerLoad_Descriptive.xlsx'); CONFIG.out_ba = fullfile(CONFIG.output_folder, 'PlayerLoad_BlandAltman.xlsx'); CONFIG.out_ratio = fullfile(CONFIG.output_folder, 'PlayerLoad_RatioMatrix.xlsx'); CONFIG.out_rank = fullfile(CONFIG.output_folder, 'PlayerLoad_RankOrder.xlsx'); CONFIG.out_winter = fullfile(CONFIG.output_folder, 'PlayerLoad_WinterElbow.xlsx'); CONFIG.fig_folder = fullfile(CONFIG.output_folder, 'figures'); % Stage 7 figures CONFIG.fig_dpi = 300; EQ_NAMES = {'EQ1_AcelT','EQ2_PL_RT_Cum','EQ3_PlayerLoad', ... 'EQ4_ImpLoad','EQ5_PL_RE','EQ6_TotalLoad', ... 'EQ7_PL_x','EQ8_PL_y','EQ9_PL_z', ... 'EQ10_PL2D','EQ11_PLTM'}; EQ_SHORT = {'EQ1','EQ2','EQ3','EQ4','EQ5','EQ6','EQ7','EQ8','EQ9','EQ10','EQ11'}; N_EQ = numel(EQ_NAMES); CONDITIONS = {'raw','kalman','butter_2hz','butter_4hz'}; N_COND = numel(CONDITIONS); % Create output folders for d = {CONFIG.output_folder, CONFIG.intermediate_folder} if ~exist(d{1}, 'dir'); mkdir(d{1}); end end fprintf('========== PLAYER LOAD PIPELINE ==========\n'); fprintf('Tracking data: %s\n', CONFIG.tracking_folder); fprintf('Event data: %s\n', CONFIG.event_folder); fprintf('Output: %s\n\n', CONFIG.output_folder); %% ========================================================================= %% STAGE 1: EXTRACT PLAYER POSITIONS FROM EVENT JSON FILES %% ========================================================================= % Reads event data JSON files and builds a position lookup table. % Position is assigned as the modal positionGroupType across all events % for each player within each game. % % Output: player_positions.csv % Columns: game_id, team, jersey, player_id, player_name, position_raw % ========================================================================= if CONFIG.skip_stage1 fprintf('--- Stage 1 skipped (skip_stage1 = true) ---\n\n'); else fprintf('--- Stage 1: Extract player positions ---\n\n'); event_files = dir(fullfile(CONFIG.event_folder, '*.json')); n_event = numel(event_files); if n_event == 0 error('No .json files found in event folder:\n %s\nCheck CONFIG.event_folder.', ... CONFIG.event_folder); end fprintf('Found %d event JSON files\n\n', n_event); posMap = containers.Map('KeyType','char','ValueType','any'); for iFile = 1:n_event jsonFile = fullfile(CONFIG.event_folder, event_files(iFile).name); [~, gameID, ~] = fileparts(event_files(iFile).name); fprintf('[%d/%d] %s ... ', iFile, n_event, gameID); try fid = fopen(jsonFile, 'r'); raw = fread(fid, '*char')'; fclose(fid); data = jsondecode(raw); catch ME fprintf('PARSE ERROR: %s\n', ME.message); continue; end if isstruct(data) nEv = numel(data); getEv = @(i) data(i); elseif iscell(data) nEv = numel(data); getEv = @(i) data{i}; else fprintf('UNKNOWN FORMAT\n'); continue; end nFound = 0; for iEv = 1:nEv ev = getEv(iEv); for side = {'home','away'} side_str = side{1}; field = [side_str 'Players']; if ~isfield(ev, field) || isempty(ev.(field)); continue; end players = ev.(field); if isstruct(players); players = num2cell(players); end for ip = 1:numel(players) p = players{ip}; jer = pff_get_num(p, 'jerseyNum'); if isnan(jer); continue; end key = sprintf('%s_%s_%d', gameID, side_str, jer); if ~isKey(posMap, key) posMap(key) = struct('gameID', gameID, ... 'team', side_str, 'jersey', jer, ... 'player_id', pff_get_num(p,'playerId'), ... 'player_name', pff_get_str(p,'playerName'), ... 'positions', {{}}); end entry = posMap(key); pos = pff_get_str(p, 'positionGroupType'); if ~isempty(pos) entry.positions{end+1} = pos; posMap(key) = entry; end nFound = nFound + 1; end end end fprintf('%d player-event entries\n', nFound); end % Build output table: modal position per player all_keys = keys(posMap); n_players = numel(all_keys); out_game = cell(n_players, 1); out_team = cell(n_players, 1); out_jer = zeros(n_players, 1); out_pid = zeros(n_players, 1); out_name = cell(n_players, 1); out_pos = cell(n_players, 1); for ik = 1:n_players e = posMap(all_keys{ik}); if isempty(e.positions) modal_pos = 'UNKNOWN'; else [uniq_pos, ~, ic] = unique(e.positions); counts = accumarray(ic, 1); [~, best] = max(counts); modal_pos = uniq_pos{best}; end out_game{ik} = e.gameID; out_team{ik} = e.team; out_jer(ik) = e.jersey; out_pid(ik) = e.player_id; out_name{ik} = e.player_name; out_pos{ik} = modal_pos; end posTable = table(string(out_game), string(out_team), out_jer, out_pid, ... string(out_name), string(out_pos), ... 'VariableNames', ... {'game_id','team','jersey','player_id','player_name','position_raw'}); writetable(posTable, CONFIG.positions_file); fprintf('\nPlayer positions saved: %d entries -> %s\n\n', n_players, CONFIG.positions_file); end %% ========================================================================= %% STAGE 2: PARSE TRACKING JSONL FILES %% ========================================================================= % Reads each game's .jsonl tracking file line by line. % Extracts raw and Kalman-smoothed XY positions for all players per frame. % Saves one .mat file per game to the intermediate folder. % % This stage is resume-safe: games already saved to .mat are skipped % unless CONFIG.skip_stage2 is false AND the file already exists. % ========================================================================= if CONFIG.skip_stage2 fprintf('--- Stage 2 skipped (skip_stage2 = true) ---\n\n'); else fprintf('--- Stage 2: Parse tracking JSONL files ---\n\n'); jsonl_files = dir(fullfile(CONFIG.tracking_folder, '*.jsonl')); n_games = numel(jsonl_files); if n_games == 0 error('No .jsonl files found in tracking folder:\n %s\nCheck CONFIG.tracking_folder.', ... CONFIG.tracking_folder); end fprintf('Found %d game files\n\n', n_games); s2_status = cell(n_games, 1); s2_rows = zeros(n_games, 1); for iFile = 1:n_games jsonlFile = fullfile(CONFIG.tracking_folder, jsonl_files(iFile).name); [~, gameID, ~] = fileparts(jsonl_files(iFile).name); outFile = fullfile(CONFIG.intermediate_folder, sprintf('raw_%s.mat', gameID)); fprintf('[%d/%d] Game %s ', iFile, n_games, gameID); if exist(outFile, 'file') fprintf('(already exists — skipping)\n'); s2_status{iFile} = 'SKIPPED'; continue; end tGame = tic; % Pre-allocate column arrays game_id_col = {}; frame_col = []; period_col = []; clock_col = []; team_col = {}; jersey_col = []; vis_col = {}; conf_col = []; x_raw_col = []; y_raw_col = []; x_smth_col = []; y_smth_col = []; try fid = fopen(jsonlFile, 'r'); lineNum = 0; while true line = fgetl(fid); if ~ischar(line); break; end lineNum = lineNum + 1; if isempty(strtrim(line)); continue; end try frm = jsondecode(line); catch continue; end fn = pff_get_num(frm, 'frameNum'); per = pff_get_num(frm, 'period'); clk = pff_get_num(frm, 'periodGameClockTime'); for side = {'home','away'} side_str = side{1}; raw_field = [side_str 'Players']; smth_field= [side_str 'PlayersSmoothed']; if ~isfield(frm, raw_field) || isempty(frm.(raw_field)); continue; end if ~isfield(frm, smth_field) || isempty(frm.(smth_field)); continue; end hp_raw = frm.(raw_field); hp_smth = frm.(smth_field); nP = min(numel(hp_raw), numel(hp_smth)); for i = 1:nP game_id_col{end+1,1} = gameID; frame_col(end+1,1) = fn; period_col(end+1,1) = per; clock_col(end+1,1) = clk; team_col{end+1,1} = side_str; jersey_col(end+1,1) = pff_get_num(hp_smth(i), 'jerseyNum'); vis_col{end+1,1} = pff_get_str(hp_smth(i), 'visibility'); conf_col{end+1,1} = pff_get_str(hp_smth(i), 'confidence'); x_raw_col(end+1,1) = pff_get_num(hp_raw(i), 'x'); y_raw_col(end+1,1) = pff_get_num(hp_raw(i), 'y'); x_smth_col(end+1,1) = pff_get_num(hp_smth(i), 'x'); y_smth_col(end+1,1) = pff_get_num(hp_smth(i), 'y'); end end if mod(lineNum, 50000) == 0 fprintf('\n ... %dk lines (%.0fs)', lineNum/1000, toc(tGame)); end end fclose(fid); catch ME if exist('fid','var') && fid > 0; fclose(fid); end fprintf(' FAILED: %s\n', ME.message); s2_status{iFile} = 'ERROR'; continue; end % Build and save table nRows = numel(frame_col); T = table(string(game_id_col), frame_col, period_col, clock_col, ... string(team_col), jersey_col, ... string(vis_col), string(conf_col), ... x_raw_col, y_raw_col, x_smth_col, y_smth_col, ... 'VariableNames', {'game_id','frame','period','game_clock_s', ... 'team','jersey','visibility','confidence', ... 'x_raw','y_raw','x_smooth','y_smooth'}); save(outFile, 'T', '-v7.3'); fprintf(' %d rows -> %s (%.0fs)\n', nRows, sprintf('raw_%s.mat', gameID), toc(tGame)); s2_status{iFile} = 'OK'; s2_rows(iFile) = nRows; clear game_id_col frame_col period_col clock_col team_col jersey_col ... vis_col conf_col x_raw_col y_raw_col x_smth_col y_smth_col T; end n_ok = sum(strcmp(s2_status, 'OK')); n_sk = sum(strcmp(s2_status, 'SKIPPED')); fprintf('\nStage 2 complete: %d processed, %d skipped, %d errors\n\n', ... n_ok, n_sk, n_games - n_ok - n_sk); end %% ========================================================================= %% STAGE 3: DERIVE ACCELERATION AND APPLY BUTTERWORTH FILTERS %% ========================================================================= % Loads each game's intermediate .mat file. % Applies four signal-processing conditions to XY positions: % (1) raw — unfiltered positional differences % (2) kalman — PFF-supplied Kalman-smoothed coordinates % (3) butter_2hz — zero-phase Butterworth low-pass at 2 Hz % (4) butter_4hz — zero-phase Butterworth low-pass at 4 Hz % % Velocity and acceleration estimated via central finite-difference scheme. % Saves one .mat per game to intermediate folder (replaces raw_ file). % % Output per game: accel_XXXX.mat % ========================================================================= if CONFIG.skip_stage3 fprintf('--- Stage 3 skipped (skip_stage3 = true) ---\n\n'); else fprintf('--- Stage 3: Derive acceleration ---\n\n'); % Load position lookup if ~exist(CONFIG.positions_file, 'file') error('player_positions.csv not found.\nRun Stage 1 first, or set skip_stage1=false.\nExpected: %s', ... CONFIG.positions_file); end posTable = readtable(CONFIG.positions_file, 'TextType','string'); posKeys = strcat(string(posTable.game_id), '_', string(posTable.team), '_', string(posTable.jersey)); posVals = string(posTable.position_raw); fprintf('Position lookup loaded: %d entries\n\n', height(posTable)); % Butterworth coefficients butter_b = cell(2,1); butter_a = cell(2,1); for ib = 1:2 Wn = CONFIG.butter_freqs(ib) / (CONFIG.fps / 2); [butter_b{ib}, butter_a{ib}] = butter(CONFIG.butter_order, Wn, 'low'); fprintf('Butterworth %d Hz: Wn = %.4f\n', CONFIG.butter_freqs(ib), Wn); end fprintf('\n'); raw_files = dir(fullfile(CONFIG.intermediate_folder, 'raw_*.mat')); n_games = numel(raw_files); if n_games == 0 error('No raw_*.mat files found in intermediate folder.\nRun Stage 2 first.'); end fprintf('Found %d intermediate files\n\n', n_games); for iFile = 1:n_games matFile = fullfile(CONFIG.intermediate_folder, raw_files(iFile).name); tok = regexp(raw_files(iFile).name, 'raw_(\w+)\.mat', 'tokens'); if isempty(tok); continue; end gameID = tok{1}{1}; outFile = fullfile(CONFIG.intermediate_folder, sprintf('accel_%s.mat', gameID)); fprintf('[%d/%d] Game %s ', iFile, n_games, gameID); if exist(outFile, 'file') fprintf('(accel already exists — skipping)\n'); continue; end tGame = tic; S = load(matFile, 'T'); T = S.T; T = T(T.team ~= "ball", :); % Resolve duplicate frames grpKey = strcat(string(T.game_id),'_',string(T.frame),'_', ... string(T.team),'_',string(T.jersey)); [~, ia, ic] = unique(grpKey, 'stable'); grpCounts = accumarray(ic, 1); dupGroups = find(grpCounts > 1); for dg = 1:numel(dupGroups) rows = find(ic == dupGroups(dg)); T.x_raw(rows(1)) = mean(T.x_raw(rows), 'omitnan'); T.y_raw(rows(1)) = mean(T.y_raw(rows), 'omitnan'); T.x_smooth(rows(1)) = mean(T.x_smooth(rows), 'omitnan'); T.y_smooth(rows(1)) = mean(T.y_smooth(rows), 'omitnan'); end T = T(ia, :); playerKeys = strcat(string(T.team),'_',string(T.jersey)); uniquePlayerKeys = unique(playerKeys, 'stable'); nPlayers = numel(uniquePlayerKeys); % Pre-allocate output column vectors out_game_id = string([]); out_team = string([]); out_jersey = double([]); out_pos = string([]); out_period = int8([]); out_frame = int32([]); out_clock = single([]); out_cond = string([]); out_vis = string([]); out_conf = string([]); out_stop = logical([]); out_ax = single([]); out_ay = single([]); out_accel = single([]); for ip = 1:nPlayers pKey = uniquePlayerKeys(ip); parts = strsplit(pKey, '_'); pTeam = parts(1); pJersey = str2double(parts(2)); lookupKey = sprintf('%s_%s_%d', gameID, pTeam, pJersey); posMatch = find(posKeys == string(lookupKey), 1); posLabel = "UNKNOWN"; if ~isempty(posMatch); posLabel = posVals(posMatch); end pMask = T.team == pTeam & T.jersey == pJersey; pData = sortrows(T(pMask,:), 'frame'); periods = unique(pData.period); for iPer = 1:numel(periods) per = periods(iPer); perData = pData(pData.period == per, :); nF = height(perData); if nF < CONFIG.min_frames; continue; end frames = int32(perData.frame); clk = single(perData.game_clock_s); vis = perData.visibility; conf = perData.confidence; stoppage = clk > single(per == 1) * CONFIG.stoppage_p1 + ... single(per == 2) * CONFIG.stoppage_p2; xr = double(perData.x_raw); yr = double(perData.y_raw); xs = double(perData.x_smooth); ys = double(perData.y_smooth); for iCond = 1:4 switch iCond case 1; px = xr; py = yr; case 2; px = xs; py = ys; case 3; px = pl_filtfilt(butter_b{1}, butter_a{1}, xr); py = pl_filtfilt(butter_b{1}, butter_a{1}, yr); case 4; px = pl_filtfilt(butter_b{2}, butter_a{2}, xr); py = pl_filtfilt(butter_b{2}, butter_a{2}, yr); end vx = pl_central_diff(px, CONFIG.dt); vy = pl_central_diff(py, CONFIG.dt); ax = single(pl_central_diff(vx, CONFIG.dt)); ay = single(pl_central_diff(vy, CONFIG.dt)); condName = string(CONDITIONS{iCond}); out_game_id = [out_game_id; repmat(string(gameID), nF, 1)]; out_team = [out_team; repmat(pTeam, nF, 1)]; out_jersey = [out_jersey; repmat(pJersey, nF, 1)]; out_pos = [out_pos; repmat(posLabel, nF, 1)]; out_period = [out_period; repmat(int8(per), nF, 1)]; out_frame = [out_frame; frames]; out_clock = [out_clock; clk]; out_cond = [out_cond; repmat(condName, nF, 1)]; out_vis = [out_vis; vis]; out_conf = [out_conf; conf]; out_stop = [out_stop; stoppage]; out_ax = [out_ax; ax]; out_ay = [out_ay; ay]; out_accel = [out_accel; sqrt(ax.^2 + ay.^2)]; end end if mod(ip, 10) == 0 || ip == nPlayers fprintf('\n Player %d/%d (%.0fs)', ip, nPlayers, toc(tGame)); end end data.game_id = out_game_id; data.team = out_team; data.jersey = out_jersey; data.position_raw = out_pos; data.period = out_period; data.frame = out_frame; data.game_clock_s = out_clock; data.smoothing_condition = out_cond; data.visibility = out_vis; data.confidence = out_conf; data.stoppage = out_stop; data.ax = out_ax; data.ay = out_ay; data.accel_mag = out_accel; data.meta.fps = CONFIG.fps; data.meta.dt = CONFIG.dt; data.meta.conditions = CONDITIONS; data.meta.created = datestr(now); save(outFile, 'data', '-v7.3'); fprintf('\n Saved accel_%s.mat (%.0fs)\n\n', gameID, toc(tGame)); clear T S data out_game_id out_team out_jersey out_pos out_period ... out_frame out_clock out_cond out_vis out_conf out_stop out_ax out_ay out_accel; end fprintf('Stage 3 complete\n\n'); end %% ========================================================================= %% STAGE 4: APPLY ALL 11 PLAYER LOAD EQUATIONS %% ========================================================================= % Loads each game's accel_*.mat file. % Accumulates all 11 equations per player-period under each condition. % Pools P1+P2 to yield player-match observations. % Saves summary table. % % The 11 equations (see Table 1 in manuscript): % EQ1 AcelT Σ √(ax² + ay²) instantaneous magnitude % EQ2 PL_RT 0.01 × Σ √((Δax²+Δay²)/100) jerk (RealTrack scalar) % EQ3 PlayerLoad Σ √((Δax²+Δay²)/100) jerk (Catapult) % EQ4 ImpulseLoad Σ √(ax²+ay²) / 9.8067 instantaneous / g % EQ5 PL_RE Σ (ax²+ay²) / 800 energy-weighted (ZXY) % EQ6 TotalLoad Σ √((Δax²+Δay²)/1000) jerk (StatSports) % EQ7 PL_x Σ √(Δax²) / 100 jerk — lateral only % EQ8 PL_y Σ √(Δay²) / 100 jerk — AP only % EQ9 PL_z Σ √(Δaz²/100) = 0 jerk — vertical (zero in 2D) % EQ10 PL2D Σ √((Δax²+Δay²)/100) = EQ3 jerk — 2D (algebraically EQ3) % EQ11 PLTM Σ √((Δax²+Δay²)/100) = EQ3 jerk (also algebraically EQ3) % % Output: PlayerLoad_Summary.mat and PlayerLoad_Summary.csv % ========================================================================= if CONFIG.skip_stage4 fprintf('--- Stage 4 skipped (skip_stage4 = true) ---\n\n'); else fprintf('--- Stage 4: Apply PlayerLoad equations ---\n\n'); accel_files = dir(fullfile(CONFIG.intermediate_folder, 'accel_*.mat')); n_files = numel(accel_files); if n_files == 0 error('No accel_*.mat files found.\nRun Stage 3 first.'); end fprintf('Found %d game files\n\n', n_files); % Global typed accumulators acc_game = string([]); acc_team = string([]); acc_jer = double([]); acc_pos = string([]); acc_per = double([]); acc_cond = string([]); acc_n_tot = double([]); acc_n_val = double([]); acc_pct_val = double([]); acc_pct_stp = double([]); acc_pct_vis = double([]); acc_EQ = zeros(0, N_EQ); tTotal = tic; for iFile = 1:n_files matFile = fullfile(CONFIG.intermediate_folder, accel_files(iFile).name); tok = regexp(accel_files(iFile).name, 'accel_(\w+)\.mat', 'tokens'); if isempty(tok); continue; end gameID = tok{1}{1}; fprintf('[%d/%d] Game %s ... ', iFile, n_files, gameID); tGame = tic; S = load(matFile, 'data'); d = S.data; n = numel(d.frame); ax = double(d.ax); ay = double(d.ay); teamNum = double(string(d.team) == "home") + 1; jerseyN = double(d.jersey); periodN = double(d.period); condStr = string(d.smoothing_condition); condNum = zeros(n, 1); condNum(condStr == "raw") = 1; condNum(condStr == "kalman") = 2; condNum(condStr == "butter_2hz") = 3; condNum(condStr == "butter_4hz") = 4; groupInt = teamNum*100000 + jerseyN*1000 + periodN*10 + condNum; [sortedInt, sortIdx] = sort(groupInt); grpChange = [true; diff(sortedInt) ~= 0]; grpIdx = cumsum(grpChange); nGroups = grpIdx(end); ax_s = ax(sortIdx); ay_s = ay(sortIdx); vis_s = string(d.visibility(sortIdx)); stop_s = logical(d.stoppage(sortIdx)); pos_s = string(d.position_raw(sortIdx)); gid_s = string(d.game_id(sortIdx)); tm_s = string(d.team(sortIdx)); jer_s = double(d.jersey(sortIdx)); per_s = double(d.period(sortIdx)); cond_s = string(d.smoothing_condition(sortIdx)); starts = find(grpChange); ends = [starts(2:end)-1; n]; g_EQ = zeros(nGroups, N_EQ); g_valid = false(nGroups, 1); g_game = string(zeros(nGroups,1)); g_team = string(zeros(nGroups,1)); g_jer = zeros(nGroups,1); g_pos = string(zeros(nGroups,1)); g_per = zeros(nGroups,1); g_cond = string(zeros(nGroups,1)); g_ntot = zeros(nGroups,1); g_nval = zeros(nGroups,1); g_pval = zeros(nGroups,1); g_pstp = zeros(nGroups,1); g_pvis = zeros(nGroups,1); for ig = 1:nGroups i1 = starts(ig); i2 = ends(ig); axg = ax_s(i1:i2); ayg = ay_s(i1:i2); valid = ~isnan(axg) & ~isnan(ayg); axv = axg(valid); ayv = ayg(valid); nv = numel(axv); n_total = i2 - i1 + 1; g_ntot(ig) = n_total; g_nval(ig) = nv; g_pval(ig) = 100 * nv / n_total; g_pstp(ig) = 100 * double(sum(stop_s(i1:i2))) / n_total; g_pvis(ig) = 100 * sum(vis_s(i1:i2) == "VISIBLE") / n_total; g_game(ig) = gid_s(i1); g_team(ig) = tm_s(i1); g_jer(ig) = jer_s(i1); g_pos(ig) = pos_s(i1); g_per(ig) = per_s(i1); g_cond(ig) = cond_s(i1); if nv < 2; continue; end dax = diff(axv); day = diff(ayv); mag2 = axv.^2 + ayv.^2; dmag2 = dax.^2 + day.^2; g_EQ(ig,:) = [ ... sum(sqrt(mag2)), ... % EQ1 AcelT sum(sqrt(dmag2) / 100) * 0.01, ... % EQ2 PL_RT sum(sqrt(dmag2) / 100), ... % EQ3 PlayerLoad sum(sqrt(mag2) / 9.8067), ... % EQ4 ImpulseLoad sum(mag2 / 800), ... % EQ5 PL_RE sum(sqrt(dmag2) / 1000), ... % EQ6 TotalLoad sum(abs(dax) / 100), ... % EQ7 PL_x (AP, longitudinal): |Delta ax| scaled /100 as the resultant sum(abs(day) / 100), ... % EQ8 PL_y (ML, lateral): |Delta ay| scaled /100 as the resultant 0, ... % EQ9 PL_z (zero in 2D) sum(sqrt(dmag2) / 100), ... % EQ10 PL2D = EQ3 sum(sqrt(dmag2) / 100)]; % EQ11 PLTM = EQ3 g_valid(ig) = true; end % Keep valid rows and append keep = g_valid; acc_game = [acc_game; g_game(keep)]; acc_team = [acc_team; g_team(keep)]; acc_jer = [acc_jer; g_jer(keep)]; acc_pos = [acc_pos; g_pos(keep)]; acc_per = [acc_per; g_per(keep)]; acc_cond = [acc_cond; g_cond(keep)]; acc_n_tot = [acc_n_tot; g_ntot(keep)]; acc_n_val= [acc_n_val;g_nval(keep)]; acc_pct_val = [acc_pct_val; g_pval(keep)]; acc_pct_stp = [acc_pct_stp; g_pstp(keep)]; acc_pct_vis = [acc_pct_vis; g_pvis(keep)]; acc_EQ = [acc_EQ; g_EQ(keep,:)]; fprintf('%d groups, %.0fs\n', sum(keep), toc(tGame)); clear S d ax ay ax_s ay_s g_EQ g_valid g_game g_team g_jer g_pos g_per g_cond; end fprintf('\nBuilding summary table (%d rows)...\n', numel(acc_game)); T_summary = table(acc_game, acc_team, acc_jer, acc_pos, acc_per, acc_cond, ... acc_n_tot, acc_n_val, acc_pct_val, acc_pct_stp, acc_pct_vis, ... acc_EQ(:,1), acc_EQ(:,2), acc_EQ(:,3), acc_EQ(:,4), ... acc_EQ(:,5), acc_EQ(:,6), acc_EQ(:,7), acc_EQ(:,8), ... acc_EQ(:,9), acc_EQ(:,10), acc_EQ(:,11), ... 'VariableNames', ... {'game_id','team','jersey','position_raw','period', ... 'smoothing_condition','n_frames_total','n_frames_valid', ... 'pct_frames_valid','pct_stoppage','pct_visible', ... EQ_NAMES{:}}); save(CONFIG.summary_mat, 'T_summary', '-v7.3'); writetable(T_summary, CONFIG.summary_csv); fprintf('Saved: %s\nSaved: %s\n', CONFIG.summary_mat, CONFIG.summary_csv); fprintf('Total time: %.1f min\n\nStage 4 complete\n\n', toc(tTotal)/60); end %% ========================================================================= %% STAGE 5: STATISTICAL ANALYSIS %% ========================================================================= % Loads the summary table, pools periods (P1+P2), and produces three % Excel workbooks containing the outputs reported in the manuscript. % % Outputs: % PlayerLoad_Descriptive.xlsx — mean ± SD by position and condition % (absolute and per-90 normalised values) % PlayerLoad_BlandAltman.xlsx — agreement + conversion for all ordered % equation pairs (both directions), each % condition and position, both bases % PlayerLoad_RatioMatrix.xlsx — pairwise mean ratios (both bases) % PlayerLoad_RankOrder.xlsx — rank-order/misclassification (both bases, % both criteria) and positional per-90 spread % ========================================================================= if CONFIG.skip_stage4 && isempty(CONFIG.summary_checkpoint_csv) fprintf('--- Stage 5 skipped (skip_stage4 = true, summary table not available) ---\n\n'); else fprintf('--- Stage 5: Statistical analysis ---\n\n'); if ~isempty(CONFIG.summary_checkpoint_csv) fprintf('Loading summary CHECKPOINT: %s ... ', CONFIG.summary_checkpoint_csv); T = readtable(CONFIG.summary_checkpoint_csv, 'TextType', 'string'); T.smoothing_condition = string(T.smoothing_condition); else if ~exist(CONFIG.summary_mat, 'file') error('Summary .mat not found. Run Stage 4 first.\nExpected: %s', CONFIG.summary_mat); end fprintf('Loading summary data... '); S = load(CONFIG.summary_mat, 'T_summary'); T = S.T_summary; end fprintf('%d rows\n\n', height(T)); % Pool P1+P2: sum EQ values and n_frames_valid per player-match fprintf('Pooling periods (P1+P2)...\n'); grpVars = {'game_id','team','jersey','position_raw','smoothing_condition'}; poolVars = [EQ_NAMES, {'n_frames_valid'}]; Tp = groupsummary(T, grpVars, 'sum', poolVars); for i = 1:numel(poolVars) Tp.Properties.VariableNames{['sum_' poolVars{i}]} = poolVars{i}; end % Per-90 normalisation Tp.minutes_played = Tp.n_frames_valid ./ (CONFIG.fps * 60); for i = 1:N_EQ Tp.([EQ_NAMES{i} '_per90']) = Tp.(EQ_NAMES{i}) ./ Tp.minutes_played .* 90; end EQ_PER90 = cellfun(@(x) [x '_per90'], EQ_NAMES, 'UniformOutput', false); positions = unique(Tp.position_raw); positions = positions(positions ~= "UNKNOWN"); positions = ['ALL'; positions]; N_POS = numel(positions); fprintf('Positions found: %s\n\n', strjoin(positions, ', ')); % --- OUTPUT 1: Descriptive statistics (absolute and per-90) ----------- fprintf('Writing descriptive statistics...\n'); for iCond = 1:N_COND cond = CONDITIONS{iCond}; condMask = Tp.smoothing_condition == cond; colLabels = {}; for e = 1:N_EQ colLabels{end+1} = [EQ_SHORT{e} '_Mean']; colLabels{end+1} = [EQ_SHORT{e} '_SD']; colLabels{end+1} = [EQ_SHORT{e} '_per90_Mean']; colLabels{end+1} = [EQ_SHORT{e} '_per90_SD']; end descData = NaN(N_POS, N_EQ * 4); for ip = 1:N_POS if positions(ip) == "ALL" sub = Tp(condMask, :); else sub = Tp(condMask & Tp.position_raw == positions(ip), :); end for e = 1:N_EQ col = (e-1)*4 + 1; v = sub.(EQ_NAMES{e}); v = v(isfinite(v)); v90 = sub.(EQ_PER90{e}); v90 = v90(isfinite(v90)); if ~isempty(v) descData(ip, col) = mean(v); descData(ip, col+1) = std(v); end if ~isempty(v90) descData(ip, col+2) = mean(v90); descData(ip, col+3) = std(v90); end end end descT = array2table(descData, 'VariableNames', colLabels, 'RowNames', cellstr(positions)); writetable(descT, CONFIG.out_descriptive, 'Sheet', cond, 'WriteRowNames', true); fprintf(' Written sheet: %s\n', cond); end % --- OUTPUT 2: Bland-Altman + conversion ------------------------------ fprintf('\nRunning Bland-Altman analysis...\n'); % Directional ordered pairs (EQ_y = slope*EQ_x + intercept) so the conversion % table matches the manuscript S2a: both EQ3->EQ5 and EQ5->EQ3 are reported. % Run on BOTH bases: the manuscript reports per-90; absolute is retained so the % public code reproduces the base-dependence result (agreement differs by base). % % INTERPRETATION NOTE (important). Bland-Altman assumes the two equations share % a scale/unit, so the bias/LoA columns are only interpretable as "agreement" % for comparably scaled pairs (e.g. EQ3~EQ5). Cross-scale pairs (e.g. EQ1 AcelT % is ~200x EQ3) produce a large bias that merely reflects the scale offset, not % disagreement; for those, read the conversion columns (slope, R2, SEE) and the % scale-free RankOrder sheet instead. The manuscript Bland-Altman figure is % therefore restricted to the single comparable-scale pair (EQ3~EQ5); the full % table below is retained for completeness/reproducibility. BASES = {'absolute', EQ_NAMES; 'per90', EQ_PER90}; N_BASE = size(BASES, 1); N_ROWS = N_EQ * (N_EQ-1) * N_COND * N_POS * N_BASE; ba_base = cell(N_ROWS,1); ba_eqx = cell(N_ROWS,1); ba_eqy = cell(N_ROWS,1); ba_cond = cell(N_ROWS,1); ba_pos = cell(N_ROWS,1); ba_n = zeros(N_ROWS,1); ba_bias = NaN(N_ROWS,1); ba_biasp = NaN(N_ROWS,1); ba_sd = NaN(N_ROWS,1); ba_loa_lo = NaN(N_ROWS,1); ba_loa_hi = NaN(N_ROWS,1); ba_r2 = NaN(N_ROWS,1); ba_slope = NaN(N_ROWS,1); ba_int = NaN(N_ROWS,1); ba_see = NaN(N_ROWS,1); ba_rmse = NaN(N_ROWS,1); ba_rmsep = NaN(N_ROWS,1); ba_loo = NaN(N_ROWS,1); row = 0; for iBase = 1:N_BASE baseName = BASES{iBase, 1}; baseCols = BASES{iBase, 2}; for iCond = 1:N_COND cond = CONDITIONS{iCond}; condMask = Tp.smoothing_condition == cond; for ip = 1:N_POS if positions(ip) == "ALL" sub = Tp(condMask, :); else sub = Tp(condMask & Tp.position_raw == positions(ip), :); end for ei = 1:N_EQ for ej = 1:N_EQ if ei == ej; continue; end x = sub.(baseCols{ei}); y = sub.(baseCols{ej}); ok = isfinite(x) & isfinite(y); x = x(ok); y = y(ok); nv = numel(x); row = row + 1; ba_base{row} = baseName; ba_eqx{row} = EQ_SHORT{ei}; ba_eqy{row} = EQ_SHORT{ej}; ba_cond{row} = cond; ba_pos{row} = char(positions(ip)); ba_n(row) = nv; if nv < 3; continue; end d = x - y; b = mean(d); sdd = std(d); ba_bias(row) = b; ba_biasp(row) = 100 * b / mean((x+y)/2); ba_sd(row) = sdd; ba_loa_lo(row) = b - 1.96*sdd; ba_loa_hi(row) = b + 1.96*sdd; ba_rmse(row) = sqrt(mean(d.^2)); % RMS of paired differences ba_rmsep(row) = 100 * ba_rmse(row) / mean((x+y)/2); % Skip the regression on degenerate pairs (e.g. EQ9 = 0 in 2D % data): conversion is undefined, but bias/LoA above stay valid. if std(x)==0 || std(y)==0; continue; end r = corrcoef(x, y); ba_r2(row) = r(1,2)^2; p = polyfit(x, y, 1); ba_slope(row) = p(1); ba_int(row) = p(2); y_hat = polyval(p, x); ba_see(row) = sqrt(mean((y - y_hat).^2)); % Leave-one-out R2 via closed-form leverage (S2a column) xbar = mean(x); Sxx = sum((x-xbar).^2); sst = sum((y-mean(y)).^2); if Sxx > 0 && sst > 0 h = 1/nv + (x-xbar).^2 / Sxx; ba_loo(row) = 1 - sum(((y - y_hat)./(1-h)).^2) / sst; end end end end fprintf(' %s / %s done\n', baseName, cond); end end baT = table(string(ba_base), string(ba_eqx), string(ba_eqy), string(ba_cond), string(ba_pos), ... ba_n, ba_bias, ba_biasp, ba_sd, ba_loa_lo, ba_loa_hi, ... ba_rmse, ba_rmsep, ba_r2, ba_loo, ba_slope, ba_int, ba_see, ... 'VariableNames', {'base','EQ_x','EQ_y','condition','position', ... 'N','bias','bias_pct','SD_diff','LoA_lower','LoA_upper', ... 'RMSE','RMSE_pct','R2','R2_LOO','slope','intercept','SEE'}); writetable(baT, CONFIG.out_ba, 'Sheet', 'BlandAltman'); fprintf('Saved: %s\n\n', CONFIG.out_ba); % --- OUTPUT 3: Ratio matrix (both bases) ------------------------------ fprintf('Writing ratio matrix...\n'); for iBase = 1:N_BASE baseName = BASES{iBase, 1}; baseCols = BASES{iBase, 2}; for iCond = 1:N_COND cond = CONDITIONS{iCond}; sub = Tp(Tp.smoothing_condition == cond, :); ratioCell = cell(N_EQ+1, N_EQ+1); ratioCell{1,1} = 'EQ \ EQ'; for e = 1:N_EQ ratioCell{1,e+1} = EQ_SHORT{e}; ratioCell{e+1,1} = EQ_SHORT{e}; end for ei = 1:N_EQ for ej = 1:N_EQ if ei == ej; ratioCell{ei+1,ej+1} = '1.000 (r=1.000)'; continue; end x = sub.(baseCols{ei}); y = sub.(baseCols{ej}); ok = isfinite(x) & isfinite(y) & y ~= 0; x = x(ok); y = y(ok); if numel(x) < 3; ratioCell{ei+1,ej+1} = 'N/A'; continue; end rc = corrcoef(x, y); ratioCell{ei+1,ej+1} = sprintf('%.4f (r=%.4f)', mean(x)/mean(y), rc(1,2)); end end ratioT = cell2table(ratioCell(2:end,:), ... 'VariableNames', ['Position', cellstr(string(ratioCell(1,2:end)))]); writetable(ratioT, CONFIG.out_ratio, 'Sheet', [cond '_' baseName]); fprintf(' Written sheet: %s_%s\n', cond, baseName); end end fprintf('Saved: %s\n\n', CONFIG.out_ratio); % --- OUTPUT 4: Rank-order + top-decile misclassification -------------- % Within-match percentile-rank agreement of EQ3 against every other % equation (Figure 3). Reports Spearman rho, rank RMSE, and TWO % misclassification rates: leaving the comparator top decile % (out-of-decile) and falling below the comparator median (below-median, % the published 2%/4% figure). Run on both bases: on absolute the % divergent family is EQ5; on per-90 it is EQ1 (the base flip). fprintf('Running rank-order / misclassification analysis (%s)...\n', CONFIG.rank_cond); e3 = find(strcmp(EQ_SHORT, 'EQ3'), 1); subK = Tp(Tp.smoothing_condition == CONFIG.rank_cond, :); [~, ~, gidx] = unique(string(subK.game_id)); % within-match grouping rk = {}; for iBase = 1:N_BASE baseName = BASES{iBase, 1}; baseCols = BASES{iBase, 2}; X = table2array(subK(:, baseCols)); R = pl_within_match_rank(X, gidx); for b = 1:N_EQ if b == e3; continue; end [rho, rmse, mOut, mBelow] = pl_rank_agree(R(:,e3), R(:,b), CONFIG.top_frac); rk(end+1,:) = {baseName, 'EQ3', EQ_SHORT{b}, rho, rmse, ... 100*mOut, 100*mBelow}; %#ok end end rankT = cell2table(rk, 'VariableNames', {'base','EQ_x','EQ_y', ... 'spearman_rho','rank_RMSE','misclass_out_of_decile_pct','misclass_below_median_pct'}); writetable(rankT, CONFIG.out_rank, 'Sheet', 'RankOrder'); % --- OUTPUT 5: Positional per-90 spread + Kruskal-Wallis -------------- % Spread of position-mean per-90 load = (max-min)/min x100, paired with a % Kruskal-Wallis epsilon-squared effect size across positions. Kalman. fprintf('Running positional spread / Kruskal-Wallis analysis...\n'); posCat = string(subK.position_raw); keepP = posCat ~= "UNKNOWN"; spRows = {}; for e = 1:N_EQ v = subK.(EQ_PER90{e}); ok = isfinite(v) & keepP; if sum(ok) < 3; continue; end [gpos, ~, gi] = unique(posCat(ok)); mpos = accumarray(gi, v(ok), [], @mean); spread = 100 * (max(mpos) - min(mpos)) / min(mpos); try [pKW, tblKW] = kruskalwallis(v(ok), cellstr(posCat(ok)), 'off'); Hstat = tblKW{2,5}; nKW = sum(ok); kKW = numel(gpos); eps2 = (Hstat - kKW + 1) / (nKW - kKW); catch pKW = NaN; Hstat = NaN; eps2 = NaN; end spRows(end+1,:) = {EQ_SHORT{e}, numel(gpos), min(mpos), max(mpos), ... spread, Hstat, pKW, eps2}; %#ok end spreadT = cell2table(spRows, 'VariableNames', {'EQ','n_positions', ... 'min_pos_mean','max_pos_mean','spread_pct','KW_H','KW_p','epsilon_sq'}); writetable(spreadT, CONFIG.out_rank, 'Sheet', 'PositionalSpread_per90'); fprintf('Saved: %s\n\n', CONFIG.out_rank); % --- OUTPUT 6: S2b exact within-family scalars (derived from the BA table) -- % Within-family pairs are exact scalar multiples (R2 = 1); the slope is the % scalar. Taken from the per-90 Kalman all-positions conversion rows. exactMask = baT.base=="per90" & baT.condition=="kalman" & baT.position=="ALL" & baT.R2 > 1-1e-6; s2bT = baT(exactMask, {'EQ_x','EQ_y','slope','R2','SEE'}); s2bT.Properties.VariableNames = {'Source','Target','Scalar','R2','SEE'}; writetable(s2bT, CONFIG.out_ba, 'Sheet', 'ExactScalars_S2b'); % --- OUTPUT 7: S6 raw-to-smoothed fold ratios (per-90, per position) -------- % Ratio = mean(raw per-90) / mean(smoothed per-90) per position and equation. posList6 = positions(positions ~= "ALL"); smoothers = {'kalman','butter_2hz','butter_4hz'}; s6 = {}; for ip = 1:numel(posList6) pmask = Tp.position_raw == posList6(ip); rawSub = Tp(pmask & Tp.smoothing_condition == "raw", :); for e = 1:N_EQ mraw = mean(rawSub.(EQ_PER90{e}), 'omitnan'); for sm = smoothers smSub = Tp(pmask & Tp.smoothing_condition == sm{1}, :); msm = mean(smSub.(EQ_PER90{e}), 'omitnan'); if isfinite(msm) && msm ~= 0 && isfinite(mraw) s6(end+1,:) = {char(posList6(ip)), EQ_SHORT{e}, sm{1}, mraw/msm}; %#ok end end end end s6T = cell2table(s6, 'VariableNames', {'position','EQ','smoother','raw_over_smoothed'}); writetable(s6T, CONFIG.out_ratio, 'Sheet', 'SmoothingRatios_S6'); fprintf('Wrote S2b (exact scalars) and S6 (smoothing ratios).\n\n'); fprintf('Stage 5 complete\n\n'); end %% ========================================================================= %% STAGE 6: WINTER RESIDUAL ANALYSIS — CUTOFF ELBOW + BOOTSTRAP CI %% ========================================================================= % Winter (2009) residual analysis on raw x-position, justifying the Butterworth % cutoffs. Reports the elbow of the MEAN residual curve (the ~1.06 Hz optimum) % and a BOOTSTRAP 95% CI for it (resample sequences with replacement, recompute % the mean curve and its elbow). The mean-curve elbow is the stable estimator; a % per-sequence elbow is unstable on single short curves and is not used for the % interval. Reads the Stage-2 raw_*.mat, so it is self-contained within this % pipeline. The standalone 0_PlayerLoad/PlayerLoad_WinterElbowSpread.m runs the % identical analysis on the raw game CSVs and reproduces the published 1.06 Hz % (bootstrap 95% CI ~1.02-1.08 Hz). % ========================================================================= if CONFIG.skip_winter || ~isempty(CONFIG.summary_checkpoint_csv) fprintf('--- Stage 6 skipped (needs Stage-2 raw data; not run in checkpoint mode) ---\n\n'); else fprintf('--- Stage 6: Winter residual analysis ---\n\n'); rawW = dir(fullfile(CONFIG.intermediate_folder, 'raw_*.mat')); if isempty(rawW) error('No raw_*.mat in %s.\nRun Stage 2 first.', CONFIG.intermediate_folder); end rng(CONFIG.winter_seed); fcW = CONFIG.winter_fc(1) : CONFIG.winter_fc(3) : CONFIG.winter_fc(2); nFcW = numel(fcW); bW = cell(nFcW,1); aW = cell(nFcW,1); for i = 1:nFcW Wn = min(fcW(i)/(CONFIG.fps/2), 0.9999); [bW{i}, aW{i}] = butter(CONFIG.butter_order, Wn, 'low'); end % Collect raw x-position sequences (one per player-period), same rule as the % standalone: dedup repeated frames, >= winter_minfrm, random winter_maxfrm window. nG = min(CONFIG.winter_ngames, numel(rawW)); gsel = randperm(numel(rawW), nG); seqs = {}; seqsK = {}; for ig = 1:nG if numel(seqs) >= CONFIG.winter_nseq; break; end Sr = load(fullfile(CONFIG.intermediate_folder, rawW(gsel(ig)).name), 'T'); Tw = Sr.T; Tw = Tw(Tw.team ~= "ball", :); gk = strcat(string(Tw.game_id),'_',string(Tw.frame),'_',string(Tw.team),'_',string(Tw.jersey)); [~, ia, ic] = unique(gk, 'stable'); gc = accumarray(ic, 1); dups = find(gc > 1); for dd = 1:numel(dups) r = find(ic == dups(dd)); Tw.x_raw(r(1)) = mean(Tw.x_raw(r), 'omitnan'); end Tw = Tw(ia, :); pk = strcat(string(Tw.team),'_',string(Tw.jersey),'_',string(Tw.period)); uk = unique(pk, 'stable'); uk = uk(randperm(numel(uk))); for ik = 1:numel(uk) if numel(seqs) >= CONFIG.winter_nseq; break; end seg = sortrows(Tw(pk == uk(ik), :), 'frame'); xr = double(seg.x_raw); xs = double(seg.x_smooth); ok = isfinite(xr); xr = xr(ok); xs = xs(ok); % x_raw filter (reproduces 1.06 Hz) if numel(xr) < CONFIG.winter_minfrm; continue; end if numel(xr) > CONFIG.winter_maxfrm s0 = randi(numel(xr) - CONFIG.winter_maxfrm); xr = xr(s0 : s0 + CONFIG.winter_maxfrm - 1); xs = xs(s0 : s0 + CONFIG.winter_maxfrm - 1); end seqs{end+1} = xr; seqsK{end+1} = xs; %#ok end end nSeqW = numel(seqs); fprintf(' Winter sequences: %d (from %d games)\n', nSeqW, nG); % Residual matrix, aggregate elbow, per-sequence elbow resW = NaN(nSeqW, nFcW); for is = 1:nSeqW sig = seqs{is}; for i = 1:nFcW try resW(is,i) = sqrt(mean((sig - filtfilt(bW{i}, aW{i}, sig)).^2)); catch end end end resMeanW = mean(resW, 1, 'omitnan'); resSDW = std(resW, 0, 1, 'omitnan'); resSEMW = resSDW / sqrt(nSeqW); [fcPoint, bestSplitW, bestP1W, bestP2W] = pl_winter_elbow(fcW, resMeanW, CONFIG.winter_fc(1), CONFIG.winter_fc(2)); % Uncertainty: bootstrap the mean-curve elbow (resample sequences with % replacement, recompute the mean residual curve and its elbow). The mean % curve is the stable estimator; a per-sequence elbow is unstable on single % short curves (spurious high tail) so it is not used for the interval. rng(CONFIG.winter_bootseed); boot = NaN(CONFIG.winter_nboot, 1); for ib = 1:CONFIG.winter_nboot idx = randi(nSeqW, nSeqW, 1); boot(ib) = pl_winter_elbow(fcW, mean(resW(idx,:), 1, 'omitnan'), ... CONFIG.winter_fc(1), CONFIG.winter_fc(2)); end ciLo = pl_pctl(boot, 2.5); ciHi = pl_pctl(boot, 97.5); % Kalman-equivalent Butterworth cutoff (for the Figure 1 reference line): % RMS residual of the Kalman smoother vs raw, mapped onto the residual curve. kalRes = NaN(nSeqW,1); for is = 1:nSeqW xr = seqs{is}; xk = seqsK{is}; nmin = min(numel(xr), numel(xk)); okk = isfinite(xr(1:nmin)) & isfinite(xk(1:nmin)); if sum(okk) >= CONFIG.winter_minfrm kalRes(is) = sqrt(mean((xr(okk)-xk(okk)).^2)); end end kalResMean = mean(kalRes, 'omitnan'); fcKalman = interp1(resMeanW(end:-1:1), fcW(end:-1:1), kalResMean, 'linear', 'extrap'); fcKalman = max(CONFIG.winter_fc(1), min(CONFIG.winter_fc(2), fcKalman)); fprintf(' Elbow point estimate: %.2f Hz (mean residual curve)\n', fcPoint); fprintf(' Bootstrap 95%% CI: %.2f to %.2f Hz (%d resamples)\n', ciLo, ciHi, CONFIG.winter_nboot); writetable(table(fcPoint, ciLo, ciHi, pl_pctl(boot,25), pl_pctl(boot,75), nSeqW, CONFIG.winter_nboot, ... 'VariableNames', {'elbow_Hz','CI95_lo','CI95_hi','IQR_lo','IQR_hi','n_seq','n_boot'}), ... CONFIG.out_winter, 'Sheet', 'ElbowCI'); fprintf('Saved: %s\n\nStage 6 complete\n\n', CONFIG.out_winter); end %% ========================================================================= %% STAGE 7: FIGURES (reproduce the manuscript figures on the per-90 base) %% ========================================================================= % Figure 1 Winter residual (from Stage 6), Figure 2 Bland-Altman EQ3~EQ5 per-90 % (single comparable-scale panel), Figure 3 rank-order per-90 (two cross-family % panels). Reuses the per-90 Tp from Stage 5 and the residual data from Stage 6. % ========================================================================= if ~exist('Tp', 'var') || ~isempty(CONFIG.summary_checkpoint_csv) fprintf('--- Stage 7 skipped (figures unchanged; not run in checkpoint mode) ---\n\n'); else fprintf('--- Stage 7: Figures ---\n\n'); if ~exist(CONFIG.fig_folder, 'dir'); mkdir(CONFIG.fig_folder); end Tk7 = Tp(Tp.smoothing_condition == CONFIG.rank_cond, :); % Kalman e3f = find(strcmp(EQ_SHORT, 'EQ3'), 1); C_jerk=[0.20 0.627 0.173]; C_hz2=[0.122 0.471 0.706]; C_hz4=[0.890 0.102 0.110]; C_opt=[0.6 0 0.6]; C_fit=[0.4 0.4 0.4]; C_energy=[0.890 0.102 0.110]; % --- Figure 1: Winter residual (needs Stage 6) --- if exist('resW','var') && exist('fcW','var') && exist('fcPoint','var') f1 = figure('Units','centimeters','Position',[2 2 17.5 9.9],'Color','w','PaperPositionMode','auto'); subplot(1,2,1); hold on; ymax = max(resMeanW + resSDW)*1.15; fill([fcW fliplr(fcW)],[resMeanW+resSDW fliplr(resMeanW-resSDW)],C_jerk,'FaceAlpha',0.15,'EdgeColor','none','HandleVisibility','off'); plot(fcW,resMeanW,'-','Color',C_jerk,'LineWidth',2,'DisplayName',sprintf('Mean \\pm SD (n = %d)',nSeqW)); xLl=linspace(fcW(1),fcW(bestSplitW),60); xRr=linspace(fcW(bestSplitW),fcW(end),60); plot(xLl,polyval(bestP1W,xLl),'--','Color',C_fit,'LineWidth',1.2,'HandleVisibility','off'); plot(xRr,polyval(bestP2W,xRr),'--','Color',C_fit,'LineWidth',1.2,'HandleVisibility','off'); plot([2 2],[0 ymax],'--','Color',C_hz2,'LineWidth',1.5,'HandleVisibility','off'); plot([4 4],[0 ymax],'--','Color',C_hz4,'LineWidth',1.5,'HandleVisibility','off'); plot([fcPoint fcPoint],[0 ymax],'-','Color',C_opt,'LineWidth',2,'HandleVisibility','off'); plot([CONFIG.winter_fc(1) CONFIG.winter_fc(2)],[kalResMean kalResMean],':','Color',[0.3 0.3 0.3],'LineWidth',1.4,'HandleVisibility','off'); text(2.08,ymax*0.97,'2 Hz','Color',C_hz2,'FontSize',8,'FontWeight','bold','VerticalAlignment','top'); text(4.08,ymax*0.97,'4 Hz','Color',C_hz4,'FontSize',8,'FontWeight','bold','VerticalAlignment','top'); text(fcPoint+0.15,ymax*0.80,sprintf('Optimal %.2f Hz\n95%% CI %.2f-%.2f',fcPoint,ciLo,ciHi),'Color',C_opt,'FontSize',8,'FontWeight','bold','VerticalAlignment','top'); text(CONFIG.winter_fc(2)*0.98,kalResMean*1.08,sprintf('Kalman \\approx %.2f Hz',fcKalman),'Color',[0.2 0.2 0.2],'FontSize',8,'FontWeight','bold','HorizontalAlignment','right'); xlabel('Cutoff frequency (Hz)','FontSize',10); ylabel('Residual (RMS, m)','FontSize',10); legend('Location','northwest','FontSize',8); xlim([CONFIG.winter_fc(1) CONFIG.winter_fc(2)]); ylim([0 ymax]); box off; grid on; set(gca,'FontSize',9); text(-0.14,1.05,'A','Units','normalized','FontSize',11,'FontWeight','bold'); subplot(1,2,2); hold on; ymax2 = max(resMeanW)*1.4; for is=1:nSeqW; plot(fcW,resW(is,:),'-','Color',[C_jerk 0.10],'LineWidth',0.6,'HandleVisibility','off'); end fill([fcW fliplr(fcW)],[resMeanW+resSEMW fliplr(resMeanW-resSEMW)],C_jerk,'FaceAlpha',0.40,'EdgeColor','none','HandleVisibility','off'); plot(fcW,resMeanW,'-','Color',C_jerk,'LineWidth',2,'DisplayName','Mean \pm SEM'); plot([2 2],[0 ymax2],'--','Color',C_hz2,'LineWidth',1.5,'HandleVisibility','off'); plot([4 4],[0 ymax2],'--','Color',C_hz4,'LineWidth',1.5,'HandleVisibility','off'); plot([fcPoint fcPoint],[0 ymax2],'-','Color',C_opt,'LineWidth',2,'HandleVisibility','off'); text(2.08,ymax2*0.97,'2 Hz','Color',C_hz2,'FontSize',8,'FontWeight','bold','VerticalAlignment','top'); text(4.08,ymax2*0.97,'4 Hz','Color',C_hz4,'FontSize',8,'FontWeight','bold','VerticalAlignment','top'); xlabel('Cutoff frequency (Hz)','FontSize',10); ylabel('Residual (RMS, m)','FontSize',10); legend('Location','northwest','FontSize',8); xlim([CONFIG.winter_fc(1) CONFIG.winter_fc(2)]); ylim([0 ymax2]); box off; grid on; set(gca,'FontSize',9); text(-0.14,1.05,'B','Units','normalized','FontSize',11,'FontWeight','bold'); pl_save_figure(f1, fullfile(CONFIG.fig_folder,'Figure1_WinterResidual'), CONFIG.fig_dpi); fprintf(' Saved Figure 1 (Winter residual)\n'); else fprintf(' Figure 1 skipped (Stage 6 not run)\n'); end % --- Figure 2: Bland-Altman EQ3 vs EQ5, per-90 (single panel) --- [grpLbl,groups,colMap] = pl_pos_group(string(Tk7.position_raw)); x = Tk7.EQ3_PlayerLoad_per90; y = Tk7.EQ5_PL_RE_per90; okf = isfinite(x)&isfinite(y); x=x(okf); y=y(okf); lbl=grpLbl(okf); dif=x-y; mn=(x+y)/2; bias=mean(dif); sdd=std(dif); loLo=bias-1.96*sdd; loHi=bias+1.96*sdd; r2v=corr(x,y)^2; pp=polyfit(mn,dif,1); f2 = figure('Units','centimeters','Position',[2 2 10.6 10.8],'Color','w','PaperPositionMode','auto'); ax2 = axes(f2); hold on; for ig=1:numel(groups); gm=lbl==groups{ig}; if any(gm); scatter(mn(gm),dif(gm),12,colMap(groups{ig}),'filled','MarkerFaceAlpha',0.45,'MarkerEdgeAlpha',0,'DisplayName',groups{ig}); end; end xl=[min(mn)*0.98 max(mn)*1.02]; plot(xl,[bias bias],'-','Color',[0.15 0.15 0.15],'LineWidth',1.8,'HandleVisibility','off'); plot(xl,[loLo loLo],'--','Color',[0.4 0.4 0.4],'LineWidth',1.2,'HandleVisibility','off'); plot(xl,[loHi loHi],'--','Color',[0.4 0.4 0.4],'LineWidth',1.2,'HandleVisibility','off'); plot(xl,polyval(pp,xl),'-.','Color',[0.8 0.3 0],'LineWidth',1.3,'HandleVisibility','off'); yr=loHi-loLo; text(xl(2)*0.98,bias+0.04*yr,sprintf('Bias = %.1f',bias),'HorizontalAlignment','right','FontSize',8,'FontWeight','bold'); text(xl(2)*0.98,loHi+0.04*yr,sprintf('+1.96 SD = %.1f',loHi),'HorizontalAlignment','right','FontSize',7.5,'Color',[0.4 0.4 0.4]); text(xl(2)*0.98,loLo-0.06*yr,sprintf('-1.96 SD = %.1f',loLo),'HorizontalAlignment','right','FontSize',7.5,'Color',[0.4 0.4 0.4]); text(xl(1)+0.02*(xl(2)-xl(1)),loHi-0.04*yr,sprintf('R^2 = %.3f',r2v),'FontSize',8.5,'Color',[0.2 0.2 0.2]); text(xl(1)+0.02*(xl(2)-xl(1)),loHi-0.11*yr,sprintf('N = %d',numel(x)),'FontSize',8.5,'Color',[0.2 0.2 0.2]); xlim(xl); ax2.XAxis.Exponent=0; title('PlayerLoad vs PL_{RE} (per-90)','FontSize',10,'FontWeight','bold'); xlabel('Mean of PlayerLoad and PL_{RE} (AU / 90 min)','FontSize',9); ylabel('PlayerLoad - PL_{RE} (AU / 90 min)','FontSize',9); legend('Location','southwest','FontSize',7.5,'NumColumns',2); box off; grid on; set(gca,'FontSize',9); pl_save_figure(f2, fullfile(CONFIG.fig_folder,'Figure2_BlandAltman'), CONFIG.fig_dpi); fprintf(' Saved Figure 2 (Bland-Altman EQ3~EQ5)\n'); % --- Figure 3: rank-order per-90 (two cross-family panels) --- [~,~,gidx7] = unique(string(Tk7.game_id)); Rp = pl_within_match_rank(table2array(Tk7(:, EQ_PER90)), gidx7); rkP = {1,'A','AcelT',C_hz2; 5,'B','PL_{RE}',C_energy}; f3 = figure('Units','centimeters','Position',[2 2 17.5 8.5],'Color','w','PaperPositionMode','auto'); for ip=1:2 ej=rkP{ip,1}; rx=Rp(:,e3f); ry=Rp(:,ej); okr=isfinite(rx)&isfinite(ry); rx=rx(okr); ry=ry(okr); rho=corr(rx,ry,'Type','Spearman'); rmse=sqrt(mean((rx-ry).^2)); top=rx>=90; pctlow=100*sum(ry(top)<50)/max(sum(top),1); subplot(1,2,ip); hold on; scatter(rx,ry,6,rkP{ip,4},'filled','MarkerFaceAlpha',0.25,'MarkerEdgeAlpha',0); plot([0 100],[0 100],'k-','LineWidth',1.5); xlim([0 100]); ylim([0 100]); axis square; xlabel('PlayerLoad within-match percentile rank','FontSize',9); ylabel(sprintf('%s within-match percentile rank',rkP{ip,3}),'FontSize',9); text(3,95,sprintf('\\rho = %.3f\nRMSE_{rank} = %.1f%%\nTop-decile below median: %.0f%%',rho,rmse,pctlow),'FontSize',8.5,'VerticalAlignment','top','BackgroundColor',[0.97 0.97 0.97],'EdgeColor',[0.8 0.8 0.8],'Margin',3); box off; grid on; set(gca,'FontSize',9); text(-0.10,1.05,rkP{ip,2},'Units','normalized','FontSize',12,'FontWeight','bold','VerticalAlignment','bottom'); end pl_save_figure(f3, fullfile(CONFIG.fig_folder,'Figure3_RankOrder'), CONFIG.fig_dpi); fprintf(' Saved Figure 3 (rank-order)\n\nStage 7 complete\n\n'); end %% ========================================================================= %% PIPELINE COMPLETE %% ========================================================================= fprintf('========== PIPELINE COMPLETE ==========\n'); fprintf('Output folder: %s\n\n', CONFIG.output_folder); fprintf('Files produced:\n'); for f = {CONFIG.positions_file, CONFIG.summary_csv, CONFIG.summary_mat, ... CONFIG.out_descriptive, CONFIG.out_ba, CONFIG.out_ratio, CONFIG.out_rank, CONFIG.out_winter} if exist(f{1}, 'file') info = dir(f{1}); fprintf(' [OK] %s (%.1f MB)\n', info.name, info.bytes/1e6); else fprintf(' [--] %s (not found)\n', f{1}); end end fprintf('\nIntermediate .mat files are in:\n %s\n', CONFIG.intermediate_folder); fprintf('These can be deleted once you have verified the summary outputs.\n'); fprintf('Figures (Stage 7): %s\n\n', CONFIG.fig_folder); %% ========================================================================= %% LOCAL FUNCTIONS %% ========================================================================= function [fc_opt, best_split, best_p1, best_p2] = pl_winter_elbow(fc_vals, res_curve, fc_min, fc_max) % Winter residual elbow via two-segment linear-fit intersection. n_fc = numel(fc_vals); best_sse = Inf; best_split = round(n_fc/2); best_p1 = [0 0]; best_p2 = [0 0]; for isplit = 3:(n_fc-3) x1 = fc_vals(1:isplit)'; y1 = res_curve(1:isplit)'; x2 = fc_vals(isplit:end)'; y2 = res_curve(isplit:end)'; if any(~isfinite(y1)) || any(~isfinite(y2)); continue; end p1 = polyfit(x1, y1, 1); p2 = polyfit(x2, y2, 1); sse = sum((y1 - polyval(p1,x1)).^2) + sum((y2 - polyval(p2,x2)).^2); if sse < best_sse; best_sse = sse; best_split = isplit; best_p1 = p1; best_p2 = p2; end end if abs(best_p1(1) - best_p2(1)) > 1e-10 fc_opt = (best_p2(2) - best_p1(2)) / (best_p1(1) - best_p2(1)); fc_opt = max(fc_min, min(fc_max, fc_opt)); else fc_opt = fc_vals(best_split); end end function p = pl_pctl(v, q) % Linear-interpolation percentile (no toolbox dependency). v = sort(v(isfinite(v))); if isempty(v); p = NaN; return; end if isscalar(v); p = v; return; end r = (q/100)*(numel(v)-1) + 1; lo = floor(r); hi = ceil(r); p = v(lo) + (r-lo)*(v(hi)-v(lo)); end function d = pl_central_diff(x, dt) % Central finite-difference scheme. Returns NaN at boundaries. n = numel(x); d = NaN(n, 1); if n < 3; return; end d(2:n-1) = (x(3:n) - x(1:n-2)) / (2 * dt); end function R = pl_within_match_rank(X, gidx) % Per-match percentile rank (0-100) of each equation, replicating Figure 3: % [~,ord]=sort(vals); pct(ord)=(1:nPl)/nPl*100. R = NaN(size(X)); for g = 1:max(gidx) idx = find(gidx == g); nPl = numel(idx); if nPl < 2; continue; end for e = 1:size(X,2) v = X(idx,e); ok = isfinite(v); if sum(ok) < 2; continue; end [~, ord] = sort(v); pct = NaN(nPl,1); pct(ord) = (1:nPl)'/nPl*100; R(idx,e) = pct; end end end function [rho, rmse, mOut, mBelow] = pl_rank_agree(rx, ry, topFrac) % Spearman rho, rank RMSE, and two misclassification rates for the EQ3 top % decile: share leaving the comparator top decile (out-of-decile) and share % falling below the comparator median (below-median). Inputs are within-match % percentile ranks. Requires Statistics and Machine Learning Toolbox (corr). ok = isfinite(rx) & isfinite(ry); rx = rx(ok); ry = ry(ok); if numel(rx) < 3; [rho,rmse,mOut,mBelow] = deal(NaN); return; end rho = corr(rx, ry, 'Type','Spearman'); rmse = sqrt(mean((rx - ry).^2)); top = rx >= 100*(1-topFrac); % EQ3 top decile (rank >= 90) if any(top) mOut = mean(ry(top) < 100*(1-topFrac)); % left the comparator top decile mBelow = mean(ry(top) < 50); % fell below the comparator median else [mOut, mBelow] = deal(NaN); end end function y = pl_filtfilt(b, a, x) % Zero-phase Butterworth filter with graceful fallback. try y = filtfilt(b, a, x); catch y = NaN(size(x)); warning('filtfilt failed — check Signal Processing Toolbox is installed.'); end end function val = pff_get_num(s, field) % Safely extract a numeric field from a struct. if isfield(s, field) && ~isempty(s.(field)) raw = s.(field); if ischar(raw) || isstring(raw) val = str2double(raw); else val = double(raw(1)); end else val = NaN; end end function val = pff_get_str(s, field) % Safely extract a string field from a struct. if isfield(s, field) && ~isempty(s.(field)) val = char(s.(field)); else val = ''; end end function pl_save_figure(fig, pathNoExt, dpi) % Save a figure as high-resolution TIFF and PNG (Stage 7). set(fig, 'PaperPositionMode', 'auto'); try exportgraphics(fig, [pathNoExt '.tif'], 'Resolution', dpi, 'ContentType', 'image'); exportgraphics(fig, [pathNoExt '.png'], 'Resolution', dpi); catch print(fig, pathNoExt, '-dtiff', ['-r' num2str(dpi)]); print(fig, pathNoExt, '-dpng', ['-r' num2str(dpi)]); end end function [grpLbl, groups, colMap] = pl_pos_group(rawPos) % Collapse raw positions to six coloured groups (Figure 2 colouring). groups = {'GK','CB','FB','CM','W','ST'}; colMap = containers.Map(groups, ... {[0.89 0.10 0.11],[0.12 0.47 0.71],[0.20 0.63 0.17], ... [1.00 0.50 0.00],[0.60 0.31 0.64],[0.65 0.34 0.14]}); m = containers.Map( ... {'GK','RCB','LCB','MCB','RB','LB','RWB','LWB','CM','DM','LW','RW','LM','RM','AM','CF'}, ... {'GK','CB','CB','CB','FB','FB','FB','FB','CM','CM','W','W','W','W','W','ST'}); grpLbl = repmat("OTHER", numel(rawPos), 1); k = keys(m); for i = 1:numel(k) msk = rawPos == string(k{i}); if any(msk); grpLbl(msk) = string(m(k{i})); end end end