Skip to content

Commit

Permalink
Parameters: assume context argument to _set is a Context argument
Browse files Browse the repository at this point in the history
	- separates internal and external calls logically
    - speed improvement
  • Loading branch information
kmantel committed Sep 12, 2019
1 parent a8b11ba commit 02a0def
Show file tree
Hide file tree
Showing 15 changed files with 42 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
INTEGRATOR_FUNCTION, INTEGRATOR_FUNCTION_TYPE
from psyneulink.core.globals.parameters import Parameter
from psyneulink.core.globals.utilities import parameter_spec, all_within_range, iscompatible
from psyneulink.core.globals.context import ContextFlags, handle_external_context
from psyneulink.core.globals.context import Context, ContextFlags, handle_external_context
from psyneulink.core.globals.preferences.componentpreferenceset import is_pref_set


Expand Down Expand Up @@ -2811,7 +2811,7 @@ def __init__(self,
params=params)

# Assign here as default, for use in initialization of function
self.parameters.previous_value._set(initializer)
self.parameters.previous_value._set(initializer, Context())
self.previous_time = starting_point

super().__init__(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -742,8 +742,8 @@ def __init__(self,
)

if self.previous_value.size != 0:
self.parameters.key_size._set(len(self.previous_value[KEYS][0]))
self.parameters.val_size._set(len(self.previous_value[VALS][0]))
self.parameters.key_size._set(len(self.previous_value[KEYS][0]), Context())
self.parameters.val_size._set(len(self.previous_value[VALS][0]), Context())

self.has_initializers = True
self.stateful_attributes = ["previous_value", "random_state"]
Expand Down Expand Up @@ -976,10 +976,10 @@ def _validate(self, context=None):
fct_msg = 'Function type'
else:
distance_function.defaults.variable = test_var
distance_function._instantiate_value()
distance_function._instantiate_value(context)
fct_msg = 'Function'
try:
distance_result = distance_function(test_var)
distance_result = distance_function(test_var, context=context)
if not np.isscalar(distance_result):
raise FunctionError("Value returned by {} specified for {} ({}) must return a scalar".
format(repr(DISTANCE_FUNCTION), self.__name__.__class__, distance_result))
Expand All @@ -995,14 +995,14 @@ def _validate(self, context=None):
else np.zeros_like(distance_result)
for i in range(self.get_current_function_param('max_entries', context))])
if isinstance(selection_function, type):
selection_function = selection_function(default_variable=test_var)
selection_function = selection_function(default_variable=test_var, context=context)
fct_string = 'Function type'
else:
selection_function.defaults.variable = test_var
selection_function._instantiate_value()
selection_function._instantiate_value(context)
fct_string = 'Function'
try:
result = np.asarray(selection_function(test_var))
result = np.asarray(selection_function(test_var, context=context))
except e:
raise FunctionError(f'{fct_string} specified for {repr(SELECTION_FUNCTION)} arg of {self.__class__} '
f'({selection_function}) must accept a 1d array as its argument')
Expand Down Expand Up @@ -1040,10 +1040,10 @@ def _instantiate_attributes_before_function(self, function=None, context=None):
self.has_initializers = True

if isinstance(self.distance_function, type):
self.distance_function = self.distance_function()
self.distance_function = self.distance_function(context=context)

if isinstance(self.selection_function, type):
self.selection_function = self.selection_function()
self.selection_function = self.selection_function(context=context)

@handle_external_context(execution_id=NotImplemented)
def reinitialize(self, *args, context=None):
Expand Down
4 changes: 2 additions & 2 deletions psyneulink/core/components/functions/userdefinedfunction.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,10 +496,10 @@ def _instantiate_attributes_before_function(self, function=None, context=None):
if attr_value is None:
attr_value = p.default_value

p._set(attr_value, skip_history=True)
p._set(attr_value, context, skip_history=True)
delattr(self, attr_name)
except AttributeError:
p._set(p.default_value, skip_history=True)
p._set(p.default_value, context, skip_history=True)

def _function(self, variable, context=None, **kwargs):

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1297,7 +1297,7 @@ def _instantiate_modulatory_signals(self, context):
# For DefaultAllocationFunction, set defaults.value to have number of items equal to num modulatory_signals
if isinstance(self.function, DefaultAllocationFunction):
self.defaults.value = np.tile(self.function.value, (num_modulatory_signals, 1))
self.parameters.modulatory_allocation._set(copy.deepcopy(self.defaults.value))
self.parameters.modulatory_allocation._set(copy.deepcopy(self.defaults.value), context)
self.function.num_modulatory_signals = num_modulatory_signals

# For other functions, assume that if its value has:
Expand All @@ -1308,7 +1308,7 @@ def _instantiate_modulatory_signals(self, context):
# leave things alone, and allow any errant indices for modulatory_signals to be caught later.
else:
self.defaults.value = np.array(self.function.value)
self.parameters.value._set(copy.deepcopy(self.defaults.value))
self.parameters.value._set(copy.deepcopy(self.defaults.value), context)

len_fct_value = len(self.function.value)

Expand Down
3 changes: 0 additions & 3 deletions psyneulink/core/components/mechanisms/mechanism.py
Original file line number Diff line number Diff line change
Expand Up @@ -2157,9 +2157,6 @@ def reinitialize(self, *args, context=None):
raise MechanismError("Reinitializing {} is not allowed because this Mechanism is not stateful. "
"(It does not have an accumulator to reinitialize).".format(self.name))

# if hasattr(self, PREVIOUS_VALUE):
# self.parameters.previous_value._set(None)

def get_current_mechanism_param(self, param_name, context=None):
if param_name == "variable":
raise MechanismError("The method 'get_current_mechanism_param' is intended for retrieving the current "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1151,10 +1151,6 @@ def _instantiate_parameter_states(self, function=None, context=None):
super()._instantiate_parameter_states(function=function, context=context)

def _instantiate_attributes_before_function(self, function=None, context=None):

# if self.integrator_mode:
# self.parameters.previous_value._set(None)

super()._instantiate_attributes_before_function(function=function, context=context)

if self.initial_value is None:
Expand Down
2 changes: 1 addition & 1 deletion psyneulink/core/components/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -2697,7 +2697,7 @@ def __init__(self, owner=None, variable=None, name=None, prefs=None):
self.parameters = self.Parameters(owner=self, parent=self.class_parameters)
self.defaults = Defaults(owner=self, variable=variable, value=variable)

self.parameters.value._set(variable)
self.parameters.value._set(variable, Context())

# self.index = PRIMARY
# self.assign = None
Expand Down
2 changes: 1 addition & 1 deletion psyneulink/core/components/states/inputstate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1394,7 +1394,7 @@ def _instantiate_input_states(owner, input_states=None, reference_value=None, co
for state in owner._input_states:
# Assign True for owner's primary InputState and the value has not already been set in InputState constructor
if state.require_projection_in_composition is None and owner.input_state == state:
state.parameters.require_projection_in_composition._set(True)
state.parameters.require_projection_in_composition._set(True, context)

# Check that number of input_states and their variables are consistent with owner.defaults.variable,
# and adjust the latter if not
Expand Down
2 changes: 1 addition & 1 deletion psyneulink/core/components/states/outputstate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1520,7 +1520,7 @@ def _instantiate_output_states(owner, output_states=None, context=None):
for state in owner._output_states:
# Assign True for owner's primary OutputState and the value has not already been set in OutputState constructor
if state.require_projection_in_composition is None and owner.output_state == state:
state.parameters.require_projection_in_composition._set(True)
state.parameters.require_projection_in_composition._set(True, context)

return state_list

Expand Down
2 changes: 1 addition & 1 deletion psyneulink/core/components/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -5046,7 +5046,7 @@ def __init__(self, owner=None, variable=None, name=None, prefs=None, context=Non
self.parameters = self.Parameters(owner=self, parent=self.class_parameters)
self.defaults = Defaults(owner=self, variable=variable, value=variable)

self.parameters.value._set(variable)
self.parameters.value._set(variable, context)

@property
def _dependent_components(self):
Expand Down
22 changes: 15 additions & 7 deletions psyneulink/core/globals/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -902,21 +902,29 @@ def set(self, value, context=None, override=False, skip_history=False, skip_log=

self._set(value, context, skip_history, skip_log, _ro_warning_stacklevel, **kwargs)

@handle_external_context()
def _set(self, value, context=None, skip_history=False, skip_log=False, _ro_warning_stacklevel=2, **kwargs):
if not self.stateful:
execution_id = None
else:
try:
execution_id = context.execution_id
except AttributeError as e:
raise ParameterError(
'_set must pass in a Context object as the context '
'argument. To set parameter values using only an '
'execution id, use set.'
) from e

if self.setter is not None:
kwargs = {
**self._default_setter_kwargs,
**kwargs
}
value = call_with_pruned_args(self.setter, value, context=context, **kwargs)

self._set_value(value, context=context, skip_history=skip_history, skip_log=skip_log)

def _set_value(self, value, execution_id=NotImplemented, context=None, skip_history=False, skip_log=False):
if execution_id is NotImplemented:
execution_id = context.execution_id
self._set_value(value, execution_id=execution_id, context=context, skip_history=skip_history, skip_log=skip_log)

def _set_value(self, value, execution_id=None, context=None, skip_history=False, skip_log=False):
# store history
if not skip_history:
if execution_id in self.values:
Expand All @@ -930,7 +938,7 @@ def _set_value(self, value, execution_id=NotImplemented, context=None, skip_hist
self._log_value(value, context)

# set value
self.values[context.execution_id] = value
self.values[execution_id] = value

@handle_external_context()
def delete(self, context=None):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -935,7 +935,7 @@ def _instantiate_modulatory_signals(self, context):
modulatory_signal._variable_spec = (OWNER_VALUE, i)
self._modulatory_signals[i] = modulatory_signal
self.defaults.value = np.tile(modulatory_signal.parameters.variable.default_value, (i+1, 1))
self.parameters.control_allocation._set(copy.deepcopy(self.defaults.value))
self.parameters.control_allocation._set(copy.deepcopy(self.defaults.value), context)

def _instantiate_prediction_mechanisms(self, system:System_Base, context=None):
"""Add prediction Mechanism and associated process for each `ORIGIN` (input) Mechanism in system
Expand Down Expand Up @@ -1076,7 +1076,7 @@ def _instantiate_prediction_mechanisms(self, system:System_Base, context=None):
predicted_input = {}
for i, origin_mech in zip(range(len(system.origin_mechanisms)), system.origin_mechanisms):
predicted_input[origin_mech] = system.processes[i].origin_mechanisms[0].defaults.variable
self.parameters.predicted_input._set(predicted_input)
self.parameters.predicted_input._set(predicted_input, context)

def _instantiate_attributes_after_function(self, context=None):
"""Validate cost function"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@
from psyneulink.core.components.states.inputstate import InputState
from psyneulink.core.components.states.outputstate import OutputState, PRIMARY, StandardOutputStates
from psyneulink.core.components.states.state import _parse_state_spec
from psyneulink.core.globals.context import ContextFlags
from psyneulink.core.globals.context import Context, ContextFlags
from psyneulink.core.globals.keywords import COMPARATOR_MECHANISM, FUNCTION, INPUT_STATES, NAME, OUTCOME, SAMPLE, TARGET, VARIABLE, kwPreferenceSetName
from psyneulink.core.globals.parameters import Parameter
from psyneulink.core.globals.preferences.componentpreferenceset import is_pref_set, kpReportOutputPref
Expand Down Expand Up @@ -404,7 +404,7 @@ def __init__(self,
)

# Require Projection to TARGET InputState (already required for SAMPLE as primary InputState)
self.input_states[1].parameters.require_projection_in_composition._set(True)
self.input_states[1].parameters.require_projection_in_composition._set(True, Context())

def _validate_params(self, request_set, target_set=None, context=None):
"""If sample and target values are specified, validate that they are compatible
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1294,15 +1294,15 @@ def _execute(self,
# all to zeros with size of Mechanism's array
# Should be OK to use attributes here because initialization should only occur during None context
self._set_multiple_parameter_values(
None,
context,
initial_value=self.input_states[RECURRENT].socket_template,
current_activity=self.input_states[RECURRENT].socket_template,
minus_phase_activity=self.input_states[RECURRENT].socket_template,
plus_phase_activity=self.input_states[RECURRENT].socket_template,
execution_phase=None,
)
if self._target_included:
self.parameters.output_activity._set(self.input_states[TARGET].socket_template)
self.parameters.output_activity._set(self.input_states[TARGET].socket_template, context)

# Initialize execution_phase as minus_phase
if self.parameters.execution_phase._get(context) is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1127,7 +1127,7 @@ def _instantiate_attributes_before_function(self, function=None, context=None):
hetero were None in the initialization call.
:param function:
"""
self.parameters.previous_value._set(None)
self.parameters.previous_value._set(None, context)

super()._instantiate_attributes_before_function(function=function, context=context)

Expand Down Expand Up @@ -1155,7 +1155,7 @@ def _instantiate_attributes_before_function(self, function=None, context=None):
matrix = hetero.copy()
np.fill_diagonal(matrix, diag)

self.parameters.matrix._set(matrix)
self.parameters.matrix._set(matrix, context)

# 9/23/17 JDC: DOESN'T matrix arg default to something?
# If no matrix was specified, then both AUTO and HETERO must be specified
Expand Down

0 comments on commit 02a0def

Please sign in to comment.