#################################################################################
# VSSL data analysis — reproduces the behavioural analyses and all Python-rendered
# figures of the paper. Run `make help` for the list of targets.
#################################################################################

PYTHON_INTERPRETER ?= $(if $(wildcard ./venv/bin/python),./venv/bin/python,python)
SOURCE_DIRS = src_paper tests

# --- Analysis parameters (values used in the paper) ---------------------------
# median split of head motion in m/frame (Methods, "Motion tracking")
motion_threshold        = 0.000036725
remove_participants     = 0
save_fig                = True
save_type               = pdf
line_fit_method         = mixedlm
sound_types             = rippled white
motion_categories       = no_motion motion
experiment_name         = default
include_sound_durations_over_1s = False

# Bayesian two-ear-summation observer (Methods, "Bayesian summation observer")
posterior_variance_mode = raw_test
prior_mode              = monaural_fitted
fixed_prior_std         = 100.0

common_args = --motion_threshold=$(motion_threshold) --save_fig=$(save_fig) \
	--save_type=$(save_type) --experiment_name=$(experiment_name)

bayesian_args = \
	--sound_types $(sound_types) \
	--motion_categories $(motion_categories) \
	--motion_threshold=$(motion_threshold) \
	--fitting_method=fit_posterior_mean \
	--experiment_name=$(experiment_name) \
	--fit_method=$(line_fit_method) \
	--posterior_variance_mode=$(posterior_variance_mode) \
	--prior_mode=$(prior_mode) \
	--fixed_prior_std=$(fixed_prior_std)

#################################################################################
# Setup
#################################################################################

## Install Python dependencies (into the active environment)
.PHONY: requirements
requirements:
	$(PYTHON_INTERPRETER) -m pip install -U pip
	$(PYTHON_INTERPRETER) -m pip install -r requirements.txt

## Run the unit tests
.PHONY: test
test:
	$(PYTHON_INTERPRETER) -m pytest -q

## Lint with flake8 / isort / black
.PHONY: lint
lint:
	flake8 src_paper tests
	isort --check --diff --profile black $(SOURCE_DIRS)
	black --check --config pyproject.toml $(SOURCE_DIRS)

## Delete compiled Python files
.PHONY: clean
clean:
	find . -type f -name "*.py[co]" -delete
	find . -type d -name "__pycache__" -delete

#################################################################################
# 1. Data processing
#################################################################################

## Process raw behavioural + motion data of both experiments -> data/processed/
.PHONY: process_data
process_data:
	$(PYTHON_INTERPRETER) src_paper/data/process_default_experiment.py --remove_participants $(remove_participants) --motion_threshold=$(motion_threshold)
	$(PYTHON_INTERPRETER) src_paper/data/process_localization_data_motion_exp.py --remove_participants $(remove_participants) --motion_threshold=$(motion_threshold)

## Fit the Bayesian two-ear-summation observer -> data/processed/bayesian_models/
.PHONY: fit_bayesian_model
fit_bayesian_model:
	$(PYTHON_INTERPRETER) src_paper/models/fit_posterior_mean.py $(bayesian_args) --save_fig=False

#################################################################################
# 2. Figures (written to reports/figures/paper_figures/)
#################################################################################

## Fig. 3a-f: human vs model regression, gain and SD (structured noise / white noise)
.PHONY: fig3
fig3:
	$(PYTHON_INTERPRETER) src_paper/visualization/all_participants/paper_main_figure.py $(common_args) --data_source=rippled

## Fig. 3h-i: human-model comparison of gain and SD (+ main-effect marginals)
.PHONY: fig3hi
fig3hi:
	$(PYTHON_INTERPRETER) src_paper/visualization/all_participants/sd_boxplots.py $(common_args) --data_source=rippled

## Fig. 4: head-motion control experiment (a: head velocity, b-d: regression / gain / SD)
.PHONY: fig4
fig4:
	$(PYTHON_INTERPRETER) src_paper/visualization/motion_experiment/plot_velocity_trajectories.py --save_fig=$(save_fig) --save_type=$(save_type) --experiment_name=$(experiment_name) --include_sound_durations_over_1s=$(include_sound_durations_over_1s)
	$(PYTHON_INTERPRETER) src_paper/visualization/motion_experiment/paper_motion_duration_by_condition_figure.py --save_fig=$(save_fig) --save_type=$(save_type) --experiment_name=$(experiment_name)

## Supp. Fig. S2: distribution of head velocity and motion / no-motion split
.PHONY: figS2
figS2:
	$(PYTHON_INTERPRETER) src_paper/visualization/all_participants/motion_histogram_all.py $(common_args)

## Supp. Fig. S3a-c, e: model with natural sounds (123 HRTFs x 215 sounds)
.PHONY: figS3
figS3:
	$(PYTHON_INTERPRETER) src_paper/visualization/cipic_model/plot_model_regression_SD.py $(common_args) --data_source=all
	$(PYTHON_INTERPRETER) src_paper/visualization/cipic_model/model_gain_correlation.py --save_fig=$(save_fig) --save_type=$(save_type) --experiment_name=$(experiment_name) --data_source=all --motion_categories no_motion motion

## Supp. Fig. S3f: motion benefit vs temporal window and head displacement
.PHONY: figS3f
figS3f:
	$(PYTHON_INTERPRETER) src_paper/visualization/cipic_model/dt_true_motion_step_sweep_gain.py --save_fig=$(save_fig) --save_type=$(save_type) --experiment_name=$(experiment_name) --stimulus_group=natural

## Supp. Fig. S4: effect of early / late noise on the model
.PHONY: figS4
figS4:
	$(PYTHON_INTERPRETER) src_paper/visualization/cipic_model/snr_sweep_localization.py --save_fig=$(save_fig) --save_type=$(save_type) --experiment_name=$(experiment_name) --data_source=rippled

#################################################################################
# 3. Statistics reported in the text (written to reports/stats/default/)
#################################################################################

## Paired t-tests with JZS Bayes factors (r = 0.707): main experiment, per condition and
## motion vs no motion (gain and SD), plus the head-motion control experiment
.PHONY: stats
stats:
	$(PYTHON_INTERPRETER) src_paper/visualization/all_participants/overall_condition_gain_comparison.py $(common_args) --data_source=rippled --metric=gain
	$(PYTHON_INTERPRETER) src_paper/visualization/all_participants/overall_condition_gain_comparison.py $(common_args) --data_source=rippled --metric=sd
	$(PYTHON_INTERPRETER) src_paper/visualization/motion_experiment/paper_motion_experiment_figure.py --save_fig=$(save_fig) --save_type=$(save_type) --experiment_name=$(experiment_name)

## All Python-rendered paper figures (expects processed data and model CSVs)
.PHONY: paper_figures
paper_figures: fig3 fig3hi fig4 figS2 figS3 figS3f figS4

## Everything from raw data: process data, fit the observer, figures and statistics
.PHONY: all
all: process_data fit_bayesian_model paper_figures stats

## Demo (no download needed): model regression / gain / SD figure from the demo subset in demo/
.PHONY: demo
demo:
	$(PYTHON_INTERPRETER) src_paper/visualization/cipic_model/plot_model_regression_SD.py \
		--motion_threshold=$(motion_threshold) --save_fig=$(save_fig) --save_type=$(save_type) \
		--experiment_name=demo --data_source=rippled \
		--model_data_file=demo/scatter_group_mean_localization_raw_demo.csv \
		--model_prediction_file=demo/scatter_group_mean_localization_lr_raw_demo.csv

#################################################################################
# Self-documenting help
#################################################################################

.DEFAULT_GOAL := help

define PRINT_HELP_PYSCRIPT
import re, sys; \
lines = '\n'.join([line for line in sys.stdin]); \
matches = re.findall(r'\n## (.*)\n[\s\S]+?\n([a-zA-Z0-9_-]+):', lines); \
print('Available rules:\n'); \
print('\n'.join(['{:25}{}'.format(*reversed(match)) for match in matches]))
endef
export PRINT_HELP_PYSCRIPT

help:
	@$(PYTHON_INTERPRETER) -c "${PRINT_HELP_PYSCRIPT}" < $(MAKEFILE_LIST)
