Class ALeastSquaresFitter

java.lang.Object
edu.cnu.mdi.splot.fit.ALeastSquaresFitter
All Implemented Interfaces:
IFitStringGetter, IFitter
Direct Known Subclasses:
ErfcFitter, ErfFitter, ExponentialDecayFitter, GaussianFitter, LorentzianFitter, MultiGaussianFitter, PolynomialFitter, PowerLawFitter

public abstract class ALeastSquaresFitter extends Object implements IFitter, IFitStringGetter
Base class for least-squares fitters built on Apache Commons Math 3.x fitting.leastsquares.

This class centralizes the common fit pipeline:

  • x/y/weights validation
  • weights-from-sigma helper
  • least-squares problem builder wiring
  • optimizer execution
  • best-effort covariance extraction
  • uniform FitResult creation

Concrete fitters typically only implement:

Chi-square note (Commons Math 3.6.1)

Optimum.getCost() returns sqrt(sum r_i^2). Therefore:
 chiSquare = cost ^ 2
 
If you supply weights as 1/sigmaY^2 in a diagonal weight matrix, this corresponds to the conventional weighted chi-square.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final String
    The "capital sigma" symbol is used in some fitters (e.g.
    protected final org.apache.commons.math3.optim.SimpleVectorValueChecker
    Absolute/relative thresholds used by the default convergence checker.
    protected final double
    Covariance extraction threshold passed to Optimum.getCovariances(threshold).
    protected final IInitialGuess
    Initial-guess strategy used when the caller does not provide an explicit guess.
    protected final int
    Maximum evaluations used by the least-squares problem (Commons Math builder).
    protected final int
    Maximum iterations used by the least-squares problem (Commons Math builder).
    static final String
    The "mu" symbol is used in some fitters (e.g.
    static final String
    The "omega" symbol is used in some fitters (e.g.
    protected final org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer
    Optimizer used for the fit (often Levenberg-Marquardt).
    static final String
    The "phi" symbol is used in some fitters (e.g.
    static final String
    The "sigma" symbol is used in some fitters (e.g.
    static final String
    The "sub 0" symbol is used in some fitters (e.g.
    static final String
    The "sub 1" symbol is used in some fitters (e.g.
    static final String
    The "sub 2" symbol is used in some fitters (e.g.
    Subscript array for parameter labels (e.g.
    static final String
    The "sub n" symbol is used in some fitters (e.g.
    static final String
    The "super 0" symbol is used in some fitters (e.g.
    static final String
    The "super 1" symbol is used in some fitters (e.g.
    static final String
    The "super 2" symbol is used in some fitters (e.g.
    static final String
    The "super n" symbol is used in some fitters (e.g.
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    protected
    ALeastSquaresFitter(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer optimizer, IInitialGuess initialGuesser)
    Construct a fitter with default iteration/evaluation/checker settings.
    protected
    ALeastSquaresFitter(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer optimizer, IInitialGuess initialGuesser, int maxIterations, int maxEvaluations, org.apache.commons.math3.optim.SimpleVectorValueChecker checker, double covarianceThreshold)
    Construct a fitter with explicit common configuration.
  • Method Summary

    Modifier and Type
    Method
    Description
    abstract Evaluator
    Create an evaluator for the fit result.
    protected static FitResult
    buildFitResult(IFitStringGetter stringGetter, double[] params, org.apache.commons.math3.linear.RealMatrix covariance, int nPoints, int nParams, org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer.Optimum opt)
    Build a FitResult from the given components.
    protected static org.apache.commons.math3.fitting.leastsquares.ParameterValidator
    clampingValidator(double[] lower, double[] upper)
    Create a ParameterValidator that clamps parameters to [lower[i], upper[i]].
    protected double[]
    defaultInitialGuess(double[] x, double[] y, double[] weights)
    Default initial guess used if the caller does not provide an explicit override.
    protected org.apache.commons.math3.fitting.leastsquares.ParameterValidator
    Default validator/bounds policy (optional).
    final FitResult
    fit(double[] x, double[] y)
    Fit with no weights, no initial guess override, and no parameter validator override.
    final FitResult
    fit(double[] x, double[] y, double[] weights)
    Fit with weights but no initial guess override and no parameter validator override.
    final FitResult
    fit(double[] x, double[] y, double[] weights, double[] initialGuessOverride, org.apache.commons.math3.fitting.leastsquares.ParameterValidator validatorOverride)
    Full fit entry point.
    protected org.apache.commons.math3.optim.SimpleVectorValueChecker
     
    protected double
     
    protected int
     
    protected int
     
    protected abstract int
     
    Get the descriptive string getter for this fitter.
    protected abstract org.apache.commons.math3.fitting.leastsquares.MultivariateJacobianFunction
    model(double[] x)
    Build the model + analytic (or numeric) Jacobian for this fitter, given x values.
    protected static org.apache.commons.math3.linear.RealMatrix
    safeCovariances(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer.Optimum opt, double threshold)
    Best-effort covariance extraction; returns null if unavailable (singular, ill-conditioned, etc.).
    protected static void
    validateWeights(double[] weights, int n)
    Validate weights array.
    protected static void
    validateXY(double[] x, double[] y, int minPoints)
    Validate x/y arrays.
    static double[]
    weightsFromSigmaY(double[] sigmaY)
    Convenience: build weights from y-uncertainties.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

    Methods inherited from interface edu.cnu.mdi.splot.fit.IFitStringGetter

    functionForm, modelName, parameterName
  • Field Details

    • SUB0

      public static final String SUB0
      The "sub 0" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "0" for parameters.
      See Also:
    • SUB1

      public static final String SUB1
      The "sub 1" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "1" for parameters.
      See Also:
    • SUB2

      public static final String SUB2
      The "sub 2" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "2" for parameters.
      See Also:
    • SUBN

      public static final String SUBN
      The "sub n" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "n" for parameters.
      See Also:
    • SUP0

      public static final String SUP0
      The "super 0" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "0" for parameters.
      See Also:
    • SUP1

      public static final String SUP1
      The "super 1" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "1" for parameters.
      See Also:
    • SUP2

      public static final String SUP2
      The "super 2" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "2" for parameters.
      See Also:
    • SUPN

      public static final String SUPN
      The "super n" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "n" for parameters.
      See Also:
    • MU

      public static final String MU
      The "mu" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "m" for parameters.
      See Also:
    • SMALLSIG

      public static final String SMALLSIG
      The "sigma" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "s" for parameters.
      See Also:
    • CAPSIG

      public static final String CAPSIG
      The "capital sigma" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "S" for parameters.
      See Also:
    • OMEGA

      public static final String OMEGA
      The "omega" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "w" for parameters.
      See Also:
    • PHI

      public static final String PHI
      The "phi" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "p" for parameters.
      See Also:
    • subArray

      public String[] subArray
      Subscript array for parameter labels (e.g. p₁, p₂, ...).
    • optimizer

      protected final org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer optimizer
      Optimizer used for the fit (often Levenberg-Marquardt).
    • initialGuesser

      protected final IInitialGuess initialGuesser
      Initial-guess strategy used when the caller does not provide an explicit guess.
    • maxIterations

      protected final int maxIterations
      Maximum iterations used by the least-squares problem (Commons Math builder). Subclasses may override via getMaxIterations().
    • maxEvaluations

      protected final int maxEvaluations
      Maximum evaluations used by the least-squares problem (Commons Math builder). Subclasses may override via getMaxEvaluations().
    • checker

      protected final org.apache.commons.math3.optim.SimpleVectorValueChecker checker
      Absolute/relative thresholds used by the default convergence checker. Subclasses may override via getChecker().
    • covarianceThreshold

      protected final double covarianceThreshold
      Covariance extraction threshold passed to Optimum.getCovariances(threshold). Subclasses may override via getCovarianceThreshold().
  • Constructor Details

    • ALeastSquaresFitter

      protected ALeastSquaresFitter(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer optimizer, IInitialGuess initialGuesser)
      Construct a fitter with default iteration/evaluation/checker settings.
      Parameters:
      optimizer - optimizer instance (e.g. Levenberg-Marquardt)
      initialGuesser - fallback initial-guess strategy (non-null)
    • ALeastSquaresFitter

      protected ALeastSquaresFitter(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer optimizer, IInitialGuess initialGuesser, int maxIterations, int maxEvaluations, org.apache.commons.math3.optim.SimpleVectorValueChecker checker, double covarianceThreshold)
      Construct a fitter with explicit common configuration.
      Parameters:
      optimizer - optimizer instance
      initialGuesser - fallback initial guess strategy
      maxIterations - maximum iterations for the least-squares builder
      maxEvaluations - maximum evaluations for the least-squares builder
      checker - convergence checker (may be null for none)
      covarianceThreshold - threshold passed to getCovariances
  • Method Details

    • getParameterCount

      protected abstract int getParameterCount()
      Returns:
      number of parameters for this fitter.
    • model

      protected abstract org.apache.commons.math3.fitting.leastsquares.MultivariateJacobianFunction model(double[] x)
      Build the model + analytic (or numeric) Jacobian for this fitter, given x values.
      Parameters:
      x - x data (length n)
      Returns:
      a MultivariateJacobianFunction compatible with Commons Math least-squares
    • defaultInitialGuess

      protected double[] defaultInitialGuess(double[] x, double[] y, double[] weights)
      Default initial guess used if the caller does not provide an explicit override. The default implementation delegates to the initialGuesser.

      Subclasses may override if they have a better model-specific guess.

      Parameters:
      x - x data
      y - y data
      weights - optional weights (may be null)
      Returns:
      initial parameter vector of length getParameterCount()
    • defaultValidator

      protected org.apache.commons.math3.fitting.leastsquares.ParameterValidator defaultValidator()
      Default validator/bounds policy (optional).

      Return null for "no validation". For simple bound constraints, consider using clampingValidator(double[], double[]).

      Returns:
      a parameter validator or null
    • getMaxIterations

      protected int getMaxIterations()
      Returns:
      max iterations used for the least-squares problem.
    • getMaxEvaluations

      protected int getMaxEvaluations()
      Returns:
      max evaluations used for the least-squares problem.
    • getChecker

      protected org.apache.commons.math3.optim.SimpleVectorValueChecker getChecker()
      Returns:
      the convergence checker (may be null).
    • getCovarianceThreshold

      protected double getCovarianceThreshold()
      Returns:
      the covariance extraction threshold.
    • validateXY

      protected static void validateXY(double[] x, double[] y, int minPoints)
      Validate x/y arrays.
      Parameters:
      x - x values
      y - y values
      minPoints - minimum required number of points
    • validateWeights

      protected static void validateWeights(double[] weights, int n)
      Validate weights array.

      Commons Math accepts any real diagonal matrix as weights, but for typical least-squares usage, weights should be finite and non-negative (often 1/sigma^2).

      Parameters:
      weights - optional weights array
      n - expected length
    • weightsFromSigmaY

      public static double[] weightsFromSigmaY(double[] sigmaY)
      Convenience: build weights from y-uncertainties.

      weights[i] = 1/(sigmaY[i]^2).

      Parameters:
      sigmaY - y uncertainties, all > 0
      Returns:
      weights array
    • clampingValidator

      protected static org.apache.commons.math3.fitting.leastsquares.ParameterValidator clampingValidator(double[] lower, double[] upper)
      Create a ParameterValidator that clamps parameters to [lower[i], upper[i]]. Use +/-infinity for "no bound".

      This is a simple, robust bounds strategy compatible with Commons Math least-squares. It is not a hard-constraint optimizer; it repairs invalid steps by clamping.

      Parameters:
      lower - lower bounds (length p)
      upper - upper bounds (length p)
      Returns:
      clamping validator
    • safeCovariances

      protected static org.apache.commons.math3.linear.RealMatrix safeCovariances(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer.Optimum opt, double threshold)
      Best-effort covariance extraction; returns null if unavailable (singular, ill-conditioned, etc.).
    • asEvaluator

      public abstract Evaluator asEvaluator(FitResult fit)
      Create an evaluator for the fit result.
      Parameters:
      fit - the fit result
      Returns:
      an evaluator
    • buildFitResult

      protected static FitResult buildFitResult(IFitStringGetter stringGetter, double[] params, org.apache.commons.math3.linear.RealMatrix covariance, int nPoints, int nParams, org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer.Optimum opt)
      Build a FitResult from the given components.
      Parameters:
      stringGetter - string getter for this fitter
      params - fitted parameters
      covariance - covariance matrix (may be null)
      nPoints - number of data points
      nParams - number of fitted parameters
      opt - optimization result from Commons Math
      Returns:
      a FitResult instance
    • getStringGetter

      public abstract IFitStringGetter getStringGetter()
      Get the descriptive string getter for this fitter.
      Returns:
      the string getter
    • fit

      public final FitResult fit(double[] x, double[] y)
      Fit with no weights, no initial guess override, and no parameter validator override.
      Specified by:
      fit in interface IFitter
      Parameters:
      x - the x data
      y - the y data
      Returns:
      the fit result
    • fit

      public final FitResult fit(double[] x, double[] y, double[] weights)
      Fit with weights but no initial guess override and no parameter validator override.
      Specified by:
      fit in interface IFitter
      Parameters:
      x - the x data
      y - the y data
      weights - the weights where w = 1/(sigmaY^2)
      Returns:
      the fit result
    • fit

      public final FitResult fit(double[] x, double[] y, double[] weights, double[] initialGuessOverride, org.apache.commons.math3.fitting.leastsquares.ParameterValidator validatorOverride)
      Full fit entry point. This is the common least-squares pipeline for all derived fitters.
      Parameters:
      x - x data
      y - y data
      weights - optional weights (length n), typically 1/sigmaY^2; may be null
      initialGuessOverride - optional explicit initial guess (length p); may be null
      validatorOverride - optional explicit parameter validator; may be null
      Returns:
      FitResult