# =============================================================================
# Cardioversion_Multiscale -- Makefile
#
#   Run every target from the REPOSITORY ROOT.   Type  `make help`  to start.
#   README.md explains each stage and lists the target behind every figure.
#
# WHAT THIS REPRODUCES
#   Every figure and table of the paper, from the published data to final plots:
#     1. IN VITRO          per-cell biomarker tables (the published seed) -> statistics
#     2. IN SILICO CELLS   single-cell electroporation model (stages 01-06)
#     3. IN SILICO TISSUE  2-D slab reentry and the pore sweep (steps 0-5)
#   The three pipelines never share targets or output folders. TISSUE reads
#   exactly one output of CELLS (the phenotype medoids written by stage 06).
#   The in-vitro SEED is data/seed/in_vitro_cells/ (per-cell metadata and
#   biomarker tables). The raw optical recordings are NOT part of the repository,
#   so the extraction of the biomarkers from them is not reproduced here.
#
# QUICK START
#   make install                 once: pip install -e .
#   make check-imports           seconds: catches a broken install early
#   make all                     the whole paper, one command (SEVERAL DAYS)
#   make all DATADIR=/path/to/storage    same, heavy results on an external drive
#   make figures                 redraw the figures from results already on disk
#
# `make all` IS RESUMABLE
#   Every stage caches finished work. If the run is interrupted (power cut,
#   closed laptop, error), run the same command again and it continues where it
#   stopped. To start from scratch, move or delete results/ first.
#
# WHERE THINGS ARE WRITTEN (default names, nothing else is created)
#   results/in_silico_cells/{single_run,dt_convergence,sensitivity,database,
#                            inference_coverage,phenotype_identification}
#   results/in_silico_cells/database/sbi_training.db     the SBI training database
#   results/in_silico_tissue/                             tissue runs and logs
#   figures/in_vitro*/  figures/in_silico_cells/  figures/in_silico_tissue/
#   With DATADIR set, results/ go to $(DATADIR)/<repo name>/results/...
#   while figures always stay in the repository.
#
# SETTINGS YOU MAY WANT TO CHANGE (all can be given on the command line)
#   DATADIR=/path/to/storage   send heavy results to a drive (default: inside the repo)
#   NWORKERS=8             parallel workers for the single-cell stages
#   NP=10                  MPI cores per tissue simulation
#   LOAD_IMP=<path>       optional ionic-model dynamic library for single-cell and tissue runs
#   EXTRA="--flag value"   extra flags forwarded to the single-cell scripts
#   DB=<path>              use another database file for stages 05/06
#                          (default: results/in_silico_cells/database/sbi_training.db)
# =============================================================================

# `make` with no target prints the help, it never starts a multi-day run.
.DEFAULT_GOAL := help

PY       := python3
SCRIPTS  := experiments/in_vitro_cells/scripts
INSILICO := experiments/in_silico_cells/scripts
TISSUE   := experiments/in_silico_tissue/scripts

EXTRA    ?=
LOAD_IMP ?=
_LOAD_IMP_FLAG = $(if $(strip $(LOAD_IMP)),--load-imp "$(LOAD_IMP)")
NWORKERS ?= 8
SHARDS   ?= 4
DATADIR  ?=

# =============================================================================
# 1. SETTINGS
# =============================================================================

# -- SBI training database (cells, stage 04) ----------------------------------
# The paper database re-simulates a FIXED table of 75,000 parameter sets,
# DB_DESIGN: N_pores, tau_resealing and six conductance / pump scalings, on 1,000
# shared (N_pores, tau_resealing) pairs. The table is the parameter set of the
# database the paper's inference was run on. Re-simulating it with the current
# model and code gives the same inputs and fresh outputs, with no random draws.
# To draw a NEW design instead, leave DB_DESIGN empty (make insilico-database
# DB_DESIGN=). That route is then 100,000 simulations built on 20,000 distinct
# (N_pores, tau_resealing)
# combinations, i.e. 5 independent conductance draws per combination (the
# expensive high-voltage phase is simulated once per combination and reused).
#   N_pores        keeps the default sampling distribution.
#   tau_resealing  half of the combinations uniformly in [0, 10] s, the other
#                  half uniformly in [10, 120] s. (The lower bound is 1 ms, as
#                  tau = 0 is not a valid time constant.)
DB_SAMPLES  ?= 100000
DB_GRID     ?= 20000
DB_TAU_FLAGS := --tau-two-band --tau-low-frac 0.5 --tau-split-s 10 --tau-max-s 120
# The fixed design of the paper database. Empty = draw a new design (flags above).
DB_DESIGN   ?= data/design/design_paper_75k.csv.gz
ifneq ($(strip $(DB_DESIGN)),)
  _DBSAMPLING := --design-csv $(DB_DESIGN)
else
  _DBSAMPLING := --n-samples $(DB_SAMPLES) --n-protocol-grid $(DB_GRID) $(DB_TAU_FLAGS)
endif

# -- Sensitivity: phase-change / ensemble figures (see fig-cells-sensitivity-traces)
# Sweeps whose time-series figures are redrawn, and the parameters in them.
_SA_TAGS   := cond_nopores,cond_2pores,protocol_af100,protocol_csqnth_disabled
_SA_PARAMS := GNa,GK1,Gto,GKr,GKs,GCaL,maxINaK,maxINaCa,maxIpCa,factorGKur,N_pores,tau_resealing

# -- In-silico TISSUE ----------------------------------------------------------
# The substrate is CV 0.40 m/s with the anisotropy taken from the measured CV
# ratio, on an irregular mesh. Which slab, S1 BCL and S2 coupling interval host
# a rotor is not known in advance, so 'tissue-search' (step 0) finds them.
# (Comments sit on their own lines: a trailing comment would add spaces to the
#  value and corrupt the paths built from it.)
#
# slab side [mm] for a MANUAL 'make tissue-step1'; tissue-search ignores it
TIS_LEN      ?= 150
# target conduction velocity [m/s]
TIS_CV       ?= 0.40
# CV_long / CV_trans, measured in human atrium (Simmons/Pezzuto, 1.91 +/- 0.16).
# The transverse conductivities are tuned to CV / this value.
TIS_CVRATIO  ?= 1.91
# refractory period [ms] of the ionic model, measured. Sets the BCL plan, the
# wavelength and which S2 coupling intervals are tried. (Not APD90.)
TIS_ERP      ?= 190
# g_il / g_it for a manual run without a CV ratio; superseded by TIS_CVRATIO.
TIS_ANISO    ?= 2
# mesh resolution [mm] = TARGET MEAN EDGE LENGTH (what 'meshtool query edges'
# reports as "Edge lengths / Mean"). Not the node spacing of a square grid.
TIS_RES      ?= 0.375
# mesh: irregular = jittered Delaunay triangulation, regular = carputils Block mesher
TIS_MESH     ?= irregular
# irregular mesh point layout: hex = equilateral lattice, square = square grid (comparison only)
TIS_LATTICE  ?= hex
# node displacement as a fraction of the lattice pitch
TIS_JITTER   ?= 0.1
# seed of the irregular mesh (meshes are cached, so one seed = the same files)
TIS_SEED     ?= 1
# largest slab area to allow [cm^2] (unfolded atrial wall: 60-150 cm^2 per atrium)
TIS_MAXAREA  ?= 300
# S1 pacing cycle length [ms] for a MANUAL 'make tissue-step1'
TIS_BCL      ?= 600

# tissue-search (step 0): slab sides [mm] to try, ascending
TIS_SEARCH_LENS ?= 120,150,165
# S1 BCLs [ms] per slab; 'auto' is what step 1 would choose itself
TIS_SEARCH_BCLS ?= auto,600,500
# the rotor must still turn this long [ms] after the S2 to be accepted
TIS_MIN_LIFE ?= 6000
# ranks per step-2 candidate, so NP / this many coupling intervals run at once
TIS_SEARCH_NP ?= 5
# how many coupling intervals to try per (slab, BCL)
TIS_N_CI     ?= 8
# reject a combination whose tissue CV is further than this [%] from TIS_CV
TIS_CVTOL    ?= 15
# Vm output interval [ms] in step 1
TIS_SPACEDT  ?= 2
# S2 coupling interval [ms] that gives the stable rotor (manual step 2)
TIS_CI       ?= 340
# 1 = also re-run that CI as one continuous 5 s movie in step 2 (extra ~30 min)
TIS_REPLAY   ?= 0
# 1 s stages watched in step 2 (the pore sweep watches S2+1 s .. S2+6 s)
TIS_S2_STAGES ?= 7

# pore sweep (step 3): the model receives 8 x N pores
PHENO_CSV    ?= $(_DBASE)/phenotype_identification/phenotype_medoids_full_details.csv
TISSUE_PORES ?= 0,0.25,0.5,0.75,1,1.5,2.25,2.75,6
# gap-junction coupling at N = 1 in the reduced-CV (uncoupled) arm
GJ_REF       ?= 0.69
# which Vm movies step 3 keeps: videos = only the cells step 5 films (all that
# is read downstream), all = every one (hundreds of GB), prune = none
TIS_VM       ?= videos
# pore-sweep cells simulated at once, each on NP / this many ranks
TIS_WORKERS  ?= 2
# MPI cores per simulation
NP           ?= 10
# if set, step 4 also copies outcome_combined.png into this folder
PAPER_FIGDIR ?=
# ad-hoc flags forwarded verbatim to each tissue step, e.g.
#   TIS_EXTRA3="--only control-cv:*:*"    TIS_EXTRA2="--s2-strength 60"
TIS_EXTRA1   ?=
TIS_EXTRA2   ?=
TIS_EXTRA3   ?=
TIS_EXTRA5   ?=
# 1 = step 5 (videos) runs at the end of tissue-pipeline, 0 = skip it
TIS_VIDEOS   ?= 1
# cells to film, "arm:phenotype:N,...". ONE list for two steps: step 3 keeps the
# Vm movies of exactly these cells and step 5 films them, so they cannot drift.
# control-cv:0:0 is the untreated rotor (baseline); the rest are the paper examples.
TIS_VIDEO_CELLS ?= control-cv:0:0,control-cv:0:0.5,reduced-cv:0:0.5,reduced-cv:0:1.5,control-cv:3:1.5,reduced-cv:1:6

# =============================================================================
# 2. PATHS (derived from the settings above; normally nothing to edit)
# =============================================================================
ifdef DATADIR
  _TISBASE  := $(DATADIR)/$(notdir $(CURDIR))/results/in_silico_tissue
  _DBASE    := $(DATADIR)/$(notdir $(CURDIR))/results/in_silico_cells
else
  _TISBASE  := results/in_silico_tissue
  _DBASE    := results/in_silico_cells
endif
_TISFIG := figures/in_silico_tissue

# Default database used by stages 05 and 06 (override with DB=<path>)
DB        ?= $(_DBASE)/database/sbi_training.db
# In-vitro seed: the per-cell tables the whole in-vitro analysis (and the cells
# inference) starts from. They are versioned in SEED_DIR and copied to INVITRO_DB,
# where the scripts look for them by default (see `invitro-seed`).
SEED_DIR   := data/seed/in_vitro_cells
INVITRO_DB := data/processed/in_vitro_cells/main_database
SEED_TABLES := metadata_by_cell.csv biomarkers_prepost_by_cell.csv \
               biomarkers_hv_by_cell.csv biomarkers_by_cell.csv
INVITRO_BIOMARKERS := $(INVITRO_DB)/biomarkers_by_cell.csv

# Output folders of every cells stage. Without DATADIR the scripts use their own
# defaults (the same folders), so no flags are needed.
ifdef DATADIR
  _DIRFLAGS := --data-dir $(_DBASE)/single_run     --fig-dir figures/in_silico_cells/diagnostics
  _DTFLAGS  := --data-dir $(_DBASE)/dt_convergence --fig-dir figures/in_silico_cells/dt_convergence
  _SAFLAGS  := --data-dir $(_DBASE)/sensitivity    --fig-dir figures/in_silico_cells/sensitivity
  _DBFLAGS  := --data-dir $(_DBASE)/database       --fig-dir figures/in_silico_cells/database
else
  _DIRFLAGS :=
  _DTFLAGS  :=
  _SAFLAGS  :=
  _DBFLAGS  :=
endif
# Stage 05 reads the database and the in-vitro table; stage 06 additionally
# reuses stage 05's best-matches file instead of recomputing the matches.
_INFFLAGS  := --db $(DB) --csv $(INVITRO_BIOMARKERS) \
              --data-dir $(_DBASE)/inference_coverage \
              --fig-dir figures/in_silico_cells/inference_coverage
_PHENFLAGS := --db $(DB) --csv $(INVITRO_BIOMARKERS) \
              --best-matches-csv $(_DBASE)/inference_coverage/best_matches_per_cell.csv \
              --data-dir $(_DBASE)/phenotype_identification \
              --fig-dir figures/in_silico_cells/phenotype_identification

.PHONY: help all all-fast preflight install check-imports \
  invitro invitro-fast invitro-seed check \
  stats stats-fast hv-stats hv-stats-fast \
  insilico-cells insilico-cells-rerun insilico-cells-figures insilico-cells-fast \
  insilico-single insilico-dt insilico-sensitivity insilico-sensitivity-fast \
  insilico-sensitivity-full insilico-sensitivity-full2 insilico-sensitivity-parallel \
  insilico-database insilico-database-test insilico-database-figures \
  insilico-inference insilico-phenotype \
  insilico-tissue tissue-pipeline tissue-search tissue-step1 tissue-step2 \
  tissue-step3 tissue-extend tissue-step4 tissue-step5 tissue-where \
  figures figures-nosim figures-invitro figures-cells figures-tissue \
  fig-invitro-stats fig-invitro-hv \
  fig-cells-single fig-cells-dt fig-cells-sensitivity fig-cells-sensitivity-traces \
  fig-cells-database fig-cells-inference fig-cells-phenotype fig-cells-phenotype-nosim \
  fig-tissue-outcome \
  setup-external-storage clean-external-storage _ensure-storage \
  clean-insilico clean-insilico-figures clean-insilico-sensitivity clean-rerun-insilico \
  clean-insilico-database clean-rerun-insilico-database \
  clean-insilico-inference clean-rerun-insilico-inference \
  clean-insilico-phenotype clean-rerun-insilico-phenotype clean-insilico-tissue

# =============================================================================
# 3. THE FULL PAPER
# =============================================================================
# Runs the three pipelines in order (the order matters: tissue needs the
# phenotype medoids of cells stage 06, which needs the database of stage 04).
# Every figure and table of the paper is produced on the way; nothing else has
# to be run afterwards. Several days. Resumable: see the header.
all: preflight
	@echo "[all] 1/3  in vitro"
	$(MAKE) invitro
	@echo "[all] 2/3  in silico cells (single run, dt, sensitivity, database, inference, phenotypes)"
	$(MAKE) insilico-cells DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"
	@echo "[all] 3/3  in silico tissue"
	$(MAKE) insilico-tissue DATADIR="$(DATADIR)"
	@echo ""
	@echo "[all] finished. Figures: figures/   Results: $(_DBASE) and $(_TISBASE)"

# Quick smoke test of every pipeline (minutes to hours, NOT paper quality)
all-fast: preflight invitro-fast insilico-cells-fast insilico-tissue

# Fails early, before any long run, if the installation is broken.
preflight: check-imports
	@$(PY) -c "import carputils" 2>/dev/null || { echo "[preflight] carputils (openCARP) cannot be imported"; exit 1; }
	@if [ -f "$(DB)" ]; then echo "[preflight] found an existing database $(DB): it will be extended, not overwritten"; fi

# =============================================================================
# 4. HOUSEKEEPING
# =============================================================================
# After any change of the src/cardioversion layout, re-run `make install`.
install:
	$(PY) -m pip install -e .

# Imports every module of the package: a broken import shows up in seconds
# instead of hours into a pipeline. Runs no simulation.
CHECK_MODULES := cardioversion \
  cardioversion.in_vitro.io cardioversion.in_vitro.analysis \
  cardioversion.in_vitro.plotting cardioversion.in_vitro.stats \
  cardioversion.in_silico.cells cardioversion.in_silico.tissue
check-imports:
	@bad=0; for m in $(CHECK_MODULES); do \
	  if out=$$($(PY) -c "import $$m" 2>&1); then echo "  ok    $$m"; \
	  else echo "  FAIL  $$m -> $$(echo "$$out" | tail -1)"; bad=1; fi; \
	done; exit $$bad

# =============================================================================
# 5. IN-VITRO PIPELINE
# =============================================================================
# The raw optical-mapping recordings are not published, so the pipeline starts
# from the per-cell tables in $(SEED_DIR) (the authorised output of the
# biomarker extraction).
#
#   seed tables -> 01 group statistics (prepost table)
#               -> 02 V_norm vs HV transition metrics (merged table)
#               -> 03 cross-table consistency check
invitro: invitro-seed
	$(MAKE) -j2 stats hv-stats
	$(MAKE) check

invitro-fast: invitro-seed
	$(MAKE) -j2 stats-fast hv-stats-fast
	$(MAKE) check

# Copy the versioned seed tables to where the scripts read them. The seed is the
# single source of truth: this overwrites the copies in INVITRO_DB every time, so
# a hand-edited copy can never leak into a result.
invitro-seed:
	@for t in $(SEED_TABLES); do \
	  [ -s "$(SEED_DIR)/$$t" ] || { echo "[invitro] seed table $(SEED_DIR)/$$t not found"; exit 1; }; \
	done
	@mkdir -p $(INVITRO_DB)
	@for t in $(SEED_TABLES); do cp -f "$(SEED_DIR)/$$t" "$(INVITRO_DB)/$$t"; done
	@echo "[invitro] seed: $(SEED_TABLES) -> $(INVITRO_DB)"

# 01 group comparison: 10,000 permutations (paper numbers, slow)
stats: invitro-seed
	$(PY) $(SCRIPTS)/01_stats_biomarkers.py --n-permutations 10000 --n-jobs -1

# 01 with 100 permutations: sanity check only, not a number to report
stats-fast: invitro-seed
	$(PY) $(SCRIPTS)/01_stats_biomarkers.py --n-permutations 100 --n-jobs -1

# 02 V_norm vs HV transition metrics + figure
hv-stats: invitro-seed
	$(PY) $(SCRIPTS)/02_hv_stats.py

hv-stats-fast: invitro-seed
	$(PY) $(SCRIPTS)/02_hv_stats.py --no-figures

# QC: cross-table consistency checks
check: invitro-seed
	$(PY) $(SCRIPTS)/03_check_dataset.py

# -- Optional: link the output folders to an external drive -----------------
# Only needed for DATADIR runs; the cells targets above call it automatically.
ifdef DATADIR
_STORAGE_SUBS := \
  results/in_silico_cells/single_run results/in_silico_cells/dt_convergence \
  results/in_silico_cells/sensitivity results/in_silico_cells/database \
  results/in_silico_cells/inference_coverage results/in_silico_cells/phenotype_identification \
  figures/in_silico_cells/diagnostics figures/in_silico_cells/dt_convergence \
  figures/in_silico_cells/sensitivity figures/in_silico_cells/database \
  figures/in_silico_cells/inference_coverage figures/in_silico_cells/phenotype_identification
_ensure-storage:
	@for sub in $(_STORAGE_SUBS); do \
	  ext="$(DATADIR)/$(notdir $(CURDIR))/$$sub"; \
	  repo_dir="$(CURDIR)/$$sub"; \
	  mkdir -p "$$ext"; \
	  if [ ! -L "$$repo_dir" ]; then \
	    mkdir -p "$$(dirname $$repo_dir)"; \
	    if [ -d "$$repo_dir" ]; then \
	      rsync -a --remove-source-files "$$repo_dir/" "$$ext/" 2>/dev/null || true; \
	      rm -rf "$$repo_dir"; \
	    fi; \
	    ln -s "$$ext" "$$repo_dir"; \
	    echo "[storage] $$sub -> $$ext"; \
	  fi; \
	done
_STORAGE_DEP := _ensure-storage
else
_STORAGE_DEP :=
endif

setup-external-storage:
ifndef DATADIR
	$(error DATADIR is not set. Usage: make setup-external-storage DATADIR=/path/to/storage)
endif
	@echo "[storage] Setting up $(DATADIR)/$(notdir $(CURDIR))/"
	@$(MAKE) _ensure-storage DATADIR="$(DATADIR)"
	@echo "[storage] Done."

clean-external-storage:
ifndef DATADIR
	$(error DATADIR is not set. Usage: make clean-external-storage DATADIR=/path/to/storage)
endif
	@echo "[storage] Removing symlinks (data on the drive is NOT deleted)"
	@for sub in $(_STORAGE_SUBS); do \
	  repo_dir="$(CURDIR)/$$sub"; \
	  [ -L "$$repo_dir" ] && rm "$$repo_dir" && echo "  [rm]  $$sub" || true; \
	done

# =============================================================================
# 6. IN-SILICO CELLS PIPELINE   (stages 01-06, single cell)
# =============================================================================
#   01 single experiment + diagnostics      04 SBI training database
#   02 HV time-step convergence             05 coverage + ABC parameter inference
#   03 sensitivity: OAT + Sobol (full2)     06 phenotype identification (medoids)
# Stages 04-06 are resumable: re-running after an interruption, or after the
# database has grown, continues instead of repeating finished work.

# The whole cells pipeline, in order
insilico-cells: $(_STORAGE_DEP)
	$(MAKE) insilico-single       DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"
	$(MAKE) insilico-dt           DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"
	$(MAKE) insilico-sensitivity  DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"
	$(MAKE) insilico-database     DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"
	$(MAKE) insilico-inference    DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"
	$(MAKE) insilico-phenotype    DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"

# Same, ignoring every cache (re-simulates stages 01-04)
insilico-cells-rerun:
	$(MAKE) insilico-cells DATADIR="$(DATADIR)" EXTRA="--force-rerun $(EXTRA)"

# Redraw the cells figures only, no simulation
insilico-cells-figures:
	$(MAKE) figures-cells DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"

# Smoke test: minimal design, no full2, no database / inference / phenotypes
insilico-cells-fast: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/01_run_single_experiment.py --overview $(_DIRFLAGS) $(_LOAD_IMP_FLAG) $(EXTRA)
	$(PY) $(INSILICO)/02_dt_convergence.py --dts 1e-1 1e-2 1e-3 $(_DTFLAGS) $(EXTRA)
	$(PY) $(INSILICO)/03_sensitivity_analysis.py --mode fast --n-workers $(NWORKERS) $(_SAFLAGS) $(EXTRA)

# -- 01, 02 ---------------------------------------------------------------------
insilico-single: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/01_run_single_experiment.py --overview $(_DIRFLAGS) $(_LOAD_IMP_FLAG) $(EXTRA)

insilico-dt: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/02_dt_convergence.py $(_DTFLAGS) $(EXTRA)

# -- 03 sensitivity ---------------------------------------------------------------
# Default: full2 (N=256 Sobol base samples with second-order indices; for the 12
# default parameters N*(2*12+2) = 6,656 Sobol runs, plus the OAT sweeps). This
# run also draws the phase-change / ensemble figures of every OAT sweep.
insilico-sensitivity insilico-sensitivity-full2: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/03_sensitivity_analysis.py --mode full2 --n-workers $(NWORKERS) $(_SAFLAGS) $(EXTRA)

# N=16, quick screen (not paper quality)
insilico-sensitivity-fast: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/03_sensitivity_analysis.py --mode fast --n-workers $(NWORKERS) $(_SAFLAGS) $(EXTRA)

# N=64
insilico-sensitivity-full: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/03_sensitivity_analysis.py --mode full --n-workers $(NWORKERS) $(_SAFLAGS) $(EXTRA)

# Several shards in parallel on one machine, then one pass to merge and draw
insilico-sensitivity-parallel: $(_STORAGE_DEP)
	@echo "Launching $(SHARDS) sensitivity shards..."
	@for k in $$(seq 0 $$(( $(SHARDS) - 1 ))); do \
	  $(PY) $(INSILICO)/03_sensitivity_analysis.py --shard $$k --n-shards $(SHARDS) $(_SAFLAGS) $(EXTRA) & \
	done; wait
	$(PY) $(INSILICO)/03_sensitivity_analysis.py --figures-only $(_SAFLAGS) $(EXTRA)

# -- 04 SBI training database -------------------------------------------------
# Re-simulates the fixed design DB_DESIGN, or with DB_DESIGN empty draws
# DB_SAMPLES simulations on DB_GRID (N_pores, tau_resealing) combinations (tau
# design: see the settings section). Resumable: an interrupted run continues
# and finished simulations are not repeated. Then re-run stages 05 and 06.
insilico-database: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/04_database_generation.py $(_DBSAMPLING) \
	  --n-workers $(NWORKERS) $(_DBFLAGS) $(EXTRA)

# 100 simulations, to check the set-up before the long run
insilico-database-test: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/04_database_generation.py --mode test $(DB_TAU_FLAGS) \
	  --n-workers $(NWORKERS) $(_DBFLAGS) $(EXTRA)

insilico-database-figures: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/04_database_generation.py --figures-only $(_DBFLAGS) $(EXTRA)

# -- 05 coverage + ABC inference ----------------------------------------------
# Reads the database and the in-vitro biomarker table (seed); no simulation. Writes
# best_matches_per_cell.csv, which stage 06 reuses. Re-run it whenever the
# database changes. Does nothing (exit 0) if the database does not exist yet.
insilico-inference: $(_STORAGE_DEP) invitro-seed
	$(PY) $(INSILICO)/05_inference_coverage.py $(_INFFLAGS) $(EXTRA)

# -- 06 phenotype identification ----------------------------------------------
# Restricts to the Electroporation cells, takes their top-5 ABC matches from
# stage 05, runs PCA on the matched simulations' biomarkers + K=4 clustering,
# fits the anchored hyperbola of each conductance against N_pores (reported in
# the tables), and re-simulates one run per medoid for the trace figures (add
# EXTRA="--skip-trace-figures" to skip the simulations). Writes
# phenotype_medoids_full_details.csv (input of the tissue pipeline) and the
# paper tables under tables/.
insilico-phenotype: $(_STORAGE_DEP) invitro-seed
	$(PY) $(INSILICO)/06_phenotype_identification.py $(_PHENFLAGS) $(EXTRA)

# =============================================================================
# 7. IN-SILICO TISSUE PIPELINE   (2-D slab reentry + phenotype pore sweep)
# =============================================================================
# Operates only on experiments/in_silico_tissue/scripts and results/figures under
# in_silico_tissue/. The only input from cells is PHENO_CSV (stage 06).
#
# The scripts write time-stamped run folders. Each step records where its result
# went in $(_TISBASE)/latest/ and the next step reads it from there, so no path
# has to be copied by hand. The console output of every step is kept in
# $(_TISBASE)/logs/ (overwritten by the next run).
#
#   step 0  00_find_reentry.py     runs steps 1 and 2 over TIS_SEARCH_LENS x
#                                  TIS_SEARCH_BCLS x coupling intervals, stops at the
#                                  FIRST rotor still turning TIS_MIN_LIFE ms after the
#                                  S2, deletes every rejected attempt
#   step 1  01_prepace_and_cv.py   prepace cell, tissue S1 x3, CV/APD90 check, save state
#   step 2  02_s2_scan.py          4th S1 + S2 at TIS_CI only -> rotor (must be sustained)
#   step 3  03_pore_sweep.py       restart 1 s after the S2, pulse, sweep
#                                  phenotype x TISSUE_PORES x {control, uncoupled}
#   step 4  04_outcome_figure.py   outcome_combined.png + outcomes.csv + DF plots
#   step 5  05_make_videos.py      one mp4 per example cell (TIS_VIDEOS=0 skips it)
#
# `make tissue-pipeline` runs 0 -> 3 -> 4 -> 5. Steps 1 and 2 remain separate
# targets for one configuration by hand, when the slab, BCL and CI are known.

tissue-pipeline insilico-tissue:
	$(MAKE) tissue-search
	$(MAKE) tissue-step3
	$(MAKE) tissue-step4
ifeq ($(strip $(TIS_VIDEOS)),1)
	$(MAKE) tissue-step5
endif
	@echo ""
	@echo "[tissue] pipeline finished."
	@$(MAKE) --no-print-directory tissue-where

# -- step 0: find the rotor ---------------------------------------------------
# Writes latest/step1_info.txt and latest/step2_cidir.txt itself, exactly as
# steps 1 and 2 would, so step 3 cannot tell the difference.
tissue-search:
	@mkdir -p $(_TISBASE)/logs $(_TISBASE)/latest
	{ $(PY) -u $(TISSUE)/00_find_reentry.py --np $(NP) \
	    --search-np $(TIS_SEARCH_NP) \
	    --lens $(TIS_SEARCH_LENS) --bcls $(TIS_SEARCH_BCLS) \
	    --cv $(TIS_CV) --cv-ratio $(TIS_CVRATIO) --cv-tol-pct $(TIS_CVTOL) \
	    --erp-ms $(TIS_ERP) --min-life-ms $(TIS_MIN_LIFE) \
	    --s2-stages $(TIS_S2_STAGES) --n-ci $(TIS_N_CI) \
	    --spacedt $(TIS_SPACEDT) --max-area-cm2 $(TIS_MAXAREA) \
	    --resolution $(TIS_RES) \
	    --mesh-type $(TIS_MESH) --mesh-lattice $(TIS_LATTICE) \
	    --mesh-jitter $(TIS_JITTER) --mesh-seed $(TIS_SEED) \
	    --base $(_TISBASE) --fig-dir $(_TISFIG) --tissue-dir $(TISSUE) \
	    $(_LOAD_IMP_FLAG) --extra1 '$(TIS_EXTRA1)' --extra2 '$(TIS_EXTRA2)'; \
	  echo $$? > $(_TISBASE)/logs/search.rc; } 2>&1 | tee $(_TISBASE)/logs/search.log
	@rc="$$(cat $(_TISBASE)/logs/search.rc)"; \
	 case "$$rc" in \
	   0) ;; \
	   2) echo "[tissue] the search ran but no rotor lasted $(TIS_MIN_LIFE) ms. Every attempt is in $(_TISBASE)/search_summary.csv; the end of $(_TISBASE)/logs/search.log says which lever to try next."; exit 1 ;; \
	   *) echo "[tissue] the search STOPPED on a setup error (rc $$rc), this is not a result about the rotor. The traceback is at the end of $(_TISBASE)/logs/search.log."; exit 1 ;; \
	 esac
	@[ -s $(_TISBASE)/latest/step2_cidir.txt ] || { echo "[tissue] the search reported success but wrote no step2_cidir.txt"; exit 1; }
	@echo "[tissue] search done -> $$(cat $(_TISBASE)/latest/step2_cidir.txt)"

# -- step 1 (one configuration, by hand) ----------------------------------------
tissue-step1:
	@mkdir -p $(_TISBASE)/logs $(_TISBASE)/latest
	{ $(PY) -u $(TISSUE)/01_prepace_and_cv.py --np $(NP) \
	    --edgelength $(TIS_LEN) --cv $(TIS_CV) --cv-ratio $(TIS_CVRATIO) \
	    --erp-ms $(TIS_ERP) --max-area-cm2 $(TIS_MAXAREA) \
	    --resolution $(TIS_RES) \
	    --mesh-type $(TIS_MESH) --mesh-lattice $(TIS_LATTICE) \
	    --mesh-jitter $(TIS_JITTER) --mesh-seed $(TIS_SEED) \
	    --bcl $(TIS_BCL) --spacedt $(TIS_SPACEDT) \
	    --outdir $(_TISBASE)/step1 --fig-dir $(_TISFIG)/step1 $(_LOAD_IMP_FLAG) $(TIS_EXTRA1); \
	  echo $$? > $(_TISBASE)/logs/step1.rc; } 2>&1 | tee $(_TISBASE)/logs/step1.log
	@[ "$$(cat $(_TISBASE)/logs/step1.rc)" = "0" ] || { echo "[tissue] step 1 FAILED, see $(_TISBASE)/logs/step1.log"; exit 1; }
	@grep '^PREPACE_INFO=' $(_TISBASE)/logs/step1.log | tail -1 | cut -d= -f2- > $(_TISBASE)/latest/step1_info.txt
	@[ -s $(_TISBASE)/latest/step1_info.txt ] || { echo "[tissue] step 1 printed no PREPACE_INFO line"; exit 1; }
	@echo "[tissue] step 1 done -> $$(cat $(_TISBASE)/latest/step1_info.txt)"

# -- step 2 ----------------------------------------------------------------------
tissue-step2:
	@[ -s $(_TISBASE)/latest/step1_info.txt ] || { echo "[tissue] no step 1 result yet: run 'make tissue-step1'"; exit 1; }
	{ $(PY) -u $(TISSUE)/02_s2_scan.py --np $(NP) \
	    --prepace-info "$$(cat $(_TISBASE)/latest/step1_info.txt)" \
	    --only-ci $(TIS_CI) --n-stages $(TIS_S2_STAGES) --probe-y-frac 0.75 \
	    --erp-ms $(TIS_ERP) \
	    $(if $(filter 1,$(TIS_REPLAY)),,--no-replay) \
	    --outdir $(_TISBASE)/step2 --fig-dir $(_TISFIG)/step2 $(TIS_EXTRA2); \
	  echo $$? > $(_TISBASE)/logs/step2.rc; } 2>&1 | tee $(_TISBASE)/logs/step2.log
	@[ "$$(cat $(_TISBASE)/logs/step2.rc)" = "0" ] || { echo "[tissue] step 2 FAILED, see $(_TISBASE)/logs/step2.log"; exit 1; }
	@RUN=$$(grep '^OUTDIR=' $(_TISBASE)/logs/step2.log | tail -1 | cut -d= -f2-); \
	 CI="$$RUN/ci$(TIS_CI)"; \
	 [ -f "$$CI/metrics.json" ] || { echo "[tissue] no $$CI/metrics.json: did CI $(TIS_CI) run?"; exit 1; }; \
	 echo "$$CI" > $(_TISBASE)/latest/step2_cidir.txt; \
	 LAB=$$($(PY) -c "import json,sys; print(json.load(open(sys.argv[1]))['metrics']['label'])" "$$CI/metrics.json"); \
	 echo "[tissue] step 2: S2 at CI $(TIS_CI) ms -> $$LAB"; \
	 [ "$$LAB" = "reentry_sustained" ] || { echo "[tissue] the rotor did not survive, so the pore sweep would be meaningless. Try another TIS_CI (e.g. make tissue-step2 TIS_CI=310)."; exit 1; }

# -- step 3: pore sweep (the long one) ---------------------------------------------
tissue-step3:
	@[ -s $(_TISBASE)/latest/step2_cidir.txt ] || { echo "[tissue] no rotor yet: run 'make tissue-search' (or step 1 then step 2 by hand)"; exit 1; }
	@[ -s $(PHENO_CSV) ] || { echo "[tissue] $(PHENO_CSV) not found: run 'make insilico-phenotype' (cells stage 06) first"; exit 1; }
	{ $(PY) -u $(TISSUE)/03_pore_sweep.py --np $(NP) \
	    --ci-dir "$$(cat $(_TISBASE)/latest/step2_cidir.txt)" \
	    --phenotype-csv $(PHENO_CSV) --pore-values $(TISSUE_PORES) \
	    --gj-ref $(GJ_REF) --vm-policy $(TIS_VM) --workers $(TIS_WORKERS) \
	    --video-cells "$(TIS_VIDEO_CELLS)" \
	    --outdir $(_TISBASE)/step3 --fig-dir $(_TISFIG)/step3 $(_LOAD_IMP_FLAG) $(TIS_EXTRA3); \
	  echo $$? > $(_TISBASE)/logs/step3.rc; } 2>&1 | tee $(_TISBASE)/logs/step3.log
	@[ "$$(cat $(_TISBASE)/logs/step3.rc)" = "0" ] || { echo "[tissue] step 3 FAILED, see $(_TISBASE)/logs/step3.log"; exit 1; }
	@grep '^OUTDIR=' $(_TISBASE)/logs/step3.log | tail -1 | cut -d= -f2- > $(_TISBASE)/latest/step3_dir.txt
	@[ -s $(_TISBASE)/latest/step3_dir.txt ] || { echo "[tissue] step 3 printed no OUTDIR line"; exit 1; }
	@echo "[tissue] step 3 done -> $$(cat $(_TISBASE)/latest/step3_dir.txt)"

# -- step 3b: add pore values to the sweep that is already on disk ---------------
# Same prepace, rotor and restart state: only cells not on disk yet are
# simulated, and the heat maps are redrawn from old and new together.
# Widen TISSUE_PORES, then:  make tissue-extend  and  make tissue-step4 tissue-step5
tissue-extend:
	@[ -s $(_TISBASE)/latest/step3_dir.txt ] || { echo "[tissue] no sweep to extend: run 'make tissue-step3' first"; exit 1; }
	@[ -s $(_TISBASE)/latest/step2_cidir.txt ] || { echo "[tissue] no step 2 result; the extension must reuse the same rotor"; exit 1; }
	@echo "[tissue] extending $$(cat $(_TISBASE)/latest/step3_dir.txt) to TISSUE_PORES=$(TISSUE_PORES)"
	{ $(PY) -u $(TISSUE)/03_pore_sweep.py --np $(NP) \
	    --ci-dir "$$(cat $(_TISBASE)/latest/step2_cidir.txt)" \
	    --extend "$$(cat $(_TISBASE)/latest/step3_dir.txt)" \
	    --phenotype-csv $(PHENO_CSV) --pore-values $(TISSUE_PORES) \
	    --gj-ref $(GJ_REF) --vm-policy $(TIS_VM) --workers $(TIS_WORKERS) \
	    --video-cells "$(TIS_VIDEO_CELLS)" \
	    --fig-dir $(_TISFIG)/step3 $(_LOAD_IMP_FLAG) $(TIS_EXTRA3); \
	  echo $$? > $(_TISBASE)/logs/step3.rc; } 2>&1 | tee $(_TISBASE)/logs/extend.log
	@[ "$$(cat $(_TISBASE)/logs/step3.rc)" = "0" ] || { echo "[tissue] the extension FAILED, see $(_TISBASE)/logs/extend.log"; exit 1; }
	@echo "[tissue] extended -> $$(cat $(_TISBASE)/latest/step3_dir.txt)"
	@echo "[tissue] now: make tissue-step4 tissue-step5"

# -- step 4: outcome figure ----------------------------------------------------------
tissue-step4:
	@[ -s $(_TISBASE)/latest/step3_dir.txt ] || { echo "[tissue] no step 3 result yet: run 'make tissue-step3'"; exit 1; }
	$(PY) $(TISSUE)/04_outcome_figure.py \
	    --sweep-dir "$$(cat $(_TISBASE)/latest/step3_dir.txt)" \
	    --fig-dir $(_TISFIG)/step3 --only-n $(TISSUE_PORES)
ifneq ($(strip $(PAPER_FIGDIR)),)
	mkdir -p "$(PAPER_FIGDIR)"
	cp $(_TISFIG)/step3/outcome_combined.png "$(PAPER_FIGDIR)/outcome_combined.png"
	@echo "[tissue] copied outcome_combined.png -> $(PAPER_FIGDIR)"
endif
	@echo "[tissue] figure: $(_TISFIG)/step3/outcome_combined.png"

# -- step 5: videos ------------------------------------------------------------------
# Needs the vm.igb files step 3 kept (exactly the TIS_VIDEO_CELLS it was given).
# A cell outside that list is skipped with a note.
tissue-step5:
	@[ -s $(_TISBASE)/latest/step3_dir.txt ] || { echo "[tissue] no step 3 result yet: run 'make tissue-step3'"; exit 1; }
	$(PY) -u $(TISSUE)/05_make_videos.py \
	    --sweep-dir "$$(cat $(_TISBASE)/latest/step3_dir.txt)" \
	    --ci-dir "$$(cat $(_TISBASE)/latest/step2_cidir.txt)" \
	    --out-dir $(_TISFIG)/step3/videos \
	    --cells "$(TIS_VIDEO_CELLS)" $(TIS_EXTRA5)
	@echo "[tissue] videos: $(_TISFIG)/step3/videos"

# Which run each step will pick up (no timestamps to look for)
tissue-where:
	@for f in step1_info step2_cidir step3_dir; do \
	  p="$(_TISBASE)/latest/$$f.txt"; \
	  if [ -s "$$p" ]; then echo "  $$f: $$(cat $$p)"; else echo "  $$f: (not run yet)"; fi; \
	done
	@w="$(_TISBASE)/latest/search_winner.txt"; \
	 if [ -s "$$w" ]; then echo ""; echo "  the search settled on:"; sed 's/^/    /' "$$w"; fi

# =============================================================================
# 8. FIGURES ONLY: redraw paper figures from results already on disk
# =============================================================================
#   make figures                everything below
#   make figures-nosim          everything except the steps that call openCARP
#   make figures-invitro | figures-cells | figures-tissue
#   make fig-<pipeline>-<name>  one figure family (see `make help`)
#
# Nothing here repeats the long jobs (no permutation statistics, Sobol design,
# database build or tissue sweep). Two families do a little work:
#   fig-cells-sensitivity-traces  re-runs the few openCARP runs behind the
#                                 phase-change / ensemble time-series figures
#   fig-cells-phenotype           re-runs the 4 medoid simulations for the trace figures
figures: figures-invitro figures-cells figures-tissue
	@echo ""
	@echo "[figures] done. In vitro: figures/in_vitro*   cells: figures/in_silico_cells   tissue: $(_TISFIG)"

figures-nosim: fig-invitro-stats fig-invitro-hv \
               fig-cells-single fig-cells-dt fig-cells-sensitivity fig-cells-database \
               fig-cells-inference fig-cells-phenotype-nosim fig-tissue-outcome

# -- in vitro ---------------------------------------------------------------------
figures-invitro: fig-invitro-stats fig-invitro-hv

# box plot, V_norm violins, normality plots, LaTeX tables; statistics are read
# from the saved group_comparison_mixed_model.csv, never recomputed
fig-invitro-stats: invitro-seed
	$(PY) $(SCRIPTS)/01_stats_biomarkers.py --figures-only

fig-invitro-hv: invitro-seed
	$(PY) $(SCRIPTS)/02_hv_stats.py

# -- in-silico cells ----------------------------------------------------------------
figures-cells: fig-cells-single fig-cells-dt fig-cells-sensitivity fig-cells-sensitivity-traces \
               fig-cells-database fig-cells-inference fig-cells-phenotype

fig-cells-single: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/01_run_single_experiment.py --overview --figures-only $(_DIRFLAGS) $(_LOAD_IMP_FLAG) $(EXTRA)

fig-cells-dt: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/02_dt_convergence.py --figures-only $(_DTFLAGS) $(EXTRA)

# heat maps and OAT / protocol curves, from the saved sensitivity results
fig-cells-sensitivity: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/03_sensitivity_analysis.py --figures-only $(_SAFLAGS) $(EXTRA)

# Phase-change and ensemble-average time series (phase_change/<sweep>/phase_*.png,
# ensemble_*.png). They need traces, so 5 values per parameter are re-simulated
# (the saved OAT results are reused, Sobol is skipped). Narrow it down, e.g.
#   make fig-cells-sensitivity-traces TAGS=cond_nopores PARAMS=Gto,GKr
# Sweep names: cond_nopores, cond_2pores, cond_10pores, protocol_af100,
# protocol_csqnth_disabled.
fig-cells-sensitivity-traces: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/03_sensitivity_analysis.py --mode full2 --skip-sobol \
	  --only-tags $(or $(TAGS),$(_SA_TAGS)) \
	  --only-params $(or $(PARAMS),$(_SA_PARAMS)) \
	  --n-workers $(NWORKERS) --phase-workers 2 $(_SAFLAGS) $(EXTRA)

fig-cells-database: $(_STORAGE_DEP)
	$(PY) $(INSILICO)/04_database_generation.py --figures-only $(_DBFLAGS) $(EXTRA)

fig-cells-inference: $(_STORAGE_DEP) invitro-seed
	$(PY) $(INSILICO)/05_inference_coverage.py $(_INFFLAGS) $(EXTRA)

fig-cells-phenotype: $(_STORAGE_DEP) invitro-seed
	$(PY) $(INSILICO)/06_phenotype_identification.py $(_PHENFLAGS) $(EXTRA)

# analysis, tables and scatter only: skips the medoid simulations
fig-cells-phenotype-nosim: $(_STORAGE_DEP) invitro-seed
	$(PY) $(INSILICO)/06_phenotype_identification.py $(_PHENFLAGS) --skip-trace-figures $(EXTRA)

# -- in-silico tissue -----------------------------------------------------------------
figures-tissue: fig-tissue-outcome

# redraws outcome_combined.png + DF plots from the sweep already on disk
fig-tissue-outcome: tissue-step4

# =============================================================================
# 9. CLEAN
# =============================================================================
# CELLS (never touches in-vitro or tissue). The database, inference and
# phenotype outputs are NEVER removed by clean-insilico (they take hours to
# build); each has its own explicit clean target.
clean-insilico-figures:
	rm -rf figures/in_silico_cells
	@echo "[clean] In-silico cells figures deleted."

clean-insilico-sensitivity:
	rm -rf $(_DBASE)/sensitivity figures/in_silico_cells/sensitivity
	@echo "[clean] Sensitivity results + figures deleted."

clean-insilico:
	rm -rf $(_DBASE)/single_run $(_DBASE)/dt_convergence $(_DBASE)/sensitivity \
	       figures/in_silico_cells/diagnostics figures/in_silico_cells/dt_convergence \
	       figures/in_silico_cells/sensitivity
	@echo "[clean] single_run / dt_convergence / sensitivity deleted."
	@echo "[clean] database, inference and phenotype outputs were NOT touched."

clean-rerun-insilico:
	$(MAKE) clean-insilico DATADIR="$(DATADIR)"
	$(MAKE) insilico-cells DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"

clean-insilico-database:
	rm -rf $(_DBASE)/database figures/in_silico_cells/database
	@echo "[clean] SBI database deleted."

clean-rerun-insilico-database:
	$(MAKE) clean-insilico-database DATADIR="$(DATADIR)"
	$(MAKE) insilico-database       DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"

clean-insilico-inference:
	rm -rf $(_DBASE)/inference_coverage figures/in_silico_cells/inference_coverage
	@echo "[clean] Inference/coverage output deleted."

clean-rerun-insilico-inference:
	$(MAKE) clean-insilico-inference DATADIR="$(DATADIR)"
	$(MAKE) insilico-inference       DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"

clean-insilico-phenotype:
	rm -rf $(_DBASE)/phenotype_identification figures/in_silico_cells/phenotype_identification
	@echo "[clean] Phenotype-identification output deleted."

clean-rerun-insilico-phenotype:
	$(MAKE) clean-insilico-phenotype DATADIR="$(DATADIR)"
	$(MAKE) insilico-phenotype       DATADIR="$(DATADIR)" EXTRA="$(EXTRA)"

# TISSUE (never touches cells or in-vitro)
clean-insilico-tissue:
	rm -rf $(_TISBASE) $(_TISFIG)
	@echo "[clean] In-silico tissue results + figures deleted."

# =============================================================================
# 10. HELP
# =============================================================================
help:
	@echo ""
	@echo "  Cardioversion_Multiscale. Run every target from the repository root."
	@echo ""
	@echo "  THE WHOLE PAPER"
	@echo "    make all                         in vitro + cells + tissue, every figure and table (days)"
	@echo "    make all DATADIR=/path/to/storage same, heavy results on an external drive"
	@echo "    make all-fast                    smoke test of every pipeline (not paper quality)"
	@echo "    (an interrupted run continues where it stopped: just run the same command)"
	@echo ""
	@echo "  SET-UP"
	@echo "    make install                     pip install -e ."
	@echo "    make check-imports               import every module, no simulation"
	@echo ""
	@echo "  FIGURES ONLY (no statistics rerun, no database, no sweep)"
	@echo "    make figures                     redraw every figure from results on disk"
	@echo "    make figures-nosim               same, skipping the steps that call openCARP"
	@echo "    make figures-invitro | figures-cells | figures-tissue"
	@echo "    make fig-invitro-stats | fig-invitro-hv"
	@echo "    make fig-cells-single | dt | sensitivity | sensitivity-traces | database | inference | phenotype"
	@echo "    make fig-tissue-outcome"
	@echo ""
	@echo "  IN VITRO"
	@echo "    make invitro                     seed tables -> stats, hv-stats, check"
	@echo "    make invitro-fast                same, quick settings"
	@echo "    make invitro-seed                copy $(SEED_DIR) to $(INVITRO_DB)"
	@echo ""
	@echo "  IN SILICO CELLS (stages 01-06)"
	@echo "    make insilico-cells              all stages in order"
	@echo "    make insilico-single | dt        01 single experiment | 02 dt convergence"
	@echo "    make insilico-sensitivity        03 OAT + Sobol (also: -fast, -full, -parallel)"
	@echo "    make insilico-database           04 database: $(if $(DB_DESIGN),re-simulate the fixed design of 75000 sets,$(DB_SAMPLES) simulations on $(DB_GRID) protocol pairs)"
	@echo "    make insilico-database-test      04 with 100 simulations, to test the set-up"
	@echo "    make insilico-inference          05 coverage + ABC inference"
	@echo "    make insilico-phenotype          06 phenotype medoids, tables and trace figures"
	@echo "    make insilico-cells-rerun        everything, ignoring caches"
	@echo "    make clean-insilico              delete single_run, dt and sensitivity results + figures"
	@echo "    make clean-insilico-database | clean-insilico-inference | clean-insilico-phenotype"
	@echo ""
	@echo "  IN SILICO TISSUE (2-D slab reentry; needs cells stage 06)"
	@echo "    make tissue-pipeline             search for a rotor, then steps 3, 4, 5"
	@echo "    make tissue-search               step 0: find slab + BCL + CI that sustain a rotor"
	@echo "    make tissue-step1|2|3|4|5        one step; each finds the previous result itself"
	@echo "    make tissue-extend               add pore values to the sweep on disk"
	@echo "    make tissue-where                show which run each step will use"
	@echo "    make clean-insilico-tissue       delete ALL tissue results + figures"
	@echo ""
	@echo "  OPTIONS (append to any command)"
	@echo "    DATADIR=/path/to/storage         heavy results to a drive (default: inside the repo)"
	@echo "    NWORKERS=8                       cells parallel workers"
	@echo "    LOAD_IMP=<path>                  ionic-model library for the single-cell run and tissue pipeline"
	@echo "    NP=10                            tissue MPI cores per simulation"
	@echo "    DB=<path>                        database for stages 05/06 (default $(DB))"
	@echo "    EXTRA=\"--flag value\"             extra flags for the cells scripts"
	@echo "    TAGS= PARAMS=                    narrow fig-cells-sensitivity-traces"
	@echo "    tissue: TIS_CV=$(TIS_CV) TIS_ERP=$(TIS_ERP) TIS_RES=$(TIS_RES) TISSUE_PORES=$(TISSUE_PORES) TIS_VM=$(TIS_VM)"
	@echo ""
