# Component¶

Subclasses

## Overview¶

Component is the base class for all of the objects used to create Compositions in PsyNeuLink. It defines a common set of attributes possessed, and methods used by all Component objects.

## Creating a Component¶

A Component is never created by calling the constructor for the Component base class. However, its __init__() method is always called when a Component subclass is instantiated; that, in turn, calls a standard set of methods (listed below) as part of the initialization procedure. Every Component has a core set of configurable parameters that can be specified in the arguments of the constructor, as well as additional parameters and attributes that may be specific to particular Components, many of which can be modified by the user, and some of which provide useful information about the Component (see Parameters and Informational Attributes below).

### Deferred Initialization¶

If information necessary to complete initialization is not specified in the constructor (e.g, the owner for a Port, or the sender or receiver for a Projection), then its full initialization is deferred until its the information is available (e.g., the Port is assigned to a Mechanism, or a Projection is assigned its sender and receiver). This allows Components to be created before all of the information they require is available (e.g., at the beginning of a script). However, for the Component to be operational, its initialization must be completed by a call to it deferred_init method. This is usually done automatically when the Component is assigned to another Component to which it belongs (e.g., assigning a Port to a Mechanism) or to a Composition (e.g., a Projection to the pathway) of a Process), as appropriate.

## Component Structure¶

### Core Structural Attributes¶

Every Component has the following set of core structural attributes. These attributes are not meant to be changed by the user once the component is constructed, with the one exception of prefs.

• componentType - species the type of Component.

• variable - used as the input to its function. Specification of the default_variable argument in the constructor for a Component determines both its format (e.g., whether its value is numeric, its dimensionality and shape if it is an array, etc.) as well as its default value (the value used when the Component is executed and no input is provided), and takes precedence over the specification of size.

Note

Internally, the attribute variable is not directly used as input to functions, to allow for parallelization. The attribute is maintained as a way for the user to monitor variable along the execution chain. During parallelization however, the attribute may not accurately represent the most current value of variable being used, due to asynchrony inherent to parallelization.

• size - the dimension of the variable attribute. The size argument of the constructor for a Component can be used as a convenient method for specifying the variable, attribute in which case it will be assigned as an array of zeros of the specified size. For example, setting size = 3 is equivalent to setting variable = [0, 0, 0] and setting size = [4, 3] is equivalent to setting variable = [[0, 0, 0, 0], [0, 0, 0]].

• function - determines the computation that a Component carries out. It is always a PsyNeuLink Function object (itself also a PsyNeuLink Component).

Note

The function of a Component can be assigned either a Function object or any other callable object in python. If the latter is assigned, it is “wrapped” in a UserDefinedFunction.

All Components have a default function (with a default set of parameters), that is used if it is not otherwise specified. The function can be specified in the function argument of the constructor for the Component, using one of the following:

• class - this must be a subclass of Function, as in the following example:

my_component = SomeComponent(function=SomeFunction)


This will create a default instance of the specified subclass, using default values for its parameters.

• Function - this can be either an existing Function object or the constructor for one, as in the following examples:

my_component = SomeComponent(function=SomeFunction)

or

some_function = SomeFunction(some_param=1)
my_component = SomeComponent(some_function)


The specified Function will be used as a template to create a new Function object that is assigned to the function attribute of the Component.

Note

In the current implementation of PsyNeuLink, if a Function object (or the constructor for one) is used to specify the function attribute of a Component, the Function object specified (or created) will only itself be assigned to the Component if it does not already belong to another Component. Otherwise, it is copied, and the copy is assigned to the Component. This is so that Functions can be used as templates for more than one Component, without being assigned simultaneously to multiple Components.

A function can also be specified in an entry of a parameter specification dictionary assigned to the params argument of the constructor for the Component, with the keyword FUNCTION as its key, and one of the specifications above as its value, as in the following example:

my_component = SomeComponent(params={FUNCTION:SomeFunction(some_param=1)})

• name - the name attribute contains the name assigned to the Component when it was created. If it was not specified, a default is assigned by the registry for subclass (see Naming for conventions used in assigning default names and handling of duplicate names).

• prefs - the prefs attribute contains the PreferenceSet assigned to the Component when it was created. If it was not specified, a default is assigned using classPreferences defined in BasePreferences Each individual preference is accessible as an attribute of the Component, the name of which is the name of the preference (see Preferences for details).

### Parameters¶

A Component defines its parameters in its parameters attribute, which contains a collection of Parameter objects, each of which stores a Parameter’s values, default values, and various properties of the parameter.

• initial_shared_parameters - the initial_shared_parameters attribute contains a dictionary of any parameters for the Component’s functions or attributes, to be used to instantiate the corresponding object. Each entry is the name of a parameter, and its value is the value of that parameter. The parameters for a function can be specified when the Component is created in one of the following ways:

• in an argument of the Component’s constructor – if all of the allowable functions for a Component’s function share some or all of their parameters in common, the shared paramters may appear as arguments in the constructor of the Component itself, which can be used to set their values.

• in an entry of a parameter specification dictionary assigned to the params argument of the constructor for the Component. The entry must use the keyword FUNCTION_PARAMS as its key, and its value must be a dictionary containing the parameters and their values. The key for each entry in the FUNCTION_PARAMS dictionary must be the name of a parameter, and its value the parameter’s value, as in the example below:

my_component = SomeComponent(function=SomeFunction
params={FUNCTION_PARAMS:{SOME_PARAM=1, SOME_OTHER_PARAM=2}})


The parameters of functions for some Components may allow other forms of specification (see Specifying Parameters for details concerning different ways in which the value of a parameter can be specified).

• reset_params - reset the value of all parameters to a set of default values as specified in its mode argument, using a value of ResetMode.

## Execution¶

A Component is executed when its execute method is called, which in turn calls its function.

### Lazy Updating¶

In general, only Compositions are executed from the command line (i.e., from the console or in a script). Mechanisms can also be executed, although this is usually just for the purposes of demonstration or debugging, and Functions can only be executed if they are standalone (that is, they do not belong to another Component). All other Components are executed only a Component that depends on them to do so. This can be one to which a Components belongs (such as the Mechanism to which a Port belongs) or that otherwise requires it to execute (for example, a updating a Port requires its afferent Projections to execute). This is referred to as “lazy updating”, since it means that most Components don’t execute unless and until they are required to do so. While this reduces unecessary computation, it can sometimes be confusing. For example, when learning occurs in a Composition, the modification to the matrix parameter of a MappingProjection that occurs on a given TRIAL does not acutally appear in its value until the next TRIAL, since it requires that the ParameterPort for the matrix be executed, which does not occur until the next time the MappingProjection is executed (i.e., in the next TRIAL). Therefore, in tracking the value of Components during execution, it is important to carefully consider the state of execution of the Components to which they belong or on which they depend for execution.

The following attributes and methods control and provide information about the execution of a Component:

### Termination¶

• num_executions_before_finished – contains the number of times the Component has executed prior to finishing (and since it last finished); depending upon the class, these may all be within a single call to the Component’s execute method, or extend over several calls. It is set to 0 each time is_finished evalutes to True. Note that this is distinct from the execution_count and num_executions attributes.

### Count and Time¶

• execution_count – maintains a record of the number of times a Component has executed since it was constructed, excluding executions carried out during initialization and validation, but including all others whether they are of the Component on its own are as part of a Composition, and irresective of the context in which they are occur. The value can be changed “manually” or programmatically by assigning an integer value directly to the attribute. Note that this is the distinct from the num_executions and num_executions_before_finished attributes.

## Class Reference¶

class psyneulink.core.components.component.Component(default_variable=None, size=None, params=None, name=None, prefs=None, context=None)

Base class for Component.

The arguments below are ones that can be used in the constructor for any Component subclass.

Note

Component is an abstract class and should never be instantiated by a direct call to its constructor. It should be instantiated using the constructor for a subclass.

Parameters
• default_variable (scalar, list or array : default [[0]]) – specifies template for the input to the Component’s function.

• size (int, list or np.ndarray of 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 takes precedence over the specification of size (see size for additonal details).

• params (Dict[param keyword: param value] : default None) – a parameter dictionary that can be used to specify the parameters for the Component and/or a custom function and its parameters. Values specified for parameters in the dictionary override any assigned to those parameters in arguments of the constructor.

• name (str : for default see name) – a string used for the name of the Component; default is assigned by relevant Registry for Component (see Naming for conventions used for default and duplicate names).

• prefs (PreferenceSet or specification dict : default Component.classPreferences) – specifies the PreferenceSet for the Component (see prefs for details).

• context (Context : default None) – specifies context in which Component is being initialized or executed.

variable

see variable

Type

2d np.array

size

see size

Type

int or array of ints

function

see function

Type

Function, function or method

value

see value

Type

2d np.array

log

see log

Type

Log

execution_count
Type

int

num_executions

see num_executions

Type

Time

current_execution_time
Type

tuple(Time.RUN, Time.TRIAL, Time.PASS, Time.TIME_STEP)

execute_until_finished
Type

bool

num_executions_before_finished
Type

int

max_executions_before_finished
Type

bool

stateful_parameters
Type

list

reset_stateful_function_when
Type

Condition

name

see name

Type

str

prefs

see prefs

Type

PreferenceSet

parameters

see parameters and Parameters for additional information.

Type

Parameters

defaults

an object that provides access to the default values of a Component's parameters; see parameter defaults for additional information.

Type

Defaults

initialization_status

indicates the state of initialization of the Component; one and only one of the following flags is always set:

Type

field of flags attribute

_model_spec_generic_type_name = NotImplemented

string describing this class’s generic type in universal model specification, if it exists and is different than the class name

_model_spec_class_name_is_generic = False

True if the class name is the class’s generic type in universal model specification, False otherwise

_specified_variable_shape_flexibility = 1

The DefaultsFlexibility ._variable_shape_flexibility takes on when variable shape was manually specified

_handle_default_variable(default_variable=None, size=None)

Finds whether default_variable can be determined using default_variable and size arguments.

Returns

• a default variable if possible

• None otherwise

_handle_size(size, variable)

If variable is None, _handle_size tries to infer variable based on the size argument to the __init__() function. This method is overwritten in subclasses like Mechanism and Port. If self is a Mechanism, it converts variable to a 2D array, (for a Mechanism, variable[i] represents the input from the i-th InputPort). If self is a Port, variable is a 1D array and size is a length-1 1D array. It performs some validations on size and variable as well. This function is overridden in Port.py. If size is NotImplemented (usually in the case of Projections/Functions), then this function passes without doing anything. Be aware that if size is NotImplemented, then variable is never cast to a particular shape.

_deferred_init(**kwargs)

Use in subclasses that require deferred initialization

_check_args(variable=None, params=None, context=None, target_set=None)

validate variable and params, instantiate variable (if necessary) and assign any runtime params.

Called by functions to validate variable and params Validation can be suppressed by turning parameter_validation attribute off target_set is a params dictionary to which params should be assigned;

Does the following: - instantiate variable (if missing or callable) - validate variable if PARAM_VALIDATION is set - resets leftover runtime params back to original values (only if execute method was called directly) - sets runtime params - validate params if PARAM_VALIDATION is set

Parameters
• variable – (anything but a dict) - variable to validate

• params – (dict) - params to validate

Target_set

(dict) - set to which params should be assigned

Returns

_validate_and_assign_runtime_params(runtime_params, context)

Validate runtime_params, cache for reset, and assign values

Check that all params belong either to Component or its function (raise error if any are found that don’t) Cache params to reset in _runtime_params_reset

_instantiate_defaults(variable=None, request_set=None, assign_missing=True, target_set=None, default_set=None, context=None)

Validate variable and/or param defaults in requested set and assign values to params in target set

Variable can be any type other than a dictionary (reserved for use as params) request_set must contain a dict of params to be assigned to target_set If assign_missing option is set, then any params defined for the class

but not included in the requested set are assigned values from the default_set; if request_set is None, then all values in the target_set are assigned from the default_set

Class defaults can not be passed as target_set
IMPLEMENTATION NOTE: for now, treating class defaults as hard coded;

could be changed in the future simply by commenting out code below

If not context: instantiates function and any ports specified in request set

(if they have changed from the previous value(s))

Parameters
• variable – (anything but a dict (variable) - value to assign as defaults.variable

• request_set – (dict) - params to be assigned

• assign_missing – (bool) - controls whether missing params are set to default_set values (default: False)

• target_set – (dict) - param set to which assignments should be made

• default_set – (dict) - values used for params missing from request_set (only if assign_missing is True)

Returns

_instantiate_parameter_classes(context=None)

An optional method that will take any Parameter values in context that are classes/types, and instantiate them.

reset_params(mode=<ResetMode.INSTANCE_TO_CLASS: 1>, context=None)

Reset current and/or instance defaults

If called with:
• CURRENT_TO_INSTANCE_DEFAULTS all current param settings are set to instance defaults

• INSTANCE_TO_CLASS all instance defaults are set to class defaults

• ALL_TO_CLASS_DEFAULTS all current and instance param settings are set to class defaults

Parameters

mode – (ResetMode) - determines which params are reset

Return none

_set_multiple_parameter_values(context, **kwargs)

Unnecessary, but can simplify multiple parameter assignments at once For every kwarg k, v pair, will attempt to set self.parameters.<k> to v for context

_parse_arg_generic(arg_val)

Argument parser for any argument that does not have a specialized parser

_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

_parse_function_variable(variable, context=None)

Parses the variable passed in to a Component into a function_variable that can be used with the Function associated with this Component

_validate(context=None)

Eventually should contain all validation methods, occurs at end of Component.__init__

_validate_variable(variable, context=None)

Validate variable and return validated variable

Convert self.class_defaults.variable specification and variable (if specified) to list of 1D np.ndarrays:

VARIABLE SPECIFICATION: ENCODING: Simple value variable: 0 -> [array([0])] Single state array (vector) variable: [0, 1] -> [array([0, 1])] Multiple port variables, each with a single value variable: [[0], [0]] -> [array[0], array[0]]

Perform top-level type validation of variable against the self.class_defaults.variable;

if the type is OK, the value is returned (which should be used by the function)

This can be overridden by a subclass to perform more detailed checking (e.g., range, recursive, etc.) It is called only if the parameter_validation attribute is True (which it is by default)

IMPLEMENTATION NOTES:
• future versions should add hierarchical/recursive content (e.g., range) checking

• add request/target pattern?? (as per _validate_params) and return validated variable?

Parameters
• variable – (anything other than a dictionary) - variable to be validated:

• context – (str)

Return variable

validated variable

_validate_params(request_set, target_set=None, context=None)

Validate params and assign validated values to targets,

This performs top-level type validation of params

This can be overridden by a subclass to perform more detailed checking (e.g., range, recursive, etc.) It is called only if the parameter_validation attribute is True (which it is by default)

IMPLEMENTATION NOTES:
• future versions should add recursive and content (e.g., range) checking

• should method return validated param set?

Parameters
• (request_set) - set of params to be validated (dict) –

• (target_set) - repository of params that have been validated (dict) –

Return none

_get_param_value_from_tuple(param_spec)

Returns param value (first item) of a (value, projection) tuple;

_validate_function(function, context=None)

Check that either params[FUNCTION] and/or self.execute are implemented

# FROM _validate_params: # It also checks FUNCTION: # if it is specified and is a type reference (rather than an instance), # it instantiates the reference (using FUNCTION_PARAMS if present) # and puts a reference to the instance in target_set[FUNCTION] # This checks for an execute method in function If a specification is not present or valid:

• it checks self.execute and, if present, kwExecute is assigned to it

• if self.execute is not present or valid, an exception is raised

When completed, there is guaranteed to be a valid method in self.function and/or self.execute;

otherwise, an exception is raised

Notes

• no new assignments (to FUNCTION or self.execute) are made here, except:

• if FUNCTION is missing, it is assigned to self.execute (if it is present)

• no instantiations are done here;

• any assignment(s) to and/or instantiation(s) of self.execute and/or params[FUNCTION]

is/are carried out in _instantiate_function

Returns

_instantiate_function(function, function_params=None, context=None)

Instantiate function defined in <subclass>.function or <subclass>.function

Instantiate params[FUNCTION] if present, and assign it to self.function

If params[FUNCTION] is present and valid,

it is assigned as the function’s execute method, overriding any direct implementation of self.function

If FUNCTION IS in params:
• if it is a Function object, it is simply assigned to self.function;

• if it is a Function class reference:

it is instantiated using self.defaults.variable and, if present, params[FUNCTION_PARAMS]

If FUNCTION IS NOT in params:
• if self.function IS implemented, it is assigned to params[FUNCTION]

• if self.function IS NOT implemented: program error (should have been caught in _validate_function)

Upon successful completion:
• self._function === self.function

• self.execute should always return the output of self.function in the first item of its output array;

this is done by Function.execute; any subclass override should do the same, so that…

• value is value[0] returned by self.execute

_check_for_composition(context=None)

Allow Component to check whether it or its attributes are suitable for inclusion in a Composition Called by Composition.add_node.

reset(*args, context=None, **kwargs)

If the component’s execute method involves execution of an IntegratorFunction Function, this method effectively begins the function’s accumulation over again at the specified value, and may update related values on the component, depending on the component type. Otherwise, it simply reassigns the Component’s value based on its default_variable.

execute(variable=None, context=None, runtime_params=None)

Executes Component’s function. See Component-specific execute method for details.

is_finished(context=None)

Set by a Component 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 a Component.

property loggable_items

Diciontary of items that can be logged in the Component’s log and their current ContextFlags. This is a convenience method that calls the loggable_items property of the Component’s log.

set_log_conditions(items log_condition=EXECUTION)

Specifies items to be logged; these must be be loggable_items of the Component’s log. This is a convenience method that calls the set_log_conditions method of the Component’s log.

set_delivery_conditions(items, delivery_condition=<LogCondition.EXECUTION: 896>)

_set_delivery_conditions( items delivery_condition=EXECUTION )

Specifies items to be delivered to external application via gRPC; these must be be loggable_items of the Component’s log. This is a convenience method that calls the _set_delivery_conditions method of the Component’s log.

log_values(entries)

Specifies items to be logged; ; these must be be loggable_items of the Component’s log. This is a convenience method that calls the log_values method of the Component’s log.

property logged_items

Dictionary of all items that have entries in the log, and their currently assigned ContextFlagss This is a convenience method that calls the logged_items property of the Component’s log.

property stateful_parameters

A list of all of this object’s parameters whose values may change during runtime

property function_parameters

The parameters object of this object’s function

property _parameter_components

Returns a set of Components that are values of this object’s Parameters

property _dependent_components

Returns a set of Components that will be executed if this Component is executed

property most_recent_context

used to set a default behavior for attributes that correspond to parameters

property _model_spec_parameter_blacklist

A set of Parameter names that should not be added to the generated constructor string