Parameters, variables, and functors#

The escape.core.objects module provides methods to create variables, parameters, and functors.

Model parameters#

There are two types of model parameters in ESCAPE: independent and dependent. Both are represented by parameter_obj type. Independent parameters are optimized during curve fitting by optimizer. Dependent parameters are those which are defined, for example, with algebraic expressions. Since both have the same type, user can control dependencies of parameters in a single model or between several models.

This gives a lot of flexibility. For example, one layer in your sample has a parameter T - thickness with initial value of \(100\quad nm\) And you know that every next layer is \(\delta T=10\quad nm\) larger, than previous. You can define thiknesses of layers as following:

>>> T = esc.par("T", 100, units="nm")
>>> dT = esc.par("dT", 10, units="nm")
>>> T1 = T + dT
>>> T2 = T + 2*dT
>>> T3 = T + 3*dT

T1, T2, T3 are dependent parameters. User can use them as input parameters for layer objects and optimizer will optimize only T and dt which are independent.

Parameters support all elementary mathematical functions including trigonometric, for example, dependent parameter can be defined as following

>>> S = esc.sin(T)*esc.cos(T)

The boundaries of independent parameter are set by default to \(\pm 50\%\) of initial value, when are not specified by user. If intitial value is zero, default boundaries are also set to zero. For more details, check full docs for par function below.

Variables and functors.#

In ESCAPE functor object fo type functor_obj represents mathematical function of given variables. ESCAPE supports functors of maximum five variables.

Variable is declared as following:

>>> x = esc.var('X')
>>> y = esc.var('Y')

Functors can be defined by user as a mathematical expression, for example, one-dimensional functor:

>>> F1 = esc.sin(x)*esc.cos(x)

or two-dimensional functor

>>> F2 = esc.sin(x)*esc.cos(y)

Special functors can be created by helper functions. Special functors normally represent a more complicated, than a simple mathematical expression, problem. For example, esc.average or esc.specrefl for the calculation of averaging integral or specular reflectivity, respectively. The advantage of this approach is a customization of any scattering problem not only in terms of parameters, but also in terms of final intensity formula. User can easily add custom non-linear background or special illumination correction.

A functor instance returns calculated value when being called

>>> F2(1.0, 2.3)
0.01743834

There are two types of functors in ESCAPE: functor_obj - double functor and cplx_functor_obj - functor which returns complex value. There is also a bool_functor_obj, which returns boolean value, but it is used as a part of conditional functor only (see below).

escape.core.entities.par(name: str = 'Parameter', value: float | int | str = 0.0, userlim: UserLimitLike | None = None, fixed: c_bool = False, scale: float = 1.0, units: str = '', trained: c_bool = False) → parameter_obj#

Create a new independent parameter object.

Args:

name: Parameter name value: Initial parameter value. Can be a number or string expression userlim: Optional parameter boundaries as (min, max) tuple or list fixed: If True, parameter value will not be optimized scale: Parameter value scale factor units: Parameter units string trained: If True, parameter will be used by neural network regressor

Returns:

A new parameter_obj instance

Raises:

TypeError: If value is not a float, int or str

The parameter can be created either from a numeric value or a string expression. If created from a string, it will be parsed into a dependent parameter. If created from a number, it will be an independent parameter.

For independent parameters, boundaries can be set explicitly via userlim, or calculated automatically.

escape.core.entities.var(names: str | List[str] | Tuple[str, ...] = 'X') → variable_obj | List[variable_obj]#

Create one or more variable objects with the given name(s).

This helper function creates variable objects that can be used in mathematical expressions. Variables are the basic building blocks for creating functors and expressions.

Args:
names: Name or list of names for the variables. Defaults to “X”.

If a single string is provided, creates one variable with that name. If a list/tuple of strings is provided, creates multiple variables.

Returns:
If names is a single string:

A single variable_obj with the given name

If names is a list/tuple:

A list of variable_obj instances, one for each provided name

Examples:

Create a single variable: >>> x = var(“x”) >>> x variable(name=’x’)

Create multiple variables: >>> x, y = var([“x”, “y”]) >>> x, y (variable(name=’x’), variable(name=’y’))

escape.core.entities.func(x, val, name: str = 'Const Functor')#

Given name name, variables list x and value or parameter val, this function returns const double functor instance.

Parameters:
x: list

Variables list.

val: double value or parameter_obj

Constant value or parameter value which functor will return when being called.

name: string

Name of the functor.

Returns:

Instance of functor_obj.

escape.core.entities.cfunc(x, val: complex, name: str = 'Const Complex Functor') → cplx_functor_obj#

Given name name, variables list x and complex value val, this function returns const complex functor instance.

Parameters:
x: list

Variables list.

val: double complex value

Constant double complex value which functor will return when being called.

name: string

Name of the functor.

Returns:

Instance of cplx_functor_obj.

escape.core.entities.reduce(func, var: variable_obj, value: float | int | str | parameter_obj, *args, name: str = 'Reduced Functor') → functor_obj | cplx_functor_obj#

Returns functor_obj or cplx_functor_obj instance which binds variables with constant values or parameters and reduces domain size of a given functor. For example, for a given initital functor f(x, y, z), one can achieve a custom functor of reduced domain size, f2(x)=f(x, y=2, z=3) by

>>> f2=reduce(f1, y, 2, z, 3) 
Parameters:

func: functor_obj or cplx_functor_obj var: variable_obj

Variable to be bound

value: ParameterLike

Constant float value or parameter for bound variable.

args: list

Other pairs of variables and values

name: string

Name of the functor.

Returns:

Instance of functor_obj or cplx_functor_obj depending on func type.

escape.core.entities.conditional(cond: constraint_obj | bool_functor_obj, ret_true: float | int | str | parameter_obj | functor_obj | cplx_functor_obj | variable_obj, ret_false: float | int | str | parameter_obj | functor_obj | cplx_functor_obj | variable_obj) → functor_obj | parameter_obj#

Create a conditional parameter or functor based on a boolean condition.

This function creates a conditional parameter or functor that returns either ret_true or ret_false based on the evaluation of the condition.

Args:

cond (Union[constraint_obj, bool_functor_obj]): The boolean condition to evaluate ret_true (Union[ParameterLike, FunctorLike]): Value to return when condition is True ret_false (Union[ParameterLike, FunctorLike]): Value to return when condition is False

Returns:
Union[functor_obj, parameter_obj]: A conditional parameter or functor.

Returns parameter_obj if cond is constraint_obj, otherwise returns functor_obj.

Raises:

TypeError: If cond is not constraint_obj or bool_functor_obj

escape.core.entities.setting(label: str, value: int | float | str | bool, units: str = '', readonly: bool = False) → setting_obj#

Create a new setting with the given label, value, units and readonly flag.

Parameters#

label :

Setting label describing its purpose.

value :

Setting value; can be int, float, str or bool.

units :

Optional units for the setting value.

readonly :

If True, the setting value cannot be modified.

Returns#

setting_obj

A setting object whose underlying C++ type is chosen based on the Python type of value.

Raises#

NotImplementedError

If value is of an unsupported type.

class escape.core.entities.setting_obj#

Generic setting class that wraps a C++ setting_t object.

This class provides an interface for settings with associated metadata like units, labels and readonly status. It manages the lifecycle of the underlying C++ object and provides Pythonic property access.

Properties#

unitsstr

The units associated with this setting value.

labelstr

A descriptive label for this setting.

is_readonlybool

Whether this setting can be modified.

valuebool | int | float | str

The current value of the setting, converted to the corresponding Python type based on the underlying C++ value type.

is_file_path#

True when this setting is a validated file-path handler.

is_readonly#

Check if this setting is read-only.

label#

Get the descriptive label for this setting.

options#

Allowed string options for option settings; empty otherwise.

options_int#

Allowed integer options for option settings; empty otherwise.

units#

Get the units string for this setting.

value#

Get the current value of this setting as a Python object.

value_type#

Return the underlying C++ value type as a short string label.

class escape.core.entities.variable_obj#

A class representing a variable in mathematical expressions.

This class provides operator overloading to allow variables to be used in mathematical expressions with other variables, parameters, functors, and numeric values. Supports arithmetic operations, comparisons, and power operations.

The variable object holds a pointer to a C++ variable_t instance that handles the underlying implementation.

name#

Get the name of the variable.

Returns:

str: The variable’s name

value#

Get the current value of the variable.

Returns:

float: The current value of the variable

class escape.core.entities.functor_obj#

Wrapper for double functor.

A functor represents a mathematical function that can be evaluated with variables and parameters. This class wraps the C++ functor_t implementation.

bind_python_object(observer=None)#
constrain(val: constraint_obj) → None#

Add constraint to functor.

Args:

val: Boolean parameter to use as constraint

constraints#

Get list of constraints on this functor.

Returns:

List[constraint_obj]: List of boolean parameter objects

static convert(value: functor_obj | cplx_functor_obj | variable_obj | float | int | str | parameter_obj, parent_or_vars: functor_obj | cplx_functor_obj | variable_obj | list[variable_obj] = None) → functor_obj#

Convert value to functor.

Args:

value: Value to convert - can be functor, variable, parameter etc. parent_or_vars: Parent functor or list of variables to use

Returns:

functor_obj: New functor representing converted value

Raises:

TypeError: If value or parent_or_vars have unsupported types

dependency_children() → list#

Return direct dependency children for this functor.

dependency_tree(depth=1) → dict#

Return a lightweight dependency tree for this functor.

device#

Get the current evaluation device for this functor.

Returns:

str: "cpu" for local evaluation, "gpu" when JIT CUDA is active (requires build with ESCAPE_WITH_GPU_JIT), or a ZeroMQ endpoint string (e.g. "tcp://host:5555") for cluster evaluation.

device_endpoint#

Get the device endpoint for this functor.

get_hash_int() → int#

Return the C++ entity hash used for stable identity.

is_feasible#

Check if functor is feasible (satisfies all constraints).

Returns:

bool: True if feasible, False otherwise

name#

Get name of functor.

Returns:

str: Name of functor

num_of_variables#

Get number of variables in this functor.

Returns:

int: Number of variables

num_threads#

Get the number of threads used for parallel evaluation of this functor.

Returns:

int: Number of threads (0 means default/auto).

num_variables#

Backwards-compatible alias for num_of_variables.

Some code and tests expect num_variables; this property simply forwards to num_of_variables.

on_state_changed()#
on_value_changed()#
parameters#

Get list of parameters used in this functor.

Returns:

List[parameter_obj]: List of parameter objects

settings#

Get settings exposed by this functor.

show(coordinates: ndarray | None = None, config: Any | None = None, **kwargs) → Any#

Show functor object in a widget.

unbind_python_object()#
unconstrain(val: constraint_obj) → None#

Remove constraint from functor.

Args:

val: Boolean parameter constraint to remove

unconstrain_all() → None#

Remove all constraints from functor.

variables#

Get list of variables used in this functor.

Returns:

List[variable_obj]: List of variable objects

class escape.core.entities.cplx_functor_obj#

A class representing a complex functor.

This class provides operator overloading to allow complex functors to be used in mathematical expressions with variables, parameters, functors, and numeric values. Supports arithmetic operations and comparisons.

The complex functor object holds a pointer to a C++ cplx_functor_t instance that handles the underlying implementation.

bind_python_object(observer=None)#
constrain(val: constraint_obj) → None#

Add constraint to functor.

Args:

val: Boolean parameter constraint to add

constraints#

Get list of constraints on functor.

Returns:

List[constraint_obj]: List of constraints

dependency_children() → list#

Return direct dependency children for this complex functor.

dependency_tree(depth=1) → dict#

Return a lightweight dependency tree for this complex functor.

get_hash_int() → int#

Return the C++ entity hash used for stable identity.

is_feasible#

Check if functor satisfies all constraints.

Returns:

bool: True if functor is feasible, False otherwise

name#

Get name of functor.

Returns:

str: Name of functor

num_of_variables#

Get number of variables used in functor.

Returns:

int: Number of variables

on_state_changed()#
on_value_changed()#
parameters#

Get list of parameters used in functor.

Returns:

List[parameter_obj]: List of parameters

settings#

Get settings exposed by this complex functor.

unbind_python_object()#
unconstrain(val: constraint_obj) → None#

Remove constraint from functor.

Args:

val: Boolean parameter constraint to remove

unconstrain_all() → None#

Remove all constraints from functor.

variables#

Get list of variables used in functor.

Returns:

List[variable_obj]: List of variables

class escape.core.entities.bool_functor_obj#

Wrapper for boolean functor.

A boolean functor represents a logical expression like f3(x) = f1(x) > f2(x). When called with value(s) x, it evaluates f1(x) and f2(x) and returns their logical comparison result.

bind_python_object(observer=None)#
dependency_children() → list#

Return direct dependency children for this boolean functor.

dependency_tree(depth=1) → dict#

Return a lightweight dependency tree for this boolean functor.

get_hash_int() → int#

Return the C++ entity hash used for stable identity.

name#

Get the functor name.

Returns:

str: Name of the functor.

num_of_variables#

Get the number of variables in this functor.

Returns:

int: Number of variables.

on_state_changed()#
on_value_changed()#
parameters#

Get the list of parameters used in this functor.

Returns:

list: List of parameter_obj instances.

settings#

Get settings exposed by this boolean functor.

unbind_python_object()#
variables#

Get the list of variable names used in this functor.

Returns:

list: List of variable_obj instances representing the variables.

class escape.core.entities.constraint_obj#

A parameter object that represents a boolean value.

This class wraps a C++ constraint_t object and provides a Python interface for boolean parameters. It is used specifically with conditional parameters to represent True/False conditions.

The object holds a pointer to the underlying C++ constraint_t instance that handles the actual implementation.

compliance#

Check if the parameter constraint is compliant.

Returns:

bool: True if constraint is compliant, False otherwise

dependency_children() → list#

Return direct dependency children for this constraint.

dependency_tree(depth=1) → dict#

Return a lightweight dependency tree for this constraint.

get_hash_int() → int#

Return the C++ entity hash used for stable identity.

id#

Get the unique identifier of this parameter.

Returns:

int: The parameter’s ID

name#

Get the name of the parameter.

Returns:

str: The parameter’s name

parameters#

Get the list of dependent parameters.

Returns:

list[parameter_obj]: List of parameter objects this depends on

settings#

Get the list of settings exposed by this constraint.

value#

Get the current boolean value.

Returns:

bool: The current True/False value

violation#

Check if the parameter constraint is violated.

Returns:

bool: True if constraint is violated, False otherwise

class escape.core.entities.parameter_obj#

Wrapper for dependent or independent parameters.

This class wraps C++ parameter objects and provides a Python interface for parameter manipulation. Parameters can be either independent (directly settable values) or dependent (calculated from other parameters).

static convert(val: float | int | str | parameter_obj, name: str = '', **kwargs) → parameter_obj#

Convert a value to a parameter object.

Parameters can be defined by formula, for example: >>> par = esc.par(value=”3.0+-1.0nm”) # Value with error >>> par = esc.par(value=”3.0nm”) # Value with units >>> par = esc.par(value=”1<=3.0<=4 nm”) # Value with bounds and units

Args:

val: Value to convert (float, parameter_obj or str) name: Optional name for the parameter **kwargs: Additional arguments for independent parameters

Returns:

parameter_obj: New parameter object

Raises:

TypeError: If val has invalid type

dependency_children() → list#

Return direct dependency children for this parameter.

dependency_tree(depth=1) → dict#

Return a lightweight dependency tree for this parameter.

dispatch_value_changed() → None#

Dispatch the parameter value-changed event after a silent update.

error#

Parameter error after optimization.

Returns:

float: The error value

fixed#

Whether the parameter is fixed during optimization.

Fixed parameters are recognized and shown by optimizer but their value is fixed during fitting.

Returns:

bool: True if parameter is fixed

force_value(val: float) → bool#

Set parameter value and new boundaries.

Sets value and adjusts boundaries relative to this value. Can only be used with independent parameters.

Args:

val: New value to set

Returns:

bool: True if successful

Raises:

RuntimeError: If parameter is dependent

get_hash_int() → int#

Return the C++ entity hash used for stable identity.

get_unscaled_boundaries() → list[float]#

Get unscaled parameter boundaries.

Returns:

list[float]: [min, max] list of boundary values

get_unscaled_value() → float#

Get unscaled parameter value.

Returns:

float: The unscaled value

id#

The parameter’s unique identifier.

Returns:

int: The parameter ID

independent#

Whether the parameter is independent.

Returns:

bool: True if parameter is independent

max#

Maximum value boundary.

Returns:

float: The maximum allowed value

min#

Minimum value boundary.

Returns:

float: The minimum allowed value

name#

The parameter’s name.

Returns:

str: The parameter name

parameters#

Get dependent parameters.

Returns:

list[parameter_obj]: List of parameters this depends on

reset(other: parameter_obj) → None#

Rebind this parameter handle to share other’s implementation.

After reset, both wrappers refer to the same underlying parameter (same value, bounds, and get_hash_int() identity).

scale#

Parameter value scale.

Returns:

float: The scale value

set_boundaries(minval: float, maxval: float) → None#

Set parameter value boundaries.

Can only be set for independent parameters.

Args:

minval: Minimum allowed value maxval: Maximum allowed value

Raises:

RuntimeError: If parameter is dependent

set_value(val: float, forced: bool = False, silent: bool = False) → bool#

Set an independent parameter value with optional force/silent flags.

settings#

Get settings exposed by this parameter.

shake(seed: int = -1) → None#

Randomly perturb the parameter value.

Args:

seed: Random seed to use, or -1 for random

trained#

Whether the parameter is used by neural network regressor.

Returns:

bool: True if parameter is trained

units#

The parameter’s units.

Returns:

str: The units string

value#

The parameter’s current value.

Returns:

float: The parameter value

weight#

Parameter weight used in optimization.

Returns:

float: The parameter’s weight value