musrfit 1.10.0
PRunSingleHistoRRF Class Reference

Class for fitting single histogram data in a Rotating Reference Frame (RRF). More...

#include <PRunSingleHistoRRF.h>

Inheritance diagram for PRunSingleHistoRRF:
Collaboration diagram for PRunSingleHistoRRF:

Public Member Functions

 PRunSingleHistoRRF ()
 Default constructor creating an empty, invalid RRF single histogram run object.
 
 PRunSingleHistoRRF (PMsrHandler *msrInfo, PRunDataHandler *rawData, UInt_t runNo, EPMusrHandleTag tag, Bool_t theoAsData)
 Main constructor initializing RRF single histogram run from MSR file and data.
 
virtual ~PRunSingleHistoRRF ()
 Virtual destructor releasing allocated resources.
 
virtual Double_t CalcChiSquare (const std::vector< Double_t > &par)
 Calculates χ² between RRF-transformed data and theory.
 
virtual Double_t CalcChiSquareExpected (const std::vector< Double_t > &par)
 Calculates expected χ² using theory variance instead of data variance.
 
virtual Double_t CalcMaxLikelihood (const std::vector< Double_t > &par)
 Calculates maximum likelihood (not yet implemented for RRF).
 
virtual void CalcTheory ()
 Evaluates theory function at all data points for viewing/plotting.
 
virtual UInt_t GetNoOfFitBins ()
 Returns the number of bins included in the current fit range.
 
virtual void SetFitRangeBin (const TString fitRange)
 Sets fit range using bin-offset syntax from COMMANDS block.
 
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 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 for RRF single histogram analysis.
 
virtual Bool_t PrepareFitData (PRawRunData *runData, const UInt_t histoNo)
 Performs full RRF transformation for fitting.
 
virtual Bool_t PrepareViewData (PRawRunData *runData, const UInt_t histoNo)
 Prepares RRF 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 all histograms.
 
virtual Bool_t GetProperDataRange ()
 Determines valid data range (first/last good bins).
 
virtual void GetProperFitRange (PMsrGlobalBlock *globalBlock)
 Determines fit time range from MSR file settings.
 
virtual Double_t GetMainFrequency (PDoubleVector &data)
 Finds the dominant precession frequency in raw data.
 
virtual Double_t EstimateN0 (Double_t &errN0, Double_t freqMax)
 Estimates initial normalization N₀ from lifetime-corrected data.
 
virtual Bool_t EstimateBkg (UInt_t histoNo)
 Estimates background from pre-t0 bins.
 

Private Attributes

Double_t fN0EstimateEndTime
 End time (μs) for N₀ estimation window. Rounded to integer number of oscillation cycles based on main frequency.
 
UInt_t fNoOfFitBins
 Number of RRF-packed bins within fit range [fStartTimeBin, fEndTimeBin)
 
Double_t fBackground
 Estimated or fixed background level in counts/bin (before packing)
 
Double_t fBkgErr
 Statistical error on background estimate (std dev of background region)
 
Int_t fRRFPacking
 RRF packing factor from GLOBAL block (number of raw bins averaged together)
 
Bool_t fTheoAsData
 Theory resolution mode: true = at data points only, false = 8× finer grid for smooth Fourier transforms.
 
Int_t fGoodBins [2]
 Good bin range: [0] = first good bin (fgb), [1] = last good bin (lgb). Used for COMMANDS block fit range specification.
 
Int_t fStartTimeBin
 First bin index in fit range (inclusive, 0-based in RRF-packed data)
 
Int_t fEndTimeBin
 Last bin index in fit range (exclusive: loop as i < fEndTimeBin)
 
PDoubleVector fForward
 Forward detector histogram data (progressively transformed during preparation)
 
PDoubleVector fM
 Lifetime-corrected histogram: M(t) = [N(t) - B] × exp(+t/τ_μ). Used for N₀ estimation.
 
PDoubleVector fMerr
 Error on M(t): σ_M = exp(+t/τ_μ) × √(N(t) + σ_B²). Includes background error.
 
PDoubleVector fW
 Weights for N₀ estimation: W(t) = 1/σ_M². Used in weighted average.
 
PDoubleVector fAerr
 Asymmetry errors before RRF packing. Used for packed error calculation.
 

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 histogram data in a Rotating Reference Frame (RRF).

PRunSingleHistoRRF implements single histogram analysis with Rotating Reference Frame transformation. This technique is essential for high transverse field (TF) μSR measurements where the precession frequency is too high to resolve directly.

Physics Background

The Problem with High-Field μSR:

  • At fields B > ~0.5 T, muon precession frequency ω = γ_μ B exceeds ~70 MHz
  • Standard time-domain analysis struggles: requires sub-ns binning → low statistics
  • Frequency-domain (Fourier) analysis has limited resolution

The RRF Solution:

  • Transform to a reference frame rotating at frequency ω_RRF ≈ ω_signal
  • In rotating frame: effective frequency Δω = ω_signal - ω_RRF << ω_signal
  • Low-frequency signal can be fit with standard time-domain techniques
  • Preserves full information: relaxation rates, frequency distributions

Mathematical Transformation

Data processing steps:

  1. Background subtraction: N(t) → N(t) - B
  2. Lifetime correction: N(t) - B → [N(t) - B] × exp(+t/τ_μ) = M(t)
  3. N₀ estimation: Fit M(t) over initial time window to extract N₀
  4. Asymmetry extraction: A(t) = M(t)/N₀ - 1
  5. RRF rotation: A_RRF(t) = 2 × A(t) × cos(ω_RRF t + φ_RRF)
  6. RRF packing: Average over multiple bins to filter high-frequency components

The factor of 2 in step 5 compensates for the loss of the counter-rotating component when the high-frequency part is suppressed by packing.

Theory function in RRF: The polarization function P(t) transforms as:

\[P_{\rm RRF}(t) = 2 \cdot P(t) \cdot \cos(\omega_{\rm RRF} t + \phi_{\rm RRF})
\]

For a simple oscillation P(t) = A·cos(ωt + φ)·exp(-λt), this becomes:

\[P_{\rm RRF}(t) = A \cdot [\cos((\omega - \omega_{\rm RRF})t + \phi - \phi_{\rm RRF}) + \text{high freq.}] \cdot e^{-\lambda t}
\]

After RRF packing, only the low-frequency component Δω = ω - ω_RRF remains.

GLOBAL Block Requirements

RRF analysis REQUIRES the following entries in the GLOBAL block:

  • rrf_freq: RRF rotation frequency (value + unit: MHz, Mc, T, G, kG)
  • rrf_phase: RRF initial phase in degrees
  • rrf_packing: Number of bins to average (filters high frequencies)

MSR File Example

GLOBAL
rrf_freq 13.554 T # RRF frequency equivalent to 13.554 Tesla
rrf_phase 45.0 # RRF phase in degrees
rrf_packing 25 # Average 25 bins to suppress high-freq component
data 200 60000 # Data range (fgb lgb)
fit 0.1 8.0 # Fit range in μs
RUN data/run2425 PSI MUE4 PSI MUSR-ROOT
fittype 8 (SingleHistoRRF)
map 1
forward 1
background 50 150
t0 210.5

Data Processing Workflow

  1. PrepareData(): Load raw histogram, determine t0, group/add histograms
  2. PrepareFitData():
    • Subtract background (estimated or fixed)
    • Apply lifetime correction: exp(+t/τ_μ)
    • Estimate N₀ using Fourier analysis to find main frequency
    • Extract asymmetry: A(t) = M(t)/N₀ - 1
    • Apply RRF rotation: A_RRF(t) = 2·A(t)·cos(ω_RRF t + φ_RRF)
    • Pack data (average over rrf_packing bins)
    • Calculate errors with proper propagation

Error Propagation

RRF asymmetry error (unpacked):

\[\sigma_{A}(t) = \frac{e^{t/\tau_\mu}}{N_0} \sqrt{N(t) + \left(\frac{N(t)-B}{N_0}\right)^2 \sigma_{N_0}^2}
\]

After RRF packing (n bins):

\[\sigma_{A_{\rm RRF}}^{\rm packed} = \frac{\sqrt{2}}{n} \sqrt{\sum_{i=1}^{n} \sigma_{A}^2(t_i)}
\]

The √2 factor accounts for the doubling in the RRF transformation.

Applications

High-TF μSR experiments:

  • Knight shift measurements (NMR-like)
  • Vortex state studies in type-II superconductors
  • Diamagnetic/paramagnetic shift measurements
  • Internal field distributions in magnets
See also
PRunSingleHisto for standard (non-RRF) single histogram analysis
PRunAsymmetryRRF for RRF asymmetry (forward-backward) analysis
PRunBase for base class interface

Definition at line 144 of file PRunSingleHistoRRF.h.

Constructor & Destructor Documentation

◆ PRunSingleHistoRRF() [1/2]

PRunSingleHistoRRF::PRunSingleHistoRRF ( )

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

Default constructor for RRF single histogram fitting class.

Initializes member variables to default/invalid states:

  • fNoOfFitBins = 0
  • fBackground = 0
  • fBkgErr = 1.0 (default error estimate)
  • fRRFPacking = -1 (invalid, must be set from GLOBAL block)
  • fTheoAsData = false
  • fGoodBins[0,1] = -1 (unset)
  • fN0EstimateEndTime = 1.0 μs

This constructor exists for container compatibility. The resulting object cannot be used until properly initialized.

Initializes all member variables to safe default values:

  • fNoOfFitBins = 0 (no bins to fit)
  • fBackground = 0 (will be estimated or set from MSR file)
  • fBkgErr = 1.0 (default error estimate)
  • fRRFPacking = -1 (invalid until set from GLOBAL block)
  • fTheoAsData = false (high-resolution theory grid)
  • fGoodBins[0,1] = -1 (calculated from data range)
  • fN0EstimateEndTime = 1.0 μs (default N₀ estimation window)
Warning
This constructor creates an invalid object that cannot be used until properly initialized with MSR file data. Use the full constructor for normal operation.
See also
PRunSingleHistoRRF(PMsrHandler*, PRunDataHandler*, UInt_t, EPMusrHandleTag, Bool_t)

Definition at line 74 of file PRunSingleHistoRRF.cpp.

References fBackground, fBkgErr, fGoodBins, fN0EstimateEndTime, fNoOfFitBins, fRRFPacking, fTheoAsData, and PRunBase::PRunBase().

◆ PRunSingleHistoRRF() [2/2]

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

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

Main constructor for RRF single histogram fitting and viewing.

Performs comprehensive validation and initialization:

  1. GLOBAL Block Validation (MANDATORY):
    • Checks GLOBAL block is present (required for RRF)
    • Validates RRF frequency is specified (rrf_freq)
    • Validates RRF packing is specified (rrf_packing)
    • Sets fValid=false and returns on any validation failure
  2. Member Initialization:
    • Extracts fRRFPacking from GLOBAL block
    • Sets fN0EstimateEndTime = 1.0 μs
    • Initializes fGoodBins to -1 (determined in PrepareData)
  3. Data Preparation:
    • Calls PrepareData() to load histogram and perform RRF transformation
    • Sets fValid=false if data preparation fails
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 resolution: true = at data points, false = 8× finer grid
Warning
Always check IsValid() after construction. GLOBAL block with RRF parameters is MANDATORY for this fit type.
See also
PrepareData() for RRF transformation details

Constructs a fully initialized RRF single histogram run object by:

  1. Validating GLOBAL block presence (mandatory for RRF analysis)
  2. Validating RRF frequency specification (rrf_freq in GLOBAL block)
  3. Validating RRF packing specification (rrf_packing in GLOBAL block)
  4. Calling PrepareData() to load histogram and perform RRF transformation

GLOBAL Block Requirements: The RRF fit type requires the following entries in the GLOBAL block:

  • rrf_freq: Rotation frequency with unit (e.g., "13.554 T", "183.7 MHz")
  • rrf_packing: Number of bins to average (integer)
  • rrf_phase: (optional) Initial phase in degrees

Error Handling: If any validation fails, the constructor:

  • Outputs detailed error message to stderr
  • Sets fValid = false
  • Returns immediately (PrepareData() is not called)
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 calculated only at data points (for viewing); if false, theory uses finer time grid (8× data resolution)
Warning
GLOBAL block with RRF parameters is MANDATORY for this fit type. Always check IsValid() after construction.
Note
After construction, check IsValid() to ensure initialization succeeded. Common failure modes:
  • Missing GLOBAL block
  • Missing rrf_freq specification
  • Missing rrf_packing specification
  • Data file not found or histogram missing
See also
PrepareData(), PrepareFitData(), PrepareViewData()

Definition at line 133 of file PRunSingleHistoRRF.cpp.

References fGoodBins, fN0EstimateEndTime, fNoOfFitBins, fRRFPacking, fTheoAsData, PRunBase::fValid, PMsrHandler::GetMsrGlobal(), PMsrGlobalBlock::GetRRFPacking(), PMsrGlobalBlock::GetRRFUnit(), if(), PMsrGlobalBlock::IsPresent(), PrepareData(), and PRunBase::PRunBase().

◆ ~PRunSingleHistoRRF()

PRunSingleHistoRRF::~PRunSingleHistoRRF ( )
virtual

Virtual destructor releasing allocated resources.

Destructor for RRF single histogram fitting class.

Clears the forward histogram vector. Base class handles theory objects.

Cleans up dynamically allocated memory:

  • Clears the forward histogram data vector (fForward)
  • Other vectors (fM, fMerr, fW, fAerr) are local to PrepareFitData and cleared automatically

Base class destructor (PRunBase) handles cleanup of:

  • Theory objects
  • Function value arrays
  • Other shared resources

Definition at line 194 of file PRunSingleHistoRRF.cpp.

References fForward.

Member Function Documentation

◆ CalcChiSquare()

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

Calculates χ² between RRF-transformed data and theory.

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

Computes chi-squared for RRF single histogram fitting:

\[\chi^2 = \sum_{i=t_{\rm start}}^{t_{\rm end}} \frac{[A_{\rm RRF}^{\rm data}(t_i) - A_{\rm RRF}^{\rm theory}(t_i)]^2}{\sigma_i^2}
\]

Algorithm:

  1. Evaluate user-defined FUNCTIONS with current parameters
  2. Pre-evaluate theory at t=1.0 to initialize LF/user functions (thread-safety)
  3. Loop over fit range with OpenMP parallelization
  4. Sum squared differences weighted by inverse variance

OpenMP Parallelization:

  • Dynamic scheduling with chunk = max(10, N_bins / N_processors)
  • Reduction on chisq accumulator
Parameters
parParameter vector from MINUIT minimizer
Returns
χ² value (sum over all bins in fit range)
Note
Unlike standard single histogram, no N₀/exp(-t/τ) factors needed since RRF transformation already produces dimensionless asymmetry.

Computes the standard chi-square goodness-of-fit statistic for RRF asymmetry:

\[\chi^2 = \sum_{i=t_{\rm start}}^{t_{\rm end}} \frac{[A_{\rm RRF}^{\rm data}(t_i) - A_{\rm RRF}^{\rm theory}(t_i)]^2}{\sigma_i^2}
\]

Unlike standard single histogram fitting, no explicit N₀ or exponential decay factors appear since the RRF transformation already produces dimensionless asymmetry with properly propagated errors.

Algorithm:

  1. Evaluate all user-defined functions from FUNCTIONS block
  2. Pre-evaluate theory at t=1.0 to initialize any stateful functions (e.g., LF relaxation, user functions with internal state)
  3. Loop over fit range bins [fStartTimeBin, fEndTimeBin)
  4. For each bin: calculate time, evaluate theory, accumulate χ²

OpenMP Parallelization: When compiled with OpenMP (HAVE_GOMP defined):

  • Dynamic scheduling with chunk size = max(10, N_bins / N_processors)
  • Private variables per thread: i, time, diff
  • Reduction performed on chisq accumulator
  • Thread-safe due to pre-evaluation of theory at t=1.0
Parameters
parParameter vector from MINUIT minimizer, containing current estimates of all fit parameters
Returns
χ² value (sum over all bins in fit range). Minimize this value during fitting to find optimal parameters.
Note
The theory function is evaluated in the RRF frame. The THEORY block should describe the low-frequency RRF signal, not the laboratory frame precession.
See also
CalcChiSquareExpected(), CalcMaxLikelihood()

Implements PRunBase.

Definition at line 240 of file PRunSingleHistoRRF.cpp.

References PRunBase::fData, fEndTimeBin, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, PRunBase::fRunInfo, fStartTimeBin, and PRunBase::fTheory.

◆ CalcChiSquareExpected()

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

Calculates expected χ² using theory variance instead of data variance.

Computes expected chi-squared where the error estimate comes from the theory prediction rather than the data:

\[\chi^2_{\rm exp} = \sum_{i} \frac{[A_{\rm RRF}^{\rm data}(t_i) - A_{\rm RRF}^{\rm theory}(t_i)]^2}{A_{\rm RRF}^{\rm theory}(t_i)}
\]

This is useful for diagnostic purposes to check fit quality.

Parameters
parParameter vector from MINUIT
Returns
Expected χ² value

Computes the expected chi-square where the error estimate in the denominator comes from the theory prediction rather than the data:

\[\chi^2_{\rm exp} = \sum_{i=t_{\rm start}}^{t_{\rm end}} \frac{[A_{\rm RRF}^{\rm data}(t_i) - A_{\rm RRF}^{\rm theory}(t_i)]^2}{A_{\rm RRF}^{\rm theory}(t_i)}
\]

This metric is useful for:

  • Diagnostic purposes to assess fit quality
  • Detecting systematic deviations from the model
  • Comparing with standard χ² to identify error estimation issues

Algorithm: Same as CalcChiSquare() but uses theory value as variance estimate instead of measured error bars. OpenMP parallelization is applied when available.

Parameters
parParameter vector from MINUIT minimizer
Returns
Expected χ² value. For a good fit, this should be approximately equal to the number of degrees of freedom (N_bins - N_params).
Warning
Theory values must be positive for valid variance estimate. Negative theory values can lead to incorrect χ² calculation.
See also
CalcChiSquare()

Implements PRunBase.

Definition at line 307 of file PRunSingleHistoRRF.cpp.

References PRunBase::fData, fEndTimeBin, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, PRunBase::fRunInfo, fStartTimeBin, and PRunBase::fTheory.

◆ CalcMaxLikelihood()

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

Calculates maximum likelihood (not yet implemented for RRF).

Calculates maximum likelihood for RRF data (NOT YET IMPLEMENTED).

Maximum likelihood estimation for RRF data is more complex due to the transformation from Poisson-distributed counts to RRF asymmetry. Currently returns 0.0.

Parameters
parParameter vector from MINUIT
Returns
0.0 (not implemented)
Todo
Implement proper ML for RRF data accounting for error propagation through the RRF transformation.

Maximum likelihood estimation for RRF single histogram data is more complex than for raw histograms due to the non-linear transformation from Poisson-distributed counts to RRF asymmetry.

Theoretical Background: For raw histogram data, the likelihood is:

\[\mathcal{L} = \prod_i \frac{\mu_i^{n_i} e^{-\mu_i}}{n_i!}
\]

where $\mu_i$ is the expected count and $n_i$ is the observed count.

For RRF-transformed data, the error propagation through the transformation must be properly accounted for in the likelihood function.

Current Implementation: Returns 0.0 (not implemented). Use χ² minimization (CalcChiSquare) instead.

Parameters
parParameter vector from MINUIT minimizer (unused)
Returns
0.0 (not implemented)
Todo
Implement proper maximum likelihood for RRF data by:
  1. Deriving the likelihood function for transformed asymmetry
  2. Accounting for error propagation through RRF transformation
  3. Including correlations introduced by packing
See also
CalcChiSquare() for currently supported fit metric

Implements PRunBase.

Definition at line 379 of file PRunSingleHistoRRF.cpp.

◆ CalcNoOfFitBins()

void PRunSingleHistoRRF::CalcNoOfFitBins ( )
virtual

Calculates start/end bin indices from fit time range.

Converts fit range times (μs) to RRF-packed bin indices:

  • fStartTimeBin = ceil((fFitStartTime - dataTimeStart) / dataTimeStep)
  • fEndTimeBin = floor((fFitEndTime - dataTimeStart) / dataTimeStep) + 1

Also updates fNoOfFitBins = fEndTimeBin - fStartTimeBin.

Note
Time step accounts for RRF packing: dataTimeStep = rawTimeStep × fRRFPacking

Converts the fit range from time (μs) to RRF-packed bin indices. This method is called whenever the fit range may have changed.

Conversion Formulas:

\[i_{\rm start} = \lceil \frac{t_{\rm start} - t_{\rm data,0}}{\Delta t_{\rm data}} \rceil
\]

\[i_{\rm end} = \lfloor \frac{t_{\rm end} - t_{\rm data,0}}{\Delta t_{\rm data}} \rfloor + 1
\]

where:

  • $t_{\rm data,0}$ = fData.GetDataTimeStart() (first RRF-packed bin center)
  • $\Delta t_{\rm data}$ = fData.GetDataTimeStep() (RRF-packed bin width)

Bounds Checking:

  • fStartTimeBin clamped to [0, data size)
  • fEndTimeBin clamped to [0, data size]
  • fNoOfFitBins = 0 if fEndTimeBin <= fStartTimeBin

Side Effects: Updates member variables:

  • fStartTimeBin: First bin index in fit range (inclusive)
  • fEndTimeBin: Last bin index in fit range (exclusive)
  • fNoOfFitBins: Number of bins = fEndTimeBin - fStartTimeBin
Note
Time step includes RRF packing: dataTimeStep = rawTimeRes × fRRFPacking
See also
GetNoOfFitBins(), SetFitRangeBin()

Definition at line 631 of file PRunSingleHistoRRF.cpp.

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

Referenced by GetNoOfFitBins(), and PrepareFitData().

◆ CalcTheory()

void PRunSingleHistoRRF::CalcTheory ( )
virtual

Evaluates theory function at all data points for viewing/plotting.

Calculates RRF theory values using current fit parameters stored in the MSR parameter list. The theory function P(t) is evaluated at each data time point and results are stored in fData for display.

Note
Theory is evaluated directly in the RRF frame, not transformed. The THEORY block should specify the low-frequency RRF signal.

Calculates the theoretical RRF asymmetry using the current MSR parameter values and stores results in fData for display. This method is called after fitting to generate the theory curve overlay.

Algorithm:

  1. Extract parameter values from MSR parameter list
  2. Evaluate all user-defined functions from FUNCTIONS block
  3. Loop over data points (size matches RRF-packed data)
  4. Calculate time: t = dataTimeStart + i × dataTimeStep
  5. Evaluate theory: P(t) = Func(t, par, funcValues)
  6. Store results via fData.AppendTheoryValue()

Theory Function: The theory is evaluated directly in the RRF frame. The THEORY block should specify the low-frequency RRF signal (after transformation), not the laboratory-frame high-frequency precession.

Example THEORY block for RRF analysis:

THEORY
asymmetry 1 (amplitude)
simpleGss 2 (Gaussian relaxation)
TFieldCos map1 fun1 (frequency shift, phase)

where the frequency in TFieldCos is the difference frequency (ω - ω_RRF).

Note
Unlike CalcChiSquare(), this method does not return a value. Results are stored internally in fData.fTheory vector.
See also
CalcChiSquare(), PrepareViewData()

Implements PRunBase.

Definition at line 424 of file PRunSingleHistoRRF.cpp.

References PRunBase::fData, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, PRunBase::fRunInfo, and PRunBase::fTheory.

◆ EstimateBkg()

Bool_t PRunSingleHistoRRF::EstimateBkg ( UInt_t histoNo)
privatevirtual

Estimates background from pre-t0 bins.

Estimates background level and error from pre-t0 histogram bins.

Calculates background level and error from specified background range:

  1. Validates background range is within histogram bounds
  2. Adjusts range to integer number of accelerator RF cycles (PSI/RAL/TRIUMF)
  3. Computes mean and standard deviation
  4. Stores in fBackground and fBkgErr
Parameters
histoNoHistogram index (for error messages)
Returns
true on success, false if background range invalid

Calculates the background (random coincidences, accidentals) from a specified range of histogram bins, typically before t0. The background range is adjusted to span an integer number of accelerator RF cycles for proper averaging.

Accelerator RF Periods:

  • PSI: ACCEL_PERIOD_PSI ns
  • RAL: ACCEL_PERIOD_RAL ns
  • TRIUMF: ACCEL_PERIOD_TRIUMF ns
  • Unknown: no RF adjustment

Algorithm:

  1. Get background range [start, end] from RUN block
  2. Swap start/end if in wrong order (with message)
  3. Determine accelerator RF period from institute name
  4. Adjust end to span integer number of RF cycles
  5. Validate range is within histogram bounds
  6. Calculate mean background: $ B = \frac{1}{n}\sum_{i={\rm start}}^{{\rm end}} N(i) $
  7. Calculate background error (standard deviation): $ \sigma_B = \sqrt{\frac{1}{n-1}\sum_{i={\rm start}}^{{\rm end}} (N(i) - B)^2} $
  8. Store results in fBackground and fBkgErr
  9. Update RUN block with estimated background value

Output Information: Prints diagnostic messages:

  • Adjusted background range (if RF adjustment applied)
  • Background value and error: "fBackground = value (error)"
Parameters
histoNoForward histogram number (for error message context)
Returns
true on success, false on error:
  • Background start out of histogram bounds
  • Background end out of histogram bounds
Note
The RF cycle adjustment ensures proper averaging over the accelerator bunch structure, reducing systematic bias.
See also
PrepareFitData()

Definition at line 1717 of file PRunSingleHistoRRF.cpp.

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

Referenced by PrepareFitData().

◆ EstimateN0()

Double_t PRunSingleHistoRRF::EstimateN0 ( Double_t & errN0,
Double_t freqMax )
privatevirtual

Estimates initial normalization N₀ from lifetime-corrected data.

Estimates initial normalization N₀ from lifetime-corrected histogram data.

Calculates N₀ as weighted average of M(t) over initial time window:

\[N_0 = \frac{\sum_{i=0}^{n} M(t_i)}{n}
\]

The window length is chosen to include an integer number of complete oscillation cycles (based on freqMax) within fN0EstimateEndTime.

Error estimate:

\[\sigma_{N_0} = \frac{\sqrt{\sum w_i^2 \sigma_{M_i}^2}}{\sum w_i}
\]

Parameters
errN0[out] Estimated error on N₀
freqMaxMain precession frequency (MHz) for window calculation
Returns
Estimated N₀ value

Calculates N₀ by averaging the lifetime-corrected signal M(t) over an initial time window. The window is chosen to span an integer number of complete precession cycles to minimize bias from oscillations.

N₀ Estimation Formula:

\[N_0 = \frac{1}{n} \sum_{i=0}^{n-1} M(t_i)
\]

where M(t) = [N(t) - B] × exp(+t/τ_μ) is the lifetime-corrected histogram stored in fM vector.

Window Determination: The end bin is calculated to include an integer number of oscillation cycles:

\[n_{\rm end} = {\rm round}\left( \left\lceil \frac{T \cdot f_{\rm max}}{2\pi} \right\rceil \cdot \frac{2\pi}{f_{\rm max} \cdot \Delta t} \right)
\]

where:

  • T = fN0EstimateEndTime (default 1.0 μs)
  • f_max = main precession frequency from GetMainFrequency()
  • Δt = fTimeResolution

Error Estimation:

\[\sigma_{N_0} = \frac{\sqrt{\sum_{i=0}^{n-1} w_i^2 \sigma_{M_i}^2}}{\sum_{i=0}^{n-1} w_i}
\]

where w_i = 1/σ_M_i² are the weights stored in fW vector.

Output Information: Prints diagnostic message: "N₀ = value (error)"

Parameters
errN0[out] Reference to store the estimated error on N₀
freqMaxMain precession frequency (MHz) from GetMainFrequency()
Returns
Estimated N₀ value (counts × exp(+t/τ))
Note
The simple average (rather than weighted average) is used for N₀ itself, while the error uses the full weight information.
See also
GetMainFrequency(), PrepareFitData()

Definition at line 1644 of file PRunSingleHistoRRF.cpp.

References fM, fMerr, fN0EstimateEndTime, PRunBase::fTimeResolution, and fW.

Referenced by PrepareFitData().

◆ GetEndTimeBin()

virtual Int_t PRunSingleHistoRRF::GetEndTimeBin ( )
inlinevirtual

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

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

Definition at line 312 of file PRunSingleHistoRRF.h.

References fEndTimeBin.

◆ GetMainFrequency()

Double_t PRunSingleHistoRRF::GetMainFrequency ( PDoubleVector & data)
privatevirtual

Finds the dominant precession frequency in raw data.

Finds the dominant precession frequency in raw histogram data.

Performs Fourier transform on raw histogram data to identify the main muon precession frequency:

  1. Creates TH1F from data in good bin range
  2. Applies strong apodization (windowing)
  3. Computes power spectrum
  4. Searches for maximum above 10 MHz (ignores DC component)

The frequency is used to:

  • Determine optimal N₀ estimation window (integer cycles)
  • Calculate suggested "optimal packing" for user information
Parameters
dataRaw histogram data vector
Returns
Maximum frequency in MHz, or 0 if not found

Performs Fourier analysis on the raw histogram to identify the main muon spin precession frequency. This is essential for:

  • Determining optimal N₀ estimation window (integer oscillation cycles)
  • Calculating suggested "optimal packing" for user information
  • Validating that the RRF frequency is appropriate

Algorithm:

  1. Create ROOT TH1F histogram from data in good bin range [fGoodBins[0], fGoodBins[1]]
  2. Set histogram binning to match time structure
  3. Apply Fourier transform using PFourier class
  4. Use strong apodization (windowing) to reduce spectral leakage
  5. Search power spectrum for maximum above 10 MHz (ignores DC component)
  6. Return frequency at maximum power

Frequency Search Constraints:

  • Ignores frequencies below 10 MHz (DC and low-frequency noise)
  • Searches for local maximum (rising then falling power)
  • Returns 0 if no clear maximum found

Output Information: The method prints diagnostic information:

  • Detected maximum frequency (MHz)
  • Suggested optimal packing for ~5-8 points per cycle
Parameters
dataRaw histogram data vector (counts per bin)
Returns
Maximum frequency in MHz, or 0 if no maximum found above 10 MHz.
Note
The frequency is used to determine the N₀ estimation window: window = ceil(fN0EstimateEndTime × freqMax / 2π) × (2π / freqMax) This ensures an integer number of complete oscillation cycles.
See also
EstimateN0(), PrepareFitData()

Definition at line 1553 of file PRunSingleHistoRRF.cpp.

References F_APODIZATION_STRONG, fGoodBins, FOURIER_UNIT_FREQ, PRunBase::fT0s, and PRunBase::fTimeResolution.

Referenced by PrepareFitData().

◆ GetNoOfFitBins()

UInt_t PRunSingleHistoRRF::GetNoOfFitBins ( )
virtual

Returns the number of bins included in the current fit range.

Triggers CalcNoOfFitBins() to ensure bin count is current, then returns the cached value.

Returns
Number of RRF-packed bins within [fFitStartTime, fFitEndTime]

Triggers CalcNoOfFitBins() to ensure the bin count is current based on the latest fit range settings, then returns the cached value.

The number of fit bins is needed for:

  • Calculating degrees of freedom: ν = N_bins - N_params
  • Reduced χ²: χ²_red = χ² / ν
  • Statistical diagnostics and fit quality assessment
Returns
Number of RRF-packed bins within [fFitStartTime, fFitEndTime]. This accounts for RRF packing: fewer bins than raw data.
Note
The fit range may be modified during fitting by COMMANDS block instructions. Always call this method to get the current count.
See also
CalcNoOfFitBins(), SetFitRangeBin()

Definition at line 473 of file PRunSingleHistoRRF.cpp.

References CalcNoOfFitBins(), and fNoOfFitBins.

◆ GetProperDataRange()

Bool_t PRunSingleHistoRRF::GetProperDataRange ( )
privatevirtual

Determines valid data range (first/last good bins).

Determines valid data range (first/last good bins) for analysis.

Establishes analysis boundaries in order of priority:

  1. RUN block data range specification
  2. GLOBAL block data range specification
  3. Automatic estimation (t0 + 10ns offset to end of histogram)

Validates that range is sensible (start < end, within histogram bounds).

Returns
true if valid data range determined, false on error

Establishes the boundaries of usable histogram data through a priority cascade. The data range defines which bins contain valid signal (after t0, before noise/overflow).

Data Range Search Priority:

  1. RUN block: data range specified in MSR file RUN block
  2. GLOBAL block: fallback data range from GLOBAL block
  3. Automatic estimation: estimate from t0 (with warning)
    • Start: t0 + 10 ns offset
    • End: histogram length

Validation:

  1. Check start < end (swap if reversed)
  2. Check start ≥ 0 and start < histogram size
  3. Check end ≥ 0 (adjust if > histogram size with warning)

Result: Sets fGoodBins[0] (first good bin) and fGoodBins[1] (last good bin). These are used for:

  • RRF transformation range
  • Fit range specification in bins (fgb+n0 lgb-n1)
  • Data validity checking
Returns
true if valid data range determined, false on:
  • Start bin out of bounds
  • End bin negative
  • Other range validation failures
Note
The data range is typically wider than the fit range. Data range defines where valid data exists; fit range defines what is fitted.
See also
GetProperFitRange(), GetProperT0()

Definition at line 1361 of file PRunSingleHistoRRF.cpp.

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

Referenced by PrepareData().

◆ GetProperFitRange()

void PRunSingleHistoRRF::GetProperFitRange ( PMsrGlobalBlock * globalBlock)
privatevirtual

Determines fit time range from MSR file settings.

Extracts fit range in order of priority:

  1. RUN block fit range (time-based or bin-based)
  2. GLOBAL block fit range (time-based or bin-based)
  3. Default to data range (fgb to lgb) with warning

Converts bin-based specifications to time using t0 and time resolution.

Parameters
globalBlockGLOBAL block with default fit settings

Extracts the fit range (time window for parameter extraction) through a priority cascade. Supports both time-based and bin-based specifications.

Fit Range Formats:

  • Time-based: fit 0.1 8.0 (in microseconds relative to t0)
  • Bin-based: fit fgb+100 lgb-500 (bins relative to good bins)

Search Priority:

  1. RUN block time-based fit range
  2. RUN block bin-based fit range (converted to time)
  3. GLOBAL block time-based fit range
  4. GLOBAL block bin-based fit range (converted to time)
  5. Default to data range (fgb to lgb) with warning

Bin-to-Time Conversion:

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

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

where Δt = fTimeResolution (raw, before RRF packing).

Result: Sets fFitStartTime and fFitEndTime in microseconds relative to t0. These define the range used in χ² calculation.

Parameters
globalBlockPointer to GLOBAL block for fallback fit range settings
Note
The converted time values are written back to the MSR data structures for log file output consistency.
Warning
If no fit range is specified, the full data range is used with a warning message. This may not be appropriate for all analyses.
See also
GetProperDataRange(), SetFitRangeBin(), CalcNoOfFitBins()

Definition at line 1480 of file PRunSingleHistoRRF.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 PRunSingleHistoRRF::GetProperT0 ( PRawRunData * runData,
PMsrGlobalBlock * globalBlock,
PUIntVector & histoNo )
privatevirtual

Determines and validates t0 values for all histograms.

Determines and validates t0 values for all histograms in the run.

Searches for t0 in order of priority:

  1. RUN block t0 specification
  2. GLOBAL block t0 specification
  3. Data file header t0 values
  4. Automatic estimation (with warning)

Also handles addt0 for addrun histograms.

Parameters
runDataRaw run data for histogram access
globalBlockGLOBAL block with default t0 values
histoNoVector of histogram indices to process
Returns
true if valid t0 found for all histograms, false on error

Searches for time-zero (t0) values through a priority cascade and performs validation. t0 marks the muon arrival time and is critical for proper timing alignment.

t0 Search Priority:

  1. RUN block: t0 values specified in the MSR file RUN block
  2. GLOBAL block: fallback t0 values from GLOBAL block
  3. Data file: t0 values stored in the raw data file header
  4. Automatic estimation: estimated from histogram shape (with warning)

Algorithm:

  1. Initialize fT0s vector with size = number of forward histograms (grouping)
  2. Set all t0 values to -1.0 (unset marker)
  3. Fill from RUN block if present
  4. Fill remaining -1.0 values from GLOBAL block
  5. Fill remaining -1.0 values from data file
  6. Fill remaining -1.0 values from automatic estimation (with warning)
  7. Validate all t0 values are within histogram bounds

Addrun Handling: When multiple runs are co-added (addrun), each additional run needs its own t0 value for proper time alignment:

  1. Initialize fAddT0s[runIdx] for each addrun
  2. Apply same priority cascade for each addrun
  3. Validate addrun t0 values

Validation:

  • t0 must be ≥ 0
  • t0 must be < histogram length
  • Error message and return false on validation failure
Parameters
runDataPointer to raw run data for histogram access and data file t0
globalBlockPointer to GLOBAL block for fallback t0 values
histoNoVector of histogram indices (0-based) for forward grouping
Returns
true if valid t0 found for all histograms, false on:
  • t0 out of histogram bounds
  • addrun data not accessible
  • addrun t0 validation failure
Warning
Automatic t0 estimation is unreliable for LEM and other specialized setups. Always specify t0 explicitly for best results.
See also
GetProperDataRange(), PrepareData()

Definition at line 1204 of file PRunSingleHistoRRF.cpp.

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

Referenced by PrepareData().

◆ GetStartTimeBin()

virtual Int_t PRunSingleHistoRRF::GetStartTimeBin ( )
inlinevirtual

Returns the first bin index in the fit range.

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

Definition at line 306 of file PRunSingleHistoRRF.h.

References fStartTimeBin.

◆ PrepareData()

Bool_t PRunSingleHistoRRF::PrepareData ( )
protectedvirtual

Main data preparation orchestrator for RRF single histogram analysis.

Coordinates loading and preprocessing of histogram data:

  1. Validates GLOBAL block presence and RRF parameters
  2. Retrieves raw run data from data handler
  3. Extracts metadata (field, energy, temperature)
  4. Collects histogram numbers from RUN block forward specification
  5. Validates histograms exist in data file
  6. Determines time resolution (ns → μs conversion)
  7. Determines t0 values via GetProperT0()
  8. Handles addrun (co-adding multiple runs)
  9. Handles grouping (combining multiple detectors)
  10. Determines data range via GetProperDataRange()
  11. Determines fit range via GetProperFitRange()
  12. Calls PrepareFitData() or PrepareViewData() based on tag
Returns
true if data preparation succeeds, false on any error
See also
PrepareFitData(), PrepareViewData()

Coordinates the loading and preprocessing of histogram data before RRF transformation. This method handles all operations common to both fitting and viewing modes.

Processing Steps:

  1. Validate object state (return false if already marked invalid)
  2. Get GLOBAL block reference for settings
  3. Load raw run data from data handler using run name from MSR file
  4. Extract metadata from data file:
    • Magnetic field (fMetaData.fField)
    • Beam energy (fMetaData.fEnergy)
    • Sample temperature(s) (fMetaData.fTemp)
  5. Collect histogram numbers from RUN block forward specification
  6. Validate all specified histograms exist in data file
  7. Determine time resolution: ns → μs conversion
  8. Determine t0 values via GetProperT0()
  9. Initialize forward histogram from first group
  10. Handle addrun (co-add multiple runs with t0 alignment)
  11. Handle grouping (combine multiple detectors with t0 alignment)
  12. Determine data range via GetProperDataRange()
  13. Determine fit range via GetProperFitRange()
  14. Dispatch to PrepareFitData() or PrepareViewData() based on tag

Run Addition (addrun): When multiple runs are specified in the RUN block, histograms are co-added with t0 alignment:

fForward[i] += addRunData[i + addT0 - mainT0]
PDoubleVector fForward
Forward detector histogram data (progressively transformed during preparation)

Detector Grouping: When multiple forward histograms are specified, they are summed with t0 alignment to form a single combined histogram.

Returns
true if data preparation succeeds, false on any error:
  • Run data not found
  • Histogram not present in data file
  • Invalid t0 determination
  • Data range validation failure
  • Fit/view data preparation failure
See also
PrepareFitData(), PrepareViewData(), GetProperT0(), GetProperDataRange()

Implements PRunBase.

Definition at line 696 of file PRunSingleHistoRRF.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(), and PrepareViewData().

Referenced by PRunSingleHistoRRF().

◆ PrepareFitData()

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

Performs full RRF transformation for fitting.

Performs full RRF transformation on histogram data for fitting.

Transforms raw histogram to RRF asymmetry through these steps:

  1. Frequency Analysis:
    • Calls GetMainFrequency() to find dominant precession frequency
    • Used to determine optimal N₀ estimation window
  2. Background Handling:
    • If background range given: estimate from data via EstimateBkg()
    • If fixed background given: use directly
    • Subtract background: N(t) → N(t) - B
  3. Lifetime Correction:
    • Apply exp(+t/τ_μ) to remove exponential decay
    • Store as M(t) = [N(t) - B] × exp(+t/τ_μ)
    • Calculate M_err = exp(+t/τ_μ) × √(N(t) + σ_B²)
  4. N₀ Estimation:
    • Call EstimateN0() to determine normalization
    • Uses weighted average over full oscillation cycles
  5. Asymmetry Extraction:
    • A(t) = M(t)/N₀ - 1
    • A_err(t) = exp(+t/τ)/N₀ × √(N(t) + [(N(t)-B)/N₀]² × σ_N₀²)
  6. RRF Rotation:
    • A_RRF(t) = 2 × A(t) × cos(ω_RRF × t + φ_RRF)
    • Factor 2 compensates for discarded counter-rotating component
  7. RRF Packing:
    • Average over fRRFPacking consecutive bins
    • Error: σ_packed = √(2 × Σσ²) / n
  8. Time Grid Setup:
    • Set data time start accounting for packing offset
    • Set data time step = raw_resolution × fRRFPacking
Parameters
runDataRaw run data handler
histoNoForward histogram number (0-based)
Returns
true on success, false on error

Takes the pre-processed histogram (grouping and addrun already applied) and transforms it into RRF asymmetry suitable for fitting. This is the core method implementing the RRF analysis technique.

Processing Steps:

1. Frequency Analysis:

  • Calls GetMainFrequency() on raw data to find dominant precession frequency
  • Used to determine optimal N₀ estimation window (integer oscillation cycles)
  • Prints "optimal packing" suggestion for user reference

2. Background Handling:

  • If fixed background specified: use directly from RUN block
  • If background range given: estimate via EstimateBkg()
  • If neither: estimate range as [0.1×t0, 0.6×t0] with warning
  • Subtract background: N(t) → N(t) - B

3. Lifetime Correction:

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

  • Removes exponential decay from signal
  • Error: $\sigma_M = e^{+t/\tau_\mu} \sqrt{N(t) + \sigma_B^2}$
  • Weights: $w = 1/\sigma_M^2$

4. N₀ Estimation:

  • Call EstimateN0() with frequency information
  • Uses average of M(t) over integer number of oscillation cycles
  • Returns N₀ and its error σ_N₀

5. Asymmetry Extraction:

\[A(t) = \frac{M(t)}{N_0} - 1
\]

Error propagation:

\[\sigma_A(t) = \frac{e^{+t/\tau_\mu}}{N_0} \sqrt{N(t) + \left(\frac{N(t)-B}{N_0}\right)^2 \sigma_{N_0}^2}
\]

6. RRF Rotation:

\[A_{\rm RRF}(t) = 2 \cdot A(t) \cdot \cos(\omega_{\rm RRF} t + \phi_{\rm RRF})
\]

  • ω_RRF from GLOBAL block (rrf_freq converted to angular frequency)
  • φ_RRF from GLOBAL block (rrf_phase in radians)
  • Factor 2 compensates for discarded counter-rotating component

7. RRF Packing:

  • Average over fRRFPacking consecutive bins
  • Data: $A_{\rm packed} = \frac{1}{n}\sum_{i=1}^{n} A_{\rm RRF}(t_i)$
  • Error: $\sigma_{\rm packed} = \frac{\sqrt{2}}{n}\sqrt{\sum_{i=1}^{n} \sigma_A^2(t_i)}$
  • √2 factor accounts for doubling in RRF rotation

8. Time Grid Setup:

  • Data time start: accounts for packing offset (center of first packed bin)
  • Data time step: rawTimeResolution × fRRFPacking
Parameters
runDataRaw run data handler (for background estimation)
histoNoForward histogram number (0-based, for background error messages)
Returns
true on success, false on error:
  • Background estimation failure
  • Invalid bin ranges
See also
PrepareViewData(), GetMainFrequency(), EstimateN0(), EstimateBkg()

Definition at line 905 of file PRunSingleHistoRRF.cpp.

References CalcNoOfFitBins(), EstimateBkg(), EstimateN0(), fAerr, fBackground, fBkgErr, PRunBase::fData, fForward, fGoodBins, fM, fMerr, PRunBase::fMsrInfo, fRRFPacking, PRunBase::fRunInfo, PRunBase::fT0s, PRunBase::fTimeResolution, fW, GetMainFrequency(), PMsrGlobalBlock::GetRRFFreq(), PMsrGlobalBlock::GetRRFPhase(), PMUON_LIFETIME, and PMUSR_UNDEFINED.

Referenced by PrepareData(), and PrepareViewData().

◆ PrepareViewData()

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

Prepares RRF data for viewing/plotting.

Prepares RRF-transformed data for viewing/plotting.

Similar to PrepareFitData() but additionally:

  • Handles view packing (if specified and > RRF packing)
  • Sets up theory calculation grid (8× finer than data if fTheoAsData=false)
  • Evaluates theory function for plotting overlay
Parameters
runDataRaw run data handler
histoNoForward histogram number
Returns
true on success, false on error
Note
View packing < RRF packing is ignored with warning since RRF packing is already applied during data transformation.

Takes the pre-processed histogram and prepares both data and theory curves for display. This method is used when the operation mode is kView rather than kFit.

Processing Steps:

1. Data Preparation:

  • Calls PrepareFitData() to perform full RRF transformation
  • Data is ready for display after this step

2. View Packing Check:

  • Checks if additional view packing is specified in PLOT block
  • If viewPacking > fRRFPacking: additional packing would be applied (TODO)
  • If viewPacking < fRRFPacking: warning issued and view packing ignored (cannot unpack already-packed RRF data)

3. Theory Grid Setup: Determines theory evaluation resolution:

  • If fTheoAsData = true: theory calculated only at data points
  • If fTheoAsData = false: theory calculated on 8× finer grid for smooth curves

Time grid:

  • Theory time start = data time start
  • Theory time step = data time step / factor (where factor = 1 or 8)

4. Theory Evaluation:

  • Extract parameter values from MSR parameter list
  • Evaluate all user-defined functions from FUNCTIONS block
  • Loop over theory grid points
  • Evaluate theory: P(t) = Func(t, par, funcValues)
  • Apply sanity check: |P(t)| > 10 → set to 0 (dirty hack for edge cases)
  • Store results via fData.AppendTheoryValue()

Theory Function: The theory is evaluated directly in the RRF frame. The THEORY block should specify the low-frequency signal after RRF transformation, not the laboratory-frame high-frequency precession.

Parameters
runDataRaw run data handler (passed to PrepareFitData)
histoNoForward histogram number (passed to PrepareFitData)
Returns
true on success, false on error (typically from PrepareFitData)
Note
The 8× theory resolution provides smoother curves for visualization and better Fourier transforms without affecting fit performance.
See also
PrepareFitData(), CalcTheory()

Definition at line 1091 of file PRunSingleHistoRRF.cpp.

References PRunBase::fData, fForward, PRunBase::fFuncValues, PRunBase::fMetaData, PRunBase::fMsrInfo, fRRFPacking, PRunBase::fRunInfo, fTheoAsData, PRunBase::fTheory, and PrepareFitData().

Referenced by PrepareData().

◆ SetFitRangeBin()

void PRunSingleHistoRRF::SetFitRangeBin ( const TString fitRange)
virtual

Sets fit range using bin-offset syntax from COMMANDS block.

Parses fit range specification in the format:

  • "FIT_RANGE fgb+n0 lgb-n1" (single range for all runs)
  • "FIT_RANGE fgb+n00 lgb-n01 fgb+n10 lgb-n11 ..." (per-run ranges)

where fgb = first good bin, lgb = last good bin, and nXY are offsets.

Converts bin specification to time using:

  • fFitStartTime = (fgb + offset - t0) × time_resolution
  • fFitEndTime = (lgb - offset - t0) × time_resolution
Parameters
fitRangeString containing FIT_RANGE specification
Note
This is called when COMMANDS block modifies fit range during fitting.

Allows dynamic modification of the fit range during fitting, as specified in the COMMANDS block. This is used for systematic studies where the fit range needs to be varied.

Syntax:

FIT_RANGE fgb[+n0] lgb[-n1] # single range for all runs
FIT_RANGE fgb+n00 lgb-n01 fgb+n10 lgb-n11 ... # per-run ranges

where:

  • fgb = first good bin (symbolic, replaced by actual value)
  • lgb = last good bin (symbolic, replaced by actual value)
  • +n0 = positive offset added to fgb
  • -n1 = positive offset subtracted from lgb

Conversion to Time:

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

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

where Δt is the raw time resolution (before RRF packing).

Multiple Run Handling:

  • Single pair: Applied to all runs
  • Multiple pairs: Must match number of RUN blocks; each run uses its own range
  • Run selection: Uses (2 × runNo + 1) to index into token array

Example:

COMMANDS
FIT_RANGE fgb+100 lgb-500 # start 100 bins after fgb, end 500 bins before lgb
Parameters
fitRangeString containing FIT_RANGE specification from COMMANDS block
Warning
Invalid syntax produces error message but does not throw exception. The previous fit range values are retained on error.
See also
GetProperFitRange(), CalcNoOfFitBins()

Definition at line 530 of file PRunSingleHistoRRF.cpp.

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

Member Data Documentation

◆ fAerr

PDoubleVector PRunSingleHistoRRF::fAerr
private

Asymmetry errors before RRF packing. Used for packed error calculation.

Definition at line 431 of file PRunSingleHistoRRF.h.

Referenced by PrepareFitData().

◆ fBackground

Double_t PRunSingleHistoRRF::fBackground
private

Estimated or fixed background level in counts/bin (before packing)

Definition at line 417 of file PRunSingleHistoRRF.h.

Referenced by EstimateBkg(), PrepareFitData(), and PRunSingleHistoRRF().

◆ fBkgErr

Double_t PRunSingleHistoRRF::fBkgErr
private

Statistical error on background estimate (std dev of background region)

Definition at line 418 of file PRunSingleHistoRRF.h.

Referenced by EstimateBkg(), PrepareFitData(), and PRunSingleHistoRRF().

◆ fEndTimeBin

Int_t PRunSingleHistoRRF::fEndTimeBin
private

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

Definition at line 425 of file PRunSingleHistoRRF.h.

Referenced by CalcChiSquare(), CalcChiSquareExpected(), CalcNoOfFitBins(), and GetEndTimeBin().

◆ fForward

PDoubleVector PRunSingleHistoRRF::fForward
private

Forward detector histogram data (progressively transformed during preparation)

Definition at line 427 of file PRunSingleHistoRRF.h.

Referenced by EstimateBkg(), GetProperDataRange(), PrepareData(), PrepareFitData(), PrepareViewData(), and ~PRunSingleHistoRRF().

◆ fGoodBins

Int_t PRunSingleHistoRRF::fGoodBins[2]
private

Good bin range: [0] = first good bin (fgb), [1] = last good bin (lgb). Used for COMMANDS block fit range specification.

Definition at line 422 of file PRunSingleHistoRRF.h.

Referenced by GetMainFrequency(), GetProperDataRange(), GetProperFitRange(), PrepareFitData(), PRunSingleHistoRRF(), PRunSingleHistoRRF(), and SetFitRangeBin().

◆ fM

PDoubleVector PRunSingleHistoRRF::fM
private

Lifetime-corrected histogram: M(t) = [N(t) - B] × exp(+t/τ_μ). Used for N₀ estimation.

Definition at line 428 of file PRunSingleHistoRRF.h.

Referenced by EstimateN0(), and PrepareFitData().

◆ fMerr

PDoubleVector PRunSingleHistoRRF::fMerr
private

Error on M(t): σ_M = exp(+t/τ_μ) × √(N(t) + σ_B²). Includes background error.

Definition at line 429 of file PRunSingleHistoRRF.h.

Referenced by EstimateN0(), and PrepareFitData().

◆ fN0EstimateEndTime

Double_t PRunSingleHistoRRF::fN0EstimateEndTime
private

End time (μs) for N₀ estimation window. Rounded to integer number of oscillation cycles based on main frequency.

Definition at line 414 of file PRunSingleHistoRRF.h.

Referenced by EstimateN0(), PRunSingleHistoRRF(), and PRunSingleHistoRRF().

◆ fNoOfFitBins

UInt_t PRunSingleHistoRRF::fNoOfFitBins
private

Number of RRF-packed bins within fit range [fStartTimeBin, fEndTimeBin)

Definition at line 416 of file PRunSingleHistoRRF.h.

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

◆ fRRFPacking

Int_t PRunSingleHistoRRF::fRRFPacking
private

RRF packing factor from GLOBAL block (number of raw bins averaged together)

Definition at line 419 of file PRunSingleHistoRRF.h.

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

◆ fStartTimeBin

Int_t PRunSingleHistoRRF::fStartTimeBin
private

First bin index in fit range (inclusive, 0-based in RRF-packed data)

Definition at line 424 of file PRunSingleHistoRRF.h.

Referenced by CalcChiSquare(), CalcChiSquareExpected(), CalcNoOfFitBins(), and GetStartTimeBin().

◆ fTheoAsData

Bool_t PRunSingleHistoRRF::fTheoAsData
private

Theory resolution mode: true = at data points only, false = 8× finer grid for smooth Fourier transforms.

Definition at line 420 of file PRunSingleHistoRRF.h.

Referenced by PrepareViewData(), PRunSingleHistoRRF(), and PRunSingleHistoRRF().

◆ fW

PDoubleVector PRunSingleHistoRRF::fW
private

Weights for N₀ estimation: W(t) = 1/σ_M². Used in weighted average.

Definition at line 430 of file PRunSingleHistoRRF.h.

Referenced by EstimateN0(), and PrepareFitData().


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