Package edu.cnu.mdi.splot.fit
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
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
FitResultcreation
Concrete fitters typically only implement:
getParameterCount()model(double[])- optionally
defaultInitialGuess(double[], double[], double[]) - optionally
defaultValidator() - optionally getModelName()
Chi-square note (Commons Math 3.6.1)
Optimum.getCost()
returns sqrt(sum r_i^2). Therefore:
chiSquare = cost ^ 2If you supply weights as
1/sigmaY^2 in a diagonal weight matrix, this
corresponds to the conventional weighted chi-square.-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe "capital sigma" symbol is used in some fitters (e.g.protected final org.apache.commons.math3.optim.SimpleVectorValueCheckerAbsolute/relative thresholds used by the default convergence checker.protected final doubleCovariance extraction threshold passed toOptimum.getCovariances(threshold).protected final IInitialGuessInitial-guess strategy used when the caller does not provide an explicit guess.protected final intMaximum evaluations used by the least-squares problem (Commons Math builder).protected final intMaximum iterations used by the least-squares problem (Commons Math builder).static final StringThe "mu" symbol is used in some fitters (e.g.static final StringThe "omega" symbol is used in some fitters (e.g.protected final org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizerOptimizer used for the fit (often Levenberg-Marquardt).static final StringThe "phi" symbol is used in some fitters (e.g.static final StringThe "sigma" symbol is used in some fitters (e.g.static final StringThe "sub 0" symbol is used in some fitters (e.g.static final StringThe "sub 1" symbol is used in some fitters (e.g.static final StringThe "sub 2" symbol is used in some fitters (e.g.String[]Subscript array for parameter labels (e.g.static final StringThe "sub n" symbol is used in some fitters (e.g.static final StringThe "super 0" symbol is used in some fitters (e.g.static final StringThe "super 1" symbol is used in some fitters (e.g.static final StringThe "super 2" symbol is used in some fitters (e.g.static final StringThe "super n" symbol is used in some fitters (e.g. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedALeastSquaresFitter(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer optimizer, IInitialGuess initialGuesser) Construct a fitter with default iteration/evaluation/checker settings.protectedALeastSquaresFitter(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 TypeMethodDescriptionabstract EvaluatorasEvaluator(FitResult fit) Create an evaluator for the fit result.protected static FitResultbuildFitResult(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.ParameterValidatorclampingValidator(double[] lower, double[] upper) Create aParameterValidatorthat 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.ParameterValidatorDefault validator/bounds policy (optional).final FitResultfit(double[] x, double[] y) Fit with no weights, no initial guess override, and no parameter validator override.final FitResultfit(double[] x, double[] y, double[] weights) Fit with weights but no initial guess override and no parameter validator override.final FitResultfit(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.SimpleVectorValueCheckerprotected doubleprotected intprotected intprotected abstract intabstract IFitStringGetterGet the descriptive string getter for this fitter.protected abstract org.apache.commons.math3.fitting.leastsquares.MultivariateJacobianFunctionmodel(double[] x) Build the model + analytic (or numeric) Jacobian for this fitter, given x values.protected static org.apache.commons.math3.linear.RealMatrixsafeCovariances(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 voidvalidateWeights(double[] weights, int n) Validate weights array.protected static voidvalidateXY(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, waitMethods inherited from interface edu.cnu.mdi.splot.fit.IFitStringGetter
functionForm, modelName, parameterName
-
Field Details
-
SUB0
The "sub 0" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "0" for parameters.- See Also:
-
SUB1
The "sub 1" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "1" for parameters.- See Also:
-
SUB2
The "sub 2" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "2" for parameters.- See Also:
-
SUBN
The "sub n" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "n" for parameters.- See Also:
-
SUP0
The "super 0" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "0" for parameters.- See Also:
-
SUP1
The "super 1" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "1" for parameters.- See Also:
-
SUP2
The "super 2" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "2" for parameters.- See Also:
-
SUPN
The "super n" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "n" for parameters.- See Also:
-
MU
The "mu" symbol is used in some fitters (e.g. Gaussian) and is more distinctive than "m" for parameters.- See Also:
-
SMALLSIG
The "sigma" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "s" for parameters.- See Also:
-
CAPSIG
The "capital sigma" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "S" for parameters.- See Also:
-
OMEGA
The "omega" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "w" for parameters.- See Also:
-
PHI
The "phi" symbol is used in some fitters (e.g. Fourier) and is more distinctive than "p" for parameters.- See Also:
-
subArray
Subscript array for parameter labels (e.g. p₁, p₂, ...). -
optimizer
protected final org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer optimizerOptimizer used for the fit (often Levenberg-Marquardt). -
initialGuesser
Initial-guess strategy used when the caller does not provide an explicit guess. -
maxIterations
protected final int maxIterationsMaximum iterations used by the least-squares problem (Commons Math builder). Subclasses may override viagetMaxIterations(). -
maxEvaluations
protected final int maxEvaluationsMaximum evaluations used by the least-squares problem (Commons Math builder). Subclasses may override viagetMaxEvaluations(). -
checker
protected final org.apache.commons.math3.optim.SimpleVectorValueChecker checkerAbsolute/relative thresholds used by the default convergence checker. Subclasses may override viagetChecker(). -
covarianceThreshold
protected final double covarianceThresholdCovariance extraction threshold passed toOptimum.getCovariances(threshold). Subclasses may override viagetCovarianceThreshold().
-
-
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 instanceinitialGuesser- fallback initial guess strategymaxIterations- maximum iterations for the least-squares buildermaxEvaluations- maximum evaluations for the least-squares builderchecker- 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
MultivariateJacobianFunctioncompatible 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 theinitialGuesser.Subclasses may override if they have a better model-specific guess.
- Parameters:
x- x datay- y dataweights- 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 valuesy- y valuesminPoints- 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 arrayn- 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 aParameterValidatorthat 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
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 fitterparams- fitted parameterscovariance- covariance matrix (may be null)nPoints- number of data pointsnParams- number of fitted parametersopt- optimization result from Commons Math- Returns:
- a FitResult instance
-
getStringGetter
Get the descriptive string getter for this fitter.- Returns:
- the string getter
-
fit
Fit with no weights, no initial guess override, and no parameter validator override. -
fit
Fit with weights but no initial guess override and no parameter validator override. -
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 datay- y dataweights- optional weights (length n), typically1/sigmaY^2; may be nullinitialGuessOverride- optional explicit initial guess (length p); may be nullvalidatorOverride- optional explicit parameter validator; may be null- Returns:
- FitResult
-