Parameters¶
PsyNeuLink parameters
are objects that represent the user-modifiable parameters of a Component.
Parameter
s have names, default values, and other attributes that define how they are used in Compositions.
Parameter
s also maintain and provide access to the data used in actual computations - default values, current values, previous values
, and
logged values.
Defaults¶
The Defaults class is used to represent the default values for a Component's parameters. Parameters have two types of defaults: instance defaults and class defaults. Class defaults belong to a PsyNeuLink class, and suggest valid types and shapes of Parameter values. Instance defaults belong to an instance of a PsyNeuLink class, and are used to validate compatibility between this instance and other PsyNeuLink objects. For example, given a TransferMechanism t:
instance defaults are accessible by
t.defaults
(e.g., for thenoise
parameter,t.defaults.noise.defaults.noise
)class defaults are accessible by
t.class_defaults
orTransferMechanism.defaults
(e.g.,t.class_defaults.noise
orTransferMechanism.defaults.noise
)
Note
t.defaults.noise
is shorthand for t.parameters.noise.default_value
, and they both refer to the default
noise
value for t
Default values are sometimes also used when the parameters value has not been specified; for example, a Component’s
defaults.variable
is used as the input to a Mechanism if its execute
method is called
without any input specified, and similarly it is used for the INPUT
Nodes of
a Composition which are not specified in the inputs argument of its run
method.
Statefulness of Parameters¶
Parameters can have different values in different execution contexts in order to ensure correctness of and allow access to simulation calculations. As a result, to inspect and use the values of a parameter, in general you need to know the execution context in which you are interested. Much of the time, this execution context is likely to be a Composition::
>>> import psyneulink as pnl
>>> c = pnl.Composition()
>>> d = pnl.Composition()
>>> t = pnl.TransferMechanism()
>>> c.add_node(t)
>>> d.add_node(t)
>>> c.run({t: 5})
[[array([5.])]]
>>> print(t.value)
[[5.]]
>>> d.run({t: 10})
[[array([10.])]]
>>> print(t.value)
[[10.]]
>>> print(t.parameters.value.get(c))
[[5.]]
>>> print(t.parameters.value.get(d))
[[10.]]
The TransferMechanism in the above snippet has a different value
for each Composition it is run in.
This holds true for all of its stateful Parameters, so they can behave differently in
different execution contexts and can be modified by modulated Modulation.
Note
The “dot notation” version - t.value
- refers to the most recent execution context in which t was executed. In
many cases, you can use this to get or set using the execution context you’d expect. However, in complex situations,
or if there is any doubt, it is best to explicitly specify the execution context using the parameter’s set
method (for a more complete descritpion of the differences between dot notation and the set
method, see Parameters.
Developers must keep in mind state when writing new Components for PsyNeuLink. Any parameters or values that may
change during a run
must become stateful Parameters, or they are at risk of computational
errors like those encountered in parallel programming.
Creating Parameters¶
To create new Parameters, reference this example of a new class B
class B(A):
class Parameters(A.Parameters):
p = 1.0
q = Parameter()
def __init__(p=None, q=1.0):
super(p=p, q=q)
create an inner class Parameters on the Component, inheriting from the parent Component’s Parameters class
an instance of B.Parameters will be assigned to the parameters attribute of the class B and all instances of B
- each attribute on B.Parameters becomes a parameter (instance of the Parameter class)
as with p, specifying only a value uses default values for the attributes of the Parameter
as with q, specifying an explicit instance of the Parameter class allows you to modify the Parameter attributes
default values for the parameters can be specified in the Parameters class body, or in the arguments for B.__init__. If both are specified and the values differ, an exception will be raised
- if you want assignments to parameter p to be validated, add a method _validate_p(value), that returns None if value is a valid assignment, or an error string if value is not a valid assignment
NOTE: a validation method for p may reference other parameters only if they are listed in p’s
dependencies
- if you want all values set to p to be parsed beforehand, add a method _parse_p(value) that returns the parsed value
for example, convert to a numpy array or float
def _parse_p(value): return np.asarray(value)
NOTE: parsers may not reference other parameters
setters and getters (used for more advanced behavior than parsing) should both return the final value to return (getter) or set (setter)
For example,
costs
of ControlMechanism has a special getter method, which computes the cost on-the-fly:def _modulatory_mechanism_costs_getter(owning_component=None, context=None): try: return [c.compute_costs(c.parameters.variable._get(context), context=context) for c in owning_component.control_signals] except TypeError: return None
and
matrix
of RecurrentTransferMechanism has a special setter method, which updates itsauto
andhetero
parameter values accordinglydef _recurrent_transfer_mechanism_matrix_setter(value, owning_component=None, context=None): try: value = get_matrix(value, owning_component.input_shapes[0], owning_component.input_shapes[0]) except AttributeError: pass if value is not None: temp_matrix = value.copy() owning_component.parameters.auto._set(np.diag(temp_matrix).copy(), context) np.fill_diagonal(temp_matrix, 0) owning_component.parameters.hetero._set(temp_matrix, context) return value
Note
The specification of Parameters is intended to mirror the PNL class hierarchy. So, it is only necessary for each new class to declare Parameters that are new, or whose specification has changed from their parent’s. Parameters not present in a given class can be inherited from parents, but will be overridden if necessary, without affecting the parents.
Special Parameter Classes¶
FunctionParameter
andSharedParameter
are used to provide simpler access to some parameters of auxiliary components. They can be passed into the constructor of the owner, and then automatically passed when constructing the auxiliary component. Thevalues
ofSharedParameter
s are shared via getter and with those of their targetParameter
.
SharedParameter
s should only be used when there is a guarantee that their target will exist, given a specific Component. For example, it is acceptable thatTransferMechanism.integration_rate
is aFunctionParameter
for therate
parameter of itsintegrator_function
, because all TransferMechanisms have an integrator function, and all integrator functions have arate
parameter. It is also acceptable thatControlSignal.intensity_cost_function
is aFunctionParameter
corresponding to its function’s intensity_cost_fct parameter, because a ControlSignal’s function is always aTransferWithCosts
and is not user-specifiable.
_user_specified¶
Currently, default argument values for __init__ methods of Components are all None to allow distinguishing between a default value a user actually passed in during construction and a default automatically assigned. Consider
pnl.TransferMechanism(noise=[[0, 0]])
pnl.TransferMechanism(default_variable=[[0]], noise=[[0, 0]])
In case 1, the default variable is not specified by the user, and is
flexible
as a result. Since noise indicates a shape,[[0, 0]]
is implicitly assigned as the Mechanism’s default variable. This is intended as a convenience specification. In case 2, the variable and noise are incompatible, and an error is raised.
Using Parameters¶
Methods that are called during runtime in general must take context as an argument and must pass this context along to other
PNL methods. The most likely place this will come up would be for the function method on a PNL Function class, or _execute method on other
Components. Any getting and setting of stateful parameter values must use this context, and using standard attributes to store data
must be avoided at risk of causing computation errors. You may use standard attributes only when their values will never change during a
Run
.
You should avoid using dot notation in internal code, as it is ambiguous and can potentially break statefulness.
Parameter
attributes:
Attribute Name |
Default value |
Description |
Dev notes |
default_value |
None |
the default value of the Parameter |
|
name |
None |
the name of the Parameter |
|
stateful |
True |
whether the parameter has different values based on execution context |
|
modulable |
False |
if True, the parameter can be modulated (if it belongs to a Mechanism or Projection
|
Currently this does not determine what gets a ParameterPort, but in the future it should |
read_only |
False |
whether the user should be able to set the value or not (e.g. variable and value are just for informational purposes). |
Can be manually set, but will trigger a warning unless override=True |
aliases |
None |
other names by which the parameter goes (e.g. allocation is the same as variable for ControlSignal). |
specify as a list of strings |
user |
True |
whether the parameter is something the user will care about (e.g. NOT context) |
|
values |
None |
stores the parameter’s values under different execution contexts |
|
getter |
None |
hook that allows overriding the retrieval of values based on a supplied method (e.g. _output_port_variable_getter) |
kwargs self, owning_component, and context will be passed in if your method uses them. modulated=True will be passed in when modulated values are requested. self: the Parameter calling the setter owning_component: the Component to which
Getters must return the resulting value |
setter |
None |
hook that allows overriding the setting of values based on a supplied method (e.g. _recurrent_transfer_mechanism_matrix_setter) |
should take a positional argument; kwargs self, owning_component, and context will be passed in if your method uses them. self - the Parameter calling the setter; owning_component - the Component to which the Parameter belongs; context - the context the setter is called with; should return the value to be set |
loggable |
True |
whether the parameter can be logged |
|
log |
None |
stores the log of the parameter if applicable |
|
log_condition |
the |
||
history |
None |
stores the history of the parameter (previous values) |
|
history_max_length |
1 |
the maximum length of the stored history |
|
fallback_default |
False |
if False, the Parameter will return None if a requested value is not present for a given execution context; if True, the Parameter’s default_value will be returned instead |
Class Reference¶
- class psyneulink.core.globals.parameters.Defaults(owner, **kwargs)¶
A class to simplify display and management of default values associated with the
Parameter
s in aParameters
class.With an instance of the Defaults class, defaults, defaults.<param_name> may be used to get or set the default value of the associated
Parameters
object- owner¶
the
Parameters
object associated with this object
- class psyneulink.core.globals.parameters.Parameter(default_value=None, name=None, stateful=True, modulable=False, structural=False, modulation_combination_function=None, read_only=False, function_arg=True, pnl_internal=False, aliases=None, user=True, values=None, getter=None, setter=None, loggable=True, log=None, log_condition=LogCondition.OFF, delivery_condition=LogCondition.OFF, history=None, history_max_length=1, history_min_length=0, fallback_default=False, retain_old_simulation_data=False, constructor_argument=None, spec=None, parse_spec=False, valid_types=None, reference=False, dependencies=None, initializer=None, port=None, mdf_name=None, specify_none=False, _owner=None, _inherited=False, _inherited_source=None, _user_specified=False, _scalar_converted=False, _tracking_compiled_struct=False, **kwargs)¶
- default_value¶
the default value of the Parameter.
- Default
None
- name¶
the name of the Parameter.
- Default
None
- stateful¶
whether the parameter has different values based on execution context.
- Default
True
- modulable¶
if True, the parameter can be modulated; if the Parameter belongs to a Mechanism or Projection, it is assigned a ParameterPort.
- Default
False
- Developer Notes
Currently this does not determine what gets a ParameterPort, but in the future it should
- modulation_combination_function¶
specifies the function used in Port._get_combined_mod_val() to combine values for the parameter if it receives more than one ModulatoryProjections; must be either the keyword MULTIPLICATIVE, PRODUCT, ADDITIVE, SUM, or a function that accepts an n dimensional array and retursn an n-1 dimensional array. If it is None, the an attempt is made to determine it from the an alias for the Parameter’s name (i.e., if that is MULTIPLICATIVE_PARAM or ADDITIVE_PARAM); otherwise the default behavior is determined by Port._get_combined_mod_val().
- Default
None
- read_only¶
whether the user should be able to set the value or not (e.g. variable and value are just for informational purposes).
- Default
False
- Developer Notes
Can be manually set, but will trigger a warning unless override=True
- function_arg¶
TBD
- Default
False
- pnl_internal¶
whether the parameter is an idiosyncrasy of PsyNeuLink or it is more intrinsic to the conceptual operation of the Component on which it resides
- Default
False
- aliases¶
other names by which the parameter goes (e.g. allocation is the same as variable for ControlSignal).
- Type
list
- Default
None
- Developer Notes
specify as a list of strings
- user¶
whether the parameter is something the user will care about (e.g. NOT context).
- Default
True
- values¶
stores the parameter’s values under different execution contexts.
- Type
dict{execution_id: value}
- Default
None
- getter¶
hook that allows overriding the retrieval of values based on a supplied method (e.g. _output_port_variable_getter).
- Type
types.FunctionType
- Default
None
- Developer Notes
kwargs self, owning_component, and context will be passed in if your method uses them. self - the Parameter calling the setter; owning_component - the Component to which the Parameter belongs; context - the context the setter is called with; should return the value
- setter¶
hook that allows overriding the setting of values based on a supplied method (e.g. _recurrent_transfer_mechanism_matrix_setter).
- Type
types.FunctionType
- Default
None
- Developer Notes
should take a positional argument; kwargs self, owning_component, and context will be passed in if your method uses them. self - the Parameter calling the setter; owning_component - the Component to which the Parameter belongs; context - the context the setter is called with; should return the value to be set
- loggable¶
whether the parameter can be logged.
- Default
True
- log¶
stores the log of the parameter if applicable.
- Type
dict{execution_id: deque([LogEntry])}
- Default
None
- log_condition¶
the LogCondition for which the parameter should be logged.
- Type
- Default
- delivery_condition¶
the LogCondition for which the parameter shoud be delivered.
- Type
- Default
- history¶
stores the history of the parameter (previous values). Also see
get_previous
.- Type
dict{execution_id: deque([LogEntry])}
- Default
None
- history_max_length¶
the maximum length of the stored history.
- Default
1
- history_min_length¶
the minimum length of the stored history. generally this does not need to be overridden, but is used to indicate if parameter history is necessary to computation.
- Default
0
- fallback_default¶
if False, the Parameter will return None if a requested value is not present for a given execution context; if True, the Parameter’s default_value will be returned instead.
- Default
False
- retain_old_simulation_data¶
if False, the Parameter signals to other PNL objects that any values generated during simulations may be deleted after they are no longer needed for computation; if True, the values should be saved for later inspection.
- Default
False
- constructor_argument¶
if not None, this indicates the argument in the owning Component’s constructor that this Parameter corresponds to.
- Default
None
- valid_types¶
if not None, this contains a tuple of
type
s that are acceptable for values of this Parameter- Default
None
- reference¶
if False, the Parameter is not used in computation for its owning Component. Instead, it is just meant to store a value that may be used to initialize other Components
- Default
False
- Developer Notes
Parameters with Function values marked as
reference will not be automatically instantiated in _instantiate_parameter_classes or validated for variable shape
- dependencies¶
if not None, this contains a set of Parameter names corresponding to Parameters whose values must be instantiated before that of this Parameter
- Default
None
- initializer¶
the name of another Parameter that serves as this Parameter’s
initializer
- Default
None
- port¶
stores a reference to the ParameterPort that modulates this Parameter, if applicable
- Default
None
- specify_none¶
if True, a user-specified value of None for this Parameter will set the _user_specified flag to True
- Default
False
- reset()¶
Resets default_value to the value specified in its Parameters class declaration, or inherits from parent Parameters classes if it is not explicitly specified.
- get(context=None, **kwargs)¶
Gets the value of this
Parameter
in the context of context If no context is specified, attributes on the associated Component will be used- Parameters
context (Context, execution_id, Composition) – the context for which the value is stored; if a Composition, uses context.default_execution_id
kwargs – any additional arguments to be passed to this
Parameter
’sgetter
if it exists
- get_previous(context=None, index=1, range_start=None, range_end=None)¶
Gets the value set before the current value of this
Parameter
in the context of context. To return a range of values, userange_start
andrange_end
. Range takes precedence over Welcome to PsyNeuLink . All history values can be accessed directly as a list inParameter.history
.- Parameters
context – Context, execution_id, Composition the context for which the value is stored; if a Composition, uses context.default_execution_id
index (
int
) – how far back to look into the history. An index of 1 means the value this Parameter had just before its current value. An index of 2 means the value before thatrange_start (
int
) – Inclusive. The index of the oldest history value to return. IfNone
, the range begins at the oldest value stored in historyrange_end (
int
) – Inclusive. The index of the newest history value to return. IfNone
, the range ends at the newest value stored in history (does not include current value inParameter.values
)
- Returns
the stored value or list of values in Parameter history
- get_delta(context=None)¶
Gets the difference between the current value and previous value of
Parameter
in the context of context- Parameters
context (Context, execution_id, Composition) – the context for which the value is stored; if a Composition, uses context.default_execution_id
- set(value, context=None, override=False, skip_history=False, skip_log=False, **kwargs)¶
Sets the value of this
Parameter
in the context of context If no context is specified, attributes on the associated Component will be used- Parameters
context (Context, execution_id, Composition) – the context for which the value is stored; if a Composition, uses context.default_execution_id
override (False) – if True, ignores a warning when attempting to set a read-only Parameter
skip_history (False) – if True, does not modify the Parameter’s history
skip_log (False) – if True, does not modify the Parameter’s log
kwargs – any additional arguments to be passed to this
Parameter
’ssetter
if it exists
- clear_log(contexts=NotImplemented)¶
Clears the log of this Parameter for every context in contexts
- clear_history(contexts=NotImplemented)¶
Clears the history of this Parameter for every context in
contexts
- _set_default_value(value, directly=False, check_scalar=False)¶
Set default_value
- Parameters
value – new default_value
directly (bool, optional) – if False, passes value through parse and validation steps. Defaults to False.
check_scalar (bool, optional) – if True, sets _scalar_converted attribute as appropriate for value. Defaults to False.
- class psyneulink.core.globals.parameters.ParameterAlias(source=None, name=None)¶
A counterpart to
Parameter
that represents a pseudo-Parameter alias that refers to anotherParameter
, but has a different name
- exception psyneulink.core.globals.parameters.ParameterError¶
- class psyneulink.core.globals.parameters.ParametersBase(owner, parent=None)¶
Base class for inner Parameters classes on Components (see
Component.Parameters
for example)- _get_parse_method(parameter)¶
- Returns
the parsing method for the parameter or for any Parameter attribute (ex: ‘modulable’) if it exists, or None if it does not
- _get_validate_method(parameter)¶
- Returns
the validation method for the parameter or for any Parameter attribute (ex: ‘modulable’) if it exists, or None if it does not
- psyneulink.core.globals.parameters.parse_context(context)¶
- Parameters
context – An execution context (context, Composition)
- Returns
the context associated with context
- class psyneulink.core.globals.parameters.FunctionParameter(default_value=None, function_parameter_name=None, function_name='function', primary=True, **kwargs)¶
A special (and most common) case
SharedParameter
that references a Parameter on one of the Component’s functions.- function_parameter_name¶
the name of the target Parameter on the owning Component’s
function_name
Parameter- Type
str
- Default
- function_name¶
the name of the owning Component’s Parameter on which
function_parameter_name
is the target Parameter of this object- Type
str
- Default
‘function’
A Parameter that is not a “true” Parameter of a Component but a reference to a Parameter on one of the Component’s attributes or other Parameters.
Values
are shared via getter and setter. Mainly used for more user-friendly access to certain Parameters, as a sort of cross-object alias.See above for when it is appropriate to use a SharedParameter
the name of the target Parameter on the owning Component’s
attribute_name
Parameter or attribute- Type
str
- Default
the name of the owning Component’s Parameter or attribute on which
shared_parameter_name
is the target Parameter of this object- Type
str
- Default
‘function’
whether the default value specified in the SharedParameter should take precedence over the default value specified in its target
- Type
bool
- Default
False
- Type
types.FunctionType
- Default
a function that returns the value of the shared_parameter_name parameter of the attribute_name Parameter/attribute of this Parameter’s owning Component
- Type
types.FunctionType
- Default
a function that sets the value of the shared_parameter_name parameter of the attribute_name Parameter/attribute of this Parameter’s owning Component and returns the set value
Gets the value set before the current value of this
Parameter
in the context of context. To return a range of values, userange_start
andrange_end
. Range takes precedence over Welcome to PsyNeuLink . All history values can be accessed directly as a list inParameter.history
.- Parameters
context – Context, execution_id, Composition the context for which the value is stored; if a Composition, uses context.default_execution_id
index (
int
) – how far back to look into the history. An index of 1 means the value this Parameter had just before its current value. An index of 2 means the value before thatrange_start (
int
) – Inclusive. The index of the oldest history value to return. IfNone
, the range begins at the oldest value stored in historyrange_end (
int
) – Inclusive. The index of the newest history value to return. IfNone
, the range ends at the newest value stored in history (does not include current value inParameter.values
)
- Returns
the stored value or list of values in Parameter history
Gets the difference between the current value and previous value of
Parameter
in the context of context- Parameters
context (Context, execution_id, Composition) – the context for which the value is stored; if a Composition, uses context.default_execution_id