API
Index
GModelFit.CartesianDomainGModelFit.DomainGModelFit.FunctDescGModelFit.IdealInstrumentGModelFit.MeasuresGModelFit.ModelGModelFit.ModelSnapshotGModelFit.ParameterGModelFit.Solvers.FitSummaryBase.getindexBase.haskeyBase.lengthBase.valuesGModelFit.axisGModelFit.comptypeGModelFit.comptypesGModelFit.coordsGModelFit.dependenciesGModelFit.domainGModelFit.evaluate!GModelFit.fitGModelFit.fit!GModelFit.fitstatGModelFit.freeze!GModelFit.isfreezedGModelFit.mockGModelFit.prepare!GModelFit.select_maincomp!GModelFit.serializeGModelFit.set_IR!GModelFit.thaw!GModelFit.uncertsGModelFit.@fd
Exported symbols
The list of GModelFit.jl exported symbols is as follows:
GModelFit.CartesianDomain — TypeCartesianDomain{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-dimCartesianDomainobject 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().
GModelFit.Domain — TypeDomain{N}An object representing a 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-dimDomainobject of the given length.
Coordinates for all points along a given axis can be obtained with the coords function.
GModelFit.Measures — TypeMeasures{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.
GModelFit.Model — TypeModelA 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
:mainis automatically assigned); - a single
FunctDescwhich will be wrapped into anFCompcomponent 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.
GModelFit.@fd — Macro@fd exprMacro 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)
3GModelFit.axis — Functionaxis(d::CartesianDomain, dim::Integer)Returns the coordinates of the grid along a given dimension as a Vector{Float64}.
GModelFit.comptype — Functioncomptype(model::Model, cname::Symbol)Return the type of a component within a Model. Return type is a String.
GModelFit.comptypes — Functioncomptypes(model::Model)Return a OrderedDict{Symbol, String} with the types of all components within a Model.
GModelFit.coords — Functioncoords(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}.
GModelFit.domain — Functiondomain(d::AbstractMeasures)Return the domain associated to an AbstractMeasures object.
GModelFit.fit — Functionfit(model::Model, data::Measures, solver=lsqfit())Fit a model to an empirical data set using the specified solver (default: lsqfit()). See also fit!.
fit(multi::Vector{Model}, data::Vector{Measures{N}}, solver=lsqfit())Fit a multi-model to a set of empirical data sets using the specified solver (default: lsqfit()). See also fit!.
GModelFit.fit! — Functionfit!(model::Model, data::Measures, solver=lsqfit())Fit a model to an empirical data set using the specified solver (default: lsqfit()). Upon return the parameter values in the Model object are set to the best fit ones. See also fit.
fit!(multi::Vector{Model}, data::Vector{Measures{N}}, solver=lsqfit())Fit a multi-model to a set of empirical data sets using the specified solver (default: lsqfit()). Upon return the parameter values in the Model objects are set to the best fit ones.
GModelFit.fitstat — Functionfitstat(model::Model, data::AbstractMeasures)Compare a model to a dataset and return the fit statistic.
fitstat(models::Vector{Model}, data::Vector{<: AbstractMeasures})Compare a multi-model to a multi-dataset and return fit statistic.
GModelFit.freeze! — Functionfreeze!(model::Model, cname::Symbol)Freeze a component in the model (i.e. treat all component parameters as fixed for fitting).
Base.getindex — Functiongetindex(model::Model, cname::Symbol)Return the model component with name cname.
Base.haskey — Functionhaskey(m::Model, name::Symbol)Check whether a component exists in model.
GModelFit.isfreezed — Functionisfreezed(model::Model, cname::Symbol)Check whether a component is freezed in the model.
Base.length — Functionlength(model::Model)Return number of components in a model.
GModelFit.select_maincomp! — Functionselect_maincomp!(model::Model, cname::Symbol)Force a component to be the final one for model evaluation.
GModelFit.thaw! — Functionthaw!(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).
GModelFit.uncerts — Functionuncerts(d::Measures)Returns the measurement uncertainties as a Vector{Float64}.
Base.values — Functionvalues(d::Measures)Returns the measurement values as a Vector{Float64}.
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.Solvers.FitSummary — TypeFitSummaryA structure summarizing the results of a fitting process.
Fields:
start::DateTime: timestamp at the beginning of the fitting process;elapsed::Float64: elapsed time (in seconds);ndata::Int: number of data empirical points;nfree::Int: number of free parameters;fitstat::Float64: fit statistics (equivalent ro reduced χ^2 forMeasuresobjects);status: minimization process status (tells whether convergence criterion has been satisfied, or if an error has occurred during fitting);solver_retval: solver return value.
Note: the solver_retval field can not be serialized, will contain nothing when deserialized.
GModelFit.FunctDesc — TypeFunctDescA "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)
3Note 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 + pGModelFit.IdealInstrument — TypeIdealInstrumentAn instrument response representing an ideal instrument, for which unfolded and folded models are identical.
This structure has no fields.
GModelFit.ModelSnapshot — TypeModelSnapshotA 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 .
GModelFit.Parameter — TypeParameterA 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.
GModelFit.dependencies — Functiondependencies(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).
GModelFit.evaluate! — Functionevaluate!(comp::AbstractComponent, domain::AbstractDomain, output::Abstractvector, param1, param2....
evaluate!(comp::AbstractComponent, domain::AbstractDomain, output::Abstractvector, deps::AbstractVector, param1, param2....Evaluate component comp on the given domain using deps dependencies and param1, param2, ... parameters. Output should be stored in theoutput` vector.
If the component has no dependencies the deps argument should not be present.
The evaluate! function is called with the output, deps and parameter arguments containing either Float64 values (to evaluate the component) or ForwardDiff.Dual values (to evaluate the component derivatives).
GModelFit.mock — Functionmock(::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 theRandom.MersenneTwistergenerator.
GModelFit.prepare! — Functionprepare!(comp::AbstractComponent, domain::AbstractDomain)Invoked to precompute component-specific quantities
This method is invoked only once when the component is first evaluated hence it is the perfect place to pre-compute quantities associated to a component evaluation on a specific domain.
prepare!(IR::AbstractInstrumentResponse, folded_domain::AbstractDomain)Invoked to precompute instrument response specific quantities.
This method is invoked when the instrument response is first evaluated hence it is the perfect place to pre-compute relevant quantities associated to the evaluation on a specific folded domain.
Extension of this method for user defined instrument response is optional, and the default implementation nothing.
GModelFit.serialize — FunctionGModelFit.serialize(filename::String, ::ModelSnapshot[, ::FitSummary[, ::Measures]]; compress=false)
GModelFit.serialize(filename::String, ::Vector{ModelSnapshot}[, ::FitSummary[, ::Vector{Measures}]]; compress=false)Serialize GModelFit object(s) using a JSON format. The serializable objects are:
ModelSnapshotandVector{ModelSnapshot}(mandatory argument);FitSummary(optional);MeasuresandVector{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
(bestfit, stats, data) = GModelFit.deserialize("my_snapshot.json")GModelFit.set_IR! — Functionset_IR!(model::Model, IR::AbstractInstrumentResponse)Set a model to use the instrument response passed as argument.
If this method is not invoked the GModelFit.IdealInstrument response will be used.