API

Index

Exported symbols

The list of GModelFit.jl exported symbols is as follows:

GModelFit.CartesianDomainType
CartesianDomain{N}

An object representing a model, or a dataset, N-dimensional cartesian domain (i.e. a grid).

Available constructors:

  • Domain(axis...): each argument is a vector containing the coordinates on a given axis (arguments may have different lengths);
  • Domain(lengths...): returns a N-dim CartesianDomain object whose axis lengths are specified in the arguments.

Note that a CartesianDomain requires at least 2 dimensions.

Coordinates for all points along a given axis can be obtained with the coords() function, while the coordinates of the grid can be obtained with axis().

source
GModelFit.DomainType
Domain{N}

An object representing a model, or a dataset, N-dimensional linear domain.

Available constructors:

  • Domain(coords...): each argument is a vector, one for each dimension (all arguments must have same lengths);
  • Domain(length): returns a 1-dim Domain object of the given length.

Coordinates for all points along a given axis can be obtained with the coords function.

source
GModelFit.MeasuresType
Measures{N}

An object representing a set of empirical measurements (with Gaussian uncertainties) as measured on a specific domain.

Available constructors:

  • Measures(domain::Domain{N}, values::AbstractVector{T}, uncerts::AbstractVector{T}) where {T <: AbstractFloat, N}
  • Measures(domain::CartesianDomain{N}, values::AbstractArray{T, N}, uncerts::AbstractArray{T, N}) where {T <: AbstractFloat, N}
  • Measures(values::AbstractVector, uncerts)

In the above constructor methods the last argument may also be a scalar value, to set the same uncertainty for all the measurements. The method accepting a CartesianDomain requires arrays with at least 2 dimensions. In the last constructor the Domain object is automatically built depending on the length of the values vector.

The domain, values and uncertainties for a Measures object can be retrieved using the domain, values and uncerts functions respectively.

source
GModelFit.ModelType
Model

A structure containing a model description.

Constructor is: Model(components...). Components may be specified as:

  • a single Dict{Symbol, AbstractComponent}, where the keys are the names and the values the component objects;
  • a single component (the default :main is automatically assigned);
  • a single FunctDesc which will be wrapped into an FComp component and a default name will be assigned (:main);
  • one or more Pair{Symbol, AbstractComponent}, where the first element is the name and the second is the component.

You may access the individual component in a Model using the indexing syntax, as if it was a Dict{Symbol, AbstractComponent}. Also, you may add new components to a Model after it has been created using the same syntax. Finally, you may use the keys() and haskey() functions with their usual meanings.

Individual components may be freezed (i.e. have all its parameters fixed during fitting, despite the individual Parameter settings) or thawed using the freeze!() and thaw!() functions. Use the isfreezed() function to check if a component is freezed.

The main component, i.e. the one whose evaluation corresponds to the overall model evaluation, is automatically identified by analyzing the component dependencies. However a specific component may be forced to be the main one by invoking select_maincomp!.

The most important function for a Model object is fit() which allows to fit the model against an empirical dataset. The fit!() function has the same purpose, with the only difference that it stores the best fit parameter values into the original Model object.

The model and all component evaluation can be evaluated has if they were a function by simply passing a Domain object.

source
GModelFit.@fdMacro
@fd expr

Macro to generate a FunctDesc object using the same syntax as for a standard Julia anonymous function.

Example

julia> f = @fd (x, p=0) -> x + p

julia> f(1, 2)
3
source
GModelFit.axisFunction
axis(d::CartesianDomain, dim::Integer)

Returns the coordinates of the grid along a given dimension as a Vector{Float64}.

source
GModelFit.compareFunction
compare(model::Model, data::Measures)

Compare a model to a dataset and return a FitStats object.

source
compare(multi::Vector{Model}, data::Vector{Measures{N}})

Compare a multi-model to a multi-dataset and return a FitStats object.

source
GModelFit.coordsFunction
coords(d::Domain{1})
coords(d::Domain, dim::Integer)
coords(d::CartesianDomain, dim::Integer)

Returns coordinates of all points along a given dimension as a Vector{Float64}.

source
GModelFit.domainFunction
domain(d::AbstractMeasures)

Return the domain associated to an AbstractMeasures object.

source
GModelFit.fitFunction
fit(model::Model, data::Measures; minimizer::AbstractMinimizer=lsqfit())

Fit a model to an empirical data set using the specified minimizer (default: lsqfit()). See also fit!.

source
fit(multi::Vector{Model}, data::Vector{Measures{N}}; minimizer::AbstractMinimizer=lsqfit())

Fit a multi-model to a set of empirical data sets using the specified minimizer (default: lsqfit()). See also fit!.

source
GModelFit.fit!Function
fit!(model::Model, data::Measures; minimizer::AbstractMinimizer=lsqfit())

Fit a model to an empirical data set using the specified minimizer (default: lsqfit()). Upon return the parameter values in the Model object are set to the best fit ones.

source
fit!(multi::Vector{Model}, data::Vector{Measures{N}}; minimizer::AbstractMinimizer=lsqfit())

Fit a multi-model to a set of empirical data sets using the specified minimizer (default: lsqfit()). Upon return the parameter values in the Model objects are set to the best fit ones.

source
GModelFit.freeze!Function
freeze!(model::Model, cname::Symbol)

Freeze a component in the model (i.e. treat all component parameters as fixed for fitting).

source
Base.getindexFunction
getindex(model::Model, cname::Symbol)

Return the model component with name cname.

source
Base.haskeyFunction
haskey(m::Model, name::Symbol)

Check whether a component exists in model.

source
GModelFit.isfreezedFunction
isfreezed(model::Model, cname::Symbol)

Check whether a component is freezed in the model.

source
Base.lengthFunction
length(model::Model)

Return number of components in a model.

source
GModelFit.thaw!Function
thaw!(model::Model, cname::Symbol)

Thaw a freezed component in the model (i.e. treat component parameters as fixed only if explicitly set in the corresponding Parameter structure).

source
GModelFit.uncertsFunction
uncerts(d::Measures)

Returns the measurement uncertainties as a Vector{Float64}.

source
Base.valuesFunction
values(d::Measures)

Returns the measurement values as a Vector{Float64}.

source

Non-exported symbols

The following symbols are not exported by the GModelFit.jl package since they are typically not used in every day work, or aimed to debugging purposes. Still, they can be useful in some case, hence they are documented here.

GModelFit.evalcounterFunction
evalcounter(meval::ModelEval, cname::Symbol)

Return the number of times a component has been evaluated.

source
GModelFit.evalcountersFunction
evalcounters(meval::ModelEval)

Return a OrderedDict{Symbol, Int} with the number of times each model component has been evaluated.

source
GModelFit.CompEvalType
CompEval(comp::AbstractComponent, domain::AbstractDomain)

A container for a component to be evaluated on a specific domain.

Fields:

  • comp::AbstractComponent: the wrapped component;
  • domain::AbstractDomain: the domain where the component is supposed to be evaluated;
  • counter::Int: the number of times the component has been evaluated since creatio of the CompEval object;
  • lastparvalues::Vector{Float64}: the parameter values used in the last evaluation. A call to update!() with the same values stored in lastparvalues will not result in a new evaluation;
  • deps::Vector{Vector{Float64}}: the evaluation buffers of all dependencies;
  • buffer::Vector{Float64}: the buffer to store the outcome of the component.
source
GModelFit.FitStatsType
FitStats

A structure representing the results of a fitting process.

Fields:

  • elapsed::Float64: elapsed time (in seconds);
  • ndata::Int: number of data empirical points;
  • nfree::Int: number of free parameters;
  • dof::Int: ndata - nfree;
  • fitstat::Float64: fit statistics (equivalent ro reduced χ^2 for Measures objects);
  • status: minimizer exit status (tells whether convergence criterion has been satisfied, or if an error has occurred during fitting);

Note: the FitStats fields are supposed to be accessed directly by the user.

source
GModelFit.FunctDescType
FunctDesc

A "Julia function" descriptor containing the reference to the function itself, a string representation of its source code definition (for displaying purposes) and the lists of its arguments. It can be invoked using the standard syntax for functions

Example:

julia> f = GModelFit.FunctDesc( (x, p=0) -> x + p,   # actual function definition
                               "(x, p=0) -> x + p",  # string representation
                               [:x],                 # vector of argument namess
                               [:(p = 0)])           # vector of `Expr` with arguments default values
julia> f(1, 2)
3

Note that it is inconvenient to directly create a FunctDescr using its constructor, and the above results can be obtained by using the @fd macro:

f = @fd (x, p=0) -> x + p
source
GModelFit.ModelEvalType
ModelEval(model::Model, domain::AbstractDomain)

A structure containing the required informations to evaluate a model on a specific domain, and to compare the outcomes to a single empirical dataset.

The model and all component evaluation can be obtained by using the Model object has if it was a function: with no arguments it will return the main component evaluation, while if a Symbol is given as argument it will return the evaluation of the component with the same name.

source
GModelFit.ModelSnapshotType
ModelSnapshot

A structure containing a snapshot (i.e. a "frozen" state) of a Model. A snapshot contains the same parameters and component evaluations of the original model, and provide the same user interface. Moreover, a ModelSnapshot can be serialized to a file and de-serialized in another Julia session (see GModelFit.serialize()).

The best fit model and parameter values returned by the fit() function are provided as a ModelSnapshot object .

source
GModelFit.MultiResidualsType
MultiResiduals{T <: AbstractMeasures, M <: AbstractMinimizer}

A structure representing the distance between a Vector{ModelEval} and a corresponding number of datasets. The "distance" is expressed in terms of weighted residuals.

A minimizer can be invoked via the minimize! function to reduce such distance by varying the parameter valuesfor each model.

Fields:

  • mevals::Vector{ModelEval}: Vector of model evaluations;
  • data::Vector{<: AbstractMeasures}: Empirical datasets to be compared to the models;
  • buffer::Vector{Float64}: Weighted residuals for each point in the domain of each dataset;
  • mzer::AbstractMinimizer: Minimizer used to reduce the residuals.
source
GModelFit.ParameterType
Parameter

A structure representing a model parameter.

Fields:

  • val::Float64: parameter value (initial guess before fitting, or best fit one after fitting);
  • low::Float64: lower limit for the value (default: -Inf);
  • high::Float64: upper limit for the value (default: +Inf);
  • fixed::Bool: whether the parameter is fixed during fitting (default: false);
  • patch::Union{Nothing, Symbol, FunctDesc}: patch prescription within the same model;
  • mpatch::Union{Nothing, FunctDesc}: patch prescription in a multi-model analysis;
  • actual::Float64: actual value for the parameter (i.e. after applying the patch prescription)`;
  • unc::Float64: 1σ uncertainty associated to the parameter value.

Note: the Parameter fields are supposed to be accessed directly by the user, without invoking any get/set method.

source
GModelFit.ResidualsType
Residuals{T <: AbstractMeasures, M <: AbstractMinimizer}

A structure representing the distance between a ModelEval and a dataset. The "distance" is expressed in terms of weighted residuals.

A minimizer can be invoked via the minimize! function to reduce such distance by varying the model parameter values.

Fields:

  • meval::ModelEval: Model evaluation on a given domain;
  • data::AbstractMeasures: Empirical dataset to be compared to the model;
  • buffer::Vector{Float64}: Weighted residuals for each point in the domain;
  • mzer::AbstractMinimizer: Minimizer used to reduce the residuals.
source
GModelFit.comptypesFunction
comptypes(model::Model)

Return a OrderedDict{Symbol, String} with the model component types.

source
GModelFit.dependenciesFunction
dependencies(comp::AbstractComponent)

Return the name of dependecies for a component. Return value must be a Vector{Symbol}.

Default implementation returns Symbol[] (i.e. no dependencies.

source
GModelFit.evaluate!Function
evaluate!(ceval::CompEval, pvalues::Vector{Float64})

Evaluate a component using the provided parameter values. Outcomes shall be stored in the CompEval.buffer vector.

source
GModelFit.last_evaluationFunction
last_evaluation(meval::ModelEval)
last_evaluation(meval::ModelEval, name::Symbol)

Return last evaluation of a component whose name is cname in a ModelEval object. If cname is not provided the evaluation of the main component is returned.

source
GModelFit.minimize!Function
minimize!(resid::Residuals)

Invoke a minimizer to reduce the residuals between a model and a dataset.

source
minimize!(mresid::MultiResiduals)

Invoke a minimizer to reduce the residuals between a set of models and a corresponding number of datasets.

source
GModelFit.mockFunction
mock(::Type{Measures}, model::Model; keywords...)
mock(::Type{Measures}, multi::Vector{Model}; keywords...)

Generate mock dataset(s) using a ground truth Model or Vector{Model} object. The first version returns a single Measures object, while the second returns a Vector{Measures}.

The measurement random errors added to the data points are drawn from a Normal distribution centered on the data value itself, and a width given by the sum of three contributions:

  • proportional part: error proportional to each data point value;
  • range part: error proportional to the range spanned by all values in a single dataset;
  • absolute part: absolute error value.

No systematic error is considered when generating mock dataset(s).

Accepted keywords:

  • properr=0.01: proportional error;
  • rangeerr=0.05: range error;
  • abserr=0.: absolute error;
  • seed=nothing: seed for the Random.MersenneTwister generator.
source
GModelFit.prepare!Function
prepare!(comp::AbstractComponent, domain::AbstractDomain)

Allocate the buffer for a component evaluation on a specific domain. Return value must be a Vector{Float64}.

This function is invoked only once when the ModelEval structure is created (typically within a fit of fit! call), hence it is the perfect place to pre-compute quantities associated to a component evaluation on a specific domain. Default implementation returns a vector filled with NaNs with the same length as the domain.

source
GModelFit.serializeFunction
GModelFit.serialize(filename::String, ::ModelSnapshot[, ::FitStats[, ::Measures]]; compress=false)
GModelFit.serialize(filename::String, ::Vector{ModelSnapshot}[, ::FitStats[, ::Vector{Measures}]]; compress=false)

Serialize GModelFit object(s) using a JSON format. The serializable objects are:

  • ModelSnapshot and Vector{ModelSnapshot} (mandatory argument);
  • FitStats (optional);
  • Measures and Vector{Measures} (optional);

If compress=true the resulting JSON file will be compressed using GZip. Objects can later be deserialized in a different Julia session with GModelFit.deserialize.

Note: The GModelFit.serialize function also accepts Model and Vector{Model} but they will be internally converted to ModelSnapshot(s).

Example:

# Create GModelFit objects
using GModelFit
model = Model(:linear => @fd (x, b=2, m=0.5) -> (b .+ x .* m))
data = Measures([4.01, 7.58, 12.13, 19.78, 29.04], 0.4)
bestfit, stats = fit(model, data)

# Serialize objects and save in a file
GModelFit.serialize("my_snapshot.json", bestfit, stats, data)

# Restore objects (possibly in a different Julia session)
using GModelFit
(bestit, stats, data) = GModelFit.deserialize("my_snapshot.json")
source
GModelFit.update!Function
update!(ceval::CompEval, pvalues::Vector{Float64})

Update a CompEval structure using the provided parameter values.

The component is actually evaluated if one of the following applies:

  • the component has never been evaluated;
  • the component has at least one dependency (whose evaluation may have changed since its last evaluation);
  • at least one parameter value has changed since last evaluation.

If none of the above applies, no evaluation occurs.

source
update!(meval::ModelEval)

Update a ModelEval structure by evaluating all components in the model.

source