Mechanisms¶

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 Process or System to which they belong, transform it in some way, and provide the result as input to other Mechanisms in the Process or System, or as the output for a Process or System 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).

Every Mechanism is made up of four fundamental components:

• Function used to transform its input(s) into its output(s);
• ParameterState(s) used to represent the parameters of its Function (and/or any parameters that are specific to the Mechanism itself);

These are described in the sections on Mechanism_Function and States (InputStates, ParameterStates and Parameters, and OutputStates), and shown graphically in a figure, under Structure below.

Creating a Mechanism¶

Mechanisms can be created in several ways. The simplest is to call the constructor for the desired type of Mechanism. Alternatively, the mechanism command can be used to create a specific type of Mechanism or an instance of default_mechanism. Mechanisms can also be specified “in context,” for example in the pathway attribute of a Process; the Mechanism can be specified in either of the ways mentioned above, or using one of the following:

• the name of an existing Mechanism;
• the name of a Mechanism type (subclass);
• a specification dictionary – this can contain an entry specifying the type of Mechanism, and/or entries specifying the value of parameters used to instantiate it. These should take the following form:

• MECHANISM_TYPE: <name of a Mechanism type>
if this entry is absent, a default_mechanism will be created.
• NAME: <str>
the string will be used as the name of the Mechanism; if this entry is absent, the name will be the name of the Mechanism’s type, suffixed with an index if there are any others of the same type for which a default name has been assigned.
• <name of parameter>:<value>
this can contain any of the standard parameters for instantiating a Mechanism or ones specific to a particular type of Mechanism (see documentation for the type). The key must be the name of the argument used to specify the parameter in the Mechanism’s constructor, and the value must be a legal value for that parameter, using any of the ways allowed for specifying a parameter. The parameter values specified will be used to instantiate the Mechanism. These can be overridden during execution by specifying Runtime Parameters, either when calling the Mechanism’s execute or run method, or where it is specified in the pathway attribute of a Process.
• automatically – PsyNeuLink automatically creates one or more Mechanisms under some circumstances. For example, a ComparatorMechanism and LearningMechanism are created automatically when learning is specified for a Process; and an ObjectiveMechanism and ControlMechanism are created when the controller is specified for a System.

Specifying States¶

Every Mechanism has one or more InputStates, ParameterStates, and OutputStates (described below) that allow it to receive and send Projections, and to execute its function). When a Mechanism is created, it automatically creates the ParameterStates it needs to represent its parameters, including those of its function. It also creates any InputStates and OutputStates required for the Projections it has been assigned. InputStates and OutputStates, and corresponding Projections (including those from ModulatorySignals) can also be specified explicitly in the input_states and output_states arguments of the Mechanism’s constructor (see InputStates and OutputStates, 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_STATES and OUTPUT_STATES, respectively (see second example below). While specifying the input_states and output_states 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 state. InputStates and OutputStates can also be added to an existing Mechanism using its add_states 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 States are specified in the input_states or output_states arguments of a Mechanism’s constructor, they replace any default States generated by the Mechanism when it is created (if no States were specified). This is particularly relevant for OutputStates, as most Mechanisms create one or more Standard OutputStates by default, that have useful properties. To retain those States if any are specified in the output_states argument, they must be included along with those states in the output_states argument (see examples). The same is true for default InputStates and the input_states argument.

This behavior differs from adding a State once the Mechanism is created. States added to Mechanism using the Mechanism’s add_states method, or by assigning the Mechanism in the owner argument of the State’s constructor, are added to the Mechanism without replacing any of its existing States, including any default States that may have been generated when the Mechanism was created (see examples in State).

Examples

The following example creates an instance of a TransferMechanism that names the default InputState MY_INPUT, and assigns three Standard OutputStates:

>>> import psyneulink as pnl
>>> my_mech = pnl.TransferMechanism(input_states=['MY_INPUT'],
...                                 output_states=[pnl.RESULT, pnl.OUTPUT_MEAN, pnl.OUTPUT_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_STATES: ['MY_INPUT'],
...                                         pnl.OUTPUT_STATES: [pnl.RESULT, pnl.OUTPUT_MEAN, pnl.OUTPUT_VARIANCE]})


See State for additional examples of specifying the States of a Mechanism.

Specifying Parameters¶

As described below, Mechanisms have ParameterStates 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).

function Attribute¶

The Function Component assigned as the primary function of a Mechanism is assigned to the Mechanism’s function attribute, and its function is assigned to the Mechanism’s function attribute.

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 <Function_Overview> 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 using the Mechanism’s assign_params method (the safest means) or by assigning it 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_states (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 OutputStates 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 OutputStates below).

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 InputState(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 OutputState(s) to assign items to its output_values attribute.

States¶

Every Mechanism has one or more of each of three types of States: InputState(s), ParameterState(s), and OutputState(s). Generally, these are created automatically when the Mechanism is created. InputStates and OutputStates (but not ParameterStates) can also be specified explicitly for a Mechanism, or added to an existing Mechanism using its add_states method, as described above).

The three types of States are shown schematically in the figure below, and described briefly in the following sections.

Schematic of a Mechanism showing its three types of States (InputState, ParameterState and OutputState). Every Mechanism has at least one (primary) InputState and one (primary) OutputState, but can have additional states of each type. It also has one ParameterState for each of its parameters and the parameters of its function. The value of each InputState is assigned as an item of the Mechanism’s variable, and the result of its function is assigned as the Mechanism’s value, the items of which are referenced by its OutputStates to determine their own values (see variable and value Attributes above, and more detailed descriptions below).

InputStates¶

These receive, aggregate and represent the input to a Mechanism, and provide this to the Mechanism’s function. Usually, a Mechanism has only one (primary) InputState, identified in its input_state attribute. However some Mechanisms have more than one InputState. For example, a ComparatorMechanism has one InputState for its SAMPLE and another for its TARGET input. All of the Mechanism’s InputStates (including its primary InputState <InputState_Primary> are listed in its input_states attribute (note the plural). The input_states attribute is a ContentAddressableList – a PsyNeuLink-defined subclass of the Python class UserList – that allows a specific InputState in the list to be accessed using its name as the index for the list (e.g., my_mechanism['InputState name']).

The value of each InputState 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 InputStates 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 InputStates in its input_states attribute. A Mechanism’s constructor does its best to insure this: if its default_variable and/or its size argument is specified, it constructs a number of InputStates (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_states)
> [(InputState InputState-0), (InputState InputState-1)]
print(my_mech_A.input_states[0].value)
> [ 0.]
print(my_mech_A.input_states[1].value)
> [ 0.  0.]

my_mech_B = pnl.TransferMechanism(default_variable=[[0],[0],[0]])
print(my_mech_B.input_states)
> [(InputState InputState-0), (InputState InputState-1), (InputState InputState-2)]


Conversely, if the input_states argument is used to specify InputStates for the Mechanism, they are used to format the Mechanism’s variable:

my_mech_C = pnl.TransferMechanism(input_states=[[0,0], 'Hello'])
print(my_mech_C.input_states)
> [(InputState InputState-0), (InputState Hello)]
print(my_mech_C.variable)
> [array([0, 0]) array([0])]


If both the default_variable (or size) and input_states arguments are specified, then the number and format of their respective items must be the same (see State for additional examples of specifying States).

If InputStates are added using the Mechanism’s add_states method, then its variable is extended to accommodate the number of InputStates 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 InputStates are specified in the Mechanism’s constructor, and/or added using its add_states method, determines the order of the items to which they are assigned assigned in he Mechanism’s variable, and are listed in its input_states 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 InputStates 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 InputStates 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 InputStates created for the Mechanism, and the format of each item determines the format for the variable and value attributes of the corresponding InputState. If any InputStates are specified in the input_states argument or an INPUT_STATES 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 the variable or value of the corresponding InputStates for any that are not explicitly specified in the input_states argument or INPUT_STATES entry (see below).
• size (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(size = [3, 2])
T2 = TransferMechanism(default_variable = [[0, 0, 0], [0, 0]])


The relationship to any specifications in the input_states argument or INPUT_STATES entry of a params dictionary is the same as for the default_variable argument, with the latter taking precedence (see above).

• input_states (list) – this can be used to explicitly specify the InputStates created for the Mechanism. Each item must be an InputState specification, and the number of items must match the number of items in the default_variable argument or size argument if either of those is specified. If the variable and/or value is explicitly specified for an InputState in the input_states argument or INPUT_STATES 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 InputState is used to specify the format of the InputState’s variable (e.g., the InputState is specified using an OutputState to project to it;). If default_variable is not specified, a default value is specified by the Mechanism. InputStates can also be specifed that shadow the inputs of other InputStates and/or Mechanisms; that is, receive Projections from all of the same senders as those specified.
• INPUT_STATES entry of a params dict (list) – specifications are treated in the same manner as those in the input_states argument, and take precedence over those.

InputStates can be added to a Mechanism using its add_states method; this extends its variable by a number of items equal to the number of InputStates added, and each new item is assigned a format compatible with the value of the corresponding InputState added; if the InputState’s variable is not specified, it is assigned the default format for an item of the owner’s variable attribute. The InputStates are appended to the end of the list in the Mechanism’s input_states attribute. Adding in States in this manner does not replace any existing States, including any default States generated when the Mechanism was constructed (this is contrast to States specified in a Mechanism’s constructor which do replace any default State(s) of the same type).

Note

Adding InputStates to a Mechanism using its add_states 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 OutputStates created for the Mechanism. It is the user’s responsibility to ensure that the assignment of InputStates to a Mechanism using the add_states is coordinated with the specification of its function, so that the total number of InputStates (listed in the Mechanism’s input_states 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 InputStates

Each InputState of a Mechanism can receive one or more Projections from other Mechanisms. When a Mechanism is created, a MappingProjection is created automatically for any OutputStates or Projections from them that are in its InputState specification, using AUTO_ASSIGN_MATRIX as the Projection’s matrix specification. However, if a specification in the input_states argument or an INPUT_STATES entry of a params dictionary cannot be resolved to an instantiated OutputState at the time the Mechanism is created, no MappingProjection is assigned to the InputState, and this must be done by some other means; any specifications in the Mechanism’s input_states attribute that are not associated with an instantiated OutputState 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 Process, this includes a Projection from the ProcessInputState for that Process. Any GatingProjections it receives are listed in its mod_afferents attribute.

ParameterStates and Parameters¶

ParameterStates provide the value for each parameter of a Mechanism and its function. One ParameterState is assigned to each of the parameters of the Mechanism and/or its function (corresponding to the arguments in their constructors). The ParameterState takes the value specified for a parameter (see below) as its variable, and uses it as the input to the ParameterState’s function, which modulates it in response to any ControlProjections received by the ParameterState (specified in its mod_afferents attribute), and assigns the result to the ParameterState’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 ParameterState’s value that is returned (thereby accurately reflecting the value used during the last execution of the Mechanism or its function). The ParameterStates for a Mechanism are listed in its parameter_states attribute.

The “base” value of a parameter (i.e., the unmodulated value used as the ParameterState’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 Mechanism_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 Mechanism_Function above).

All of the Mechanism’s parameters are listed in a dictionary in its user_params attribute; that dictionary contains a FUNCTION_PARAMS entry that contains a sub-dictionary with the parameters of the Mechanism’s function. The FUNCTION_PARAMS sub-dictionary is also accessible directly from the Mechanism’s function_params attribute.

OutputStates¶

These represent the output(s) of a Mechanism. A Mechanism can have several OutputStates, and each can send Projections that transmit its value to other Mechanisms and/or as the output of the Process or System to which the Mechanism belongs. Every Mechanism has at least one OutputState, referred to as its primary OutputState. If OutputStates are not explicitly specified for a Mechanism, a primary OutputState is automatically created and assigned to its output_state attribute (note the singular), and also to the first entry of the Mechanism’s output_states attribute (note the plural). The value of the primary OutputState 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 OutputStates 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 OutputStates are available for each type of Mechanism, and custom ones can be configured (see OutputState Specification. These can be assigned in the output_states argument of the Mechanism’s constructor.

All of a Mechanism’s OutputStates (including the primary one) are listed in its output_states attribute (note the plural). The output_states attribute is a ContentAddressableList – a PsyNeuLink-defined subclass of the Python class UserList – that allows a specific OutputState in the list to be accessed using its name as the index for the list (e.g., my_mechanism['OutputState name']). This list can also be used to assign additional OutputStates to the Mechanism after it has been created.

The value of each of the Mechanism’s OutputStates is assigned as an item in the Mechanism’s output_values attribute, in the same order in which they are listed in its output_states 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 OutputStates can modify the item of the Mechanisms value to which they refer – see OutputStates).

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), or using the Mechanism’s assign_params method. The Mechanism-specific attributes are listed below by their argument names / keywords, along with a description of how they are specified:

• input_states / INPUT_STATES - a list specifying the Mechanism’s input_states (see InputState Specification for details of specification).
• output_states / OUTPUT_STATES - specifies specialized OutputStates required by a Mechanism subclass (see OutputState Specification for details of specification).
• monitor_for_learning / MONITOR_FOR_LEARNING - specifies which of the Mechanism’s OutputStates 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:

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 InputState(s) and OutputState(s):

• INPUT_LABELS_DICT – used to specify labels for values of the InputState(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 OutputState(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 and targets arguments of the run method of a System
• report the values of the InputState(s) and OutputState(s) of a Mechanism
• visualize the inputs and outputs of the System’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:

• <state name or index>:<sub-dictionary> – this is used to specify labels that are specific to individual States of the type corresponding to the dictionary;

For example, if a Mechanism has two InputStates, 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 InputStates.

>>> 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 state of a particular type (only one InputState or only one OutputState)
• only the index zero InputState or index zero OutputState needs labels

In these cases, a label dictionary for that type of state may simply contain the label:value entries described above. The label:value mapping will only apply to the index zero state of the state type for which this option is used. Any additional states of that type will not have value labels. For example, if the input_labels_dictionary below were applied to a Mechanism with multiple InputState, only the index zero InputState 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 InputState values in an input specification dictionary. Keep in mind that each label must be specified in the input_labels_dict of the Origin 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})
>>> P = pnl.Process(pathway=[M])
>>> S = pnl.System(processes=[P])
>>> 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 = S.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 the learning sequence. This is the same Mechanism used to specify target values for a particular learning sequence 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})
>>> P = pnl.Process(pathway=[M1, M2],
...                 learning=pnl.ENABLED,
...                 learning_rate=0.25)
>>> S = pnl.System(processes=[P])
>>> 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 = S.run(inputs=input_dictionary,
...                 targets=target_dictionary)


Several attributes are available for viewing the labels for the current value(s) of a Mechanism’s InputState(s) and OutputState(s).

• The label attribute of an InputState or OutputState returns the current label of its value, if one exists, and its value otherwise.
• The input_labels and output_labels attributes of Mechanisms return a list containing the labels corresponding to the value(s) of the InputState(s) or OutputState(s) of the Mechanism, respectively. If the current value of a state does not have a corresponding label, then its numeric value is used 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})
>>> P = pnl.Process(pathway=[M])
>>> S = pnl.System(processes=[P])
>>> input_dictionary =  {M: [[1, 0, 0]]}
>>> results = S.run(inputs=input_dictionary)
>>> M.get_output_labels(S)
['red']
>>> M.output_states[0].get_label(S)
'red'


Labels may be used to visualize the input and outputs of Mechanisms in a System via the show_structure option of the System’s show_graph method with the keyword LABELS.

>>> S.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 InputState. For example, the label ‘red’, may translate to different values on different InputStates of the same Mechanism, and on different Mechanisms of a System.

Attribute Dictionary¶

A Mechanism has an attributes_dict attribute containing a dictionary of its attributes that can be used to specify the variable of its OutputStates (see OutputState Customization).

Role in Processes and Systems¶

Mechanisms that are part of one or more Processes are assigned designations that indicate the role they play in those Processes, and similarly for role they play in any Systems to which they belong. These designations are listed in the Mechanism’s processes and systems attributes, respectively. Any Mechanism designated as ORIGIN receives a MappingProjection to its primary InputState from the Process(es) to which it belongs. Accordingly, when the Process (or System of which the Process is a part) is executed, those Mechanisms receive the input provided to the Process (or System). The output_values of any Mechanism designated as the TERMINAL Mechanism for a Process is assigned as the output of that Process, and similarly for any System to which it belongs.

Note

A Mechanism that is the ORIGIN or TERMINAL of a Process does not necessarily have the same role in the System(s) to which the Mechanism or Process belongs (see example).

Execution¶

A Mechanism can be executed using its execute or run methods. This can be useful in testing a Mechanism and/or debugging. However, more typically, Mechanisms are executed as part of a Process or System. For either of these, the Mechanism must be included in the pathway of a Process. There, it can be specified on its own, or as the first item of a tuple that also has an optional set of runtime parameters (see Process Mechanisms for additional details about specifying a Mechanism in a Process pathway).

Runtime Parameters¶

Note

This is an advanced feature, and is generally not required for most applications.

The parameters of a Mechanism are usually specified when the Mechanism is created. However, these can be overridden when it executed. This can be done in a parameter specification dictionary assigned to the runtime_param argument of the Mechanism’s execute method, or in a tuple with the Mechanism in the pathway of a Process. Any value assigned to a parameter in a runtime_params dictionary will override the current value of the parameter for that (and only that) execution of the Mechanism; the value will return to its previous value following that execution.

The runtime parameters for a Mechanism are specified using a dictionary that contains one or more entries, each of which is for a parameter of the Mechanism or its function, or for one of the Mechanism's States. Entries for parameters of the Mechanism or its function use the standard format for parameter specification dictionaries. Entries for the Mechanism’s States can be used to specify runtime parameters of the corresponding State, its function, or any of the Projections to that state. Each entry for the parameters of a State uses a key corresponding to the type of State (INPUT_STATE_PARAMS, OUTPUT_STATE_PARAMS or PARAMETER_STATE_PARAMS), and a value that is a sub-dictionary containing a dictionary with the runtime parameter specifications for all States of that type). Within that sub-dictionary, specification of parameters for the State or its function use the standard format for a parameter specification dictionary. Parameters for all of the State's Projections can be specified in an entry with the key PROJECTION_PARAMS, and a sub-dictionary that contains the parameter specifications; parameters for Projections of a particular type can be placed in an entry with a key specifying the type (MAPPING_PROJECTION_PARAMS, LEARNING_PROJECTION_PARAMS, CONTROL_PROJECTION_PARAMS, or GATING_PROJECTION_PARAMS; and parameters for a specific Projection can be placed in an entry with a key specifying the name of the Projection and a sub-dictionary with the specifications.

Class Reference¶

class psyneulink.core.components.mechanisms.mechanism.Mechanism_Base(default_variable=None, size=None, input_states=None, output_states=None, params=None, name=None, prefs=None, context=None, function=None)

Base class for Mechanism.

Note

Mechanism is an abstract class and should never be instantiated by a direct call to its constructor. It should be instantiated using the mechanism command (see it for description of parameters), by calling the constructor for a subclass, or using other methods for specifying a Mechanism in context (see Creating a Mechanism).

variable

at least ndarray : default self.defaults.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 a value of one of the Mechanism’s InputStates (in the order they are listed in its input_states attribute), and the first item (i.e., item 0) corresponding to the value of the primary InputState. 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’s function.

input_state

InputState : default default InputStateprimary InputState for the Mechanism; same as first entry of its input_states attribute. Its value is assigned as the first item of the Mechanism’s variable.

input_states

ContentAddressableList[str, InputState] – a list of the Mechanism’s InputStates. The first (and possibly only) entry is always the Mechanism’s primary InputState (i.e., the one in the its input_state attribute).

input_values

List[List or 1d np.array] : default self.defaults.variable – each item in the list corresponds to the value of one of the Mechanism’s InputStates listed in its input_states attribute. The value of each item is the same as the corresponding item in the Mechanism’s variable attribute. The latter is a 2d np.array; the input_values attribute provides this information in a simpler list format.

input_labels_dict

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 InputState(s) of the Mechanism; see Value Label Dictionaries for additional details.

input_labels

list – contains the labels corresponding to the value(s) of the InputState(s) of the Mechanism. If the current value of an InputState does not have a corresponding label, then its numeric value is used instead.

external_input_values

list – same as input_values, but containing the value only of InputStates that are not designated as internal_only.

parameter_states

ContentAddressableList[str, ParameterState] – a read-only list of the Mechanism’s ParameterStates, one for each of its configurable parameters, including those of its function. The value of the parameters of the Mechanism and its function are also accessible as (and can be modified using) attributes of the Mechanism (see ParameterStates and Parameters).

function

Function, function or method – 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’s value attribute.

function_params

Dict[str, value] – 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.

value

ndarray – output of the Mechanism’s function. It is always at least a 2d np.array, with the items of axis 0 corresponding to the values referenced by the corresponding index attribute of the Mechanism’s OutputStates. The first item is generally referenced by the Mechanism’s primary OutputState (i.e., the one in the its output_state attribute). The value is None until the Mechanism has been executed at least once.

Note

the value of a Mechanism is not necessarily the same as its output_values attribute, which lists the values of its OutputStates.

output_state

OutputStateprimary OutputState for the Mechanism; same as first entry of its output_states attribute.

output_states

ContentAddressableList[str, OutputState] – list of the Mechanism’s OutputStates.

There is always at least one entry, which identifies the Mechanism’s primary OutputState.

a list of the Mechanism’s OutputStates. The first (and possibly only) entry is always the Mechanism’s primary OutputState (i.e., the one in the its output_state attribute).

output_values

List[value] – each item in the list corresponds to the value of one of the Mechanism’s OutputStates listed in its output_states attribute.

Note

The output_values of a Mechanism is not necessarily the same as its value attribute, since an OutputState’s function and/or its assign attribute may use the Mechanism’s value to generate a derived quantity for the value of that OutputState (and its corresponding item in the the Mechanism’s output_values attribute).

output_labels_dict

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 OutputState(s) of the Mechanism; see Value Label Dictionaries for additional details.

output_labels

list – contains the labels corresponding to the value(s) of the OutputState(s) of the Mechanism. If the current value of an OutputState does not have a corresponding label, then its numeric value is used instead.

condition

Condition : None – condition to be associated with the Mechanism in the Scheduler responsible for executing it in each System 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 System by assigning a Condition for the Mechanism directly to a Scheduler that is then assigned to the System.

states

ContentAddressableList – a list of all of the Mechanism’s States, composed from its input_states, parameter_states, and output_states attributes.

projections

ContentAddressableList – a list of all of the Mechanism’s Projections, composed from the path_afferents of all of its input_states, the mod_afferents of all of its input_states, parameter_states, and output_states, and the efferents of all of its output_states.

afferents

ContentAddressableList – a list of all of the Mechanism’s afferent Projections, composed from the path_afferents of all of its input_states, and the mod_afferents of all of its input_states, parameter_states, and output_states.,

path_afferents

ContentAddressableList – a list of all of the Mechanism’s afferent PathwayProjections, composed from the path_afferents attributes of all of its input_states.

mod_afferents

ContentAddressableList – a list of all of the Mechanism’s afferent ModulatoryProjections, composed from the mod_afferents attributes of all of its input_states, parameter_states, and output_states.

efferents

ContentAddressableList – a list of all of the Mechanism’s efferent Projections, composed from the efferents attributes of all of its output_states.

senders

ContentAddressableList – 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 AdaptiveMechanisms (that send ModulatoryProjections (also see modulators).

modulators

ContentAddressableList – a list of all of the AdapativeMechanisms that send ModulatoryProjections to the Mechanism (i.e., the senders of its mod_afferents (also see senders).

receivers

ContentAddressableList – a list of all of the Mechanisms that receive Projections from the Mechanism (i.e., the receivers of its efferents.

processes

Dict[Process, str] – a dictionary of the Processes to which the Mechanism belongs, that designates its role in each. The key of each entry is a Process to which the Mechansim belongs, and its value is the Mechanism’s role in that Process.

systems

Dict[System, str] – a dictionary of the Systems to which the Mechanism belongs, that designates its role in each. The key of each entry is a System to which the Mechanism belongs, and its value is the Mechanism’s role in that System.

attributes_dict

Dict[keyword, value] – a dictionary containing the attributes (and their current values) that can be used to specify the variable of the Mechanism’s OutputState (see OutputState Customization).

name

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

prefs

PreferenceSet or specification dict – the PreferenceSet for the Mechanism; if it is not specified in the prefs argument of the constructor, a default is assigned using classPreferences defined in __init__.py (see PreferenceSet for details).

add_states(states)

Add one or more States to the Mechanism. Only InputStates and OutputStates can be added; ParameterStates cannot be added to a Mechanism after it has been constructed.

If the owner of a State specified in the states argument is not the same as the Mechanism to which it is being added an error is generated. If the name of a specified State is the same as an existing one with the same name, an index is appended to its name, and incremented for each State subsequently added with the same name (see naming conventions). If a specified State already belongs to the Mechanism, the request is ignored.

Note

Adding InputStates to a Mechanism changes the size of its variable attribute, which may produce an incompatibility with its function (see Mechanism InputStates for a more detailed explanation).

Parameters: states (State or List[State]) – one more InputStates or OutputStates to be added to the Mechanism. State specification(s) can be an InputState or OutputState object, class reference, class keyword, or State specification dictionary (the latter must have a STATE_TYPE entry specifying the class or keyword for InputState or OutputState). a dictionary with two entries, containing the list of InputStates and OutputStates added. (Returns) – ------- – with entries containing InputStates and/or OutputStates added (Dictionary) –
afferents

Return all afferent Projections

attributes_dict

Note – this needs to be updated each time it is called, as it must be able to report current values

efferents

Return list of all of the Mechanism’s Projections

execute(input=None, execution_id=None, runtime_params=None, context=None)

Carry out a single execution of the Mechanism.

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 InputState(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_states, and each item must be compatible with the format (number and type of elements) of the variable of the corresponding InputState (see Run Inputs for details of input specification formats). runtime_params (Optional[Dict[str, Dict[str, Dict[str, value]]]]:) – a dictionary that can include any of the parameters used as arguments to instantiate the Mechanism or its function. Any value assigned to a parameter will override the current value of that parameter for only the current execution of the Mechanism. When runtime_params are passed down from the Composition level Run method, parameters reset to their original values immediately following the execution during which runtime_params were used. When execute is called directly, (such as for debugging), runtime_params exhibit “lazy updating”: parameter values will not reset to their original values until the beginning of the next execution. Mechanism’s output_values – list with the value of each of the Mechanism’s OutputStates after either one TIME_STEP or a TRIAL. List[value]
initialize(value, execution_context=None)

Assign an initial value to the Mechanism’s value attribute and update its OutputStates.

Parameters: value (List[value] or 1d ndarray) – value used to initialize the first item of the Mechanism’s value attribute.
input_labels

Returns a list with as many items as there are InputStates of the Mechanism. Each list item represents the value of the corresponding InputState, and is populated by a string label (from the input_labels_dict) when one exists, and the numeric value otherwise.

is_finished(execution_context=None)

set by a Mechanism to signal completion of its execution in a trial; used by Component-based Conditions to predicate the execution of one or more other Components on the Mechanism.

mod_afferents

Return all of the Mechanism’s afferent modulatory Projections

modulators

Return all Mechanisms that send Projections to self

output_labels

Returns a list with as many items as there are OutputStates of the Mechanism. Each list item represents the value of the corresponding OutputState, and is populated by a string label (from the output_labels_dict) when one exists, and the numeric value otherwise.

path_afferents

Return list of path_afferent Projections to all of the Mechanism’s input_states

plot(x_range=None)

Generate a plot of the Mechanism’s function using the specified parameter values (see DDM.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’s function. 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] Plot of Mechanism’s function  – Matplotlib window of the Mechanism’s function plotted with specified parameters over the specified x_range Matplotlib window
projections

Return all Projections

receivers

Return all Mechanisms that send Projections to self

reinitialize(*args, execution_context=None)

If the mechanism’s function is an IntegratorFunction, or if the mechanism has and integrator_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 reassigns previous_value to None.

If the mechanism’s function is an IntegratorFunction, its reinitialize method:

1. Calls the function’s own reinitialize method (see Note below for details)
2. Sets the mechanism’s value to the output of the function’s reinitialize method
3. Updates its output states based on its new value

If the mechanism has an integrator_function, its reinitialize method:

(1) Calls the integrator_function's <TransferMechanism.integrator_function> own reinitialize
<IntegratorFunction.reinitialize> method (see Note below for details)

(2) Executes its function <Mechanism_Base.function> using the output of the integrator_function's
<TransferMechanism.integrator_function> reinitialize <IntegratorFunction.reinitialize> 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 states <Mechanism_Base.output_state> based on its new value
<Mechanism_Base.value>


Note

The reinitialize method of an IntegratorFunction Function typically resets the function’s previous_value (and any other stateful_attributes) and value to the quantity (or quantities) specified. If reinitialize is called without arguments, the initializer value (or the values of each of the attributes in initializers) is used instead. The reinitialize method may vary across different Integrators. See individual functions for details on their stateful_attributes, as well as other reinitialization steps that the reinitialize method may carry out.

remove_states(states)

Remove one or more States from the Mechanism. Only InputStates can be removed; ParameterStates cannot be removed from a Mechanism.

Each Specified state must be owned by the Mechanism, otherwise the request is ignored.

Note

Removing InputStates from a Mechanism changes the size of its variable attribute, which may produce an incompatibility with its function (see Mechanism InputStates for more detailed information).

Parameters: states (State or List[State]) – one more InputStates or OutputStates to be removed from the Mechanism. State specification(s) can be an InputState or OutputState object or the name of one.
run(inputs, num_trials=None, call_before_execution=None, call_after_execution=None)

Run a sequence of executions.

Parameters: inputs (List[input] or ndarray(input) : default default_variable) – the inputs used for each in a sequence of executions of the Mechanism (see Inputs for a detailed description of formatting requirements and options). num_trials (int) – number of trials to execute. call_before_execution (function : default None) – called before each execution of the Mechanism. call_after_execution (function : default None) – called after each execution of the Mechanism. Mechanism’s output_values – list with the value of each of the Mechanism’s OutputStates for each execution of the Mechanism. List[value]
senders

Return all Mechanisms that send Projections to self

show_structure(show_functions: bool = False, show_mech_function_params: bool = False, show_state_function_params: bool = False, show_values: bool = False, use_labels: bool = False, show_headers: bool = False, show_roles: bool = False, composition=None, compact_cim: bool = False, node_border: str = '1', output_fmt: <typecheck.tc_predicates.enum object at 0x114e6a5c0> = 'pdf')

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 as True when it is called.

Parameters: show_functions (bool : default False) – show the function of the Mechanism and each of its States. show_mech_function_params (bool : default False) – show the parameters of the Mechanism’s function if show_functions is True. show_state_function_params (bool : default False) – show parameters for the function of the Mechanism’s States if show_functions is True). show_values (bool : default False) – show the value of the Mechanism and each of its States (prefixed by “=”). use_labels (bool : default False) – use labels for values if show_values is True; labels must be specified in the input_labels_dict (for InputState values) and output_labels_dict (for OutputState values), otherwise the value is used. show_headers (bool : default False) – show the Mechanism, InputState, ParameterState and OutputState headers. show_roles (bool : default False) – show the roles of the Mechanism in the Composition specified in the composition argument (composition is not specified, show_roles 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 InputState fields for input_CIM and OutputState 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. HTML for structure (Example) – border="1" cellborder="0" cellspacing="0" bgcolor="tan"> <- MAIN TABLE (<) –
<- OUTPUTSTATES OUTER TABLE <- OUTPUTSTATES HEADER
OutputStates
<- OUTPUTSTATE CELLS TABLE
OutputState 1
function 1
=value
OutputState 2
function 2
=value
Mech name
Roles
<- PARAMETERSTATES OUTER TABLE <- PARAMETERSTATES HEADER
ParameterStates
<- PARAMETERSTATE CELLS TABLE
Param 1
function 1
= value
Param 2
function 2
= value
<- INPUTSTATES OUTER TABLE <- INPUTSTATES HEADER
InputStates
<- INPUTSTATE CELLS TABLE
InputState 1
function 1
= value
InputState 2
function 2
= value
– <- BEGIN MECHANISM & PARAMETERSTATES () – <- MECHANISM CELL (OUTERMOST TABLE) – <- BEGIN INPUTSTATES () – – > –
states`

Return list of all of the Mechanism’s States