diff --git a/release_tests/montecarlo/mc_data_comparison/README.md b/release_tests/montecarlo/mc_data_comparison/README.md index 5fcd741..3b48245 100644 --- a/release_tests/montecarlo/mc_data_comparison/README.md +++ b/release_tests/montecarlo/mc_data_comparison/README.md @@ -7,7 +7,7 @@ Scripts and tools to compare Monte Carlo (MC) distributions with observational r ## Quick Start ```console -./compareDatawithMC.sh +./compareDatawithMC.sh ``` Where `` specifies the observation conditions: @@ -24,7 +24,8 @@ NOTE! The zenith angle bins are different compared to those used in the Crab Neb ### Input Data Requirements - MC simulation files for each minor epoch (organized by atmosphere type) -- Crab Nebula mscw results and matching `*.mscw.xgb_stereo.root` files for each run +- Crab Nebula mscw results; XGB comparisons also need matching MC and Crab + stereo friend files for the chosen suffixes - Run lists for Crab observations (generated separately) ## Preparation Steps @@ -57,11 +58,45 @@ The leading `*` is part of the parameter-file syntax. To provide multiple atmosp ### Step 2: Execute Comparison +Choose a comparison configuration from `configs/`. For example, from this +folder run the mscw-smeared XGB comparison with: + ```console -cd release_tests/montecarlo/mc_data_comparison/ -./compareDatawithMC.sh SZE +./compareDatawithMC.sh ../../../../EventDisplay_Release_v492/runparameter/V6.AP.runparameter.precuts.dat SZE configs/mscw-smear-v1-xgb.conf +``` + +The provided cases are: + +| Configuration | MC mscw | Reconstruction | +| --- | --- | --- | +| `configs/nominal-dispbdt.conf` | Nominal | DispBDT | +| `configs/nominal-xgb.conf` | Nominal | XGB without ML smearing | +| `configs/ml-smear05-xgb.conf` | Nominal | XGB with ML-level smear05 | +| `configs/mscw-smear-v1-dispbdt.conf` | mscw-smear v1 | DispBDT | +| `configs/mscw-smear-v1-xgb.conf` | mscw-smear v1 | XGB from the smeared mscw | + +A configuration is a plain text file, for example: + +```text +variant = mscwsmear_v1 +mscw_directory = MSCW_RECID0_DISP_mscwsmear_v1 +reconstruction = XGB +mc_xgb_suffix = xgb_stereo +data_xgb_suffix = xgb_stereo ``` +Copy and edit a configuration for another case. `variant` labels the output; +`mscw_directory` is the actual directory under each +`_ATM_gamma`. Both use letters, numbers, underscores or +hyphens. `reconstruction` is `XGB` or `DispBDT`. The suffixes identify MC and +Crab friend files; both default to `xgb_stereo` and are unused for DispBDT. +The same mscw directory name must exist for each selected epoch and atmosphere. +Separate MC/data suffixes require the updated `compareDatawithMC` executable. + +A label does not verify the smearing recipe. Inspect the production logs and +settings and ensure each MC friend was generated from its adjacent mscw file. +The wrapper does not run inference. The worker uses energy method 0. + This will: 1. Parse the run parameter file @@ -73,25 +108,59 @@ This will: ### Step 3: Monitor Progress - Condor jobs are submitted with resource requests: 4000MB RAM, 10GB disk -- Temporary symbolic links are created in: `{output_dir}/tmp/{uuid}/` +- Temporary symbolic links are created in: `{output_dir}/tmp/` - **Note**: Temporary directories must be cleaned up manually after completion ## Output Structure -Results are written to: +Each result is stored directly in its runlist directory, for example: ```text -EventDisplay_Release_/mc_data_comparison/// -├── _ATM___/ -│ ├── mcdatacomparison.runparameter -│ ├── mcdatacomparison.root -│ ├── mcdatacomparison.log -│ └── *.pdf # Comparison plots -└── tmp/ # Temporary symlinks (manual cleanup required) +mc_data_comparison/AP_DISP/CARE_202404/ +└── MC-nominal/XGB/MC-xgb_stereo/DATA-xgb_stereo/ + └── V6_2023_2024w_MC-ATM61_SZE_wobble0.5_NSB400/ + └── data-ATM61/ + ├── comparison.conf + ├── comparison-settings.txt + ├── input-runparameter.dat + ├── crab-runlist.dat + ├── mcdatacomparison.runparameter + ├── mcdatacomparison.root + ├── mcdatacomparison.log + └── tmp/ # includes the generated worker and Condor logs ``` +`MC-mscwsmear_v1` separates the mscw-smeared input, while the XGB suffix +separates ML-only variants. Each submission records resolved MC and data paths, +friend paths, and input settings; inspect the saved worker script for its exact +cut and reconstruction parameters. Preserve the production logs and smearing +configuration separately: a name alone does not establish provenance. A repeated submission to an existing result directory is rejected; move or remove the existing directory before submitting again. Previous outputs are not moved or relabeled. The +`data-ATM61` and `data-generic-runlist` directories represent different Crab +runlists; the generic list is not necessarily restricted to that atmosphere. + +The PDF includes an exploratory r68 versus reconstructed-energy page for MC +and ON−OFF excess. It counts the 68% quantile in the existing linear-theta² +histograms and does not extrapolate the tail. It is therefore the containment +inside the selected theta² cut, not an estimate of the untruncated PSF. The standalone ROOT macro compares two saved configurations: + +```console +root -l -b -q 'compare_containment.C("configs/nominal-xgb.conf","configs/ml-smear05-xgb.conf")' +``` + +It searches `../../../../EventDisplay_Release_v492/mc_data_comparison` for +completed results with matching saved configurations. Optional third and fourth +arguments set the search directory and output PDF. Each configuration must +match exactly one result; ambiguous matches are listed. The MC curves and the +Crab excess from each result are plotted. MC points use filled markers and +Crab points use open markers in the matching color. Check that the selected results +use comparable Crab runlists and observing conditions. Older outputs without +saved configurations cannot be found. All inputs must have matching +`angularTheta2Cut` metadata. The within-bin error estimate is not a statistical +containment uncertainty; use run bootstrapping for that. + ## Special Cases -- **CARE_RedHV simulations**: Handled with modified BDT cut (BDT=0 instead of 1) +- **Gamma/hadron BDT**: The current worker script sets `BDT=0`; inspect its + `BDT` setting when choosing gamma/hadron cuts independently of direction reconstruction. - **Summer vs Winter Atmosphere**: Automatically selected based on epoch suffix ('s' or 'w') - **Wobble Mode**: Forces atmosphere 61 and 1.0° wobble offset diff --git a/release_tests/montecarlo/mc_data_comparison/compareDatawithMC.sh b/release_tests/montecarlo/mc_data_comparison/compareDatawithMC.sh index ef1f845..134d3a2 100755 --- a/release_tests/montecarlo/mc_data_comparison/compareDatawithMC.sh +++ b/release_tests/montecarlo/mc_data_comparison/compareDatawithMC.sh @@ -8,9 +8,9 @@ set -e -if [[ $# < 2 ]]; then +if [[ $# != 3 ]]; then echo " - ./compareDatawithMC.sh + ./compareDatawithMC.sh --> choose zenith angle / wobble range SZE: small zenith angles (0.5 deg wobble) MZE: medium large zenith angles (0.5 deg wobble) @@ -19,14 +19,14 @@ echo " Input are MC and Crab mscw files. " -exit +exit 1 fi ########################### # read run parameter file if [[ ! -e ${1} ]]; then echo "Error, run parameter file not found: ${1}" - exit + exit 1 fi RUNPAR="${1}" # Eventdisplay version @@ -56,12 +56,59 @@ if [[ ! -z $VERITAS_ANALYSIS_TYPE ]]; then DIRRECOTYPE="" fi fi -# Stereo reconstruction method -# (0: dispBDT, 2: XGB) -RECOMETHOD=2 -STEREOMETHOD="" +# Read configuration as data, never as shell code. Do not inherit case settings +# from the environment, so the saved file describes the actual comparison. +CONFIG=$3 +if [[ ! -f $CONFIG ]]; then + echo "Error: comparison config not found: $CONFIG" >&2 + exit 1 +fi +MC_VARIANT= MC_MSCW_DIR= RECOMETHOD= MC_XGB_SUFFIX=xgb_stereo DATA_XGB_SUFFIX=xgb_stereo +declare -A seen +while IFS= read -r line || [[ -n $line ]]; do + [[ $line =~ ^[[:space:]]*(#|$) ]] && continue + if [[ ! $line =~ ^[[:space:]]*([a-z_]+)[[:space:]]*=[[:space:]]*([a-zA-Z0-9_-]+)[[:space:]]*$ ]]; then + echo "Error: invalid comparison config line: $line" >&2 + exit 1 + fi + key=${BASH_REMATCH[1]}; value=${BASH_REMATCH[2]} + if [[ ${seen[$key]+yes} ]]; then + echo "Error: duplicate comparison setting: $key" >&2 + exit 1 + fi + seen[$key]=1 + case $key in + variant) MC_VARIANT=$value ;; + mscw_directory) MC_MSCW_DIR=$value ;; + reconstruction) case $value in + DispBDT) RECOMETHOD=0 ;; + XGB) RECOMETHOD=2 ;; + *) echo "Error: reconstruction must be DispBDT or XGB" >&2; exit 1 ;; + esac ;; + mc_xgb_suffix) MC_XGB_SUFFIX=$value ;; + data_xgb_suffix) DATA_XGB_SUFFIX=$value ;; + *) echo "Error: unknown comparison setting: $key" >&2; exit 1 ;; + esac +done < "$CONFIG" +if [[ ! ${MC_VARIANT:-} =~ ^[a-zA-Z0-9_-]+$ || ! ${MC_MSCW_DIR:-} =~ ^[a-zA-Z0-9_-]+$ ]]; then + echo "Error: comparison config requires variant and mscw_directory" >&2 + exit 1 +fi +if [[ -z $RECOMETHOD ]]; then + echo "Error: comparison config requires reconstruction" >&2 + exit 1 +fi +for suffix in "$MC_XGB_SUFFIX" "$DATA_XGB_SUFFIX"; do + if [[ ! $suffix =~ ^[a-zA-Z0-9_-]+$ ]]; then + echo "Error: XGB suffix must contain only letters, numbers, underscores or hyphens: $suffix" >&2 + exit 1 + fi +done +RECONSTRUCTION="DispBDT" +RECONSTRUCTION_DIR="$RECONSTRUCTION" if [[ $RECOMETHOD == 2 ]]; then - STEREOMETHOD="_XGB" + RECONSTRUCTION="XGB_MC-${MC_XGB_SUFFIX}_DATA-${DATA_XGB_SUFFIX}" + RECONSTRUCTION_DIR="XGB/MC-${MC_XGB_SUFFIX}/DATA-${DATA_XGB_SUFFIX}" fi ########################### @@ -76,29 +123,29 @@ case "$ELE" in ;; esac # Directory for simulations -SIMDIR=${VERITAS_IRFPRODUCTION_DIR}/${VERSION}_fs25/${ANALYSISTYPE}/$SIMTYPE/ +SIMDIR=${VERITAS_IRFPRODUCTION_DIR}/${VERSION}/${ANALYSISTYPE}/$SIMTYPE/ if [[ ! -e ${SIMDIR} ]]; then echo "Error: simulation directory not found: $SIMDIR" - exit + exit 1 fi # Directory for mscw data files DDIR="$VERITAS_PREPROCESSED_DATA_DIR/${ANALYSISTYPE}/mscw/" if [[ ! -e ${DDIR} ]]; then echo "Error: data directory not found: $DDIR" - exit + exit 1 fi # Directory with Crab run lists CDIR="../../../../EventDisplay_Release_${VERSION}/Crab/runlists" if [[ ! -e ${CDIR} ]]; then echo "Error: directory with Crab run lists not found: $CDIR" - exit + exit 1 fi # output directory for MC/Data comparison -BDIR="../../../../EventDisplay_Release_${VERSION}/mc_data_comparison/${ANALYSISTYPE}${DIRRECOTYPE}${STEREOMETHOD}/${SIMTYPE}/" -mkdir -p ${BDIR} -BDIR=$(readlink -f "../../../../EventDisplay_Release_${VERSION}/mc_data_comparison/${ANALYSISTYPE}${DIRRECOTYPE}${STEREOMETHOD}/${SIMTYPE}/") +BDIR="../../../../EventDisplay_Release_${VERSION}/mc_data_comparison/${ANALYSISTYPE}${DIRRECOTYPE}/${SIMTYPE}/MC-${MC_VARIANT}/${RECONSTRUCTION_DIR}" +mkdir -p "$BDIR" +BDIR=$(readlink -f "$BDIR") echo "Results will be written to $BDIR" PWDIR=$(pwd) @@ -241,55 +288,85 @@ do continue fi - # output directory - ODIR=${BDIR}/${I}${A}${RUNLISTTAG}_${ELE}_${MCWOFF}_${NSB} - mkdir -p ${ODIR} + # Name MC conditions and the selected Crab runlist separately. + DATASET="data-generic-runlist" + if [[ "$RUNLIST" == *"_ATM${atm}_"* ]]; then + DATASET="data-ATM${atm}" + fi + if [[ $SIMTYPE == "CARE_RedHV"* ]]; then + SIMATM="61" + fi + CONFIGDIR="${BDIR}/${I}_MC-ATM${SIMATM}_${ELE}_wobble${MCWOFF}_NSB${NSB}/${DATASET}" + SIMMSCW="$MC_MSCW_DIR" + MCFILE="$SIMDIR/${MC_EPOCH}_ATM${SIMATM}_gamma/${SIMMSCW}/${simfile}" + if [[ ! -f "$MCFILE" ]]; then + echo "Error: MC mscw file not found: $MCFILE" >&2 + exit 1 + fi + MCFILE=$(readlink -f "$MCFILE") + MCFRIEND="${MCFILE%.mscw.root}.mscw.${MC_XGB_SUFFIX}.root" + if [[ $RECOMETHOD == 2 && ! -f "$MCFRIEND" ]]; then + echo "Error: MC XGB stereo file not found: $MCFRIEND" >&2 + exit 1 + fi + mkdir -p "$(dirname "$CONFIGDIR")" + if ! mkdir "$CONFIGDIR" 2>/dev/null; then + echo "Error: output directory already exists: $CONFIGDIR (move or remove it before resubmitting)" >&2 + exit 1 + fi + ODIR="$CONFIGDIR" + PLOTLABEL="comparison_MC-${MC_VARIANT}_${RECONSTRUCTION}_${DATASET}" + echo "Comparison output: $ODIR" + mkdir -p "$ODIR/tmp" + cp "$RUNLIST" "$ODIR/crab-runlist.dat" + printf 'MC variant: %s\nMC directory: %s\nMC file: %s\nMC XGB friend: %s\nData XGB suffix: %s\nReconstruction: %s\nCrab runlist: %s\n' \ + "$MC_VARIANT" "$SIMMSCW" "$MCFILE" "$([[ $RECOMETHOD == 2 ]] && printf '%s' "$MCFRIEND" || printf 'not used')" "$DATA_XGB_SUFFIX" "$RECONSTRUCTION" "$(readlink -f "$RUNLIST")" > "$ODIR/comparison-settings.txt" + cp "$RUNPAR" "$ODIR/input-runparameter.dat" + cp "$CONFIG" "$ODIR/comparison.conf" # tmp mscw file in output directory - DMSCWDIR=${ODIR}/tmp/$(uuidgen) + # Each result has its own staging directory and Condor logs. + DMSCWDIR=${ODIR}/tmp mkdir -p "$DMSCWDIR" - DFILES=$(cat $RUNLIST) + DFILES=$(cat "$RUNLIST") for D in $DFILES; do if ! MSCWFILE=$(get_mscw_file "$DDIR" "$D"); then echo "Error: mscw file not found for run ${D} in ${DDIR}" exit 1 fi ln -s -f "${MSCWFILE}" "$DMSCWDIR"/"$D".mscw.root + printf 'Data mscw: %s\n' "$(readlink -f "$MSCWFILE")" >> "$ODIR/comparison-settings.txt" if [[ ${RECOMETHOD} -eq 2 ]]; then - XGBFILE="${MSCWFILE%.mscw.root}.mscw.xgb_stereo.root" + XGBFILE="${MSCWFILE%.mscw.root}.mscw.${DATA_XGB_SUFFIX}.root" if [[ ! -e "${XGBFILE}" ]]; then echo "Error: XGB stereo file not found for run ${D}: ${XGBFILE}" exit 1 fi - ln -s -f "${XGBFILE}" "$DMSCWDIR"/"$D".mscw.xgb_stereo.root + ln -s -f "${XGBFILE}" "$DMSCWDIR"/"$D".mscw."${DATA_XGB_SUFFIX}".root + printf 'Data XGB friend: %s\n' "$(readlink -f "$XGBFILE")" >> "$ODIR/comparison-settings.txt" fi done echo "TEMP DIRECTORY (to be deleted by hand): $DMSCWDIR" # runparameter file - if [[ -e $ODIR/mcdatacomparison.runparameter ]] - then - rm -f $ODIR/mcdatacomparison.runparameter - fi - echo "Runparameter file $ODIR/mcdatacomparison.runparameter" - SIMMSCW="MSCW_RECID0${DIRRECOTYPE}" + RUNPARAMETER="$DMSCWDIR/mcdatacomparison.runparameter" + echo "Runparameter file $RUNPARAMETER" # write run parameter file - if [[ $SIMTYPE == "CARE_RedHV"* ]]; then - SIMATM="61" - echo "* SIMS $SIMDIR/${MC_EPOCH}_ATM${SIMATM}_gamma/${SIMMSCW}/${simfile} 4 ${MCWOFF} 0. 0. 0. ${ZEMIN} ${ZEMAX}" > $ODIR/mcdatacomparison.runparameter - else - echo "* SIMS $SIMDIR/${MC_EPOCH}_ATM${SIMATM}_gamma/${SIMMSCW}/${simfile} 4 ${MCWOFF} 0. 0. 0. ${ZEMIN} ${ZEMAX}" > $ODIR/mcdatacomparison.runparameter - fi - echo "* ON ${DMSCWDIR}/[0-9]*.mscw.root 4 -99. -99. 0. 360. ${ZEMIN} ${ZEMAX}" >> $ODIR/mcdatacomparison.runparameter - echo "* OFF ${DMSCWDIR}/[0-9]*.mscw.root 4 -99. -99. 0. 360. ${ZEMIN} ${ZEMAX}" >> $ODIR/mcdatacomparison.runparameter - echo " run parameter file: $ODIR/mcdatacomparison.runparameter" + echo "* SIMS $MCFILE 4 ${MCWOFF} 0. 0. 0. ${ZEMIN} ${ZEMAX}" > "$RUNPARAMETER" + echo "* ON ${DMSCWDIR}/[0-9]*.mscw.root 4 -99. -99. 0. 360. ${ZEMIN} ${ZEMAX}" >> "$RUNPARAMETER" + echo "* OFF ${DMSCWDIR}/[0-9]*.mscw.root 4 -99. -99. 0. 360. ${ZEMIN} ${ZEMAX}" >> "$RUNPARAMETER" + cp "$RUNPARAMETER" "$ODIR/mcdatacomparison.runparameter" FSCRIPT="$DMSCWDIR/compareDatawithMC_qsub_${SIMTYPE}_${I}${A}${RUNLISTTAG}_${ELE}_${MCWOFF}_${NSB}" rm -f ${FSCRIPT}.sh sed -e "s|OUTDIR|$ODIR|" \ -e "s|EEPOCHTM|${MC_EPOCH}_ATM${SIMATM}|" \ -e "s|CURRENTDIR|$PWDIR|" \ + -e "s|RUNPARAMETERFILE|$RUNPARAMETER|" \ + -e "s|PLOTLABEL|$PLOTLABEL|" \ + -e "s|MCXGBSUFFIX|$MC_XGB_SUFFIX|" \ + -e "s|DATAXGBSUFFIX|$DATA_XGB_SUFFIX|" \ -e "s|METHODRECO|$RECOMETHOD|" compareDatawithMC_qsub.sh > ${FSCRIPT}.sh echo "Run script: $FSCRIPT" diff --git a/release_tests/montecarlo/mc_data_comparison/compareDatawithMC_qsub.sh b/release_tests/montecarlo/mc_data_comparison/compareDatawithMC_qsub.sh index 96ed38c..d855a66 100755 --- a/release_tests/montecarlo/mc_data_comparison/compareDatawithMC_qsub.sh +++ b/release_tests/montecarlo/mc_data_comparison/compareDatawithMC_qsub.sh @@ -1,38 +1,49 @@ #!/bin/bash # run script for data - MC comparison # +set -e -source $EVNDISPSYS/setObservatory.sh VTS +source "$EVNDISPSYS/setObservatory.sh" VTS ODIR=OUTDIR CDIR=CURRENTDIR EPOCHATM=EEPOCHTM RECOMETHOD=METHODRECO -BDT="1" +BDT="0" if [[ ${ODIR} == *"CARE_RedHV"* ]]; then BDT="0" fi CUT="-3" T2="0.035" -XGBSUFFIX="xgb_stereo" +MC_XGB_SUFFIX="MCXGBSUFFIX" +DATA_XGB_SUFFIX="DATAXGBSUFFIX" +RUNPARAMETER="RUNPARAMETERFILE" MAXZE="20." ERECOMETHOD="0" PP=$(pwd) -cd ${CDIR} +cd "$CDIR" -$EVNDISPSYS/bin/compareDatawithMC \ - $ODIR/mcdatacomparison.runparameter \ +if [[ $RECOMETHOD == 2 && $MC_XGB_SUFFIX != "$DATA_XGB_SUFFIX" ]]; then + if ! "$EVNDISPSYS/bin/compareDatawithMC" | grep -q 'data XGB stereo file suffix'; then + echo "Error: compareDatawithMC does not support a separate data XGB suffix" >&2 + exit 1 + fi +fi + +cp "$RUNPARAMETER" "$ODIR/mcdatacomparison.runparameter" +"$EVNDISPSYS/bin/compareDatawithMC" \ + "$RUNPARAMETER" \ $CUT \ - $ODIR/mcdatacomparison.root \ + "$ODIR/mcdatacomparison.root" \ ${BDT} $EPOCHATM $ERECOMETHOD \ - ${XGBSUFFIX} ${MAXZE} ${T2} $RECOMETHOD \ - > $ODIR/mcdatacomparison.log + "$MC_XGB_SUFFIX" ${MAXZE} ${T2} "$RECOMETHOD" "$DATA_XGB_SUFFIX" \ + > "$ODIR/mcdatacomparison.log" # prepare all plots -root -l -q -b "plot_compare.C(\"$ODIR\")" +root -l -q -b "plot_compare.C(\"$ODIR\",\"PLOTLABEL\")" # remove results root file # rm -f -v $ODIR/mcdatacomparison.root -cd ${PP} +cd "$PP" diff --git a/release_tests/montecarlo/mc_data_comparison/compare_containment.C b/release_tests/montecarlo/mc_data_comparison/compare_containment.C new file mode 100644 index 0000000..d25a007 --- /dev/null +++ b/release_tests/montecarlo/mc_data_comparison/compare_containment.C @@ -0,0 +1,277 @@ +// Compare counted angular containment from existing compareDatawithMC ROOT files. +// Usage: root -l -b -q 'compare_containment.C("configs/nominal-xgb.conf","configs/ml-smear05-xgb.conf")' + +#include "TCanvas.h" +#include "TFile.h" +#include "TGraphErrors.h" +#include "TH1D.h" +#include "TH2D.h" +#include "TLegend.h" +#include "TLatex.h" +#include "TParameter.h" +#include "TString.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +struct Series +{ + std::string type; + std::string label; + std::string path; + TFile* file = nullptr; + TGraphErrors* graph = nullptr; +}; + +bool countR68( TH1D* h, double theta2Cut, double& r68, double& error ) +{ + if( !h || h->Integral( 1, h->GetNbinsX() ) <= 0. ) return false; + double total = 0.; + for( int bin = 1; bin <= h->GetNbinsX(); bin++ ) + { + double low = h->GetXaxis()->GetBinLowEdge( bin ); + double high = h->GetXaxis()->GetBinUpEdge( bin ); + if( low >= theta2Cut ) continue; + total += h->GetBinContent( bin ) * ( std::min( high, theta2Cut ) - low ) / ( high - low ); + } + if( total <= 0. ) return false; + + const double target = 0.68 * total; + double cumulative = 0.; + for( int bin = 1; bin <= h->GetNbinsX(); bin++ ) + { + double low = h->GetXaxis()->GetBinLowEdge( bin ); + double high = h->GetXaxis()->GetBinUpEdge( bin ); + if( low >= theta2Cut ) break; + high = std::min( high, theta2Cut ); + double content = h->GetBinContent( bin ) * ( high - low ) / ( h->GetXaxis()->GetBinUpEdge( bin ) - low ); + if( content < 0. ) return false; + if( cumulative + content >= target && content > 0. ) + { + double theta2 = low + ( target - cumulative ) / content * ( high - low ); + r68 = std::sqrt( theta2 ); + // Approximate within-bin quantile resolution; not a full statistical interval. + error = ( high - low ) / ( 2. * r68 * std::sqrt( 12. * content ) ); + return std::isfinite( r68 ) && r68 > 0.; + } + cumulative += content; + } + return false; +} + +bool configSettings( const std::filesystem::path& path, std::map& values ) +{ + std::ifstream input( path ); + if( !input ) return false; + std::string line; + while( std::getline( input, line ) ) + { + auto begin = line.find_first_not_of( " \t\r" ); + if( begin == std::string::npos || line[begin] == '#' ) continue; + auto eq = line.find( '=' ); + if( eq == std::string::npos ) return false; + auto trim = []( std::string s ) { + auto first = s.find_first_not_of( " \t\r" ); + auto last = s.find_last_not_of( " \t\r" ); + return first == std::string::npos ? std::string() : s.substr( first, last - first + 1 ); + }; + std::string key = trim( line.substr( 0, eq ) ), value = trim( line.substr( eq + 1 ) ); + if( key.empty() || value.empty() || !values.emplace( key, value ).second ) return false; + } + if( !values.count( "variant" ) || !values.count( "mscw_directory" ) || !values.count( "reconstruction" ) ) return false; + if( values["reconstruction"] == "DispBDT" ) + { + values.erase( "mc_xgb_suffix" ); values.erase( "data_xgb_suffix" ); + } + else if( values["reconstruction"] == "XGB" ) + { + if( !values.count( "mc_xgb_suffix" ) ) values["mc_xgb_suffix"] = "xgb_stereo"; + if( !values.count( "data_xgb_suffix" ) ) values["data_xgb_suffix"] = "xgb_stereo"; + } + else return false; + return true; +} + +bool configSeries( const char* config, const char* results, Series& item ) +{ + namespace fs = std::filesystem; + if( fs::path( config ).extension() == ".root" ) + { + if( !fs::is_regular_file( config ) ) { std::cerr << "ROOT file not found: " << config << "\n"; return false; } + item.type = "MC"; item.label = fs::path( config ).parent_path().filename().string(); item.path = config; + std::cout << "Using " << item.path << "\n"; + return true; + } + std::map wanted; + if( !configSettings( config, wanted ) ) + { + std::cerr << "Invalid configuration: " << config << "\n"; + return false; + } + std::cout << "Searching for " << config << " under " << fs::absolute( results ) << std::endl; + std::cout << " variant=" << wanted["variant"] << ", mscw_directory=" << wanted["mscw_directory"] + << ", reconstruction=" << wanted["reconstruction"] << std::endl; + std::vector matches; + std::vector legacy; + unsigned savedCount = 0, missingRoot = 0; + std::error_code ec; + fs::recursive_directory_iterator it( results, ec ), end; + if( ec ) { std::cerr << "Cannot search " << results << ": " << ec.message() << "\n"; return false; } + for( ; it != end; it.increment( ec ) ) + { + if( ec ) { std::cerr << "Search failed: " << ec.message() << "\n"; return false; } + if( it->is_directory() && it->path().filename() == "tmp" ) + { + it.disable_recursion_pending(); + continue; + } + if( it->path().filename() == "mcdatacomparison.root" && wanted["variant"] == "nominal" && ((wanted["reconstruction"] == "DispBDT" && it->path().string().find( "/DispBDT/" ) != std::string::npos) || (wanted["reconstruction"] == "XGB" && it->path().string().find( "/XGB/MC-" + wanted["mc_xgb_suffix"] + "/DATA-" + wanted["data_xgb_suffix"] + "/" ) != std::string::npos)) && !fs::exists( it->path().parent_path() / "comparison.conf" ) ) legacy.push_back( it->path() ); + if( it->path().filename() != "comparison.conf" ) continue; + ++savedCount; + std::map found; + fs::path root = it->path().parent_path() / "mcdatacomparison.root"; + if( !configSettings( it->path(), found ) ) + std::cerr << " Invalid saved configuration: " << it->path() << "\n"; + else if( found == wanted ) + { + if( fs::is_regular_file( root ) ) matches.push_back( root ); + else { ++missingRoot; std::cout << " Matching configuration has no ROOT output: " << it->path() << "\n"; } + } + } + if( matches.empty() && legacy.size() ) + { + std::cerr << " Using legacy nominal result; its MC directory is not recorded.\n"; + matches = legacy; + } + if( matches.size() > 1 ) + { + std::vector atm; + for( const auto& candidate : matches ) if( candidate.string().find( "/data-ATM61/" ) != std::string::npos ) atm.push_back( candidate ); + if( atm.size() == 1 ) { std::cout << " Selecting ATM61 runlist.\n"; matches = atm; } + } + std::cout << " Checked " << savedCount << " saved configurations; " << matches.size() + << " completed matches, " << missingRoot << " without ROOT output.\n"; + if( matches.empty() ) std::cerr << " Older results without comparison.conf cannot be matched automatically.\n"; + if( matches.size() != 1 ) + { + std::cerr << config << ": expected one completed result, found " << matches.size() << "\n"; + for( const auto& match : matches ) std::cerr << " " << match << "\n"; + return false; + } + std::cout << " Selected " << matches[0] << "\n"; + item.type = "MC"; item.label = fs::path( config ).stem().string(); item.path = matches[0].string(); + return true; +} + +bool fillGraph( TH2D* h, double theta2Cut, TGraphErrors* graph, const std::string& label ) +{ + if( !h ) return false; + for( int bin = 1; bin <= h->GetNbinsX(); bin++ ) + { + TH1D* projection = h->ProjectionY( Form( "projection_%s_%d", label.c_str(), bin ), bin, bin ); + double radius = 0., error = 0.; + if( countR68( projection, theta2Cut, radius, error ) ) + { + int point = graph->GetN(); + graph->SetPoint( point, h->GetXaxis()->GetBinCenter( bin ), radius ); + graph->SetPointError( point, 0., error ); + std::cout << label << ": energy bin " << bin << " log10(E/TeV)=" + << h->GetXaxis()->GetBinCenter( bin ) << " r68=" << radius << " +/- " << error << " deg\n"; + } + else std::cout << label << ": omitted energy bin " << bin << " (invalid cumulative profile or no 68% crossing)\n"; + delete projection; + } + return graph->GetN() > 0; +} +} + +void compare_containment( const char* firstConfig, const char* secondConfig, const char* results = "../../../../EventDisplay_Release_v492/mc_data_comparison", const char* outputPdf = "containment_comparison.pdf" ) +{ + std::vector series( 2 ); + bool firstFound = configSeries( firstConfig, results, series[0] ); + bool secondFound = configSeries( secondConfig, results, series[1] ); + if( !firstFound || !secondFound ) return; + if( std::filesystem::path( firstConfig ).extension() == ".root" ) series[0].label = "nominal"; + if( std::filesystem::path( secondConfig ).extension() == ".root" ) series[1].label = "comparison"; + Series firstData = series[0]; firstData.type = "DATA"; firstData.label = "Crab: " + firstData.label; + Series secondData = series[1]; secondData.type = "DATA"; secondData.label = "Crab: " + secondData.label; + series[0].label = "MC: " + series[0].label; + series[1].label = "MC: " + series[1].label; + series.push_back( firstData ); series.push_back( secondData ); + + double theta2Cut = -1.; + double xMin = 1.e9, xMax = -1.e9, yMax = 0.; + const int colors[] = {kRed + 1, kBlue + 1, kRed + 1, kBlue + 1}; + const int markers[] = {20, 21, 24, 25}; + + for( Series& item : series ) + { + item.file = TFile::Open( item.path.c_str() ); + if( !item.file || item.file->IsZombie() ) + { + std::cerr << "Cannot open ROOT file for " << item.label << ": " << item.path << "\n"; + return; + } + TParameter* cut = dynamic_cast*>( item.file->Get( "angularTheta2Cut" ) ); + if( !cut || cut->GetVal() <= 0. ) + { + std::cerr << "Missing valid angularTheta2Cut metadata in " << item.path << "\n"; + return; + } + if( theta2Cut < 0. ) theta2Cut = cut->GetVal(); + else if( std::abs( cut->GetVal() - theta2Cut ) > 1.e-9 ) + { + std::cerr << "Input files have different theta2 cuts (" << theta2Cut << " and " << cut->GetVal() << ")\n"; + return; + } + const char* histogram = item.type == "MC" ? "htheta2Erec_SIMS" : "htheta2Erec_DIFF"; + TH2D* h = dynamic_cast( item.file->Get( histogram ) ); + if( !h ) + { + std::cerr << "Missing " << histogram << " in " << item.path << "\n"; + return; + } + item.graph = new TGraphErrors(); + if( !fillGraph( h, theta2Cut, item.graph, item.label ) ) + { + std::cerr << "No valid containment points for " << item.label << "\n"; + return; + } + std::size_t style = (&item - series.data()) % ( sizeof( colors ) / sizeof( colors[0] ) ); + item.graph->SetMarkerStyle( markers[style] ); + item.graph->SetMarkerColor( colors[style] ); + item.graph->SetLineColor( colors[style] ); + for( int point = 0; point < item.graph->GetN(); point++ ) + { + double x = 0., y = 0.; + item.graph->GetPoint( point, x, y ); + xMin = std::min( xMin, x ); xMax = std::max( xMax, x ); yMax = std::max( yMax, y ); + } + } + + double xPadding = std::max( 0.1, 0.05 * ( xMax - xMin ) ); + TCanvas canvas( "containment_comparison", "Angular containment comparison", 1000, 700 ); + canvas.SetGrid(); canvas.SetBottomMargin( 0.18 ); + TH1F* frame = canvas.DrawFrame( xMin - xPadding, 0., xMax + xPadding, yMax * 1.25 ); + frame->SetTitle( "68% angular containment versus reconstructed energy;log_{10}(E_{rec}/TeV);r_{68} [deg]" ); + TLegend legend( 0.48, 0.66, 0.89, 0.89 ); + for( Series& item : series ) + { + item.graph->Draw( "P SAME" ); + legend.AddEntry( item.graph, item.label.c_str(), "p" ); + } + legend.Draw(); + TLatex note; note.SetNDC(); note.SetTextSize( 0.026 ); + note.DrawLatex( 0.12, 0.07, Form( "Counted within #theta^{2} < %.4g deg^{2}; no tail extrapolation", theta2Cut ) ); + canvas.SaveAs( outputPdf ); + std::cout << "Comparison output: " << std::filesystem::absolute( outputPdf ).lexically_normal() << std::endl; +} diff --git a/release_tests/montecarlo/mc_data_comparison/configs/README.md b/release_tests/montecarlo/mc_data_comparison/configs/README.md new file mode 100644 index 0000000..9d6ea85 --- /dev/null +++ b/release_tests/montecarlo/mc_data_comparison/configs/README.md @@ -0,0 +1,27 @@ +# Comparison configurations + +These files select the MC production, reconstruction method and, for XGB, +friend-file suffixes. Pass one to `../compareDatawithMC.sh` when submitting a +comparison. They describe the inputs; they do not contain the results. + +For release v492, results are stored under +`EventDisplay_Release_v492/mc_data_comparison/`, in directories for the analysis, +simulation type, MC variant, reconstruction, observing conditions and Crab +runlist. Each result directory contains `comparison.conf`, +`comparison-settings.txt`, `mcdatacomparison.root` and the comparison PDF. +Older results can lack `comparison.conf`. A repeat submission to an existing +result directory is rejected to preserve its files. + +From the parent directory, compare two configurations with: + +```sh +root -l -b -q 'compare_containment.C("configs/nominal-xgb.conf", "configs/mscw-smear-v1-xgb.conf")' +``` + +The macro searches the v492 results by default and writes +`containment_comparison.pdf` in the current directory, printing its full path. +It plots both MC and Crab curves for each result. Filled markers show MC; +open markers show Crab, with colors matching each configuration. When several results +match, it selects a unique ATM61 result if available; otherwise it reports the +ambiguity. Check the printed paths and input settings for the intended conditions. +The parent [README](../README.md) describes the settings and optional arguments. diff --git a/release_tests/montecarlo/mc_data_comparison/configs/nominal-dispbdt.conf b/release_tests/montecarlo/mc_data_comparison/configs/nominal-dispbdt.conf new file mode 100644 index 0000000..e32c998 --- /dev/null +++ b/release_tests/montecarlo/mc_data_comparison/configs/nominal-dispbdt.conf @@ -0,0 +1,4 @@ +# Nominal mscw; standard DispBDT reconstruction, no XGB friends. +variant = nominal +mscw_directory = MSCW_RECID0_DISP_org +reconstruction = DispBDT diff --git a/release_tests/montecarlo/mc_data_comparison/configs/nominal-xgb.conf b/release_tests/montecarlo/mc_data_comparison/configs/nominal-xgb.conf new file mode 100644 index 0000000..9fd3d97 --- /dev/null +++ b/release_tests/montecarlo/mc_data_comparison/configs/nominal-xgb.conf @@ -0,0 +1,6 @@ +# Nominal mscw; nominal XGB prediction for MC and Crab. +variant = nominal +mscw_directory = MSCW_RECID0_DISP_org +reconstruction = XGB +mc_xgb_suffix = xgb_stereo +data_xgb_suffix = xgb_stereo diff --git a/release_tests/montecarlo/mc_data_comparison/plot_compare.C b/release_tests/montecarlo/mc_data_comparison/plot_compare.C index 863e057..2d89969 100644 --- a/release_tests/montecarlo/mc_data_comparison/plot_compare.C +++ b/release_tests/montecarlo/mc_data_comparison/plot_compare.C @@ -7,7 +7,7 @@ R__LOAD_LIBRARY($EVNDISPSYS/lib/libVAnaSum.so); -void plot_compare( string oDir ) +void plot_compare( string oDir, string outputName = "mcdatacomparison" ) { string i_name = oDir + "/mcdatacomparison"; @@ -15,6 +15,6 @@ void plot_compare( string oDir ) VPlotCompareDataWithMC a( i_name + ".root" ); if( !a.isZombie() ) { - a.plot( i_name ); + a.plot( oDir + "/" + outputName ); } } diff --git a/release_tests/sources/Crab/anasum_from_runlists.sh b/release_tests/sources/Crab/anasum_from_runlists.sh index 97fb0ae..ae251ae 100755 --- a/release_tests/sources/Crab/anasum_from_runlists.sh +++ b/release_tests/sources/Crab/anasum_from_runlists.sh @@ -8,6 +8,7 @@ echo " Combine anasum file from run lists ./anasum_from_runlist.sh + Uses the run lists of the active '* EPOCH' lines of the runparameter file. Depends on the runlists generated by runlist_generator_from_anasum_log.sh " @@ -32,29 +33,47 @@ MEPOCH=($(grep MAJOREPOCH ${1} | grep "*" | awk '{print $3}')) # Source name OBJECT=($(grep SOURCE ${1} | grep "*" | awk '{print $3}')) CUTS="" -# CUT lines contain both a full cut token and a short alias. -# Always consume the alias in field 4 to avoid mixing naming schemes. -while IFS= read -r cut_alias; do - if [[ -z "$cut_alias" ]]; then - echo "Error, malformed '* CUT' line in runparameter file: ${1}" +# CUT lines have the format "* CUT " (exactly five fields). +# The old format with a second (alias) name is not supported. +while IFS= read -r cut_name; do + if [[ -z "$cut_name" ]]; then + echo "Error, malformed '* CUT' line in runparameter file (expected '* CUT '): ${1}" exit 1 fi - CUTS="$CUTS $cut_alias" -done < <(awk '/^\* CUT[[:space:]]+/ { if (NF < 4) { print ""; next } print $4 }' "${1}") + CUTS="$CUTS $cut_name" +done < <(awk '/^\* CUT[[:space:]]+/ { if (NF != 5 || $4 !~ /^[0-9.]+$/ || $5 !~ /^[0-9.]+$/) { print ""; next } print $3 }' "${1}") if [[ -z "$CUTS" ]]; then - echo "Error, no CUT aliases (field 4 of '* CUT' lines) found in runparameter file: ${1}" + echo "Error, no '* CUT ' lines found in runparameter file: ${1}" exit 1 fi echo "CUTS $CUTS" -# run lists -VDIR=$(readlink -f ../../../../EventDisplay_Release_${VERSION}/${OBJECT}/runlists) -if [[ $MEPOCH == *"redHV"* ]]; then - RLISTS="$(ls -1 ${VDIR}/*.dat | grep redHV)" -else - RLISTS="$(ls -1 ${VDIR}/*$MEPOCH*.dat | grep -v redHV)" +# Epochs: active '* EPOCH ' lines (lines without '*' are switched off) +mapfile -t EPOCHS < <(awk '$1 == "*" && $2 == "EPOCH" {print $3}' "${1}") +if [[ ${#EPOCHS[@]} -eq 0 ]]; then + echo "Error, no active '* EPOCH' lines found in runparameter file: ${1}" + exit 1 fi +echo "EPOCHS ${EPOCHS[*]}" + +# run lists: only those of the active epochs +# (runlist_releaseTesting.dat and runlist_releaseTesting_*.dat); +# for the major epoch alone (e.g. V6), minor-epoch lists (e.g. V6_2012_2013a_*) are excluded +VDIR=$(readlink -f ../../../../EventDisplay_Release_${VERSION}/${OBJECT}/runlists) +RLISTS="" +for EPOCH in "${EPOCHS[@]}"; do + EPOCH_LISTS=$(ls -1 "${VDIR}/runlist_releaseTesting${EPOCH}.dat" "${VDIR}/runlist_releaseTesting${EPOCH}"_*.dat 2>/dev/null || true) + if [[ "$EPOCH" == "${MEPOCH[0]}" ]]; then + EPOCH_LISTS=$(echo "$EPOCH_LISTS" | grep -v "_20[0-9][0-9]_20[0-9][0-9]" || true) + fi + if [[ -z "$EPOCH_LISTS" ]]; then + echo "Error, no run lists found for epoch $EPOCH in $VDIR" + exit 1 + fi + RLISTS="$RLISTS $EPOCH_LISTS" +done +RLISTS=$(echo "$RLISTS" | tr ' ' '\n' | sort -u | grep .) echo "RUNLISTS: $RLISTS" cd "${EVNDISPSCRIPTS}"