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().


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.


A structure representing the results of a fitting process.


  • timestamp::DateTime: time at which the fitting process has started;
  • 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, without invoking any get() method.


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


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)

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

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

An object representing a set of empirical measurements (with Gaussian uncertainties)

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}

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.

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


A structure containing a model description, whose evaluation is suitable to be compared to a single empirical dataset.

Constructor is: Model(domain::AbstractDomain, components...) where the first argument is either a Domain or CartesianDomain object, and the remaining one(s) is (are) the model component(s), which may be given as:

  • a single Dict{Symbol, AbstractComponent}, where the keys are the names and the values the component objects;
  • a single component, which will have a default name is assigned (:main);
  • a single FunctDesc, which will be wrapped into an LComp 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 synatx. 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 typically automatically identified by analyzing the component dependencies. However a specific component may be forced to be the main one by invoking select_maincomp!.

The model is automatically evaluated whenever needed, however there are a few cases where it is not possible to trigger an automatic evaluation, e.g. immediately after the user modifies a Parameter value. In this case an evaluation can be forced by invoking update!().

The most important function for a Model object is fit(), which allows to fit the model against an empirical dataset. The ! in the name reminds us that, after fitting, the parameter values will be set to the best fit ones (rather than retaining their original values).

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.


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 best fit parameter values returned as a ModelSnapshot object by the fit() function.


A structure representing a model parameter.


  • 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.

getindex(d::Union{Domain, CartesianDomain}, dim::Integer)

Shortcut for coords(d, dim).

haskey(m::Model, name::Symbol)

Check whether a component exists in model.


Returns the measurement values as a Vector{Float64}.

axis(d::CartesianDomain, dim::Integer)

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

compare(model::Model, data::Measures)

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

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

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

comptype(model::Model, cname::Symbol)

Return a component type as a string.


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

coords(d::Domain, dim::Integer)
coords(d::CartesianDomain, dim::Integer)

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


Return the domain where the model is evaluated.

evalcounter(model::Model, cname::Symbol)

Return the number of times a component has been evaluated.


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

fit(model::Model, data::Measures; minimizer::AbstractMinimizer=lsqfit())

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

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()).

freeze!(model::Model, cname::Symbol)

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

isfreezed(model::Model, cname::Symbol)

Check whether a component is freezed in the model.

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.
select_maincomp!(model::Model, cname::Symbol)

Force a component to be the final one for model evaluation.

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).


# Create GModelFit objects
using GModelFit
dom  = Domain(1:5)
model = Model(dom, :linear => @λ (x, b=2, m=0.5) -> (b .+ x .* m))
data = Measures(dom, [4.01, 7.58, 12.13, 19.78, 29.04], 0.4)
best, fitstats = fit(model, data)

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

# Restore objects (possibly in a different Julia session)
using GModelFit
(best, fitstats, data) = GModelFit.deserialize("my_snapshot.json")
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).


Returns the measurement uncertainties as a Vector{Float64}.


Evaluate a Model and update internal structures.

@λ expr

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


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

julia> f(1, 2)