Skip to content

Commit

Permalink
treewide: Use ndarray.item() to convert single element numpy arrays t…
Browse files Browse the repository at this point in the history
…o scalars (#3063)

Reduces number of warnings from ~84000 -> ~11000 (~87%)

Signed-off-by: Jan Vesely <[email protected]>
  • Loading branch information
jvesely authored Oct 11, 2024
1 parent 9534a9d commit 962807b
Show file tree
Hide file tree
Showing 9 changed files with 20 additions and 20 deletions.
4 changes: 2 additions & 2 deletions psyneulink/core/components/functions/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def _random_state_getter(self, owning_component, context, modulated=False):
# 'has_modulation' indicates that seed has an active modulatory projection
# 'modulated' indicates that the modulated value is requested
if has_modulation and modulated:
seed_value = [int(owning_component._get_current_parameter_value(seed_param, context))]
seed_value = [int(owning_component._get_current_parameter_value(seed_param, context).item())]
else:
seed_value = [int(seed_param._get(context=context))]

Expand Down Expand Up @@ -832,7 +832,7 @@ def convert_output_type(self, value, output_type=None):
# Note: if 2D or 1D array has more than two items, generate exception
elif output_type is FunctionOutputType.NP_0D_ARRAY:
if object_has_single_value(value):
value = np.array(float(value))
value = np.asfarray(value)
else:
raise FunctionError(f"Can't convert value ({value}) with more than a single number to a raw number.")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2191,7 +2191,7 @@ def _function(self,
delta values : 1d np.array
"""
gamma = self._get_current_parameter_value(GAMMA, context)
gamma = self._get_current_parameter_value(GAMMA, context).item()
sample = variable[0]
reward = variable[1]
delta = np.zeros(sample.shape)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1225,13 +1225,13 @@ def _function(self,
"""

attentional_drift_rate = float(self._get_current_parameter_value(DRIFT_RATE, context))
stimulus_drift_rate = float(variable)
attentional_drift_rate = self._get_current_parameter_value(DRIFT_RATE, context).item()
stimulus_drift_rate = variable.item()
drift_rate = attentional_drift_rate * stimulus_drift_rate
threshold = self._get_current_parameter_value(THRESHOLD, context)
starting_value = float(self._get_current_parameter_value(STARTING_VALUE, context))
noise = float(self._get_current_parameter_value(NOISE, context))
non_decision_time = float(self._get_current_parameter_value(NON_DECISION_TIME, context))
starting_value = self._get_current_parameter_value(STARTING_VALUE, context).item()
noise = self._get_current_parameter_value(NOISE, context).item()
non_decision_time = self._get_current_parameter_value(NON_DECISION_TIME, context).item()

# drift_rate = float(self.drift_rate) * float(variable)
# threshold = float(self.threshold)
Expand Down
12 changes: 6 additions & 6 deletions psyneulink/core/components/functions/stateful/memoryfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,10 +396,10 @@ def _distance_field_weights_setter(value, owning_component=None, context=None):
# NOTE: need the following to accommodate various forms of specification (single value, None's, etc)
# that are resolved elsewhere
# FIX: STANDARDIZE FORMAT FOR FIELDWEIGHTS HERE (AS LIST OF INTS) AND GET RID OF THE FOLLOWING
test_val = np.array([int(val) if val else 0 for val in value])
test_val = np.full(len(variable),test_val) if len(test_val) == 1 else test_val
test_curr_field_weights = np.array([int(val) if val else 0 for val in current_field_weights])
test_curr_field_weights = (np.full(len(variable),test_curr_field_weights) if len(variable) == 1
test_val = np.array([int(np.array(val).item()) if val else 0 for val in value])
test_val = np.full(len(variable), test_val) if len(test_val) == 1 else test_val
test_curr_field_weights = np.array([int(np.array(val).item()) if val else 0 for val in current_field_weights])
test_curr_field_weights = (np.full(len(variable), test_curr_field_weights) if len(variable) == 1
else test_curr_field_weights)
if np.all(test_curr_field_weights == test_val) and not owning_component.is_initializing:
pass
Expand Down Expand Up @@ -2777,8 +2777,8 @@ def get_memory(self, query_key:Union[list, np.ndarray], context=None):
indices_of_selected_items = np.flatnonzero(selection_array)

# Single key identified
if len(indices_of_selected_items)==1:
index_of_selected_item = int(np.flatnonzero(selection_array))
if len(indices_of_selected_items) == 1:
index_of_selected_item = int(np.flatnonzero(selection_array).item())
# More than one key identified
else:
selected_keys = _memory[KEYS]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,6 @@ def compute_costs(self, intensity, context=None):
all_costs = [[intensity_cost, adjustment_cost, duration_cost]]

# Combine the costs. Convert to a float because reRedcu
combined_cost = float(self.combine_costs_function(all_costs, context=context))
combined_cost = float(self.combine_costs_function(all_costs, context=context).item())

return max(0.0, combined_cost)
4 changes: 2 additions & 2 deletions psyneulink/core/compositions/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -1380,9 +1380,9 @@ def node_execution_report(self,
# 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
try:
input_string = [float("{:0.3}".format(float(i))) for i in input_val].__str__().strip("[]")
input_string = ", ".join([np.format_float_positional(i.item(), precision=2, trim='0') for i in input_val])
# input_string = re.sub(r'[\[,\],\n]', '', str([float("{:0.3}".format(float(i))) for i in input_val]))
except TypeError:
except ValueError:
input_string = node.parameters.variable.get(context)

input_report = f"input: {input_string}"
Expand Down
2 changes: 1 addition & 1 deletion psyneulink/core/scheduling/condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def func(threshold, comparator, indices, atol, rtol, execution_id):
for i in indices:
param_value = param_value[i]

param_value = float(param_value)
param_value = float(np.array(param_value).item())

if comparator == '==':
return np.isclose(param_value, threshold, atol=atol, rtol=rtol)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1110,7 +1110,7 @@ def _execute(
format(self.function.name, self.name))

# Convert ER to decision variable:
threshold = float(self.function._get_current_parameter_value(THRESHOLD, context))
threshold = float(self.function._get_current_parameter_value(THRESHOLD, context).item())
random_state = self._get_current_parameter_value(self.parameters.random_state, context)
if random_state.uniform() < return_value[self.PROBABILITY_LOWER_THRESHOLD_INDEX]:
return_value[self.DECISION_VARIABLE_INDEX] = np.atleast_1d(-1 * threshold)
Expand Down
2 changes: 1 addition & 1 deletion psyneulink/library/compositions/regressioncfa.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ def compute_terms(self, control_allocation, context=None):
# Compute value of each control_signal from its variable
c = np.zeros((len(control_allocation), ))
for i, var in enumerate(control_allocation):
c[i] = self.control_signal_functions[i](var, context=context)
c[i] = self.control_signal_functions[i](var, context=context).item()
computed_terms[PV.C] = c

# Compute costs for new control_signal values
Expand Down

0 comments on commit 962807b

Please sign in to comment.