# Home

## 25. Parameter and model definitions

## `sasmodels.modelinfo`

### Model Info and Parameter Tables

Defines `ModelInfo` and `ParameterTable` and the routines for manipulating them. In particular, `make_model_info()` converts a kernel module into the model info block as seen by the rest of the sasmodels library.

class sasmodels.modelinfo.ModelInfo

  Bases: `object`

  Interpret the model definition file, categorizing the parameters.

  The module can be loaded with a normal python import statement if you know which module you need, or with __import__(‘sasmodels.model.’+name) if the name is in a string.

  The structure should be mostly static, other than the delayed definition of Iq, Iqac and Iqabc if they need to be defined.

  get_hidden_parameters(control)

    Returns the set of hidden parameters for the model. control is the value of the control parameter. Note that multiplicity models have an implicit control parameter, which is the parameter that controls the multiplicity.

  Imagnetic: None | str | Callable[[...], ndarray] = None

    Returns I(qx, qy, a, b, …). The interface follows `Iq`.

  Iq: None | str | Callable[[...], ndarray] = None

    Returns I(q, a, b, …) for parameters a, b, etc. defined by the parameter table. Iq can be defined as a python function, or as a C function. If it is defined in C, then set Iq to the body of the C function, including the return statement. This function takes values for q and each of the parameters as separate double values (which may be converted to float or long double by sasmodels). All source code files listed in `source` will be loaded before the Iq function is defined. If Iq is not present, then sources should define static double Iq(double q, double a, double b, …) which will return I(q, a, b, …). Multiplicity parameters are sent as pointers to doubles. Constants in floating point expressions should include the decimal point. See `generate` for more details. If have_Fq is True, then Iq should return an interleaved array of \([\sum F(q_1), \sum F^2(q_1), \ldots, \sum F(q_n), \sum F^2(q_n)]\).

  Iqabc: None | str | Callable[[...], ndarray] = None

    Returns I(qa, qb, qc, a, b, …). The interface follows `Iq`.

  Iqac: None | str | Callable[[...], ndarray] = None

    Returns I(qab, qc, a, b, …). The interface follows `Iq`.

  Iqxy: None | str | Callable[[...], ndarray] = None

    Returns I(qx, qy, a, b, …). The interface follows `Iq`.

  base: ParameterTable = None

    For reparameterized systems, base is the base parameter table. For normal systems it is simply a copy of parameters.

  basefile: str | None = None

    Base file is usually filename, but not when a model has been reparameterized, in which case it is the file containing the original model definition. This is needed to signal an additional dependency for the model time stamp, and so that the compiler reports correct file for syntax errors.

  c_code: str | None = None

    inline source code, added after all elements of source

  category: str | None = None

    Location of the model description in the documentation. This takes the form of “section” or “section:subsection”. So for example, porod uses category=”shape-independent” so it is in the Shape-Independent Functions section whereas capped_cylinder uses: category=”shape:cylinder”, which puts it in the Cylinder Functions section.

  composition: tuple[str, list[ModelInfo]] | None = None

    Composition is None if this is an independent model, or it is a tuple with comoposition type (‘product’ or ‘misture’) and a list of `ModelInfo` blocks for the composed objects. This allows us to rebuild a complete mixture or product model from the info block. composition is not given in the model definition file, but instead arises when the model is constructed using names such as sphere*hardsphere or cylinder+sphere.

  description: str = None

    Long description of the model.

  docs: str = None

    Doc string from the top of the model file. This should be formatted using ReStructuredText format, with latex markup in “.. math” environments, or in dollar signs. This will be automatically extracted to a .rst file by `generate.make_doc()`, then converted to HTML or PDF by Sphinx.

  filename: str | None = None

    Full path to the file defining the kernel, if any.

  form_volume: None | str | Callable[[ndarray], float] = None

    Returns the form volume for python-based models. Form volume is needed for volume normalization in the polydispersity integral. If no parameters are volume parameters, then form volume is not needed. For C-based models, (with `source` defined, or with `Iq` defined using a string containing C code), form_volume must also be C code, either defined as a string, or in the sources.

  have_Fq = False

    True if the model defines an Fq function with signature `void Fq(double q, double *F1, double *F2, ...)`

  hidden: Callable[[int], set[str]] | None = None

    Different variants require different parameters. In order to show just the parameters needed for the variant selected, you should provide a function hidden(control) -> set([‘a’, ‘b’, …]) indicating which parameters need to be hidden. For multiplicity models, you need to use the complete name of the parameter, including its number. So for example, if variant “a” uses only sld1 and sld2, then sld3, sld4 and sld5 of multiplicity parameter sld[5] should be in the hidden set.

  id: str = None

    Id of the kernel used to load it from the filesystem.

  lineno: dict[str, int] = None

    Line numbers for symbols defining C code

  name: str = None

    Display name of the model, which defaults to the model id but with capitalization of the parts so for example core_shell defaults to “Core Shell”.

  opencl: bool = None

    True if the model can be run as an opencl model. If for some reason the model cannot be run in opencl (e.g., because the model passes functions by reference), then set this to false.

  parameters: ParameterTable = None

    Model parameter table. Parameters are defined using a list of parameter definitions, each of which is contains parameter name, units, default value, limits, type and description. See `Parameter` for details on the individual parameters. The parameters are gathered into a `ParameterTable`, which provides various views into the parameter list.

  profile: Callable[[ndarray], None] | None = None

    Returns a model profile curve x, y. If profile is defined, this curve will appear in response to the Show button in SasView. Use `profile_axes` to set the axis labels. Note that y values will be scaled by 1e6 before plotting.

  profile_axes: tuple[str, str] = None

    Axis labels for the `profile` plot. The default is [‘x’, ‘y’]. Only the x component is used for now.

  radius_effective: None | Callable[[int, ndarray], float] = None

    Computes the effective radius of the shape given the volume parameters. Only needed for models defined in python that can be used for monodisperse approximation for non-dilute solutions, P@S. The first argument is the integer effective radius mode, with default 0.

  radius_effective_modes: list[str] = None

    List of options for computing the effective radius of the shape, or None if the model is not usable as a form factor model.

  random: Callable[[], dict[str, float]] | None = None

    Returns a random parameter set for the model

  sesans: Callable[[ndarray], ndarray] | None = None

    Returns sesans(z, a, b, …) for models which can directly compute the SESANS correlation function. Note: not currently implemented.

  shell_volume: None | str | Callable[[ndarray], float] = None

    Returns the shell volume for python-based models. Form volume and shell volume are needed for volume normalization in the polydispersity integral and structure interactions for hollow shapes. If no parameters are volume parameters, then shell volume is not needed. For C-based models, (with `source` defined, or with `Iq` defined using a string containing C code), shell_volume must also be C code, either defined as a string, or in the sources.

  single: bool = None

    True if the model can be computed accurately with single precision. This is True by default, but models such as bcc_paracrystal set it to False because they require double precision calculations.

  source: list[str] = None

    List of C source files used to define the model. The source files should define the Iq function, and possibly Iqac or Iqabc if the model defines orientation parameters. Files containing the most basic functions must appear first in the list, followed by the files that use those functions.

  structure_factor: bool = None

    True if the model is a structure factor used to model the interaction between form factor models. This will default to False if it is not provided in the file.

  tests: list[tuple[Mapping[str, float | list[float]], str | float | list[float] | tuple[float, float] | list[tuple[float, float]], float | list[float]]] = None

    The set of tests that must pass. The format of the tests is described in `model_test`.

  title: str = None

    Short description of the model.

  translation: str | None = None

    Parameter translation code to convert from parameters table from caller to the base table used to evaluate the model.

  valid: str = None

    Expression which evaluates to True if the input parameters are valid and the model can be computed, or False otherwise. Invalid parameter sets will not be included in the weighted \(I(Q)\) calculation or its volume normalization. Use C syntax for the expressions, with || for or && for and and ! for not. Any non-magnetic parameter can be used.

class sasmodels.modelinfo.Parameter(name: str, units: str = '', default: float = nan, limits: tuple[float, float] = (-inf, inf), ptype: str = '', description: str = '')

  Bases: `object`

  The available kernel parameters are defined as a list, with each parameter defined as a sublist with the following elements:

  name is the name that will be displayed to the user. Names should be lower case, with words separated by underscore. If acronyms are used, the whole acronym should be upper case. For vector parameters, the name will be followed by [len] where len is an integer length of the vector, or the name of the parameter which controls the length. The attribute id will be created from name without the length.

  units should be one of degrees for angles, Ang for lengths, 1e-6/Ang^2 for SLDs.

  default will be the initial value for the model when it is selected, or when an initial value is not otherwise specified.

  limits ([lb, ub]) are the hard limits on the parameter value, used to limit the polydispersity density function. In the fit, the parameter limits given to the fit are the limits on the central value of the parameter. If there is polydispersity, it will evaluate parameter values outside the fit limits, but not outside the hard limits specified in the model. If there are no limits, use +/-inf imported from numpy.

  type indicates how the parameter will be used. “volume” parameters will be used in all functions. “orientation” parameters are not passed, but will be used to convert from qx, qy to qa, qb, qc in calls to Iqxy and Imagnetic. If type is the empty string, the parameter will be used in all of Iq, Iqxy and Imagnetic. “sld” parameters can automatically be promoted to magnetic parameters, each of which will have a magnitude and a direction, which may be different from other sld parameters. The volume parameters are used for calls to form_volume within the kernel (required for volume normalization), to shell_volume (for hollow shapes), and to radius_effective (for structure factor interactions) respectively.

  description is a short description of the parameter. This will be displayed in the parameter table and used as a tool tip for the parameter value in the user interface.

  Additional values can be set after the parameter is created:

  - length is the length of the field if it is a vector field

  - length_control is the parameter which sets the vector length

  - is_control is True if the parameter is a control parameter for a vector

  - polydisperse is true if the parameter accepts a polydispersity

  - relative_pd is true if that polydispersity is a portion of the value (so a 10% length dipsersity would use a polydispersity value of 0.1) rather than absolute dispersisity (such as an angle plus or minus 15 degrees).

  choices is the option names for a drop down list of options, as for example, might be used to set the value of a shape parameter.

  Control parameters are used for variant models such as rpa which have different cases with different parameters, as well as models like spherical_sld with its user defined number of shells. The control parameter should appear in the parameter table along with the parameters it is is controlling. For variant models, use [CASES] in place of the parameter limits Within the parameter definition table, with case names such as:

      CASES = ["diblock copolymer", "triblock copolymer", ...]

  This should give limits=[[case1, case2, …]], but the model loader translates it to limits=[0, len(CASES)-1], and adds choices=CASES to the `Parameter` definition. Note that models can use a list of cases as a parameter without it being a control parameter. Either way, the parameter is sent to the model evaluator as float(choice_num), where choices are numbered from 0. `ModelInfo.get_hidden_parameters()` will determine which parameers to display.

  The class contructor should not be called directly, but instead the parameter table is built using `make_parameter_table()` and `parse_parameter()` therein.

  as_definition() → str

    Declare space for the variable in a parameter structure.

    For example, the parameter thickness with length 3 will return “double thickness[3];”, with no spaces before and no new line character afterward.

  as_function_argument() → str

    Declare the variable as a function argument.

    For example, the parameter thickness with length 3 will return “double *thickness”, with no spaces before and no comma afterward.

class sasmodels.modelinfo.ParameterTable(parameters: list[Parameter])

  Bases: `object`

  ParameterTable manages the list of available parameters.

  There are a couple of complications which mean that the list of parameters for the kernel differs from the list of parameters that the user sees.

  (1) Common parameters. Scale and background are implicit to every model, but are not passed to the kernel.

  (2) Vector parameters. Vector parameters are passed to the kernel as a pointer to an array, e.g., thick[], but they are seen by the user as n separate parameters thick1, thick2, …

  Therefore, the parameter table is organized by how it is expected to be used. The following information is needed to set up the kernel functions:

  - kernel_parameters is the list of parameters in the kernel parameter table, with vector parameter p declared as p[].

  - iq_parameters is the list of parameters to the Iq(q, …) function, with vector parameter p sent as p[].

  - form_volume_parameters is the list of parameters to the form_volume(…) function, with vector parameter p sent as p[].

  Problem details, which sets up the polydispersity loops, requires the following:

  - theta_offset is the offset of the theta parameter in the kernel parameter table, with vector parameters counted as n individual parameters p1, p2, …, or offset is -1 if there is no theta parameter.

  - max_pd is the maximum number of polydisperse parameters, with vector parameters counted as n individual parameters p1, p2, … Note that this number is limited to sasmodels.modelinfo.MAX_PD.

  - npars is the total number of parameters to the kernel, with vector parameters counted as n individual parameters p1, p2, …

  - common_parameters is the list of common parameters, with a unique copy for each model so that structure factors can have a default background of 0.0.

  - call_parameters is the complete list of parameters to the kernel, including scale and background, with vector parameters recorded as individual parameters p1, p2, …

  - active_1d is the set of names that may be polydisperse for 1d data

  - active_2d is the set of names that may be polydisperse for 2d data

  User parameters are the set of parameters visible to the user, including the scale and background parameters that the kernel does not see. User parameters don’t use vector notation, and instead use p1, p2, …

  check_angles(strict=False)

    Check that orientation angles are theta, phi and possibly psi.

    strict should be True when checking a parameter table defined in a model file, but False when checking from mixture models, etc., where the parameters aren’t being passed to a calculator directly.

  check_duplicates()

    Check for duplicate parameter names

  set_zero_background() → None

    Set the default background to zero for this model. This is done for structure factor models.

  user_parameters(pars: dict[str, float], is2d: bool = True) → list[Parameter]

    Return the list of parameters for the given data type.

    Vector parameters are expanded in place. If multiple parameters share the same vector length, then the parameters will be interleaved in the result. The control parameters come first. For example, if the parameter table is ordered as:

        sld_core
        sld_shell[num_shells]
        sld_solvent
        thickness[num_shells]
        num_shells

    and pars[num_shells]=2 then the returned list will be:

        num_shells
        scale
        background
        sld_core
        sld_shell1
        thickness1
        sld_shell2
        thickness2
        sld_solvent

    Note that shell/thickness pairs are grouped together in the result even though they were not grouped in the incoming table. The control parameter is always returned first since the GUI will want to set it early, and rerender the table when it is changed.

    Parameters marked as sld will automatically have a set of associated magnetic parameters (p_M0, p_mtheta, p_mphi), as well as polarization information (up_theta, up_phi, up_frac_i, up_frac_f).

sasmodels.modelinfo.derive_table(table: ParameterTable, insert: list[str], remove: list[Parameter], insert_after: dict[str, str] | None = None) → ParameterTable

  Create a derived parameter table.

  Parameters given in insert are added to the table and parameters named in remove are deleted from the table. If insert_after is provided, then it indicates where in the new parameter table the parameters are inserted.

sasmodels.modelinfo.expand_pars(partable: ParameterTable, pars: Mapping[str, float | list[float]] = None) → Mapping[str, float]

  Create a parameter set from key-value pairs.

  pars are the key-value pairs to use for the parameters. Any parameters not specified in pars are set from the partable defaults.

  If pars references vector fields, such as thickness[n], then support different ways of assigning the parameter values, including assigning a specific value (e.g., thickness3=50.0), assigning a new value to all (e.g., thickness=50.0) or assigning values using list notation.

sasmodels.modelinfo.isstr(x: Any) → bool

  Return True if the object is a string.

sasmodels.modelinfo.make_model_info(kernel_module: ModuleType) → ModelInfo

  Extract the model definition from the loaded kernel module.

  Fill in default values for parts of the module that are not provided.

  Note: vectorized Iq and Iqac/Iqabc functions will be created for python models when the model is first called, not when the model is loaded.

sasmodels.modelinfo.make_parameter_table(pars: list[tuple[str, str, float, tuple[float, float], str, str]]) → ParameterTable

  Construct a parameter table from a list of parameter definitions.

  This is used by the module processor to convert the parameter block into the parameter table seen in the `ModelInfo` for the module.

sasmodels.modelinfo.parse_parameter(name: str, units: str = '', default: float = nan, user_limits: Sequence[Any] = None, ptype: str = '', description: str = '') → Parameter

  Parse an individual parameter from the parameter definition block.

  This does type and value checking on the definition, leading to early failure in the model loading process and easier debugging.

sasmodels.modelinfo.prefix_parameter(par: Parameter, prefix: str) → Parameter

  Return a copy of the parameter with its name prefixed.

sasmodels.modelinfo.suffix_parameter(par: Parameter, suffix: str) → Parameter

  Return a copy of the parameter with its name prefixed.

sasmodels.modelinfo.C_SYMBOLS = ['Imagnetic', 'Iq', 'Iqxy', 'Iqac', 'Iqabc', 'form_volume', 'shell_volume', 'c_code', 'valid']

  Set of variables defined in the model that might contain C code

sasmodels.modelinfo.MAX_PD = 5

  Maximum number of simultaneously polydisperse parameters