musrfit 1.10.0
PRunSingleHisto Class Reference

Class for fitting single detector histograms (basic time-differential μSR). More...

#include <PRunSingleHisto.h>

Inheritance diagram for PRunSingleHisto:
Collaboration diagram for PRunSingleHisto:

Public Member Functions

 PRunSingleHisto ()
 Default constructor creating an empty, invalid single histogram run object.
 
 PRunSingleHisto (PMsrHandler *msrInfo, PRunDataHandler *rawData, UInt_t runNo, EPMusrHandleTag tag, Bool_t theoAsData)
 Main constructor initializing a single histogram run from MSR file and data.
 
virtual ~PRunSingleHisto ()
 Virtual destructor cleaning up allocated resources.
 
virtual Double_t CalcChiSquare (const std::vector< Double_t > &par)
 Calculates χ² between histogram data and theory.
 
virtual Double_t CalcChiSquareExpected (const std::vector< Double_t > &par)
 Calculates expected χ² based on theory predictions.
 
virtual Double_t CalcMaxLikelihood (const std::vector< Double_t > &par)
 Calculates maximum likelihood for Poisson-distributed histogram counts.
 
virtual Double_t CalcMaxLikelihoodExpected (const std::vector< Double_t > &par)
 Calculates expected maximum likelihood.
 
virtual void CalcTheory ()
 Evaluates theory function at all data points or high-resolution grid.
 
virtual UInt_t GetNoOfFitBins ()
 Returns the number of bins included in the fit range.
 
virtual void SetFitRangeBin (const TString fitRange)
 Sets fit range using bin-offset specification (COMMANDS block syntax).
 
virtual Double_t GetBackground ()
 Returns the estimated background level.
 
virtual Int_t GetStartTimeBin ()
 Returns the first bin index in the fit range.
 
virtual Int_t GetEndTimeBin ()
 Returns the last bin index in the fit range (exclusive).
 
virtual Int_t GetPacking ()
 Returns the bin packing factor.
 
virtual Bool_t GetScaleN0AndBkg ()
 Returns the N₀/background scaling mode.
 
virtual void CalcNoOfFitBins ()
 Calculates start/end bin indices from fit time range.
 
- Public Member Functions inherited from PRunBase
 PRunBase ()
 Default constructor.
 
 PRunBase (PMsrHandler *msrInfo, PRunDataHandler *rawData, UInt_t runNo, EPMusrHandleTag tag)
 Constructor initializing run from MSR file and raw data.
 
virtual ~PRunBase ()
 Virtual destructor.
 
virtual void SetFitRange (PDoublePairVector fitRange)
 Sets the fit time range for this run.
 
virtual UInt_t GetRunNo ()
 Returns the run number (0-based index in MSR file).
 
virtual PRunDataGetData ()
 Returns pointer to processed data container.
 
virtual void CleanUp ()
 Cleans up internal data structures.
 
virtual Bool_t IsValid ()
 Returns validity status of this run object.
 

Protected Member Functions

virtual Bool_t PrepareData ()
 Main data preparation orchestrator.
 
virtual Bool_t PrepareFitData (PRawRunData *runData, const UInt_t histoNo)
 Prepares histogram data for fitting.
 
virtual Bool_t PrepareRawViewData (PRawRunData *runData, const UInt_t histoNo)
 Prepares raw histogram data for viewing (minimal processing).
 
virtual Bool_t PrepareViewData (PRawRunData *runData, const UInt_t histoNo)
 Prepares processed histogram data for viewing/plotting.
 
- Protected Member Functions inherited from PRunBase
virtual void DeadTimeCorrection (std::vector< PDoubleVector > &histos, PUIntVector &histoNo)
 carry out dead time correction
 
virtual void CalculateKaiserFilterCoeff (Double_t wc, Double_t A, Double_t dw)
 Calculates Kaiser window FIR filter coefficients for RRF smoothing.
 
virtual void FilterTheo ()
 Applies Kaiser FIR filter to theory values for RRF fits.
 

Private Member Functions

virtual Bool_t GetProperT0 (PRawRunData *runData, PMsrGlobalBlock *globalBlock, PUIntVector &histoNo)
 Determines and validates t0 values for histogram.
 
virtual Bool_t GetProperDataRange ()
 Determines data range (region of valid histogram data).
 
virtual void GetProperFitRange (PMsrGlobalBlock *globalBlock)
 Determines fit range from MSR file settings.
 
virtual void EstimateN0 ()
 Estimates initial normalization N₀ from histogram data.
 
virtual Bool_t EstimateBkg (UInt_t histoNo)
 Estimates background from pre-t0 bins.
 
virtual Bool_t IsScaleN0AndBkg ()
 Determines if N₀ and background should be scaled to 1/ns.
 

Private Attributes

Bool_t fScaleN0AndBkg
 Scaling mode: true = scale N₀ and B to 1/ns, false = leave as 1/bin (determined by IsScaleN0AndBkg())
 
UInt_t fNoOfFitBins
 Number of bins within fit range (fStartTimeBin to fEndTimeBin)
 
Double_t fBackground
 Background level in counts/bin (estimated from pre-t0 bins or fixed value from RUN block)
 
Int_t fPacking
 Bin packing factor (REQUIRED: from RUN or GLOBAL block)
 
Bool_t fTheoAsData
 Theory mode: true = at data points, false = high-resolution grid for smooth Fourier transforms.
 
Int_t fGoodBins [2]
 Good bin markers for COMMANDS block: [0]=fgb (first good bin/t0), [1]=lgb (last good bin)
 
PDoubleVector fForward
 Forward detector histogram (background-corrected, packed)
 
Int_t fStartTimeBin
 First bin index in fit range (inclusive, 0-based after packing)
 
Int_t fEndTimeBin
 Last bin index in fit range (exclusive: loop as i < fEndTimeBin)
 

Additional Inherited Members

- Protected Attributes inherited from PRunBase
Bool_t fValid
 Flag indicating if run object initialized successfully; false if any error occurred.
 
EPMusrHandleTag fHandleTag
 Operation mode: kFit (fitting), kView (display only), kEmpty (uninitialized)
 
Int_t fRunNo
 Run number (0-based index in MSR file RUN blocks)
 
PMsrHandlerfMsrInfo
 Pointer to MSR file handler (owned externally, not deleted here)
 
PMsrRunBlockfRunInfo
 Pointer to this run's RUN block settings within fMsrInfo.
 
PRunDataHandlerfRawData
 Pointer to raw data handler (owned externally, not deleted here)
 
PRunData fData
 Processed data container: background-corrected, packed, with theory values.
 
Double_t fTimeResolution
 Time resolution of raw histogram data in microseconds (μs), e.g., 0.01953125 μs for PSI GPS.
 
PMetaData fMetaData
 Experimental metadata extracted from data file header (magnetic field, temperature, beam energy)
 
PDoubleVector fT0s
 Time-zero bin values for all histograms in this run (forward, backward, etc.)
 
std::vector< PDoubleVectorfAddT0s
 Time-zero bin values for additional runs to be added to main run.
 
Double_t fFitStartTime
 Fit range start time in microseconds (μs) relative to t0.
 
Double_t fFitEndTime
 Fit range end time in microseconds (μs) relative to t0.
 
PDoubleVector fFuncValues
 Cached values of user-defined functions from FUNCTIONS block, evaluated at current parameters.
 
std::unique_ptr< PTheoryfTheory
 Theory function evaluator (smart pointer, automatically deleted)
 
PDoubleVector fKaiserFilter
 Kaiser window FIR filter coefficients for smoothing RRF theory curves.
 

Detailed Description

Class for fitting single detector histograms (basic time-differential μSR).

PRunSingleHisto implements the most fundamental μSR analysis: fitting a single positron detector histogram to extract relaxation parameters. This is the basis for all μSR measurements and is used when asymmetry analysis is not appropriate or desired.

Physics and Applications

Single histogram measurements are used for:

  • Time-differential μSR: Measure μ⁺ decay positron time spectrum
  • Detector calibration: Characterize individual detector response
  • Transverse field (TF): When forward/backward separation unnecessary
  • High statistics: Use all positrons (no F-B discrimination)
  • Specialized geometries: Non-standard detector arrangements
  • Method development: Test fitting algorithms on single detector

Data Structure and Analysis

Histogram content:

  • Raw counts vs. time from a single positron detector
  • Time-zero (t0): Muon arrival time marking start of decay
  • Background: Constant or estimated from pre-t0 bins
  • Signal: N(t) = N₀·exp(-t/τ_μ)·P(t) + B

where:

  • N₀ = initial count rate (normalization parameter)
  • τ_μ = 2.197 μs (muon lifetime)
  • P(t) = polarization function (contains physics: relaxation, oscillation, etc.)
  • B = background (random coincidences, accidentals)

Analysis Workflow

  1. Load Histogram: Read raw detector counts from data file
  2. Determine t0: Identify muon arrival time
  3. Background Subtraction:
    • Fixed: Subtract specified constant
    • Estimated: Calculate from pre-t0 bins, subtract with error propagation
  4. Bin Packing: Rebin to improve statistics (optional)
  5. Fit Range: Select time window for parameter extraction
  6. Theory Evaluation: N_theory(t) = N₀·exp(-t/τ_μ)·P_theory(t) + B
  7. Minimization: χ² or maximum likelihood via MINUIT

Theory Function

The fitted function is typically:

\[ N(t) = N_0 e^{-t/\tau_\mu} P(t) + B \]

Common polarization functions P(t):

  • Static Gaussian: P(t) = exp(-σ²t²/2)
  • Static Lorentzian: P(t) = exp(-λt)
  • Dynamic relaxation: P(t) = exp(-(λt)^β) (stretched exponential)
  • Oscillating: P(t) = cos(ωt + φ) · exp(-λt)
  • Kubo-Toyabe: Complex relaxation functions for spin systems

Key Parameters

Normalization (N₀):

  • Can be fit parameter or fixed value
  • Can be derived from FUNCTIONS block
  • Automatically scaled to 1/ns or 1/bin (fScaleN0AndBkg)

Background (B):

  • Fixed: From "background" entry in RUN block
  • Estimated: Calculated from pre-t0 bin range
  • Units: counts/bin

Packing:

  • Number of consecutive bins to combine
  • REQUIRED parameter (RUN or GLOBAL block)
  • Higher packing → better statistics, worse time resolution

MSR File Example

RUN data/run2425 PSI MUE4 PSI MUSR-ROOT (name beamline)
fittype 0 (SingleHisto)
map 1 (forward histogram number)
forward 1
packing 50 (combine 50 bins → one packed bin)
background 50 150 (estimate from bins 50-150)
data 200 2000 (use bins 200-2000 for analysis)
t0 210.5 (muon arrival bin)
fit 0.1 10.0 (fit from 0.1 to 10.0 μs after t0)
THEORY
asymmetry 1
simpleGss 2 (Gaussian relaxation σ)
+ 3 (constant background offset)

Single Histo vs. Asymmetry

FeatureSingle HistogramAsymmetry
DetectorsOne (forward)Two (forward + backward)
Quantity fittedN(t) countsA(t) = (F-αB)/(F+αB)
StatisticsAll positronsF and B separately
BackgroundAdditive BCancels in asymmetry
α parameterN/ARequired (F/B asymmetry)
Use casesTF, calibrationLF, ZF, weak TF
See also
PRunAsymmetry for forward-backward asymmetry analysis
PRunSingleHistoRRF for rotating reference frame (high-TF)
PRunBase for base class interface and common functionality

Definition at line 143 of file PRunSingleHisto.h.

Constructor & Destructor Documentation

◆ PRunSingleHisto() [1/2]

PRunSingleHisto::PRunSingleHisto ( )

Default constructor creating an empty, invalid single histogram run object.

Default constructor for single histogram fitting class.

Initializes all member variables to default/invalid states:

  • fScaleN0AndBkg = true (scale to 1/ns by default)
  • fNoOfFitBins = 0 (no bins to fit)
  • fBackground = 0 (no background)
  • fPacking = -1 (unspecified - will cause error if not set)
  • fTheoAsData = false (high-resolution theory grid)
  • Good bins markers = -1 (unset)
  • Fit range bins = -1 (unset)

This constructor is needed for creating vectors of PRunSingleHisto objects. The resulting object cannot be used until properly initialized via the main constructor.

Initializes all member variables to safe default values:

  • fScaleN0AndBkg = true (normalize N₀ and background to 1/ns)
  • fPacking = -1 (invalid until set from MSR file)
  • fBackground = 0 (will be estimated or set from MSR file)
  • fStartTimeBin / fEndTimeBin = -1 (calculated from fit range)
  • fGoodBins[0,1] = -1 (calculated from data range)
Warning
This constructor creates an invalid object until initialized with MSR file data. Use the full constructor for normal operation.

Definition at line 65 of file PRunSingleHisto.cpp.

References fBackground, fEndTimeBin, fGoodBins, fNoOfFitBins, fPacking, fScaleN0AndBkg, fStartTimeBin, fTheoAsData, and PRunBase::PRunBase().

◆ PRunSingleHisto() [2/2]

PRunSingleHisto::PRunSingleHisto ( PMsrHandler * msrInfo,
PRunDataHandler * rawData,
UInt_t runNo,
EPMusrHandleTag tag,
Bool_t theoAsData )

Main constructor initializing a single histogram run from MSR file and data.

Main constructor for single histogram fitting and viewing.

Performs comprehensive initialization:

  1. Base Class Initialization:
    • Calls PRunBase constructor
    • Initializes theory engine, parameter mappings, FUNCTIONS block
  2. N₀/Background Scaling:
    • Calls IsScaleN0AndBkg() to determine scaling mode
    • Sets fScaleN0AndBkg flag (true = scale to 1/ns, false = leave as 1/bin)
  3. Packing Validation (CRITICAL):
    • Attempts to read packing from RUN block
    • Falls back to GLOBAL block if not in RUN
    • SEVERE ERROR if packing == -1 (mandatory parameter)
    • Marks run invalid and returns if packing not found
  4. Member Initialization:
    • Good bin markers, fit range bins set to -1 (determined later)
    • Background initialized to 0 (set during PrepareData if specified)
  5. Data Preparation:

The object is marked as invalid (fValid=false) if:

  • Packing parameter is missing from both RUN and GLOBAL blocks
  • PrepareData() fails (file not found, invalid t0, etc.)
Parameters
msrInfoPointer to MSR file handler (must remain valid)
rawDataPointer to raw data handler for histogram loading
runNoRun number (0-based index in MSR file RUN blocks)
tagOperation mode: kFit (fitting), kView (display/plotting)
theoAsDataTheory mode: true = at data points, false = high-resolution
Warning
Always check IsValid() after construction. Packing is MANDATORY.
See also
PrepareData() for data preprocessing details
IsScaleN0AndBkg() for scaling determination

Constructs a fully initialized single histogram run object by:

  1. Extracting packing value from RUN block (or falling back to GLOBAL block)
  2. Determining if N₀ and background should be scaled to 1/ns
  3. Calling PrepareData() to load and process histogram data
  4. Setting up fit ranges and background estimation
Parameters
msrInfoPointer to MSR file handler (NOT owned, must outlive this object)
rawDataPointer to raw run data handler (NOT owned, must outlive this object)
runNoZero-based index of the RUN block in the MSR file
tagOperation mode: kFit (fitting) or kView (viewing/plotting)
theoAsDataIf true, theory is calculated only at data points (for viewing); if false, theory uses finer time grid (8× data resolution)
Warning
Packing MUST be specified either in the RUN block or GLOBAL block. If packing is not found, the constructor sets fValid=false and returns.
Note
After construction, check IsValid() to ensure initialization succeeded.
See also
PrepareData(), IsScaleN0AndBkg()

Definition at line 108 of file PRunSingleHisto.cpp.

References fBackground, fEndTimeBin, fGoodBins, PRunBase::fMsrInfo, fNoOfFitBins, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, fStartTimeBin, fTheoAsData, PRunBase::fValid, IsScaleN0AndBkg(), PrepareData(), and PRunBase::PRunBase().

◆ ~PRunSingleHisto()

PRunSingleHisto::~PRunSingleHisto ( )
virtual

Virtual destructor cleaning up allocated resources.

Destructor for single histogram fitting class.

Releases memory used by the forward histogram vector (fForward). Base class destructor handles cleanup of theory objects and other shared resources.

Cleans up dynamically allocated memory:

  • Clears the forward histogram data vector
  • Base class destructor handles theory objects and other shared resources

Definition at line 153 of file PRunSingleHisto.cpp.

References fForward.

Member Function Documentation

◆ CalcChiSquare()

Double_t PRunSingleHisto::CalcChiSquare ( const std::vector< Double_t > & par)
virtual

Calculates χ² between histogram data and theory.

Calculates χ² between data and theory (least-squares fit metric).

Computes chi-squared for single histogram fitting:

\[ \chi^2 = \sum_{i} \frac{(N_i^{\rm data} - N_i^{\rm theory})^2}{\sigma_i^2} \]

where N_theory(t) = N₀·exp(-t/τ_μ)·P(t) + B

Uses OpenMP parallelization when available. N₀ can be a fit parameter or derived from FUNCTIONS block.

Parameters
parParameter vector from MINUIT
Returns
χ² value (minimize during fitting)

Computes the standard chi-square goodness-of-fit statistic:

\[\chi^2 = \sum_{i=t_{\rm start}}^{t_{\rm end}} \frac{[N_i - N_{\rm theo}(t_i)]^2}{\sigma_i^2}
\]

where the theory function is:

\[N_{\rm theo}(t) = N_0 e^{-t/\tau_\mu} [1 + P(t)] + B
\]

Algorithm:

  1. Extract N₀ from parameter vector or evaluate as a function
  2. Extract muon lifetime τ (defaults to PMUON_LIFETIME if not fitted)
  3. Extract background B (from fit parameter, fixed value, or estimated range)
  4. Evaluate all user-defined functions in FUNCTIONS block
  5. Pre-calculate theory at t=1.0 to initialize LF/user functions (thread-safe)
  6. Loop over fit range bins [fStartTimeBin, fEndTimeBin) using OpenMP parallelization
  7. Accumulate χ² with reduction across threads
  8. Apply correction factor if fScaleN0AndBkg is true

N₀ Parameter vs. Function Handling:

  • If norm parameter number < MSR_PARAM_FUN_OFFSET: N₀ is a fit parameter
  • If norm parameter number ≥ MSR_PARAM_FUN_OFFSET: N₀ is a user-defined function

OpenMP Parallelization:

  • Dynamic scheduling with chunk size = (N_bins / N_processors), minimum 10
  • Private variables per thread: i, time, diff
  • Reduction performed on chisq sum

Scaling Correction: If fScaleN0AndBkg is true, χ² is multiplied by:

\[\text{correction} = \text{packing} \times (t_{\rm res} \times 1000)
\]

This accounts for the fact that data scales like pack×t_res, but errors scale like √(pack×t_res), ensuring correct χ² when normalizing to 1/ns.

Parameters
parParameter vector from MINUIT2 optimizer (1-based indexing in MSR file, but 0-based in this vector)
Returns
Chi-square value for the current parameter set
See also
CalcChiSquareExpected(), CalcMaxLikelihood(), PTheory::Func()

Implements PRunBase.

Definition at line 208 of file PRunSingleHisto.cpp.

References fBackground, PRunBase::fData, fEndTimeBin, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, fStartTimeBin, PRunBase::fTheory, PRunBase::fTimeResolution, MSR_PARAM_FUN_OFFSET, PMUON_LIFETIME, and PMUSR_UNDEFINED.

◆ CalcChiSquareExpected()

Double_t PRunSingleHisto::CalcChiSquareExpected ( const std::vector< Double_t > & par)
virtual

Calculates expected χ² based on theory predictions.

Calculates expected χ² using theory as variance (alternative fit metric).

Parameters
parParameter vector from MINUIT
Returns
Expected χ² (for statistical diagnostics)

Computes chi-square using the expected variance (theory value) instead of observed variance. This is sometimes called the "Neyman χ²" or "expected χ²":

\[\chi^2_{\rm exp} = \sum_{i=t_{\rm start}}^{t_{\rm end}} \frac{[N_i - N_{\rm theo}(t_i)]^2}{N_{\rm theo}(t_i)}
\]

Difference from Standard χ²:

  • Standard χ²: variance = σ²ᵢ (from observed data)
  • Expected χ²: variance = N_theo(tᵢ) (from theory prediction)

This metric can be useful when:

  • Theory predictions are more reliable than data errors
  • Data contains zero or very low counts (standard χ² undefined)
  • Testing model consistency against expected distribution

Algorithm:

  1. Extract N₀ from parameter vector or evaluate as a function
  2. Extract muon lifetime τ (defaults to PMUON_LIFETIME if not fitted)
  3. Extract background B (from fit parameter, fixed value, or estimated range)
  4. Evaluate all user-defined functions in FUNCTIONS block
  5. Pre-calculate theory at t=1.0 to initialize LF/user functions (thread-safe)
  6. Loop over fit range bins [fStartTimeBin, fEndTimeBin) using OpenMP parallelization
  7. Accumulate χ²_exp with reduction across threads
  8. Apply correction factor if fScaleN0AndBkg is true

OpenMP Parallelization:

  • Dynamic scheduling with chunk size = (N_bins / N_processors), minimum 10
  • Private variables per thread: i, time, theo, diff
  • Reduction performed on chisq sum
Parameters
parParameter vector from MINUIT2 optimizer
Returns
Expected chi-square value for the current parameter set
See also
CalcChiSquare(), CalcMaxLikelihood()

Implements PRunBase.

Definition at line 323 of file PRunSingleHisto.cpp.

References fBackground, PRunBase::fData, fEndTimeBin, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, fStartTimeBin, PRunBase::fTheory, PRunBase::fTimeResolution, MSR_PARAM_FUN_OFFSET, PMUON_LIFETIME, and PMUSR_UNDEFINED.

◆ CalcMaxLikelihood()

Double_t PRunSingleHisto::CalcMaxLikelihood ( const std::vector< Double_t > & par)
virtual

Calculates maximum likelihood for Poisson-distributed histogram counts.

Calculates -2 log(maximum likelihood) for Poisson-distributed histogram data.

Computes -2ln(L) for low-count data (< 10-20 counts/bin). Superior to χ² when Gaussian approximation invalid.

Parameters
parParameter vector from MINUIT
Returns
-2×ln(L) value

Computes the negative log-likelihood assuming Poisson statistics for each bin. This is the preferred fit metric for low-count data where Gaussian approximations break down. The likelihood function is:

\[-2\ln\mathcal{L} = 2 \sum_{i} \left[ N_{\rm theo}(t_i) - N_i + N_i \ln\frac{N_i}{N_{\rm theo}(t_i)} \right]
\]

This is derived from the Poisson probability:

\[P(N_i | N_{\rm theo}) = \frac{N_{\rm theo}^{N_i} e^{-N_{\rm theo}}}{N_i!}
\]

The factor of 2 makes -2ln(L) asymptotically distributed as χ² for large N, allowing use of standard error estimation from MINUIT.

Algorithm:

  1. Extract N₀ from parameter vector or evaluate as a function
  2. Extract muon lifetime τ (defaults to PMUON_LIFETIME if not fitted)
  3. Extract background B (from fit parameter, fixed value, or estimated range)
  4. Evaluate all user-defined functions in FUNCTIONS block
  5. Pre-calculate theory at t=1.0 to initialize LF/user functions (thread-safe)
  6. Calculate normalizer = packing × t_res × 1000 (if fScaleN0AndBkg is true)
  7. Loop over fit range bins [fStartTimeBin, fEndTimeBin) using OpenMP parallelization
  8. For each bin:
    • Calculate theory N_theo(t)
    • If N_theo ≤ 0: skip bin with warning (negative theory is unphysical)
    • If N_data > 10⁻⁹: add (theo - data) + data×ln(data/theo)
    • If N_data ≈ 0: add (theo - data) only (limit as data→0)
  9. Accumulate -2ln(L) with reduction across threads
  10. Apply normalizer scaling

Edge Cases:

  • Zero data (Nᵢ = 0): Uses limit: -2ln(L) → 2×N_theo
  • Negative theory: Skips bin and prints warning (should not occur with valid parameters)
  • Data threshold: Uses 10⁻⁹ to distinguish zero from non-zero data

OpenMP Parallelization:

  • Dynamic scheduling with chunk size = (N_bins / N_processors), minimum 10
  • Private variables per thread: i, time, theo, data
  • Reduction performed on mllh sum (note: reduction(-:mllh) for subtraction)

When to Use Maximum Likelihood vs. χ²:

  • Use likelihood: Low count rates (< 100 counts/bin), asymmetric errors
  • Use χ²: High count rates (> 100 counts/bin), Gaussian regime
Parameters
parParameter vector from MINUIT2 optimizer
Returns
-2 × log(maximum likelihood) for the current parameter set
See also
CalcChiSquare(), CalcMaxLikelihoodExpected()
PDG Review of Particle Physics: Statistics section (http://pdg.lbl.gov)

Implements PRunBase.

Definition at line 455 of file PRunSingleHisto.cpp.

References fBackground, PRunBase::fData, fEndTimeBin, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, fStartTimeBin, PRunBase::fTheory, PRunBase::fTimeResolution, MSR_PARAM_FUN_OFFSET, PMUON_LIFETIME, and PMUSR_UNDEFINED.

◆ CalcMaxLikelihoodExpected()

Double_t PRunSingleHisto::CalcMaxLikelihoodExpected ( const std::vector< Double_t > & par)
virtual

Calculates expected maximum likelihood.

Calculates expected -2 log(maximum likelihood) using G-test formulation.

Parameters
parParameter vector from MINUIT
Returns
Expected -2×ln(L)

Computes an alternative form of the Poisson likelihood using only the data×ln(data/theo) term. This is related to the G-test (likelihood ratio test) and represents the "expected" contribution to the likelihood:

\[-2\ln\mathcal{L}_{\rm exp} = 2 \sum_{i} N_i \ln\frac{N_i}{N_{\rm theo}(t_i)}
\]

Difference from CalcMaxLikelihood():

  • Full likelihood: includes (theo - data) + data×ln(data/theo)
  • Expected likelihood: includes only data×ln(data/theo)

The omitted (theo - data) term represents the "prior" expectation and is constant for a given theory. This formulation is sometimes used in:

  • G-test for goodness-of-fit (likelihood ratio test)
  • Comparing relative likelihoods between models

Algorithm:

  1. Extract N₀, τ, and background B (same as CalcMaxLikelihood)
  2. Evaluate all user-defined functions in FUNCTIONS block
  3. Pre-calculate theory at t=1.0 to initialize LF/user functions (thread-safe)
  4. Calculate normalizer = packing × t_res × 1000 (if fScaleN0AndBkg is true)
  5. Loop over fit range bins using OpenMP parallelization
  6. For each bin with N_data > 10⁻⁹:
    • Calculate theory N_theo(t)
    • Add data × ln(data/theo) to likelihood sum
  7. Skip bins with N_data ≈ 0 (zero contribution to expected likelihood)
  8. Apply normalizer × 2.0 scaling
Warning
The comment "is this correct?? needs to be checked. See G-test" in the code indicates this implementation may need verification.

OpenMP Parallelization:

  • Dynamic scheduling with chunk size = (N_bins / N_processors), minimum 10
  • Private variables per thread: i, time, theo, data
  • Reduction performed on mllh sum
Parameters
parParameter vector from MINUIT2 optimizer
Returns
-2 × log(expected likelihood) for the current parameter set
See also
CalcMaxLikelihood(), G-test (likelihood ratio test)

Definition at line 590 of file PRunSingleHisto.cpp.

References fBackground, PRunBase::fData, fEndTimeBin, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, fStartTimeBin, PRunBase::fTheory, PRunBase::fTimeResolution, MSR_PARAM_FUN_OFFSET, PMUON_LIFETIME, and PMUSR_UNDEFINED.

◆ CalcNoOfFitBins()

void PRunSingleHisto::CalcNoOfFitBins ( )
virtual

Calculates start/end bin indices from fit time range.

Calculates the number of bins in the fit range and caches bin indices.

Converts fit range (μs) to bin indices, accounting for t0, time resolution, and packing. Updates fStartTimeBin, fEndTimeBin, fNoOfFitBins.

Converts the fit time range [fFitStartTime, fFitEndTime] to bin indices [fStartTimeBin, fEndTimeBin) and computes the total number of fit bins.

Algorithm:

  1. Calculate start bin: $ \lceil \frac{t_{\rm start} - t_{\rm data,0}}{\Delta t} \rceil $
  2. Clamp fStartTimeBin to [0, N_data)
  3. Calculate end bin: $ \lfloor \frac{t_{\rm end} - t_{\rm data,0}}{\Delta t} \rfloor + 1 $
  4. Clamp fEndTimeBin to [0, N_data]
  5. Compute fNoOfFitBins = fEndTimeBin - fStartTimeBin (or 0 if invalid)

where:

  • t_data,0 = fData.GetDataTimeStart() (time of first data bin)
  • Δt = fData.GetDataTimeStep() (time bin width after packing)

Edge Cases:

  • If fStartTimeBin < 0: clamped to 0
  • If fEndTimeBin > N_data: clamped to N_data
  • If fEndTimeBin ≤ fStartTimeBin: fNoOfFitBins = 0 (invalid range)
Note
This method is called automatically by GetNoOfFitBins() and by PrepareData() after setting up the data arrays.
See also
GetNoOfFitBins(), SetFitRangeBin()

Definition at line 951 of file PRunSingleHisto.cpp.

References PRunBase::fData, fEndTimeBin, PRunBase::fFitEndTime, PRunBase::fFitStartTime, fNoOfFitBins, and fStartTimeBin.

Referenced by GetNoOfFitBins(), PrepareFitData(), PrepareRawViewData(), and PrepareViewData().

◆ CalcTheory()

void PRunSingleHisto::CalcTheory ( )
virtual

Evaluates theory function at all data points or high-resolution grid.

Calculates theory curve N(t) for the current parameter values.

Calculates N_theory(t) = N₀·exp(-t/τ_μ)·P_theory(t) + B using THEORY block functions. Stores results in fData for χ² calculation.

Evaluates the single histogram theory function:

\[N(t) = N_0 e^{-t/\tau_\mu} [1 + P(t)] + B
\]

for all time bins in the data set, storing results in fData.fTheory. This is used for:

  • Displaying fitted theory curves in plots
  • Calculating residuals (data - theory)
  • Exporting theory predictions

Algorithm:

  1. Extract current parameter values from MSR parameter list
  2. Determine N₀ (from parameter or function evaluation)
  3. Determine muon lifetime τ (from parameter or default PMUON_LIFETIME)
  4. Determine background B (from fit parameter, fixed value, or estimate)
  5. Evaluate all user-defined functions in FUNCTIONS block
  6. Loop over all data bins (not just fit range):
    • Calculate time t for bin i
    • Evaluate P(t) = fTheory->Func(t, par, fFuncValues)
    • Calculate N(t) and append to theory vector
  7. Clean up temporary parameter vector

Time Grid:

  • Start time: fData.GetDataTimeStart()
  • Time step: fData.GetDataTimeStep()
  • Number of points: fData.GetValue()->size()
Note
Theory is calculated for the entire data range, not just the fit range, to enable full visualization of the model.
See also
PRunDataHandler::AppendTheoryValue(), PTheory::Func()

Implements PRunBase.

Definition at line 714 of file PRunSingleHisto.cpp.

References fBackground, PRunBase::fData, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, PRunBase::fRunInfo, PRunBase::fTheory, MSR_PARAM_FUN_OFFSET, PMUON_LIFETIME, and PMUSR_UNDEFINED.

◆ EstimateBkg()

Bool_t PRunSingleHisto::EstimateBkg ( UInt_t histoNo)
privatevirtual

Estimates background from pre-t0 bins.

Estimates background count rate from pre-t0 bins.

Calculates background average and error from specified bin range (typically before t0). Sets fBackground member.

Parameters
histoNoHistogram index
Returns
True on success, false if background range invalid

Calculates the average background rate from bins before the muon pulse arrives. For pulsed beam facilities (PSI, RAL, TRIUMF), adjusts the background interval to be a multiple of the beam period to avoid systematic biases from beam structure.

Algorithm:

  1. Extract background range [start, end] from MSR file (in bins)
  2. Validate start < end (swap if necessary)
  3. If pulsed beam (PSI/RAL/TRIUMF):
    • Calculate interval duration in time: t_bkg = (end - start) × t_res × packing
    • Find number of complete beam cycles: N_cycles = floor(t_bkg / T_beam)
    • Adjust end bin to match N_cycles × T_beam exactly
  4. Validate start and end are within histogram bounds
  5. Sum counts in [start, end]: Σ fForward[i]
  6. Calculate average: fBackground = Σ counts / (end - start)

Beam periods:

  • PSI: 19.75 ns (50.63 MHz cyclotron)
  • RAL (ISIS): 320 ns (3.125 MHz target)
  • TRIUMF: 43.0 ns (23.26 MHz cyclotron)
  • Other facilities: No period correction applied

Why adjust to beam period? Pulsed beams have time-dependent backgrounds from:

  • Flash (instantaneous background from beam pulse)
  • Prompt particles
  • Pion background

Averaging over complete beam cycles ensures unbiased background estimates by including all phases of the pulsed structure.

Edge cases:

  • If interval < 1 beam period: uses original end bin (no correction)
  • If start ≥ histogram length: returns false with error
  • If end ≥ histogram length: returns false with error
Parameters
histoNoForward histogram number (for error messages, currently not directly used)
Returns
true if background estimated successfully, false if bins out of bounds
Note
The estimated background is stored in fBackground member variable and subtracted from data in PrepareFitData() if not fitted.
See also
PrepareFitData(), ACCEL_PERIOD_PSI, ACCEL_PERIOD_RAL, ACCEL_PERIOD_TRIUMF

Definition at line 2310 of file PRunSingleHisto.cpp.

References ACCEL_PERIOD_PSI, ACCEL_PERIOD_RAL, ACCEL_PERIOD_TRIUMF, fBackground, fForward, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, and PRunBase::fTimeResolution.

Referenced by PrepareFitData(), PrepareRawViewData(), and PrepareViewData().

◆ EstimateN0()

void PRunSingleHisto::EstimateN0 ( )
privatevirtual

Estimates initial normalization N₀ from histogram data.

Automatically estimates the normalization parameter N₀ from data.

Calculates N₀ estimate from histogram amplitude, used as starting value if N₀ is a fit parameter.

Provides an intelligent initial guess for N₀ to help MINUIT convergence. The estimate is based on the maximum count rate in the fit range, accounting for muon decay and background.

When estimation is performed:

  • MSR file requests estimation (estimate_n0 flag in GLOBAL block)
  • Norm parameter is a fit parameter (not fixed, not a function)
  • Parameter step size ≠ 0 (i.e., not fixed)

When estimation is skipped:

  • Norm is a function (paramNo > MSR_PARAM_FUN_OFFSET)
  • Norm parameter is fixed (step = 0)
  • Invalid parameter number

Estimation algorithm:

  1. Find maximum value in fit range: max_data = max(N(t) in fit range)
  2. Find corresponding time t_max
  3. Extract or estimate background B
  4. Correct for exponential decay: N₀_est = (max_data - B) / exp(-t_max/τ_μ)
  5. Adjust for scaling if fScaleN0AndBkg is true
  6. Update parameter value and step size in MSR parameter list

Background handling:

  • If background is fitted: extract current background parameter value
  • If fixed background given: use fixed value
  • If background range given: use fBackground estimate
  • Otherwise: assume B = 0

Scaling adjustment: If fScaleN0AndBkg is true (normalizing to 1/ns), the estimate is divided by:

\[\text{scale factor} = \text{packing} \times (t_{\rm res} \times 1000)
\]

Note
This method modifies the MSR parameter list in place, updating both the parameter value and the step size (for MINUIT error estimation).
See also
IsScaleN0AndBkg(), EstimateBkg(), PrepareFitData()

Definition at line 2174 of file PRunSingleHisto.cpp.

References fForward, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, PRunBase::fT0s, PRunBase::fTimeResolution, and PMUON_LIFETIME.

Referenced by PrepareFitData().

◆ GetBackground()

virtual Double_t PRunSingleHisto::GetBackground ( )
inlinevirtual

Returns the estimated background level.

Returns
Background in counts/bin

Definition at line 286 of file PRunSingleHisto.h.

References fBackground.

◆ GetEndTimeBin()

virtual Int_t PRunSingleHisto::GetEndTimeBin ( )
inlinevirtual

Returns the last bin index in the fit range (exclusive).

Returns
End bin index (loop condition: i < fEndTimeBin)

Definition at line 298 of file PRunSingleHisto.h.

References fEndTimeBin.

◆ GetNoOfFitBins()

UInt_t PRunSingleHisto::GetNoOfFitBins ( )
virtual

Returns the number of bins included in the fit range.

Returns the number of bins in the current fit range.

Used for degrees of freedom: ν = N_bins - N_params

Returns
Number of bins in fit range

Calculates (if not already done) and returns the number of data bins that will be included in the χ² or likelihood calculation. This is determined by the fit range [fFitStartTime, fFitEndTime] and the data time grid.

The calculation is performed by CalcNoOfFitBins(), which sets:

  • fStartTimeBin: first bin index in fit range
  • fEndTimeBin: one past last bin index in fit range
  • fNoOfFitBins = fEndTimeBin - fStartTimeBin
Returns
Number of bins in the fit range (degrees of freedom = N_bins - N_params)
See also
CalcNoOfFitBins(), SetFitRangeBin()

Definition at line 792 of file PRunSingleHisto.cpp.

References CalcNoOfFitBins(), and fNoOfFitBins.

◆ GetPacking()

virtual Int_t PRunSingleHisto::GetPacking ( )
inlinevirtual

Returns the bin packing factor.

Returns
Number of raw bins combined into one packed bin

Definition at line 304 of file PRunSingleHisto.h.

References fPacking.

◆ GetProperDataRange()

Bool_t PRunSingleHisto::GetProperDataRange ( )
privatevirtual

Determines data range (region of valid histogram data).

Determines the data range (first good bin / last good bin).

Establishes start/end bins for analysis from RUN block "data" entry. Data range is typically wider than fit range.

Returns
True if valid data range determined

Establishes which histogram bins contain valid muon decay data by finding the "first good bin" (fgb) and "last good bin" (lgb). This range excludes:

  • Pre-t0 bins (before muon arrival)
  • Early bins affected by detector dead time or pileup
  • Late bins with insufficient statistics

Priority hierarchy (highest to lowest):

  1. RUN block: Explicitly specified fgb/lgb in RUN block
  2. GLOBAL block: Default fgb/lgb from GLOBAL block
  3. Auto-estimation: Fallback estimates with warning

Auto-estimation (if not specified):

  • fgb: t0 + 10 ns (to avoid dead time issues)
  • lgb: End of histogram (all bins)

Validation:

  1. Check fgb < lgb (swap if necessary)
  2. Check 0 ≤ fgb < histogram length
  3. Check 0 ≤ lgb ≤ histogram length
  4. If lgb > histogram length: clamp to (length - 1) and print warning

Storage: Results are stored in:

  • fGoodBins[0] = fgb (first good bin index)
  • fGoodBins[1] = lgb (last good bin index)

These values are used by:

Returns
true if data range is valid and within bounds, false if validation fails
Warning
Auto-estimated ranges may not be appropriate for all detectors. Explicit specification in MSR file is strongly recommended.
Note
This method is called by PrepareData() after histogram grouping but before packing and fit range determination.
See also
PrepareData(), GetProperFitRange(), fGoodBins

Definition at line 1962 of file PRunSingleHisto.cpp.

References fForward, fGoodBins, PRunBase::fMsrInfo, PRunBase::fRunInfo, PRunBase::fT0s, and PRunBase::fTimeResolution.

Referenced by PrepareData().

◆ GetProperFitRange()

void PRunSingleHisto::GetProperFitRange ( PMsrGlobalBlock * globalBlock)
privatevirtual

Determines fit range from MSR file settings.

Determines the fit range (start and end times for χ² calculation).

Extracts fit time window from RUN or GLOBAL block "fit" entry. Format: time-based (μs) or bin-based (fgb+n0 lgb-n1).

Parameters
globalBlockGLOBAL block with default fit settings

Establishes the time window [t_start, t_end] over which the fit will be performed. The fit range can be specified in two ways:

Specification methods:

  1. Time-based: fit <start> <end> in microseconds
    • Example: fit 0.1 10.0 (fit from 0.1 to 10.0 μs after t0)
  2. Bin-based: fit fgb[+offset0] lgb[-offset1] in bins
    • Example: fit fgb+10 lgb-20 (fit from 10 bins after fgb to 20 bins before lgb)

Priority hierarchy (highest to lowest):

  1. RUN block time-based: fit <start> <end> in RUN block
  2. RUN block bin-based: fit fgb+n0 lgb-n1 in RUN block
  3. GLOBAL block time-based: fit <start> <end> in GLOBAL block
  4. GLOBAL block bin-based: fit fgb+n0 lgb-n1 in GLOBAL block
  5. Auto-fallback: Use entire data range [fgb, lgb]

Bin-based conversion to time: When fit range is given in bins, it's converted to time:

\[t_{\rm start} = (\text{fgb} + n_0 - t_0) \times \Delta t
\]

\[t_{\rm end} = (\text{lgb} - n_1 - t_0) \times \Delta t
\]

where:

  • fgb/lgb = first/last good bin from GetProperDataRange()
  • n₀/n₁ = offsets (can be positive or negative)
  • t₀ = time-zero bin
  • Δt = time resolution (fTimeResolution in μs)

Storage and updates:

  • fFitStartTime, fFitEndTime are set to the determined range
  • If bin-based, the converted time values are written back to the MSR data structure for log file reporting

Fallback behavior: If no fit range is specified anywhere, uses the entire data range:

\[t_{\rm start} = (\text{fgb} - t_0) \times \Delta t
\]

\[t_{\rm end} = (\text{lgb} - t_0) \times \Delta t
\]

and prints a warning to std::cerr.

Parameters
globalBlockPointer to GLOBAL block from MSR file
Note
This method is called by PrepareData() after GetProperDataRange() has established fGoodBins[0] and fGoodBins[1].
See also
PrepareData(), GetProperDataRange(), SetFitRangeBin(), CalcNoOfFitBins()

Definition at line 2096 of file PRunSingleHisto.cpp.

References PRunBase::fFitEndTime, PRunBase::fFitStartTime, fGoodBins, PRunBase::fRunInfo, PRunBase::fT0s, PRunBase::fTimeResolution, PMsrGlobalBlock::GetFitRange(), PMsrGlobalBlock::GetFitRangeOffset(), PMsrGlobalBlock::IsFitRangeInBin(), PMUSR_UNDEFINED, and PMsrGlobalBlock::SetFitRange().

Referenced by PrepareData().

◆ GetProperT0()

Bool_t PRunSingleHisto::GetProperT0 ( PRawRunData * runData,
PMsrGlobalBlock * globalBlock,
PUIntVector & histoNo )
privatevirtual

Determines and validates t0 values for histogram.

Determines time-zero (t0) values for all histograms using hierarchical fallback.

Extracts time-zero from RUN block, data file header, GLOBAL block, or automatic determination. Validates t0 is within histogram bounds.

Parameters
runDataRaw run data
globalBlockGLOBAL block settings
histoNoVector of histogram indices
Returns
True if valid t0 found

Time-zero (t0) marks the muon arrival time in each detector histogram, the reference point from which decay time is measured. This method uses a priority system to find t0 values:

Priority hierarchy (highest to lowest):

  1. RUN block t0: Explicitly specified in the RUN block (highest priority)
  2. GLOBAL block t0: Default t0 for all runs in the GLOBAL block
  3. Data file t0: Stored in the raw data file (from previous analysis)
  4. Estimated t0: Automatic estimation (UNRELIABLE, prints warning)

For ADDRUN support: If multiple runs are added (fRunInfo->GetRunNameSize() > 1), this method also determines t0 values for each added run (fAddT0s) using the same hierarchy. Proper t0 alignment is essential for correct ADDRUN operation.

Algorithm:

  1. Resize fT0s vector to histogram count (number of grouped detectors)
  2. Initialize all t0 values to -1.0 (sentinel for "not set")
  3. Fill from RUN block (if specified)
  4. Fill from GLOBAL block where still -1.0
  5. Fill from data file where still -1.0
  6. Fill from estimation where still -1.0 (prints WARNING)
  7. Validate all t0 values are within histogram bounds
  8. If ADDRUN present: repeat steps 2-6 for each added run

Validation: After fallback, checks that each t0 satisfies:

\[0 \leq t_0 \leq N_{\rm bins}
\]

If validation fails, returns false with error message.

Parameters
runDataPointer to raw run data handler for main run
globalBlockPointer to GLOBAL block from MSR file
histoNoVector of histogram indices (zero-based, after redGreen offset correction)
Returns
true if all t0 values found and validated, false if any t0 is out of bounds
Warning
Estimated t0 values (fallback option #4) are often UNRELIABLE, especially for low-energy muons (LEM). Manual specification in MSR file is strongly recommended. A warning is printed to std::cerr when estimation is used.
Note
This method updates fT0s (main run) and fAddT0s (ADDRUN) member variables. It also updates the MSR file handler with found t0 values for persistence.
See also
PrepareData(), fT0s, fAddT0s

Definition at line 1797 of file PRunSingleHisto.cpp.

References PRunBase::fAddT0s, PRunBase::fRawData, PRunBase::fRunInfo, PRunBase::fT0s, PRawRunData::GetDataBin(), PMsrGlobalBlock::GetT0Bin(), PRawRunData::GetT0Bin(), PRawRunData::GetT0BinEstimated(), and PMsrGlobalBlock::GetT0BinSize().

Referenced by PrepareData().

◆ GetScaleN0AndBkg()

virtual Bool_t PRunSingleHisto::GetScaleN0AndBkg ( )
inlinevirtual

Returns the N₀/background scaling mode.

Returns
true = scaled to 1/ns, false = left as 1/bin

Definition at line 310 of file PRunSingleHisto.h.

References fScaleN0AndBkg.

◆ GetStartTimeBin()

virtual Int_t PRunSingleHisto::GetStartTimeBin ( )
inlinevirtual

Returns the first bin index in the fit range.

Returns
Start bin index (0-based, after packing)

Definition at line 292 of file PRunSingleHisto.h.

References fStartTimeBin.

◆ IsScaleN0AndBkg()

Bool_t PRunSingleHisto::IsScaleN0AndBkg ( )
privatevirtual

Determines if N₀ and background should be scaled to 1/ns.

Determines if N₀ and background should be normalized to 1/ns.

Checks time resolution and fitting preferences to decide scaling mode. Returns true for standard time bins (scale to 1/ns), false otherwise.

Returns
True if scaling should be applied

Checks whether N₀ and background parameters should be scaled to represent count rates per nanosecond (1/ns) rather than counts per packed bin.

Default behavior: Scaling is ENABLED (true)

This makes fitted parameters physically meaningful and independent of packing:

  • N₀ represents the initial muon decay rate at t=0 in counts/ns
  • Background B represents constant background rate in counts/ns

To disable scaling: Add to MSR file COMMAND block:

SCALE_N0_BKG FALSE
#define FALSE
Definition mud.h:161

When to disable scaling:

  • When N₀ and B should represent total counts per packed bin
  • When comparing with older analysis that didn't use scaling
  • When packing is 1 (no difference between modes)

Effect on fit parameters:

  • Scaled (default): N₀ and B independent of packing choice
  • Unscaled: N₀ and B depend on packing value

Implementation details: Scaling is applied in:

These operations cancel out mathematically but keep parameters in 1/ns units.

Returns
true if N₀ and background should be scaled to 1/ns (default), false if they should represent counts per packed bin
Note
This method is called during construction to set fScaleN0AndBkg.
See also
CalcChiSquare(), CalcMaxLikelihood(), PrepareFitData(), EstimateBkg()

Definition at line 2426 of file PRunSingleHisto.cpp.

References PRunBase::fMsrInfo.

Referenced by PRunSingleHisto().

◆ PrepareData()

Bool_t PRunSingleHisto::PrepareData ( )
protectedvirtual

Main data preparation orchestrator.

Main data preprocessing pipeline for single histogram runs.

Coordinates histogram loading and preprocessing: determines operation mode, calls PrepareFitData() or PrepareViewData(), validates success.

Returns
True if data preparation succeeds, false on error

Orchestrates the complete data loading and preprocessing workflow:

  1. Load raw data: Fetch run from PRunDataHandler using run name
  2. Extract metadata: Magnetic field, beam energy, temperature(s)
  3. Validate histograms: Check that forward histogram numbers exist in data file
  4. Get time resolution: Extract bin width (typically 0.1-10 ns)
  5. Determine t0: Call GetProperT0() for muon arrival times
  6. Load histogram data: Copy forward histogram bins from raw data
  7. Add runs (ADDRUN): If multiple runs specified, add them with t0 alignment
  8. Group histograms: Sum multiple detectors within a group (with t0 alignment)
  9. Get data range (fgb/lgb): Call GetProperDataRange() for good bin limits
  10. Get fit range: Call GetProperFitRange() for fit time window
  11. Check lifetime correction: Determine if exponential decay should be removed (for viewing)
  12. Dispatch to preparation:

ADDRUN t0 Alignment: When adding runs, histograms are aligned by their t0 values:

forward[k][j] += addRunData[k]->at(j + addT0[k] - mainT0[k])

This ensures muon arrival times coincide across added runs.

Grouping t0 Alignment: When grouping histograms, they are aligned to the first histogram's t0:

fForward[j] += forward[i][j + t0[i] - t0[0]]
PDoubleVector fForward
Forward detector histogram (background-corrected, packed)
Returns
true if all preprocessing steps succeeded, false otherwise
Note
If any step fails (missing data file, invalid histogram numbers, t0 errors), this method returns false and error messages are printed to std::cerr.
See also
GetProperT0(), GetProperDataRange(), GetProperFitRange(), PrepareFitData(), PrepareRawViewData(), PrepareViewData()

Implements PRunBase.

Definition at line 1011 of file PRunSingleHisto.cpp.

References PRunBase::DeadTimeCorrection(), PRunBase::fAddT0s, fForward, PRunBase::fHandleTag, PRunBase::fMetaData, PRunBase::fMsrInfo, PRunBase::fRawData, PRunBase::fRunInfo, PRunBase::fT0s, PRunBase::fTimeResolution, PRunBase::fValid, PRawRunData::GetDataBin(), PRawRunData::GetEnergy(), PRawRunData::GetField(), PRawRunData::GetNoOfTemperatures(), GetProperDataRange(), GetProperFitRange(), GetProperT0(), PRawRunData::GetTemperature(), PRawRunData::GetTimeResolution(), PRawRunData::IsPresent(), kFit, kView, PrepareFitData(), PrepareRawViewData(), and PrepareViewData().

Referenced by PRunSingleHisto().

◆ PrepareFitData()

Bool_t PRunSingleHisto::PrepareFitData ( PRawRunData * runData,
const UInt_t histoNo )
protectedvirtual

Prepares histogram data for fitting.

Prepares histogram data for fitting (kFit mode).

Loads forward histogram, extracts metadata, determines t0, subtracts background, packs bins, propagates errors, sets up time grid and fit ranges.

Parameters
runDataRaw run data handler
histoNoHistogram index in data file
Returns
True on success, false if preprocessing fails

Performs final data transformations after PrepareData() has loaded and grouped the raw histogram data:

  1. Estimate N₀ (optional): If MSR file requests it, call EstimateN0()
  2. Handle background:
    • If background is fitted: leave data unchanged
    • If fixed background given: subtract it from all bins
    • If background range given: call EstimateBkg() and subtract estimate
    • If nothing specified: auto-estimate from bins [0.1×t0, 0.6×t0] with warning
  3. Packing (rebinning): Combine consecutive bins to improve statistics:
    • If packing = 1: copy bins directly
    • If packing > 1: sum every 'packing' bins into one
  4. Normalization: If fScaleN0AndBkg is true, divide by (packing × t_res × 1000) to normalize counts to 1/ns
  5. Error calculation:
    • If N > 0: σ = √N (Poisson statistics)
    • If N = 0: σ = 1/normalizer (avoid division by zero in χ²)
  6. Set time grid:
    • Data start time: (fgb - 0.5 + pack/2 - t0) × t_res
    • Data time step: pack × t_res
  7. Calculate fit bins: Call CalcNoOfFitBins() to set fStartTimeBin, fEndTimeBin

Packing Algorithm:

for (i = fgb; i < lgb; i++) {
value += forward[i];
if ((i-fgb) % packing == 0 && i != fgb) {
data.push_back(value / normalizer);
error.push_back(sqrt(value) / normalizer);
value = 0;
}
}

Background Handling Priority:

  1. Check if background is fitted (bkgFitParamNo ≠ -1) → leave data as-is
  2. Check if fixed background given (bkgFix ≠ PMUSR_UNDEFINED) → subtract fixed value
  3. Check if background range given (bkgRange[0] ≥ 0) → estimate and subtract
  4. Fallback: auto-estimate from [0.1×t0, 0.6×t0] → print warning
Parameters
runDataPointer to raw run data handler (for metadata access)
histoNoForward histogram number (for background estimation)
Returns
true if preparation succeeded, false if EstimateBkg() failed
Note
This method populates fData (PRunData object) with packed data ready for fitting.
See also
PrepareData(), EstimateBkg(), EstimateN0(), CalcNoOfFitBins()

Definition at line 1213 of file PRunSingleHisto.cpp.

References CalcNoOfFitBins(), EstimateBkg(), EstimateN0(), PRunBase::fData, fForward, fGoodBins, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, PRunBase::fT0s, PRunBase::fTimeResolution, and PMUSR_UNDEFINED.

Referenced by PrepareData().

◆ PrepareRawViewData()

Bool_t PRunSingleHisto::PrepareRawViewData ( PRawRunData * runData,
const UInt_t histoNo )
protectedvirtual

Prepares raw histogram data for viewing (minimal processing).

Lighter-weight preprocessing for raw histogram visualization without background subtraction or full fitting infrastructure.

Parameters
runDataRaw run data handler
histoNoHistogram index
Returns
True on success

Take the pre-processed data (i.e. grouping and addrun are preformed) and form the histogram for viewing without any life time correction.

The following steps are preformed:

  1. check if view packing is whished.
  2. check that 'first good data bin', 'last good data bin', and 't0' makes any sense
  3. packing (i.e. rebinnig)
  4. calculate theory

return:

  • true, if everything went smooth
  • false, otherwise.
Parameters
runDataraw run data handler
histoNoforward histogram number

Definition at line 1306 of file PRunSingleHisto.cpp.

References CalcNoOfFitBins(), EstimateBkg(), fBackground, PRunBase::fData, fForward, PRunBase::fFuncValues, fGoodBins, PRunBase::fMetaData, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, PRunBase::fT0s, fTheoAsData, PRunBase::fTheory, PRunBase::fTimeResolution, MSR_PARAM_FUN_OFFSET, PMUON_LIFETIME, and PMUSR_UNDEFINED.

Referenced by PrepareData().

◆ PrepareViewData()

Bool_t PRunSingleHisto::PrepareViewData ( PRawRunData * runData,
const UInt_t histoNo )
protectedvirtual

Prepares processed histogram data for viewing/plotting.

Similar to PrepareFitData() but optimized for visualization with potentially wider time range for context.

Parameters
runDataRaw run data handler
histoNoHistogram index
Returns
True on success

Take the pre-processed data (i.e. grouping and addrun are preformed) and form the histogram for viewing with life time correction, i.e. the exponential decay is removed.

The following steps are preformed:

  1. check if view packing is whished.
  2. check that 'first good data bin', 'last good data bin', and 't0' makes any sense
  3. transform data sets (see below).
  4. calculate theory

Muon life time corrected data: Starting from

\[ N(t) = N_0 e^{-t/\tau} [ 1 + A(t) ] + \mathrm{Bkg} \]

it follows that

\[ A(t) = (-1) + e^{+t/\tau}\, \frac{N(t)-\mathrm{Bkg}}{N_0}. \]

For the error estimate only the statistical error of $ N(t) $ is used, and hence

\[ \Delta A(t) = \frac{e^{t/\tau}}{N_0}\,\sqrt{\frac{N(t)}{p}} \]

where $ p $ is the packing, and $ N(t) $ are the packed data, i.e.

\[ N(t_i) = \frac{1}{p}\, \sum_{j=i}^{i+p} n_j \]

with $ n_j $ the raw histogram data bins.

return:

  • true, if everything went smooth
  • false, otherwise
Parameters
runDataraw run data handler
histoNoforward histogram number

Definition at line 1495 of file PRunSingleHisto.cpp.

References CalcNoOfFitBins(), PRunBase::CalculateKaiserFilterCoeff(), EstimateBkg(), fBackground, PRunBase::fData, fForward, PRunBase::fFuncValues, fGoodBins, PRunBase::FilterTheo(), PRunBase::fMetaData, PRunBase::fMsrInfo, fPacking, PRunBase::fRunInfo, fScaleN0AndBkg, PRunBase::fT0s, fTheoAsData, PRunBase::fTheory, PRunBase::fTimeResolution, GAMMA_BAR_MUON, MSR_PARAM_FUN_OFFSET, PMUON_LIFETIME, PMUSR_UNDEFINED, RRF_UNIT_G, RRF_UNIT_kHz, RRF_UNIT_Mcs, RRF_UNIT_MHz, and RRF_UNIT_T.

Referenced by PrepareData().

◆ SetFitRangeBin()

void PRunSingleHisto::SetFitRangeBin ( const TString fitRange)
virtual

Sets fit range using bin-offset specification (COMMANDS block syntax).

Dynamically changes the fit range from COMMAND block instructions.

Format: "fit_range fgb+n0 lgb-n1"

Parameters
fitRangeString with bin offsets from good bin markers

Parses and applies a FIT_RANGE command to modify the fit range on the fly, typically used during interactive fitting sessions or systematic scans.

Syntax (in COMMAND block):

FIT_RANGE fgb[+n00] lgb[-n01] [fgb[+n10] lgb[-n11] ... fgb[+nN0] lgb[-nN1]]

where:

  • fgb: First good bin (start of fit range)
  • lgb: Last good bin (end of fit range)
  • +nXY / -nXY: Optional offsets to shift the range (+ extends, - contracts)
  • Multiple pairs: If N+1 pairs given, they apply to each of N RUN blocks

Two modes:

  1. Single pair: FIT_RANGE fgb lgb applies to all runs
  2. Per-run pairs: FIT_RANGE fgb₀ lgb₀ fgb₁ lgb₁ ... applies pair i to RUN block i

Algorithm:

  1. Tokenize the fitRange string by spaces/tabs
  2. If 3 tokens (FIT_RANGE + 2 values): apply to this run
  3. If >3 tokens and odd number: extract pair for this run's index (fRunNo)
  4. Parse offsets from + or - characters in fgb/lgb strings
  5. Calculate new fFitStartTime and fFitEndTime:
    • fFitStartTime = (fGoodBins[0] + offset - t0) × t_res
    • fFitEndTime = (fGoodBins[1] - offset - t0) × t_res

Example:

FIT_RANGE 100+10 500-20 # Fit from bin 110 to bin 480 (applying offsets)
Parameters
fitRangeString from COMMAND block containing FIT_RANGE specification
Note
Errors in parsing (wrong number of tokens) are reported to std::cerr and the command is ignored.
See also
CalcNoOfFitBins(), GetProperFitRange()

Definition at line 845 of file PRunSingleHisto.cpp.

References PRunBase::fFitEndTime, PRunBase::fFitStartTime, fGoodBins, PRunBase::fRunNo, PRunBase::fT0s, and PRunBase::fTimeResolution.

Member Data Documentation

◆ fBackground

Double_t PRunSingleHisto::fBackground
private

Background level in counts/bin (estimated from pre-t0 bins or fixed value from RUN block)

Definition at line 370 of file PRunSingleHisto.h.

Referenced by CalcChiSquare(), CalcChiSquareExpected(), CalcMaxLikelihood(), CalcMaxLikelihoodExpected(), CalcTheory(), EstimateBkg(), GetBackground(), PrepareRawViewData(), PrepareViewData(), PRunSingleHisto(), and PRunSingleHisto().

◆ fEndTimeBin

Int_t PRunSingleHisto::fEndTimeBin
private

Last bin index in fit range (exclusive: loop as i < fEndTimeBin)

Definition at line 379 of file PRunSingleHisto.h.

Referenced by CalcChiSquare(), CalcChiSquareExpected(), CalcMaxLikelihood(), CalcMaxLikelihoodExpected(), CalcNoOfFitBins(), GetEndTimeBin(), PRunSingleHisto(), and PRunSingleHisto().

◆ fForward

PDoubleVector PRunSingleHisto::fForward
private

Forward detector histogram (background-corrected, packed)

Definition at line 376 of file PRunSingleHisto.h.

Referenced by EstimateBkg(), EstimateN0(), GetProperDataRange(), PrepareData(), PrepareFitData(), PrepareRawViewData(), PrepareViewData(), and ~PRunSingleHisto().

◆ fGoodBins

Int_t PRunSingleHisto::fGoodBins[2]
private

Good bin markers for COMMANDS block: [0]=fgb (first good bin/t0), [1]=lgb (last good bin)

Definition at line 374 of file PRunSingleHisto.h.

Referenced by GetProperDataRange(), GetProperFitRange(), PrepareFitData(), PrepareRawViewData(), PrepareViewData(), PRunSingleHisto(), PRunSingleHisto(), and SetFitRangeBin().

◆ fNoOfFitBins

UInt_t PRunSingleHisto::fNoOfFitBins
private

Number of bins within fit range (fStartTimeBin to fEndTimeBin)

Definition at line 369 of file PRunSingleHisto.h.

Referenced by CalcNoOfFitBins(), GetNoOfFitBins(), PRunSingleHisto(), and PRunSingleHisto().

◆ fPacking

Int_t PRunSingleHisto::fPacking
private

◆ fScaleN0AndBkg

Bool_t PRunSingleHisto::fScaleN0AndBkg
private

◆ fStartTimeBin

Int_t PRunSingleHisto::fStartTimeBin
private

First bin index in fit range (inclusive, 0-based after packing)

Definition at line 378 of file PRunSingleHisto.h.

Referenced by CalcChiSquare(), CalcChiSquareExpected(), CalcMaxLikelihood(), CalcMaxLikelihoodExpected(), CalcNoOfFitBins(), GetStartTimeBin(), PRunSingleHisto(), and PRunSingleHisto().

◆ fTheoAsData

Bool_t PRunSingleHisto::fTheoAsData
private

Theory mode: true = at data points, false = high-resolution grid for smooth Fourier transforms.

Definition at line 372 of file PRunSingleHisto.h.

Referenced by PrepareRawViewData(), PrepareViewData(), PRunSingleHisto(), and PRunSingleHisto().


The documentation for this class was generated from the following files: