Mechanism¶
Contents¶
Overview¶
A Mechanism takes an input, transforms it in some way, and makes the result available as its output. There are two types of Mechanisms in PsyNeuLink:
ProcessingMechanisms aggregate the input they receive from other Mechanisms, and/or the input to the Composition to which they belong, transform it in some way, and provide the result as input to other Mechanisms in the Composition, or as the output for the Composition itself. There are a variety of different types of ProcessingMechanism, that accept various forms of input and transform them in different ways (see ProcessingMechanisms for a list).
to modulate the parameters of other Mechanisms or Projections. There are three basic ModulatoryMechanisms:
LearningMechanism - these receive training (target) values, and compare them with the output of a Mechanism to generate LearningSignals that are used to modify MappingProjections (see
learning
).ControlMechanism - these evaluate the output of a specified set of Mechanisms, and generate ControlSignals used to modify the parameters of those or other Mechanisms.
GatingMechanism - these use their input(s) to determine whether and how to modify the
value
of the InputPort(s) and/or OutputPort(s) of other Mechanisms.Each type of ModulatoryMechanism is associated with a corresponding type of ModulatorySignal (a type of OutputPort specialized for use with the ModulatoryMechanism) and ModulatoryProjection.
Every Mechanism is made up of four fundamental components:
InputPort(s) used to receive and represent its input(s);
Function used to transform its input(s) into its output(s);
ParameterPort(s) used to represent the parameters of its Function (and/or any parameters that are specific to the Mechanism itself);
OutputPort(s) used to represent its output(s)
These are described in the sections on Function and Ports (InputPorts, ParameterPorts and Parameters, and OutputPorts), and shown graphically in a figure, under Structure below.
Creating a Mechanism¶
Mechanisms are created by calling the constructor for a particular type. PsyNeuLink also automatically creates one or more Mechanisms under some circumstances. For example, a ComparatorMechanism and LearningMechanism are created automatically when learning is specified for a Composition; and an ObjectiveMechanism may be created when a ControlMechanism is created.
Specifying Ports¶
Every Mechanism has one or more InputPorts, ParameterPorts, and OutputPorts (described below) that allow it to receive and send Projections,
and to execute its function
). When a Mechanism is created, it automatically creates the
ParameterPorts it needs to represent its parameters, including those of its function
.
It also creates any InputPorts and OutputPorts required for the Projections it has been assigned. InputPorts and
OutputPorts, and corresponding Projections (including those from ModulatorySignals) can also be
specified explicitly in the input_ports and output_ports arguments of the Mechanism’s constructor (see
InputPorts and OutputPorts, respectively, as well as the first example
below, and Examples). They can also be specified in a parameter specification dictionary assigned to the Mechanism’s params argument, using entries with the keys
INPUT_PORTS and OUTPUT_PORTS, respectively (see second example below). While
specifying the input_ports and output_ports arguments directly is simpler and more convenient,
the dictionary format allows parameter sets to be created elsewhere and/or re-used. The value of each entry can be
any of the allowable forms for specifying a port. InputPorts and OutputPorts can also be
added to an existing Mechanism using its add_ports
method, although this is generally
not needed and can have consequences that must be considered (e.g., see note),
and therefore is not recommended.
Note
When Ports are specified in the input_ports or output_ports arguments of a Mechanism’s constructor, they replace any default Ports generated by the Mechanism when it is created (if no Ports were specified). This is particularly relevant for OutputPorts, as most Mechanisms create one or more Standard OutputPorts by default, that have useful properties. To retain those Ports if any are specified in the output_ports argument, they must be included along with those ports in the output_ports argument (see examples). The same is true for default InputPorts and the input_ports argument.
This behavior differs from adding a Port once the Mechanism is created. Ports added to Mechanism using the Mechanism’s
add_ports
method, or by assigning the Mechanism in the owner argument of the Port’s constructor, are added to the Mechanism without replacing any of its existing Ports, including any default Ports that may have been generated when the Mechanism was created (see examples in Port).
Examples
The following example creates an instance of a TransferMechanism that names the default InputPort MY_INPUT
,
and assigns three Standard OutputPorts:
>>> import psyneulink as pnl
>>> my_mech = pnl.TransferMechanism(input_ports=['MY_INPUT'],
... output_ports=[pnl.RESULT, pnl.MEAN, pnl.VARIANCE])
This shows how the same Mechanism can be specified using a dictionary assigned to the params argument:
>>> my_mech = pnl.TransferMechanism(params={pnl.INPUT_PORTS: ['MY_INPUT'],
... pnl.OUTPUT_PORTS: [pnl.RESULT, pnl.MEAN, pnl.VARIANCE]})
See Port for additional examples of specifying the Ports of a Mechanism.
Specifying Parameters¶
As described below, Mechanisms have ParameterPorts that provide the
current value of a parameter used by the Mechanism and/or its function
when it is executed. These can also be used by a ControlMechanism to control the parameters of
the Mechanism and/or it function
. The value of any of these, and their control, can be
specified in the corresponding argument of the constructor for the Mechanism and/or its function
, or in a parameter specification dictionary assigned to the params argument of its
constructor, as described under Specifying Parameters.
Structure¶
Function¶
The core of every Mechanism is its function, which transforms its input to generate its output. The function is
specified by the Mechanism’s function
attribute. Every type of Mechanism has at least one
(primary) function, and some have additional (auxiliary) ones (for example, TransferMechanism and
EVCControlMechanism). Mechanism functions are generally from the PsyNeuLink Function class. Most Mechanisms
allow their function to be specified, using the function
argument of the Mechanism’s constructor. The function can
be specified using the name of Function class, or its constructor (including arguments that specify its
parameters). For example, the function
of a TransferMechanism, which is Linear
by
default, can be specified to be the Logistic
function as follows:
>>> my_mechanism = pnl.TransferMechanism(function=pnl.Logistic(gain=1.0, bias=-4))
Notice that the parameters of the function
(in this case, gain
and bias
) can be specified by including
them in its constructor. Some Mechanisms support only a single function. In that case, the function
argument is not available in the Mechanism’s constructor, but it does include arguments for the function’s
parameters. For example, the function
of a ComparatorMechanism is always the LinearCombination
function,
so the Mechanisms’ constructor does not have a function
argument. However, it does have a
comparison_operation argument, that is used to set the LinearCombination function’s operation
parameter.
The parameters for a Mechanism’s primary function can also be specified as entries in a FUNCTION_PARAMS entry of a
parameter specification dictionary in the params argument of the Mechanism’s
constructor. For example, the parameters of the Logistic
function in the example above can
also be assigned as follows:
>>> my_mechanism = pnl.TransferMechanism(function=pnl.Logistic,
... params={pnl.FUNCTION_PARAMS: {pnl.GAIN: 1.0, pnl.BIAS: -4.0}})
Again, while not as simple as specifying these as arguments in the function’s constructor, this format is more flexible. Any values specified in the parameter dictionary will override any specified within the constructor for the function itself (see DDM for an example).
Note
It is important to recognize the distinction between a Function and its function
attribute (note the difference in capitalization). A Function is a PsyNeuLink Component, that can be created using a constructor; a function is an attribute that contains a callable method
belonging to a Function, and that is executed when the Component to which the Function belongs is executed.
Functions are used to assign, store, and apply parameter values associated with their function (see Function for a more detailed explanation).
The parameters of a Mechanism’s function
are attributes of its function
, and can be accessed using standard “dot” notation for that object. For
example, the gain
and bias
parameters of the Logistic
function in the example
above can be access as my_mechanism.function.gain
and my_mechanism.function.bias
. They are
also assigned to a dictionary in the Mechanism’s function_params
attribute,
and can be accessed using the parameter’s name as the key for its entry in the dictionary. For example,
the parameters in the example above could also be accessed as my_mechanism.function_params[GAIN]
and
my_mechanism.function_params[GAIN]
Some Mechanisms have auxiliary functions that are inherent (i.e., not made available as arguments in the Mechanism’s
constructor; e.g., the integrator_function
of a TransferMechanism);
however, the Mechanism may include parameters for those functions in its constructor (e.g., the noise argument in
the constructor for a TransferMechanism is used as the noise
parameter of the
AdaptiveIntegrator
assigned to the TransferMechanism’s integrator_function
).
Custom Functions¶
A Mechanism’s function
can be customized by assigning a user-defined function (e.g.,
a lambda function), so long as it takes arguments and returns values that are compatible with those of the
Mechanism’s defaults for that function. This is also true for auxiliary functions that appear as arguments in a
Mechanism’s constructor (e.g., the EVCControlMechanism). A user-defined function can be assigned
directly to the corresponding attribute of the Mechanism
(for its primary function, its function
attribute). When a user-defined function is
specified, it is automatically converted to a UserDefinedFunction.
Note
It is strongly advised that auxiliary functions that are inherent to a Mechanism
(i.e., ones that do not appear as an argument in the Mechanism’s constructor,
such as the integrator_function
of a
TransferMechanism) not be assigned custom functions; this is because their
parameters are included as arguments in the constructor for the Mechanism,
and thus changing the function could produce confusing and/or unpredictable effects.
variable
and value
attributes¶
The input to a Mechanism’s function
is provided by the Mechanism’s variable
attribute. This is an ndarray that is at least 2d, with one item of its outermost
dimension (axis 0) for each of the Mechanism’s input_ports
(see
below). The result of the function
is placed in the
Mechanism’s value
attribute which is also at least a 2d array. The Mechanism’s value
is referenced by its OutputPorts to generate their own value
attributes, each of which is assigned as the value of an item of the list in the Mechanism’s
output_values
attribute (see OutputPorts below), which is the value
returned by a call to the Mechanism’s execute
method.
Note
The input to a Mechanism is not necessarily the same as the input to its function
. The
input to a Mechanism is first processed by its InputPort(s), and then assigned to the
Mechanism’s variable
attribute, which is used as the input to its function
. Similarly, the result of a Mechanism’s function is not necessarily the same as the
Mechanism’s output. The result of the function
is assigned to the Mechanism’s value
attribute, which is then used by its OutputPort(s) to assign
items to its output_values
attribute.
Ports¶
Every Mechanism has one or more of each of three types of Ports: InputPort(s),
ParameterPort(s), and OutputPort(s). Generally, these are created automatically
when the Mechanism is created. InputPorts and OutputPorts (but not ParameterPorts) can also be specified explicitly
for a Mechanism, or added to an existing Mechanism using its add_ports
method, as
described above).
The three types of Ports are shown schematically in the figure below, and described briefly in the following sections.
InputPorts¶
These receive, potentially combine, and represent the input to a Mechanism, and provide this to the Mechanism’s
function
. Usually, a Mechanism has only one (primary) InputPort,
identified in its input_port
attribute. However some Mechanisms have more than one
InputPort. For example, a ComparatorMechanism has one InputPort for its SAMPLE and another for its TARGET
input. All of the Mechanism’s InputPorts (including its primary InputPort <InputPort_Primary>` are listed in its
input_ports
attribute (note the plural).
The input_ports
attribute is a ContentAddressableList
– a PsyNeuLink-defined subclass of the Python class UserList –
that allows a specific InputPort in the list to be accessed using its name as the index for the list
(e.g., my_mechanism['InputPort name']
).
The value
of each InputPort for a Mechanism is assigned to a different item of the Mechanism’s
variable
attribute (a 2d np.array), as well as to a corresponding item of its input_values
attribute (a list). The variable
provides the input to the
Mechanism’s function
, while its input_values
provides a
convenient way of accessing the value of its individual items. Because there is a one-to-one correspondence between
a Mechanism’s InputPorts and the items of its variable
, their size along their outermost
dimension (axis 0) must be equal; that is, the number of items in the Mechanism’s variable
attribute must equal the number of InputPorts in its input_ports
attribute. A
Mechanism’s constructor does its best to insure this: if its default_variable and/or its input_shapes argument is
specified, it constructs a number of InputPorts (and each with a value
) corresponding to the
items specified for the Mechanism’s variable
, as in the examples below:
my_mech_A = pnl.TransferMechanism(default_variable=[[0],[0,0]])
print(my_mech_A.input_ports)
> [(InputPort InputPort-0), (InputPort InputPort-1)]
print(my_mech_A.input_ports[0].value)
> [ 0.]
print(my_mech_A.input_ports[1].value)
> [ 0. 0.]
my_mech_B = pnl.TransferMechanism(default_variable=[[0],[0],[0]])
print(my_mech_B.input_ports)
> [(InputPort InputPort-0), (InputPort InputPort-1), (InputPort InputPort-2)]
Conversely, if the input_ports argument is used to specify InputPorts for the Mechanism, they are used to format the Mechanism’s variable:
my_mech_C = pnl.TransferMechanism(input_ports=[[0,0], 'Hello'])
print(my_mech_C.input_ports)
> [(InputPort InputPort-0), (InputPort Hello)]
print(my_mech_C.variable)
> [array([0, 0]) array([0])]
If both the default_variable (or input_shapes) and input_ports arguments are specified, then the number and format of their respective items must be the same (see Port for additional examples of specifying Ports).
If InputPorts are added using the Mechanism’s add_ports
method, then its
variable
is extended to accommodate the number of InputPorts added (note that this must
be coordinated with the Mechanism’s function
, which takes the Mechanism’s variable
as its input (see note).
The order in which InputPorts are specified in the Mechanism’s constructor,
and/or added using its add_ports
method, determines the
order of the items to which they are assigned assigned in he Mechanism’s variable
,
and are listed in its input_ports
and input_values
attribute. Note that a Mechanism’s input_values
attribute has the same information as
the Mechanism’s variable
, but in the form of a list rather than an ndarray.
Specifying InputPorts and a Mechanism’s variable
Attribute
When a Mechanism is created, the number and format of the items in its variable
attribute, as well as the number of InputPorts it has and their variable
and value
attributes, are determined by one of the following arguments in the Mechanism’s constructor:
default_variable (at least 2d ndarray) – determines the number and format of the items of the Mechanism’s
variable
attribute. The number of items in its outermost dimension (axis 0) determines the number of InputPorts created for the Mechanism, and the format of each item determines the format for thevariable
andvalue
attributes of the corresponding InputPort. If any InputPorts are specified in the input_ports argument or an INPUT_PORTS entry of a specification dictionary assigned to the params argument of the Mechanism’s constructor, then the number must match the number of items in default_variable, or an error is generated. The format of the items in default_variable are used to specify the format of thevariable
orvalue
of the corresponding InputPorts for any that are not explicitly specified in the input_ports argument or INPUT_PORTS entry (see below).
input_shapes (int, list or ndarray) – specifies the number and length of items in the Mechanism’s variable, if default_variable is not specified. For example, the following mechanisms are equivalent:
T1 = TransferMechanism(input_shapes = [3, 2]) T2 = TransferMechanism(default_variable = [[0, 0, 0], [0, 0]])
The relationship to any specifications in the input_ports argument or INPUT_PORTS entry of a params dictionary is the same as for the default_variable argument, with the latter taking precedence (see above).
input_ports (list) – this can be used to explicitly specify the InputPorts created for the Mechanism. Each item must be an InputPort specification, and the number of items must match the number of items in the default_variable argument or input_shapes argument if either of those is specified. If the
variable
and/orvalue
is explicitly specified for an InputPort in the input_ports argument or INPUT_PORTS entry of a params dictionary, it must be compatible with the value of the corresponding item of default_variable; otherwise, the format of the item in default_variable corresponding to the InputPort is used to specify the format of the InputPort’svariable
(e.g., the InputPort is specified using an OutputPort to project to it;). If default_variable is not specified, a default value is specified by the Mechanism. InputPorts can also be specifed that shadow the inputs of other InputPorts and/or Mechanisms; that is, receive Projections from all of the samesenders
as those specified.
INPUT_PORTS entry of a params dict (list) – specifications are treated in the same manner as those in the input_ports argument, and take precedence over those.
Adding InputPorts
InputPorts can be added to a Mechanism using its add_ports
method; this extends its
variable
by a number of items equal to the number of InputPorts added, and each new item
is assigned a format compatible with the value
of the corresponding InputPort added; if the
InputPort’s variable
is not specified, it is assigned the default format for an item of the
owner’s variable
attribute. The InputPorts are appended to the end of the list in the
Mechanism’s input_ports
attribute. Adding in Ports in this manner does not
replace any existing Ports, including any default Ports generated when the Mechanism was constructed (this is
contrast to Ports specified in a Mechanism’s constructor which do replace any default Port(s) of the same type).
Note
Adding InputPorts to a Mechanism using its add_ports
method may introduce an
incompatibility with the Mechanism’s function
, which takes the Mechanism’s variable
as its input; such an incompatibility will generate an error. It may also influence
the number of OutputPorts created for the Mechanism. It is the user’s responsibility to ensure that the
assignment of InputPorts to a Mechanism using the add_ports
is coordinated with
the specification of its function
, so that the total number of InputPorts (listed
in the Mechanism’s input_ports
attribute matches the number of items expected
for the input to the function specified in the Mechanism’s function
attribute
(i.e., its length along axis 0).
Projections to InputPorts
Each InputPort of a Mechanism can receive one or more Projections from other Mechanisms. When a
Mechanism is created, a MappingProjection is created automatically for any OutputPorts or Projections from them that
are in its InputPort specification, using AUTO_ASSIGN_MATRIX
as the Projection’s matrix
specification. However, if a specification in the input_ports argument
or an INPUT_PORTS entry of a params dictionary cannot be resolved to an instantiated OutputPort at the time the
Mechanism is created, no MappingProjection is assigned to the InputPort, and this must be done by some other means;
any specifications in the Mechanism’s input_ports
attribute that are not
associated with an instantiated OutputPort at the time the Mechanism is executed are ignored.
The PathwayProjections (e.g., MappingProjections) it receives are listed
in its path_afferents
attribute. If the Mechanism is an ORIGIN
Mechanism of a
Composition, this includes a Projection from the Composition’s input_CIM
. Any
ControlProjections or GatingProjections it receives are listed in its
mod_afferents
attribute.
ParameterPorts and Parameters¶
ParameterPorts provide the value for each parameter of a Mechanism and its function
. One ParameterPort is assigned to each of the parameters of the Mechanism and/or its
function
(corresponding to the arguments in their constructors). The ParameterPort takes
the value specified for a parameter (see below) as its variable
, and uses it as the input to the ParameterPort’s function
,
which modulates it in response to any ControlProjections received
by the ParameterPort (specified in its mod_afferents
attribute), and assigns the
result to the ParameterPort’s value
. This is the value used by the Mechanism or its
function
when the Mechanism executes. Accordingly, when the value
of a parameter is accessed (e.g., using “dot” notation, such as my_mech.my_param
), it is actually the
ParameterPort’s value
that is returned (thereby accurately reflecting the value used
during the last execution of the Mechanism or its function
). The ParameterPorts for a
Mechanism are listed in its parameter_ports
attribute.
The “base” value of a parameter (i.e., the unmodulated value used as the ParameterPort’s variable
and the input to its function
) can specified when a Mechanism
and/or its function
are first created, using the corresponding arguments of their
constructors (see Function above). Parameter values can also be specified later, by direct assignment of a
value to the attribute for the parameter, or by using the Mechanism’s assign_param
method (the recommended means;
see Specifying Parameters). Note that the attributes for the parameters of a Mechanism’s function
usually belong to the Function referenced in its function
attribute, not the Mechanism itself, and therefore must be assigned to the Function
Component (see Function above).
OutputPorts¶
These represent the output(s) of a Mechanism. A Mechanism can have several OutputPorts, and each can
send Projections that transmit its value to other Mechanisms and/or as the output of the Composition to which
the Mechanism belongs. Every Mechanism has at least one OutputPort, referred to as its primary OutputPort. If OutputPorts are not explicitly specified for a Mechanism, a primary OutputPort is
automatically created and assigned to its output_port
attribute (note the singular),
and also to the first entry of the Mechanism’s output_ports
attribute (note the
plural). The value
of the primary OutputPort is assigned as the first (and often only) item
of the Mechanism’s value
attribute, which is the result of the Mechanism’s function
. Additional OutputPorts can be assigned to represent values corresponding to other items
of the Mechanism’s value
(if there are any) and/or values derived from any or all of those
items. Standard OutputPorts are available for each type of Mechanism, and custom ones can
be configured (see OutputPort Specification. These can be assigned in the
output_ports argument of the Mechanism’s constructor.
All of a Mechanism’s OutputPorts (including the primary one) are listed in its output_ports
attribute (note the plural). The output_ports
attribute is a ContentAddressableList – a PsyNeuLink-defined subclass of the Python class
UserList – that
allows a specific OutputPort in the list to be accessed using its name as the index for the list (e.g.,
my_mechanism['OutputPort name']
). This list can also be used to assign additional OutputPorts to the Mechanism
after it has been created.
The value
of each of the Mechanism’s OutputPorts is assigned as an item in the Mechanism’s
output_values
attribute, in the same order in which they are listed in its
output_ports
attribute. Note, that the output_values
attribute of a Mechanism is distinct from its value
attribute, which contains the full and
unmodified results of its function
(this is because OutputPorts can modify the item of
the Mechanism`s value
to which they refer – see OutputPorts).
Additional Attributes¶
Additional Constructor Arguments¶
In addition to the standard attributes of any Component, Mechanisms have a set of
Mechanism-specific attributes (listed below). These can be specified in arguments of the Mechanism’s constructor,
in a parameter specification dictionary assigned to the params argument of the
Mechanism’s constructor, by direct reference to the corresponding attribute of the Mechanisms after it has been
constructed (e.g., my_mechanism.param
). The Mechanism-specific
attributes are listed below by their argument names / keywords, along with a description of how they are specified:
input_ports / INPUT_PORTS - a list specifying the Mechanism’s input_ports (see InputPort Specification for details of specification).
input_labels / INPUT_LABEL_DICTS - a dict specifying labels that can be used as inputs (see Value Label Dictionaries for details of specification).
output_ports / OUTPUT_PORTS - specifies specialized OutputPorts required by a Mechanism subclass (see OutputPort Specification for details of specification).
output_labels / OUTPUT_LABEL_DICTS - a dict specifying labels that can be for reporting outputs (see Value Label Dictionaries for details of specification).
monitor_for_learning / MONITOR_FOR_LEARNING - specifies which of the Mechanism’s OutputPorts is used for learning (see Learning for details of specification).
Projection Convenience Properties¶
A Mechanism also has several convenience properties, listed below, that list its Projections and the Mechanisms that send/receive these:
projections
– all of the Projections sent or received by the Mechanism;
afferents
– all of the Projections received by the Mechanism;
path_afferents
– all of the PathwayProjections received by the Mechanism;
mod_afferents
– all of the ModulatoryProjections received by the Mechanism;
efferents
– all of the Projections sent by the Mechanism;
senders
– all of the Mechanisms that send a Projection to the Mechanism
modulators
– all of the ModulatoryMechanisms that send a ModulatoryProjection to the Mechanism
receivers
– all of the Mechanisms that receive a Projection from the Mechanism
Each of these is a ContentAddressableList
, which means that the names of the Components in each list can be listed by
appending .names
to the property. For examples, the names of all of the Mechanisms that receive a Projection from
my_mech
can be accessed by my_mech.receivers.names
.
Value Label Dictionaries¶
Overview
Mechanisms have two attributes that can be used to specify labels for the values of its InputPort(s) and OutputPort(s):
INPUT_LABELS_DICT – used to specify labels for values of the InputPort(s) of the Mechanism; if specified, the dictionary is contained in the Mechanism’s
input_labels_dict
attribute.OUTPUT_LABELS_DICT – used to specify labels for values of the OutputPort(s) of the Mechanism; if specified, the dictionary is contained in the Mechanism’s
output_labels_dict
attribute.
The labels specified in these dictionaries can be used to:
specify items in the inputs argument of the
run
method of a Composition, or thetargets
argument of itslearn
method.report the values of the InputPort(s) and OutputPort(s) of a Mechanism
visualize the inputs and outputs of the Composition’s Mechanisms
Specifying Label Dictionaries
Label dictionaries can only be specified in a parameters dictionary assigned to the params argument of the Mechanism’s constructor, using the keywords described above. A standard label dictionary contains key:value pairs of the following form:
<port name or index>:<sub-dictionary> – this is used to specify labels that are specific to individual Ports of the type corresponding to the dictionary;
key - either the name of a Port of that type, or its index in the list of Ports of that type (i.e,
input_ports
oroutput_ports
);value - a dictionary containing label:value entries to be used for that Port, where the label is a string and the shape of the value matches the shape of the
InputPort value
orOutputPort value
for which it is providing a label:value mapping.For example, if a Mechanism has two InputPorts, named SAMPLE and TARGET, then INPUT_LABELS_DICT could be assigned two entries, SAMPLE:<dict> and TARGET:<dict> or, correspondingly, 0:<dict> and 1:<dict>, in which each dictionary contains separate label:value entries for the SAMPLE and TARGET InputPorts.
>>> input_labels_dictionary = {pnl.SAMPLE: {"red": [0],
... "green": [1]},
... pnl.TARGET: {"red": [0],
... "green": [1]}}
In the following two cases, a shorthand notation is allowed:
a Mechanism has only one port of a particular type (only one InputPort or only one OutputPort)
only the index zero InputPort or index zero OutputPort needs labels
In these cases, a label dictionary for that type of port may simply contain the label:value entries described above. The label:value mapping will only apply to the index zero port of the port type for which this option is used. Any additional ports of that type will not have value labels. For example, if the input_labels_dictionary below were applied to a Mechanism with multiple InputPort, only the index zero InputPort would use the labels “red” and “green”.
>>> input_labels_dictionary = {"red": [0],
... "green": [1]}
Using Label Dictionaries
When using labels to specify items in the inputs arguments of the run
method, labels may directly replace any or all of the InputPort values
in an
input specification dictionary. Keep in mind that each label must be specified in the input_labels_dict
of the INPUT
Mechanism to which inputs are being specified, and must map to a
value that would have been valid in that position of the input dictionary.
>>> import psyneulink as pnl
>>> input_labels_dict = {"red": [[1, 0, 0]],
... "green": [[0, 1, 0]],
... "blue": [[0, 0, 1]]}
>>> M = pnl.ProcessingMechanism(default_variable=[[0, 0, 0]],
... params={pnl.INPUT_LABELS_DICT: input_labels_dict})
>>> C = pnl.Composition(pathways=[M])
>>> input_dictionary = {M: ['red', 'green', 'blue', 'red']}
>>> # (equivalent to {M: [[[1, 0, 0]], [[0, 1, 0]], [[0, 0, 1]], [[1, 0, 0]]]}, which is a valid input specification)
>>> results = C.run(inputs=input_dictionary)
The same general rules apply when using labels to specify target values
for a pathway with learning.
With target values, however, the labels must be included in the output_labels_dict
of the Mechanism that projects to the TARGET
Mechanism (see TARGET Mechanisms), or in
other words, the last Mechanism in a learning pathway. This is the same
Mechanism used to specify target values for a particular learning pathway in the targets dictionary
.
>>> input_labels_dict_M1 = {"red": [[1]],
... "green": [[0]]}
>>> output_labels_dict_M2 = {"red": [1],
... "green": [0]}
>>> M1 = pnl.ProcessingMechanism(params={pnl.INPUT_LABELS_DICT: input_labels_dict_M1})
>>> M2 = pnl.ProcessingMechanism(params={pnl.OUTPUT_LABELS_DICT: output_labels_dict_M2})
>>> C = pnl.Composition()
>>> learning_pathway = C.add_backpropagation_learning_pathway(pathway=[M1, M2], learning_rate=0.25)
>>> input_dictionary = {M1: ['red', 'green', 'green', 'red']}
>>> # (equivalent to {M1: [[[1]], [[0]], [[0]], [[1]]]}, which is a valid input specification)
>>> target_dictionary = {M2: ['red', 'green', 'green', 'red']}
>>> # (equivalent to {M2: [[1], [0], [0], [1]]}, which is a valid target specification)
>>> results = C.learn(inputs=input_dictionary,
... targets=target_dictionary)
Several attributes are available for viewing the labels for the current value(s) of a Mechanism’s InputPort(s) and OutputPort(s).
The
label
attribute of an InputPort or OutputPort returns the current label of its value, if one exists, and its numeric value otherwise.The
labeled_input_values
andlabeled_output_values
attributes of a Mechanism return lists containing the labels corresponding to the value(s) of the InputPort(s) or OutputPort(s) of the Mechanism, respectively. If the current value of a Port does not have a corresponding label, then its numeric value is reported instead.>>> output_labels_dict = {"red": [1, 0, 0], ... "green": [0, 1, 0], ... "blue": [0, 0, 1]} >>> M = pnl.ProcessingMechanism(default_variable=[[0, 0, 0]], ... params={pnl.OUTPUT_LABELS_DICT: output_labels_dict}) >>> C = pnl.Composition(pathways=[M]) >>> input_dictionary = {M: [[1, 0, 0]]} >>> results = C.run(inputs=input_dictionary) >>> M.labeled_output_values(C) ['red'] >>> M.output_ports[0].labeled_value(C) 'red'
Labels may be used to visualize the input and outputs of Mechanisms in a Composition with the show_structure option
of the Composition’s show_graph`show_graph
method with the keyword LABELS.
>>> C.show_graph(show_mechanism_structure=pnl.LABELS)
Note
A given label dictionary only applies to the Mechanism to which it belongs, and a given label only applies to its corresponding InputPort. For example, the label ‘red’, may translate to different values on different InputPorts of the same Mechanism, and on different Mechanisms of a Composition.
Mechanisms in Compositions¶
Mechanisms are most commonly used as Nodes in a Composition's graph, where they are connected to other Nodes using Projections.
Role in Compositions¶
When a Mechanism is added to a Composition_Addition_Methods>
, it is assigned as a Node in the
graph of that Comopsition, and one or more NodeRoles
indicating the role(s) that
the Node play(s) in the Composition. These can be listed by calling the Comopsition's `get_roles_by_nodes
with the Mechanism as its argument. The NodeRoles assigned to a Mechanism can
be different for different Compositions. If a Mechanism is designated as an INPUT
Node, it receives a
MappingProjection to its primary InputPort from the Composition. When the Composition is
executed, that InputPort receives the input specified for the Mechanism in the inputs argument of the Composition’s execution method; or,
if it is a nested Composition, then the Mechanism gets its input from a Node that projects to
it from the outer Composition. If a Mechanism is designated as an OUTPUT
Node, its output_values
are included in the value returned by its execution method and the Composition’s results
attribute.
Execution¶
When a Mechanism executes, the following sequence of actions is carried out:
The Mechanism updates its InputPort(s) by executing the
function
of each. The resultingvalue
(s) are used to assemble the Mechanism’svariable
. Eachvalue
is added to an outer array, such that each item of the Mechanism’svariable
corresponds to an InputPortvalue
. The array is placed in the Mechanism’sinput_values
attribute, and also passed as the input to the Mechanism’sfunction
after updating itsParameterPorts
.The Mechanism updates its ParameterPort(s) by executing each of their
functions
, the results of which are assigned as the values used for the corresponding Parameters, which include those of the Mechanism’sfunction
.The Mechanism’s
variable
is passed as the input to the itsfunction
, and the function is execute using the parameter values generating by the execution of its ParameterPorts. The result of the Mechanism’sfunction
is placed in the Mechanism’svalue
attribute.The Mechanism updates its OutputPort(s) are updated based on
value
, by executing thefunction
of each. The resultingvalue
for each Outport is placed in the Mechanism’soutput_values
attribute.
A Mechanism may be executed by calling its execute
method directly:
>>> my_simple_mechanism = pnl.ProcessingMechanism()
>>> my_simple_mechanism.execute(1.0)
This can be useful for testing a Mechanism and/or debugging. However, more typically, Mechanisms are executed as part of a Composition.
Execution in a Composition¶
A Mechanism can be assigned to one or more Compositions; the values of its parameters,
including its variable
and value
attributes, are maintained
separately for each context in which it is executed which, by default, is distinct
for each Composition in which it is executed; these execution-specific values can be accessed using the parameter’s
get
method. A parameter’s value can also be accessed using standard dot,
which returns its most recenty assigned value, irrespective of the context (including Composition) in which it was
assigned.
Runtime Parameters¶
Note
This is an advanced feature, but is generally not required for most applications. It is included for convenience; similar functionality can be achieved by setting the values of parameters programmatically before the Mechanism is executed and then resetting them afterwards.
The runtime parameter values are those assigned to a Mechanism and its Components (i.e., its function
and Ports <Mechanism_Ports
) when they execute. These are generally the values specified
in the corresponding constructors, assigned explicitly after construction (see Parameters), or the
default values. However, these values can be overidden for a particular execution, by specifying the desired values
in the runtime_params argument of the Mechanism’s execute
method (see below) or the execution method of a Composition
to which it belongs (see Runtime Parameters). When assigned in the context of a Composition, Conditions can be specified that determine when the values apply. Any values assigned using runtime_params
that apply will override the current value of the parameter for that (and only that) execution (if the Mechanism’s
execute
is used) or as long as its Condition applies (if executed in a Composition),
after which the value will return to its previous value. The value of a parameter can be modified on a permanent
basis, either for a given execution context using a its set
method; or for all execution contexts, by setting its default value using the Mechanism’s defaults
attribute.
Runtime specification ditionary: parameters of a Mechanism and its function¶
Runtime parameter values are specified in the runtime_params argument of a Mechanism’s execute
method using a dictionary, in which each entry contains the name of the
of a parameter (as the key) and the value to assign to it, as in the following example:
>>> T = pnl.TransferMechanism(function=Linear)
>>> T.function.slope.base
1.0 # Default for slope
>>> T.clip
None # Default for clip is None
>>> T.execute(2.0,
... runtime_params={"slope": 3.0,
... "clip": (0,5)})
array([[5.]]) # = 2 (input) * 3 (slope) = 6, but clipped at 5
>>> T.function.slope.base
1.0 # slope is restored 1.0
>>> T.clip
None # clip is restored to None
Note that even though slope
is a parameter of the Mechanism’s function
(in this case,
Linear
), the function itself does not have to be specified in the key of the runtime_params dictionary (although it
does have to be used when accessing or assigning the parameter’s value using dot notation,
as shown above).
If a parameter is assigned a new value before the execution, that value is restored after the execution; that is, the parameter is assigned its previous value and not its default, as shown below:
>>> T.function.slope.base = 10
>>> T.clip = (0,3)
>>> T.function.slope
10
>>> T.clip
(0, 3)
>>> T.execute(3.0,
... runtime_params={"slope": 4.0,
... "clip": (0,4)})
array([[4.]]) # = 3 (input) * 4 (slope) = 12, but clipped at 4
>>> T.function.slope.base
10 # slope is restored 10.0, its previously assigned value
>>> T.clip
(0, 3) # clip is restored to (0,3), its previously assigned value
Runtime specification ditionary: parameters of a Mechanism’s Ports and Projections¶
Runtime values can also be assigned to the parameters of a Mechanism’s Ports and/or their afferent
Projections
in entries of a runtime_params dict,
Ports. Runtime values are assigned to the parameters of Ports (and/or their function
s)
in entries with a key that designates the type of Port (INPUT_PORT_PARAMS, OUTPUT_PORT_PARAMS or
PARAMETER_PORT_PARAMS), and a sub-dictionary containing the specifications for that type of Port as the value.
The sub-dictionary can contain entries with specification that apply to all Ports of that type and/or individual
Ports. If the key of an entry is the name of a parameter of the Port (or its function
), the
specified value applies to all Ports of that type. Parameters for individual Ports are specified using the Port
or its name
as the key, and a dictionary containing parameter specifications as its value.
Note
If the
variable
of a Port is specified as a runtime parameter, then its afferent Projections will not be executed (see Lazy Evaluation), but itsfunction
will be.If the
value
of a Port is specified, neither its afferent Projections nor itfunction
will be executed.If the
variable
and/orvalue
is specified for all of the OutputPorts of a Mechanism, then it’s function will not be executed, and thevalue
will retain its previous value (again in accord with Lazy Evaluation), though its OutputPorts will be executed using the assigned values, and it’s execution_count and num_executions attributes will be incremented (since the OutputPorts – Components of the Mechanism – executed).As expected, specifying
value
supersedes any specification ofvariable
or of the parameters of itsfunction
.
Projections. The sub-dictionary specifying the parameters of a Port can also contain specifications for parameters
of its afferent Projections Projections. These are placed in entries with a key that designates
the type of Projection, and a sub-dictionary containing the specifications for that type of Port as the value. The
key for each type of projecction is its componentType appended with _PARAMS
(e.g.,
MAPPING_PROJECTION_PARAMS, CONTROL_PROJECTION_PARAMS, etc.). The sub-dictionary can contain specifications that
apply to all Projections of that type and/or individual Projections. If the key of an entryis the name of a parameter
of the Projection (or its function
), the specified value applies to all Projections of that
type. Parameters for individual Projections are specified using the Projections or its name
as the key, and a dictionary containing parameter specifications as its value.
Note
If the
value
of a Projection is specified as a runtime parameter, then it will not be executed (see Lazy Evaluation); accordingly, specifyingvalue
supersedes any specification ofvariable
or of the parameters of itsfunction <Projection_Base.function>.
Class Reference¶
- class psyneulink.core.components.mechanisms.mechanism.Mechanism_Base(default_variable=None, input_shapes=None, input_ports, function, output_ports)¶
Base class for Mechanism.
The arguments below can be used in the constructor for any subclass of Mechanism. See Component and subclasses for additional arguments and attributes.
Note
Mechanism is an abstract class and should never be instantiated by a direct call to its constructor. Mechanisms should be instantiated by calling the constructor for the desired subclass, or using other methods for specifying a Mechanism in context (see Creating a Mechanism)
- Parameters
default_variable (number, list or np.ndarray : default None) – specifies the input to the Mechanism to use if none is provided in a call to its
execute
method; also serves as a template to specify the shape of thevariable
for its InputPorts and thevariable
of itsfunction
if those are not specified. If it is not specified, then a subclass-specific default is assigned (usually [[0]]).input_shapes (int, or Iterable of tuples or ints : default None) –
specifies default_variable as array(s) of zeros if default_variable is not passed as an argument; if default_variable is specified, it must be equivalent to input_shapes. For example, the following Mechanisms are equivalent:
my_mech = ProcessingMechanism(input_shapes = [3, 2]) my_mech = ProcessingMechanism(default_variable = [[0, 0, 0], [0, 0]])
When specified as an iterable, each element of input_shapes is used as the size of the corresponding InputPort.
input_ports (str, list, dict, or np.ndarray : default None) – specifies the InputPorts for the Mechanism; if it is not specified, a single InputPort is created using the value of default_variable as its
variable
; if more than one is specified, the number and, if specified, their values must be compatible with any specifications made for default_variable or input_shapes (see InputPorts for additional details).input_labels (dict) – specifies labels (strings) that can be used to specify numeric values as input to the Mechanism; entries must be either label:value pairs, or sub-dictionaries containing label:value pairs, in which each label (key) specifies a string associated with a value for the corresponding InputPort(s) of the Mechanism; see Value Label Dictionaries for additional details.
function (Function : default Linear) – specifies the function used to generate the Mechanism’s
value
; can be a PsyNeuLink Function or a UserDefinedFunction; itvalue
is used to determine the shape of the primary outputPort of the Mechanism.output_ports (str, list or np.ndarray : default None) – specifies the OutputPorts for the Mechanism; if it is not specified, a single OutputPort is created the
value
of which is assigned the first item in the outermost dimension (axis 0) of the Mechanism’svalue
(see OutputPorts for additional details).output_labels (dict) – specifies labels (strings) that can be reported in place of numeric values as output(s) of the Mechanism; entries must be either label:value pairs, or sub-dictionaries containing label:value pairs, in which each label (key) specifies a string associated with a value for the OutputPort(s) of the Mechanism; see Value Label Dictionaries for additional details.
- variable¶
used as input to the Mechanism’s
function
. It is always at least a 2d np.array, with each item of axis 0 corresponding to avalue
of one of the Mechanism’s InputPorts (in the order they are listed in itsinput_ports
attribute), and the first item (i.e., item 0) corresponding to thevalue
of the primary InputPort. When specified in the variable argument of the constructor for the Mechanism, it is used as a template to define the format (shape and type of elements) of the input the Mechanism’sfunction
.- Type
at least 2d array
- input_port¶
primary InputPort for the Mechanism; same as first entry of its
input_ports
attribute. Itsvalue
is assigned as the first item of the Mechanism’svariable
.- Type
- input_ports¶
a list of the Mechanism’s InputPorts. The first (and possibly only) entry is always the Mechanism’s primary InputPort (i.e., the one in the its
input_port
attribute).- Type
ContentAddressableList[str, InputPort]
- input_values¶
each item in the list corresponds to the
value
of one of the Mechanism’s InputPorts listed in itsinput_ports
attribute. The value of each item is the same as the corresponding item in the Mechanism’svariable
attribute. The latter is a 2d np.array; theinput_values
attribute provides this information in a simpler list format.- Type
List[List or 1d np.array]
- input_labels_dict¶
contains entries that are either label:value pairs, or sub-dictionaries containing label:value pairs, in which each label (key) specifies a string associated with a value for the corresponding InputPort(s) of the Mechanism; see Value Label Dictionaries for additional details.
- Type
dict
- labeled_input_values¶
contains the labels corresponding to the current value(s) of the InputPort(s) of the Mechanism. If the current value of an InputPort does not have a corresponding label, then its numeric value is used instead.
- Type
list[str]
- external_input_ports¶
list of the
input_ports
for the Mechanism that are not designated asinternal_only
; these receive inputs from a Composition if the Mechanism is one of itsINPUT
Nodes.- Type
list[InputPort]
- external_input_shape¶
list of the
input_shape
s of the Mechanism’s externalinput_ports
(i.e., excluding any InputPorts designated asinternal_only
), that shows the shape of the inputs expected for the Mechanism. Each item corresponds to an expectedpath_afferent Projection
, and its shape is the expectedvalue
of that Projection.- Type
List[List or 1d np.array]
- external_input_variables¶
list of the
variable
s of the Mechanism’sexternal_input_ports
.- Type
List[List or 1d np.array]
- external_input_values¶
list of the
value
s of the Mechanism’sexternal_input_ports
.- Type
List[List or 1d np.array]
- default_external_inputs¶
list of the
default_input
s of the Mechanism’sexternal_input_ports
.- Type
List[1d np.array]
- parameter_ports¶
a read-only list of the Mechanism’s ParameterPorts, one for each of its modulable parameters, including those of its
function
. The value of the parameters of the Mechanism and itsfunction
are also accessible as (and can be modified using) attributes of the Mechanism (see ParameterPorts and Parameters).- Type
ContentAddressableList[str, ParameterPort]
- function¶
the primary function for the Mechanism, called when it is executed. It takes the Mechanism’s
variable
attribute as its input, and its result is assigned to the Mechanism’svalue
attribute (seeComponent_Function
for additional details).- Type
Function, function or method
- function_params¶
contains the parameters for the Mechanism’s
function
. The key of each entry is the name of a parameter of the function, and its value is the parameter’s value.- Type
Dict[str, value]
- value¶
result of the Mechanism’s
execute
method, which is usually (but not always) thevalue
of itfunction
. It is always at least a 2d np.array, with the items of axis 0 corresponding to the values referenced by the correspondingindex
attribute of the Mechanism’s OutputPorts. The first item is generally referenced by the Mechanism’s primary OutputPort (i.e., the one in the itsoutput_port
attribute), as well as the first item ofoutput_values
. Thevalue
isNone
until the Mechanism has been executed at least once.Note
the
value
of a Mechanism is not necessarily the same as itsoutput_values
attribute, which lists thevalues
of itsOutputPorts
.- Type
2d np.array [array(float64)]
- output_port¶
primary OutputPort for the Mechanism; same as first entry of its
output_ports
attribute.- Type
- output_ports¶
list of the Mechanism’s OutputPorts. The first (and possibly only) entry is always the Mechanism’s primary OutputPort (i.e., the one in the its
output_port
attribute).- Type
ContentAddressableList[str, OutputPort]
- output_values¶
each item in the list corresponds to the
value
of one of the Mechanism’s OutputPorts listed in itsoutput_ports
attribute.Note
The
output_values
of a Mechanism is not necessarily the same as itsvalue
attribute, since an OutputPort’sfunction
and/or itsassign
attribute may use the Mechanism’svalue
to generate a derived quantity for thevalue
of that OutputPort (and its corresponding item in the the Mechanism’soutput_values
attribute).- Type
List[array(float64)]
- labeled_output_values¶
contains the labels corresponding to the current value(s) of the OutputPort(s) of the Mechanism. If the current value of an OutputPort does not have a corresponding label, then its numeric value is used instead.
- Type
list
- output_labels_dict¶
contains entries that are either label:value pairs, or sub-dictionaries containing label:value pairs, in which each label (key) specifies a string associated with a value for the OutputPort(s) of the Mechanism; see Value Label Dictionaries for additional details.
- Type
dict
- standard_output_ports¶
list of the dictionary specifications for StandardOutputPorts that can be assigned as OutputPorts; subclasses may extend this list to include additional ones.
- RESULT1d np.array
first item in the outermost dimension (axis 0) of the Mechanism’s
value
.- OWNER_VALUElist
Full ndarray of Mechanism’s
value
.- MECHANISM_VALUElist
Synonym for OWNER_VALUE.
- Type
list[dict]
- standard_output_port_names¶
list of the names of the
standard_output_ports
that can be used to specify a StandardOutputPort in the output_ports argument of the Mechanism’s constructor, and to reference it in Mechanism’s list ofoutput_ports
.- Type
list[str]
- ports¶
a list of all of the Mechanism’s Ports, composed from its
input_ports
,parameter_ports
, andoutput_ports
attributes.- Type
ContentAddressableList
- projections¶
a list of all of the Mechanism’s Projections, composed from the
path_afferents
of all of itsinput_ports
, themod_afferents
of all of itsinput_ports
,parameter_ports
, andoutput_ports
, and theefferents
of all of itsoutput_ports
.- Type
ContentAddressableList
- afferents¶
a list of all of the Mechanism’s afferent Projections, composed from the
path_afferents
of all of itsinput_ports
, and themod_afferents
of all of itsinput_ports
,parameter_ports
, andoutput_ports
.,- Type
ContentAddressableList
- path_afferents¶
a list of all of the Mechanism’s afferent PathwayProjections, composed from the
path_afferents
attributes of all of itsinput_ports
.- Type
ContentAddressableList
- mod_afferents¶
a list of all of the Mechanism’s afferent ModulatoryProjections, composed from the
mod_afferents
attributes of all of itsinput_ports
,parameter_ports
, andoutput_ports
.- Type
ContentAddressableList
- efferents¶
a list of all of the Mechanism’s efferent Projections, composed from the
efferents
attributes of all of itsoutput_ports
.- Type
ContentAddressableList
- senders¶
a list of all of the Mechanisms that send Projections to the Mechanism (i.e., the senders of its
afferents
; this includes both ProcessingMechanisms (that send MappingProjections and ModulatoryMechanisms (that send ModulatoryProjections (also seemodulators
).- Type
ContentAddressableList
- modulators¶
a list of all of the AdapativeMechanisms that send ModulatoryProjections to the Mechanism (i.e., the senders of its
mod_afferents
(also seesenders
).- Type
ContentAddressableList
- receivers¶
a list of all of the Mechanisms that receive Projections from the Mechanism (i.e., the receivers of its
efferents
.- Type
ContentAddressableList
- condition¶
condition to be associated with the Mechanism in the Scheduler responsible for executing it in each Composition to which it is assigned; if it is not specified (i.e., its value is
None
), the default Condition for a Component is used. It can be overridden in a given Composition by assigning a Condition for the Mechanism directly to a Scheduler that is then assigned to the Composition.- Type
Condition : None
- name¶
the name of the Mechanism; if it is not specified in the name argument of the constructor, a default is assigned by MechanismRegistry (see Naming for conventions used for default and duplicate names).
- Type
str
- prefs¶
the
PreferenceSet
for the Mechanism; if it is not specified in the prefs argument of the constructor, a default is assigned usingclassPreferences
defined in __init__.py (see Preferences for details). .. _portRegistry : Registryregistry containing dicts for each Port type (InputPort, OutputPort and ParameterPort) with instance dicts for the instances of each type and an instance count for each Port type in the Mechanism. Note: registering instances of Port types with the Mechanism (rather than in the PortRegistry)
allows the same name to be used for instances of a Port type belonging to different Mechanisms without adding index suffixes for that name across Mechanisms while still indexing multiple uses of the same base name within a Mechanism.
- Type
PreferenceSet or specification dict
- _parse_arg_variable(variable)¶
Transforms variable into a form that Components expect. Used to allow users to pass input in convenient forms, like a single float when a list for input ports is expected
- Returns
- Return type
The transformed input
- _handle_default_variable(default_variable=None, input_shapes=None, input_ports=None, function=None, params=None)¶
Finds whether default_variable can be determined using default_variable and input_shapes arguments.
- Returns
a default variable if possible
None otherwise
- _handle_arg_input_ports(input_ports)¶
Takes user-inputted argument input_ports and returns an defaults.variable-like object that it represents
- Returns
A, B where
A is a defaults.variable-like object
B is True if **input_ports* contained an explicit variable specification, False otherwise*
- _validate_variable(variable, context=None)¶
Convert variable to 2D np.array: one 1D value for each InputPort
# VARIABLE SPECIFICATION: ENCODING: # Simple value variable: 0 -> [array([0])] # Single port array (vector) variable: [0, 1] -> [array([0, 1]) # Multiple port variables, each with a single value variable: [[0], [0]] -> [array[0], array[0]]
- Parameters
variable –
context –
- Returns
- _validate_params(request_set, target_set=None, context=None)¶
validate TimeScale, INPUT_PORTS, FUNCTION_PARAMS, OUTPUT_PORTS and MONITOR_FOR_CONTROL
- Go through target_set params (populated by Component._validate_params) and validate values for:
- INPUT_PORTS:
<MechanismsInputPort or Projection object or class, specification dict for one, 2-item tuple, or numeric value(s)>; if it is missing or not one of the above types, it is set to self.defaults.variable
- FUNCTION_PARAMS: <dict>, every entry of which must be one of the following:
ParameterPort or Projection object or class, specification dict for one, 2-item tuple, or numeric value(s); if invalid, default is assigned
- OUTPUT_PORTS:
<MechanismsOutputPort object or class, specification dict, or numeric value(s); if it is missing or not one of the above types, it is set to None here;
and then to default value of value (output of execute method) in instantiate_output_port (since execute method must be instantiated before self.defaults.value is known)
if OUTPUT_PORTS is a list or OrderedDict, it is passed along (to instantiate_output_ports) if it is a OutputPort class ref, object or specification dict, it is placed in a list
- MONITORED_PORTS:
** DOCUMENT
Note: PARAMETER_PORTS are validated separately – ** DOCUMENT WHY
- TBI - Generalize to go through all params, reading from each its type (from a registry),
and calling on corresponding subclass to get default values (if param not found) (as PROJECTION_TYPE and PROJECTION_SENDER are currently handled)
- _instantiate_function(function, function_params=None, context=None)¶
Assign weights and exponents if specified in input_ports
- _instantiate_input_ports(input_ports=None, reference_value=None, context=None)¶
Call Port._instantiate_input_ports to instantiate orderedDict of InputPort(s)
- This is a stub, implemented to allow Mechanism subclasses to override _instantiate_input_ports
or process InputPorts before and/or after call to _instantiate_input_ports
- _instantiate_parameter_ports(function=None, context=None)¶
Call Port._instantiate_parameter_ports to instantiate a ParameterPort for each parameter with modulable=True
- This is a stub, implemented to allow Mechanism subclasses to override _instantiate_parameter_ports
or process InputPorts before and/or after call to _instantiate_parameter_ports :param function:
- _instantiate_output_ports(context=None)¶
Call Port._instantiate_output_ports to instantiate orderedDict of OutputPort(s)
- This is a stub, implemented to allow Mechanism subclasses to override _instantiate_output_ports
or process InputPorts before and/or after call to _instantiate_output_ports
- _add_projection_from_mechanism(receiver, port, projection, context=None)¶
Add projection to specified port
- _projection_added(projection, context=None)¶
Stub that can be overidden by subclasses that need to know when a projection is added to the Mechanism
- reset(*args, force=False, context=None, **kwargs)¶
Reset
value
if Mechanisms is stateful.If the mechanism’s
function
is anIntegratorFunction
, or if the mechanism has andintegrator_function
(see TransferMechanism), this method effectively begins the function’s accumulation over again at the specified value, and updates related attributes on the mechanism. It also clears thevalue
history
, thus effectively setting the previous value toNone
.If the mechanism’s
function
is anIntegratorFunction
, itsreset
method:Calls the function’s own
reset
method (see Note below for details)Sets the mechanism’s
value
to the output of the function’s reset methodUpdates its
output ports
based on its newvalue
If the mechanism has an
integrator_function
, itsreset
method:(1) Calls the `integrator_function's <TransferMechanism.integrator_function>` own `reset <IntegratorFunction.reset>` method (see Note below for details) (2) Executes its `function <Mechanism_Base.function>` using the output of the `integrator_function's <TransferMechanism.integrator_function>` `reset <IntegratorFunction.reset>` method as the function's variable (3) Sets the mechanism's `value <Mechanism_Base.value>` to the output of its function (4) Updates its `output ports <Mechanism_Base.output_port>` based on its new `value <Mechanism_Base.value>`
Note
The reset method of an IntegratorFunction Function typically resets the function’s
previous_value
(and any otherstateful_attributes
) andvalue
to the quantity (or quantities) specified. Ifreset
is called without arguments, theinitializer
value (or the values of each of the attributes ininitializers
) is used instead. Thereset
method may vary across different Integrators. See individual functions for details on theirstateful_attributes
, as well as other reinitialization steps that the reset method may carry out.
- execute(input=None, context=None, runtime_params=None, report_output=None, report_params=None, report_num=None)¶
Carry out a single execution of the Mechanism.
Execution sequence:
Handle initialization if
initialization_status
is ContextFlags.INITIALIZINGAssign any
Port-specific runtime params
to correspondingruntime_params
dict.While
is_finished
fromInputPorts
andruntime_params
.update
input_ports
update
parameter_ports
execute Mechanism (calling _execute method) and set
value
parameterupdate
output_ports
Note:> if execution is occurring as part of initialization, each output_port is reset to 0 > otherwise, their values are left as is until the next update
update num_executions and check
max_executions
Report execution (if reportOutputPref is set)
- Parameters
input (List[value] or ndarray : default self.defaults.variable) – input to use for execution of the Mechanism. This must be consistent with the format of the Mechanism’s InputPort(s): the number of items in the outermost level of the list, or axis 0 of the ndarray, must equal the number of the Mechanism’s
input_ports
, and each item must be compatible with the format (number and type of elements) of thevariable
of the corresponding InputPort (see Run Inputs for details of input specification formats).runtime_params ([Dict[str, Dict[str, Dict[str, value]]]] : None) – a dictionary specifying values for
Parameters
of the Mechanism or those of any of its Components (function
, Ports and/or their afferent Projections), that temporarily override their values for the current execution, and are then restored to their previous values following execution (see Runtime specification ditionary: parameters of a Mechanism and its function for details of specification).context (Context or str : None) – the context in which the Mechanism is executed, usually specified by its
execution_id
(see Execution Contexts for additional information about execution contexts.
- Returns
Mechanism’s output_values – list with the
value
of each of the Mechanism’s OutputPorts after either oneTIME_STEP
or aTRIAL
.- Return type
List[value]
- _get_variable_from_input(input, context=None)¶
Return array of results from each InputPort function executed with corresponding input item as its variable This is called when Mechanism is executed on its own (e.g., during init or from the command line). It: - bypasses call to Port._update(), thus ignoring any afferent Projections assigned to the Mechanism; - assigns each item of input to variable of corresponding InputPort; - executes function of each InputPort using corresponding item of input as its variable; - returns array of values generated by execution of each InputPort function.
- _update_input_ports(runtime_input_port_params=None, context=None)¶
Update value for each InputPort in self.input_ports:
Call execute method for all (MappingProjection) Projections in Port.path_afferents Aggregate results (using InputPort execute method) Update InputPort.value
- _update_output_ports(runtime_output_port_params=None, context=None)¶
Execute function for each OutputPort and assign result of each to corresponding item of self.output_values
owner_value arg can be used to override existing (or absent) value of owner as variable for OutputPorts and assign a specified (set of) value(s).
- initialize(value, context=None)¶
Assign an initial value to the Mechanism’s
value
attribute and update its OutputPorts.- Parameters
value (List[value] or 1d ndarray) – value used to initialize the first item of the Mechanism’s
value
attribute.
- _parse_runtime_params(runtime_params, context)¶
Move Port param specifications and nested Project-specific specifications into sub-dicts.
Move any specifications for Port types into type-specific sub-dicts For each type-specific sub-dict,
move any specifications for individual Ports into PORT_SPECIFIC sub-dict
move any specifications for Projection types into type-specific subdicts
move any specifications for individual Projections into PORT_SPECIFIC sub-dict
- Returns
dict – dict containing three sub-dicts, one for each of the three Port types, of the following form:
- {‘<Port type>_PARAMS’: parameter of Port type or its functionvalue,
’PORT_SPECIFIC_PARAMS’ : {<Port or Port name> : {parameter : value}} ‘<Projection type>_PARAMS’ : {parameter of Projection type or its function : value}, ‘PROJECTION_SPECIFIC_PARAMS’ : {<Projection or name> : {parameter : value}}}
- Return type
{port_param_keyword : Port type-specific dict}
- _gen_llvm_function(*, extra_args=[], ctx, tags)¶
Overloaded main function LLVM generation method.
Mechanisms need to support “is_finished” execution variant (used by scheduling conditions) on top of the variants supported by Component.
- _gen_llvm_function_body(ctx, builder, base_params, state, arg_in, arg_out, *, tags)¶
Overloaded LLVM code generation method.
Implements main mechanisms loop (while not finished). Calls two other internal Mechanism functions; ‘is_finished’ to terminate the loop, and ‘_gen_llvm_function_internal’ to generate body of the loop (invocation of Ports and Functions).
- _show_structure(show_functions=False, show_mech_function_params=False, show_port_function_params=False, show_values=False, use_labels=False, show_headers=False, show_roles=False, show_conditions=False, composition=None, compact_cim=False, condition=None, node_border='1', output_fmt='pdf', context=None)¶
Generate a detailed display of a the structure of a Mechanism.
Note
This method relies on graphviz, which must be installed and imported (standard with PsyNeuLink pip install)
Displays the structure of a Mechanism using html table format and shape=’plaintext’. This method is called by
Composition.show_graph
if its show_mechanism_structure argument is specified asTrue
when it is called.- Parameters
show_functions (bool : default False) – show the
function
of the Mechanism and each of its Ports.show_mech_function_params (bool : default False) – show the parameters of the Mechanism’s
function
if show_functions is True.show_port_function_params (bool : default False) – show parameters for the
function
of the Mechanism’s Ports if show_functions is True).show_values (bool : default False) – show the
value
of the Mechanism and each of its Ports (prefixed by “=”).use_labels (bool : default False) – use labels for values if show_values is
True
; labels must be specified in theinput_labels_dict
(for InputPort values) andoutput_labels_dict
(for OutputPort values), otherwise the value is used.show_headers (bool : default False) –
show the Mechanism, InputPort, ParameterPort and OutputPort headers.
composition argument (if composition is not specified, show_roles is ignored).
show_conditions (bool : default False) – show the conditions used by Composition to determine whether/when to execute each Mechanism (if composition is not specified, show_conditions is ignored).
composition (Composition : default None) – specifies the Composition (to which the Mechanism must belong) for which to show its role (see roles); if this is not specified, the show_roles argument is ignored.
compact_cim (bool : default False) – specifies whether to suppress InputPort fields for input_CIM and OutputPort fields for output_CIM
output_fmt (keyword : default 'pdf') –
‘pdf’: generate and open a pdf with the visualization;
’jupyter’: return the object (ideal for working in jupyter/ipython notebooks)
’struct’: return a string that specifies the structure of the Mechanism using html table format for use in a GraphViz node specification.
structure (Example HTML for) –
<<table border="1" cellborder="0" cellspacing="0" bgcolor="tan"> <- MAIN TABLE <tr> <- BEGIN OutputPorts <td colspan="2"><table border="0" cellborder="0" BGCOLOR="bisque"> <- OutputPorts OUTER TABLE <tr> <td colspan="1"><b>OutputPorts</b></td> <- OutputPorts HEADER </tr> <tr> <td><table border="0" cellborder="1"> <- OutputPort CELLS TABLE <tr> <td port="OutputPortPort1">OutputPort 1<br/><i>function 1</i><br/><i>=value</i></td> <td port="OutputPortPort2">OutputPort 2<br/><i>function 2</i><br/><i>=value</i></td> </tr> </table></td> </tr> </table></td> </tr> <tr> <- BEGIN MECHANISM & ParameterPorts <td port="Mech name"><b>Mech name</b><br/><i>Roles</i></td> <- MECHANISM CELL (OUTERMOST TABLE) <td><table border="0" cellborder="0" BGCOLOR="bisque"> <- ParameterPorts OUTER TABLE <tr> <td><b>ParameterPorts</b></td> <- ParameterPorts HEADER </tr> <tr> <td><table border="0" cellborder="1"> <- ParameterPort CELLS TABLE <tr><td port="ParamPort1">Param 1<br/><i>function 1</i><br/><i>= value</i></td></tr> <tr><td port="ParamPort1">Param 2<br/><i>function 2</i><br/><i>= value</i></td></tr> </table></td> </tr> </table></td> </tr> <tr> <- BEGIN InputPorts <td colspan="2"><table border="0" cellborder="0" BGCOLOR="bisque"> <- InputPortS OUTER TABLE <tr> <td colspan="1"><b>InputPorts</b></td> <- InputPorts HEADER </tr> <tr> <td><table border="0" cellborder="1"> <- InputPort CELLS TABLE <tr> <td port="InputPortPort1">InputPort 1<br/><i>function 1</i><br/><i>= value</i></td> <td port="InputPortPort2">InputPort 2<br/><i>function 2</i><br/><i>= value</i></td> </tr> </table></td> </tr> </table></td> </tr> </table>>
- plot(x_range=None)¶
Generate a plot of the Mechanism’s
function
using the specified parameter values (seeDDM.plot
for details of the animated DDM plot).- Parameters
x_range (List) –
specify the range over which the
function
should be plotted. x_range must be provided as a list containing two floats: lowest value of x and highest value of x. Default values depend on the Mechanism’sfunction
.Logistic Function: default x_range = [-5.0, 5.0]
Exponential Function: default x_range = [0.1, 5.0]
All Other Functions: default x_range = [-10.0, 10.0]
- Returns
Plot of Mechanism’s `function <Mechanism_Base.function>` – Matplotlib window of the Mechanism’s
function
plotted with specified parameters over the specified x_range- Return type
Matplotlib window
- add_ports(ports)¶
Add one or more Ports to the Mechanism. Only InputPorts and OutputPorts can be added; ParameterPorts cannot be added to a Mechanism after it has been constructed.
If the
owner
of a Port specified in the ports argument is not the same as the Mechanism to which it is being added an error is generated. If the name of a specified Port is the same as an existing one with the same name, an index is appended to its name, and incremented for each Port subsequently added with the same name (see naming conventions). If a specified Port already belongs to the Mechanism, the request is ignored.Note
Adding InputPorts to a Mechanism changes the size of its
variable
attribute, which may produce an incompatibility with itsfunction
(see Mechanism InputPorts for a more detailed explanation).- Parameters
ports (Port or List[Port]) – one more InputPorts or OutputPorts to be added to the Mechanism. Port specification(s) can be an InputPort or OutputPort object, class reference, class keyword, or Port specification dictionary (the latter must have a PORT_TYPE entry specifying the class or keyword for InputPort or OutputPort).
entries (Returns a dictionary with two) –
added. (containing the list of InputPorts and OutputPorts) –
------- –
added (Dictionary with entries containing InputPorts and/or OutputPorts) –
- remove_ports(ports)¶
Remove one or more Ports from the Mechanism. Only
InputPorts
can be removed; ParameterPorts cannot be removed from a Mechanism.Each Specified port must be owned by the Mechanism, otherwise the request is ignored.
Note
Removing InputPorts from a Mechanism changes the size of its
variable
attribute, which may produce an incompatibility with itsfunction
(see Mechanism InputPorts for more detailed information).- Parameters
ports (Port or List[Port]) – one more ports to be removed from the Mechanism. Port specification(s) can be an Port object or the name of one.
- _get_standardized_label_dicts()¶
Gets dict of Mechanism’s input and output port labels in a standardized form
- Returns
{ INPUT_PORTS: {(int) port_index: {{label_1: value_1}, {label_2: value_2}} }, OUTPUT_PORTS: {(int) port_index: {{label_1: value_1}, {label_2: value_2}} } }
- Return type
dict
- _get_standardized_label_dict(label_type)¶
Parses input or output label dicts into a standardized form
- Parameters
port_type ((str)) –
port_type –
- Returns
{INPUT_PORTS/OUTPUT_PORTS: {(int) port_index: {{label_1: value_1}, {label_2: value_2}} } }
- Return type
dict
- _get_port_value_labels(port_type, context=None)¶
Return list of labels for the value of each Port of specified port_type. If the labels_dict has subdicts (one for each Port), get label for the value of each Port from its subdict. If the labels dict does not have subdicts, then use the same dict for the only (or all) Port(s)
- property external_input_shape¶
Alias for _default_external_input_shape
- property external_input_variables¶
Returns variables of all external InputPorts that belong to the Mechanism
- property labeled_input_values¶
Returns a list with as many items as there are InputPorts of the Mechanism. Each list item represents the value of the corresponding InputPort, and is populated by a string label (from the input_labels_dict) when one exists, and the numeric value otherwise.
- property labeled_output_values¶
Returns a list with as many items as there are OutputPorts of the Mechanism. Each list item represents the value of the corresponding OutputPort, and is populated by a string label (from the output_labels_dict) when one exists, and the numeric value otherwise.
- property ports¶
Return list of all of the Mechanism’s Ports
- property path_afferents¶
Return list of the
path_afferents
for all of the Mechanism’s input_ports
- property mod_afferents¶
Return all of the Mechanism’s afferent modulatory Projections
- property afferents¶
Return list of all of the Mechanism’s afferent Projections
- property efferents¶
Return list of all of the Mechanism’s efferent Projections
- property projections¶
Return all Projections
- property senders¶
Return all Mechanisms that send Projections to self
- property receivers¶
Return all Mechanisms that send Projections to self
- property modulators¶
Return all Mechanisms that send Projections to self
- property _dependent_components¶
Returns a set of Components that will be executed if this Component is executed