Skip to content

Commit

Permalink
Merge pull request #1725 from PrincetonUniversity/devel
Browse files Browse the repository at this point in the history
Devel
  • Loading branch information
dillontsmith authored Jul 22, 2020
2 parents 16e9407 + 0aa4ea4 commit 001a7a6
Show file tree
Hide file tree
Showing 53 changed files with 257 additions and 269 deletions.
39 changes: 18 additions & 21 deletions psyneulink/core/components/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -1884,7 +1884,7 @@ def _initialize_parameters(self, context=None, **param_defaults):
# assign defaults based on pass in params and class defaults
defaults = {
k: v for (k, v) in self.class_defaults.values(show_all=True).items()
if not k in alias_names
if k not in alias_names
}

if param_defaults is not None:
Expand Down Expand Up @@ -1945,25 +1945,22 @@ def _is_user_specified(parameter):
and param_defaults[parameter.name] is not None
)

for p in self.parameters:
p._user_specified = _is_user_specified(p)

if isinstance(p, ParameterAlias):
if p._user_specified:
if _is_user_specified(p.source):
if param_defaults[p.name] is not param_defaults[p.source.name]:
raise ComponentError(
f"Multiple values ({p.name}: {param_defaults[p.name]}"
f"\t{p.source.name}: {param_defaults[p.source.name]} "
f"assigned to identical Parameters. {p.name} is an alias "
f"of {p.source.name}",
component=self,
)

else:
param_defaults[p.source.name] = param_defaults[p.name]
for p in filter(lambda x: isinstance(x, ParameterAlias), self.parameters):
if _is_user_specified(p):
if _is_user_specified(p.source):
if param_defaults[p.name] is not param_defaults[p.source.name]:
raise ComponentError(
f"Multiple values ({p.name}: {param_defaults[p.name]}"
f"\t{p.source.name}: {param_defaults[p.source.name]} "
f"assigned to identical Parameters. {p.name} is an alias "
f"of {p.source.name}",
component=self,
)
else:
param_defaults[p.source.name] = param_defaults[p.name]

continue
for p in filter(lambda x: not isinstance(x, ParameterAlias), self.parameters):
p._user_specified = _is_user_specified(p)

# copy spec so it is not overwritten later
# TODO: check if this is necessary
Expand Down Expand Up @@ -2311,7 +2308,7 @@ def _validate_params(self, request_set, target_set=None, context=None):
# setattr(self, "_"+param_name, param_value)

# Check that param is in self.defaults (if not, it is assumed to be invalid for this object)
if not param_name in self.defaults.names(show_all=True):
if param_name not in self.defaults.names(show_all=True):
continue

# The default value of the param is None: suppress type checking
Expand Down Expand Up @@ -2538,7 +2535,7 @@ def _get_param_value_for_modulatory_spec(self, param_name, param_value):
else:
raise ComponentError("PROGRAM ERROR: got {} instead of string, Component, or Class".format(param_value))

if not param_spec in MODULATORY_SPEC_KEYWORDS:
if param_spec not in MODULATORY_SPEC_KEYWORDS:
return(param_value)

try:
Expand Down
2 changes: 1 addition & 1 deletion psyneulink/core/components/functions/objectivefunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,7 @@ def _function(self,
else:
assert False, '{} not a recognized metric in {}'.format(self.metric, self.__class__.__name__)

if self.normalize and not self.metric in {MAX_ABS_DIFF, CORRELATION}:
if self.normalize and self.metric not in {MAX_ABS_DIFF, CORRELATION}:
if self.metric == ENERGY:
result /= len(v1) ** 2
else:
Expand Down
5 changes: 5 additions & 0 deletions psyneulink/core/components/functions/optimizationfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@
#
# ****************************************** OPTIMIZATION FUNCTIONS **************************************************
"""
Contents
--------
* `OptimizationFunction`
* `GradientOptimization`
* `GridSearch`
* `GaussianProcess`
COMMENT:
uncomment this when ParamEstimationFunction is ready for users
* `ParamEstimationFunction`
COMMENT
Overview
--------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4425,6 +4425,3 @@ def __gen_llvm_dw_dt(self, builder, ctx, w, previous_v, param_vals):

res = builder.fdiv(sum, param_vals["time_constant_w"])
return res



Original file line number Diff line number Diff line change
Expand Up @@ -1347,5 +1347,3 @@ def memory(self):
return np.array(list(zip(self._memory[KEYS],self._memory[VALS])))
except:
return np.array([])


8 changes: 4 additions & 4 deletions psyneulink/core/components/functions/transferfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ def _gen_llvm_function_body(self, ctx, builder, params, state, arg_in, arg_out,
self._gen_llvm_transfer(ctx=ctx, vi=vi, vo=vo,
params=params, state=state, *args, tags=tags)
else:
self._gen_llvm_transfer(b, idx, ctx=ctx, vi=arg_in, vo=arg_out,
params=params, state=state, tags=tags)
self._gen_llvm_transfer(b, idx, ctx=ctx, vi=arg_in, vo=arg_out,
params=params, state=state, tags=tags)

return builder

Expand Down Expand Up @@ -1265,7 +1265,7 @@ def _gen_llvm_transfer(self, builder, index, ctx, vi, vo, params, state, *, tags

denominator = builder.fadd(exp_val.type(1), exp_val)
denominator = builder.fmul(denominator, denominator)

val = builder.fdiv(numerator, denominator)
val = builder.fmul(val, mult)
else:
Expand Down Expand Up @@ -4124,7 +4124,7 @@ def toggle_cost(self, cost_function_name:tc.any(str, CostFunctions),

enabled_cost_functions = self.parameters.enabled_cost_functions.get(execution_context)
if assignment:
if not cost_function_name in self.parameters.names():
if cost_function_name not in self.parameters.names():
raise FunctionError("Unable to toggle {} ON as function assignment is \'None\'".
format(cost_function_name))
if not enabled_cost_functions:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -605,4 +605,3 @@ def _wrapper(params, state, arg_in, arg_out):
builder.call(wrapper_ptr, [params, state, arg_in, arg_out])

return builder

18 changes: 7 additions & 11 deletions psyneulink/core/components/mechanisms/mechanism.py
Original file line number Diff line number Diff line change
Expand Up @@ -2512,7 +2512,7 @@ def execute(self,

self.parameters.num_executions_before_finished._set(num_executions, override=True, context=context)

if num_executions >= max_executions:
if num_executions >= max_executions:
self.parameters.is_finished_flag._set(True, context)
warnings.warn(f"Maximum number of executions ({max_executions}) reached for {self.name}.")
break
Expand Down Expand Up @@ -3095,10 +3095,7 @@ def _report_mechanism_execution(self, input_val=None, params=None, output=None,
except TypeError:
input_string = input_val

print ("\n\'{}\'{} executed:\n- input: {}".
format(self.name,
mechanism_string,
input_string))
print("\n\'{}\'{} executed:\n- input: {}".format(self.name, mechanism_string, input_string))

if params:
print("- params:")
Expand All @@ -3123,14 +3120,14 @@ def _report_mechanism_execution(self, input_val=None, params=None, output=None,
param_is_function = True
else:
param = param_value
print ("\t{}: {}".format(param_name, str(param).__str__().strip("[]")))
print("\t{}: {}".format(param_name, str(param).__str__().strip("[]")))
if param_is_function:
# Sort for consistency of output
func_params_keys_sorted = sorted(self.function.parameters.names())
for fct_param_name in func_params_keys_sorted:
print ("\t\t{}: {}".
format(fct_param_name,
str(getattr(self.function.parameters, fct_param_name)).__str__().strip("[]")))
print("\t\t{}: {}".
format(fct_param_name,
str(getattr(self.function.parameters, fct_param_name)).__str__().strip("[]")))

# FIX: kmantel: previous version would fail on anything but iterables of things that can be cast to floats
# if you want more specific output, you can add conditional tests here
Expand Down Expand Up @@ -3749,7 +3746,7 @@ def _get_standardized_label_dict(self, label_type):
i = ports[k].position_in_mechanism
_label_dict[i] = v
else:
if not 0 in _label_dict:
if 0 not in _label_dict:
_label_dict[0] = {}
_label_dict[0].update({k:v})
return _label_dict
Expand Down Expand Up @@ -4146,4 +4143,3 @@ def output_port_values(self):
def output_values(self):
"""Return dict with output_values for all Mechanisms in MechanismList"""
return self._get_attributes_dict('values', 'value')

Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,3 @@

__all__ = list(defaultcontrolmechanism.__all__)
__all__.extend(optimizationcontrolmechanism.__all__)

Original file line number Diff line number Diff line change
Expand Up @@ -1595,32 +1595,32 @@ def show(self):
weight = self.monitored_output_ports_weights_and_exponents[monitored_port_index][0]
exponent = self.monitored_output_ports_weights_and_exponents[monitored_port_index][1]

print ("\t\t{0}: {1} (exp: {2}; wt: {3})".
format(monitored_port_Mech.name, monitored_port.name, weight, exponent))
print("\t\t{0}: {1} (exp: {2}; wt: {3})".
format(monitored_port_Mech.name, monitored_port.name, weight, exponent))

try:
if self.control_signals:
print ("\n\tControlling the following Mechanism parameters:".format(self.name))
print("\n\tControlling the following Mechanism parameters:".format(self.name))
# Sort for consistency of output:
port_Names_sorted = sorted(self.control_signals.names)
for port_Name in port_Names_sorted:
for projection in self.control_signals[port_Name].efferents:
print ("\t\t{0}: {1}".format(projection.receiver.owner.name, projection.receiver.name))
print("\t\t{0}: {1}".format(projection.receiver.owner.name, projection.receiver.name))
except:
pass

try:
if self.gating_signals:
print ("\n\tGating the following Ports:".format(self.name))
print("\n\tGating the following Ports:".format(self.name))
# Sort for consistency of output:
port_Names_sorted = sorted(self.gating_signals.names)
for port_Name in port_Names_sorted:
for projection in self.gating_signals[port_Name].efferents:
print ("\t\t{0}: {1}".format(projection.receiver.owner.name, projection.receiver.name))
print("\t\t{0}: {1}".format(projection.receiver.owner.name, projection.receiver.name))
except:
pass

print ("\n---------------------------------------------------------")
print("\n---------------------------------------------------------")

def add_to_monitor(self, monitor_specs, context=None):
"""Instantiate OutputPorts to be monitored by ControlMechanism's `objective_mechanism
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,7 @@ def __init__(self,
"""Implement OptimizationControlMechanism"""

# If agent_rep hasn't been specified, put into deferred init
if agent_rep==None:
if agent_rep is None:
if context.source==ContextFlags.COMMAND_LINE:
# Temporarily name InputPort
self._assign_deferred_init_name(self.__class__.__name__, context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1160,7 +1160,7 @@ def _validate_params(self, request_set, target_set=None, context=None):
for error_source in error_sources:
if (not isinstance(error_source, (ObjectiveMechanism, LearningMechanism, OutputPort))
or (isinstance(error_source, OutputPort)
and not error_source in error_source.owner.output_ports[ERROR_SIGNAL])):
and error_source not in error_source.owner.output_ports[ERROR_SIGNAL])):
raise LearningMechanismError(f"{repr(ERROR_SOURCES)} arg for {self.name} ({error_source}) "
f"must be an {ObjectiveMechanism.__name__}, "
f"another {LearningMechanism.__name__}, an {repr(ERROR_SIGNAL)} "
Expand All @@ -1178,7 +1178,7 @@ def _validate_params(self, request_set, target_set=None, context=None):
# Validate that the receiver of the LearningProjection (if specified)
# is a MappingProjection and in the same System as self (if specified)
if learning_signal[PARAMS] and PROJECTIONS in learning_signal[PARAMS]:
for learning_projection in learning_signal[PARAMS][PROJECTIONS]:
for learning_projection in learning_signal[PARAMS][PROJECTIONS]:
_validate_receiver(sender_mech=self,
projection=learning_projection,
expected_owner_type=MappingProjection,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,11 @@ def remove_ports(self, ports, context=None):
super(CompositionInterfaceMechanism, self).remove_ports(ports, context)
input_ports_marked_for_deletion = set()
for port in self.user_added_ports[INPUT_PORTS]:
if not port in self.input_ports:
if port not in self.input_ports:
input_ports_marked_for_deletion.add(port)
self.user_added_ports[INPUT_PORTS] = self.user_added_ports[INPUT_PORTS] - input_ports_marked_for_deletion
output_ports_marked_for_deletion = set()
for port in self.user_added_ports[OUTPUT_PORTS]:
if not port in self.output_ports:
if port not in self.output_ports:
output_ports_marked_for_deletion.add(port)
self.user_added_ports[OUTPUT_PORTS] = self.user_added_ports[OUTPUT_PORTS] - output_ports_marked_for_deletion
Original file line number Diff line number Diff line change
Expand Up @@ -1102,8 +1102,8 @@ def _validate_termination_threshold(self, termination_threshold):
return 'must be a float or int.'

def _validate_termination_comparison_op(self, termination_comparison_op):
if (not termination_comparison_op in comparison_operators.keys()
and not termination_comparison_op in comparison_operators.values()):
if (termination_comparison_op not in comparison_operators.keys()
and termination_comparison_op not in comparison_operators.values()):
return f"must be boolean comparison operator or one of the following strings:" \
f" {','.join(comparison_operators.keys())}."

Expand Down
2 changes: 1 addition & 1 deletion psyneulink/core/components/ports/inputport.py
Original file line number Diff line number Diff line change
Expand Up @@ -1045,7 +1045,7 @@ def _parse_port_specific_specs(self, owner, port_dict, port_specific_spec):
# (actual assignment is made in _parse_port_spec)
if reference_value is None:
port_dict[REFERENCE_VALUE]=port_spec
elif not iscompatible(port_spec, reference_value):
elif not iscompatible(port_spec, reference_value):
raise PortError(f"Value in first item of 2-item tuple specification {InputPort.__name__} of "
f"{owner.name} ({port_spec}) is not compatible with its {REFERENCE_VALUE} "
f"({reference_value}).")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -386,4 +386,3 @@ def _assign_default_port_Name(self, context=None):
# Otherwise, allow ModulatorySignal to construct default name as usual
else:
super()._assign_default_port_Name(context=context)

Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ def _instantiate_attributes_after_function(self, context=None):
if self.owner and self.modulation is None:
self.modulation = self.owner.modulation
if self.modulation is not None:
if not self.modulation in modulation_type_keywords:
if self.modulation not in modulation_type_keywords:
try:
getattr(self.function.parameters, self.modulation)
except:
Expand Down
4 changes: 2 additions & 2 deletions psyneulink/core/components/ports/outputport.py
Original file line number Diff line number Diff line change
Expand Up @@ -1027,7 +1027,7 @@ def _instantiate_projections(self, projections, context=None):
self._instantiate_projections_to_port(projections=modulatory_projections, context=context)

# Treat all remaining specifications in projections as ones for outgoing MappingProjections
pathway_projections = [proj for proj in projections if not proj in modulatory_projections]
pathway_projections = [proj for proj in projections if proj not in modulatory_projections]
for proj in pathway_projections:
self._instantiate_projection_from_port(projection_spec=MappingProjection,
receiver=proj,
Expand Down Expand Up @@ -1115,7 +1115,7 @@ def _parse_port_specific_specs(self, owner, port_dict, port_specific_spec):
# (actual assignment is made in _parse_port_spec)
if reference_value is None:
port_dict[REFERENCE_VALUE]=port_spec
elif not iscompatible(port_spec, reference_value):
elif not iscompatible(port_spec, reference_value):
raise OutputPortError("Value in first item of 2-item tuple specification for {} of {} ({}) "
"is not compatible with its {} ({})".
format(OutputPort.__name__, owner.name, port_spec,
Expand Down
4 changes: 2 additions & 2 deletions psyneulink/core/components/ports/parameterport.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ def _parse_port_specific_specs(self, owner, port_dict, port_specific_spec):
# (actual assignment is made in _parse_port_spec)
if reference_value is None:
port_dict[REFERENCE_VALUE]=port_spec
elif not iscompatible(port_spec, reference_value):
elif not iscompatible(port_spec, reference_value):
raise PortError("Value in first item of 2-item tuple specification for {} of {} ({}) "
"is not compatible with its {} ({})".
format(ParameterPort.__name__, owner.name, port_spec,
Expand Down Expand Up @@ -1089,7 +1089,7 @@ def _get_parameter_port(sender_owner, sender_type, param_name, component):
"of {} or its function"
.format(param_name, sender_type, sender_owner.name, component))
# Check that the Mechanism has a ParameterPort for the param
if not param_name in component._parameter_ports.names:
if param_name not in component._parameter_ports.names:
raise ParameterPortError("There is no ParameterPort for the parameter ({}) of {} "
"specified in {} for {}".
format(param_name, component.name, sender_type, sender_owner.name))
Loading

0 comments on commit 001a7a6

Please sign in to comment.