# p_astro pipeline for the small-sky testbed:
#   4 component mass models -> combined+validated model -> decision-surface map
#
#   make        # builds everything (component builds take ~15 min each)
#   make plot   # just the map, once pastro-model.h5 exists
#
# Normalization: 150 detected events/yr anchored at a 160 Mpc fiducial-BNS
# range, counting threshold 1/yr, live range = the anchor range.  chi uses
# the built-in default 0.037 -- the ensemble self-consistency fit on the
# reference injection campaign (agrees with crossover density matching to
# ~3%; crossover chi*150 = 5.5/yr).  Override with --far-calibration after
# refitting (pastro.fit_far_calibration) when the ranking statistic or its
# FAR normalization changes.  See the chi section of docs/user-guide/pastro.md.

# The refined small-sky bank, built by ../Makefile on demand.
BANK = ../small-sky-bank-refined.h5
BUILD_FLAGS = --processes 6 --window 50000 --match-dispersion 0.1 --verbose

# Recovered injections of the reference campaign as (FAR Hz, network SNR)
# pairs, for the rho(FAR) calibration: 934,890 rows, 34 MB.  Fetched on
# first use from LIGO-T2600332-v3 ("IR1 AllSky SGNL Mass-Model & P-Astro"),
# md5 04fa446a11c03cb182fb5a23cdc5fa5d; git-ignored.
FARSNR = far_snr.txt
FAR_SNR_URL ?= https://dcc.ligo.org/public/0209/T2600332/003/far_snr.txt

FAR = 3.2e-8

all : plot

$(BANK) :
	$(MAKE) -C $(dir $@) $(notdir $@)

$(FARSNR) :
	curl -fSL -o $@.tmp '$(FAR_SNR_URL)' && mv $@.tmp $@

%.h5 : %.yaml $(BANK)
	sgn-manifold-cbc-bank-mass-model --bank $(BANK) --yaml $< --output-h5 $@ $(BUILD_FLAGS)

pastro-model.h5 : bns.h5 nsbh.h5 bbh.h5 pop.h5 $(FARSNR)
	sgn-manifold-cbc-p-astro-combine \
		--bns bns.h5 --nsbh nsbh.h5 --bbh bbh.h5 --pop pop.h5 \
		--far-snr $(FARSNR) \
		--output-h5 $@ --verbose

plot : pastro-model.h5
	sgn-manifold-cbc-p-astro-plot \
		--model pastro-model.h5 \
		--event-rate 150 --event-rate-range-mpc 160 \
		--event-rate-far 3.17e-8 \
		--bns-range-mpc 160 \
		--far $(FAR) \
		--output-prefix smallsky

# p_astro vs FAR operating curves for one representative template per region
plot-far : pastro-model.h5
	for sel in "1.4 1.4 bns" "10 1.4 nsbh" "35 30 bbh"; do \
		set -- $$sel; \
		sgn-manifold-cbc-p-astro-plot \
			--model pastro-model.h5 \
			--event-rate 150 --event-rate-range-mpc 160 \
			--event-rate-far 3.17e-8 \
			--bns-range-mpc 160 \
			--m1 $$1 --m2 $$2 \
			--output-prefix smallsky-$$3; \
	done

clean :
	rm -f bns.h5 nsbh.h5 bbh.h5 pop.h5 pastro-model.h5 *.png

# also drop the downloaded campaign
distclean : clean
	rm -f $(FARSNR)

.PHONY : all plot plot-far clean distclean
