Skip to content

Commit

Permalink
Merge pull request #1473 from brian-team/fix_numpy_warnings
Browse files Browse the repository at this point in the history
Fix numpy warnings
  • Loading branch information
mstimberg committed Jun 14, 2023
2 parents ce4884f + 94acfcc commit 98a30dd
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 22 deletions.
4 changes: 2 additions & 2 deletions brian2/codegen/generators/GSL_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -818,7 +818,7 @@ def add_gsl_variables_as_non_scalar(self, diff_vars):
def add_meta_variables(self, options):
if options["use_last_timestep"]:
try:
N = int(self.variables["N"].get_value())
N = self.variables["N"].item()
self.owner.variables.add_array(
"_last_timestep",
size=N,
Expand All @@ -838,7 +838,7 @@ def add_meta_variables(self, options):
pointer_last_timestep = None

if options["save_failed_steps"]:
N = int(self.variables["N"].get_value())
N = self.variables["N"].item()
try:
self.owner.variables.add_array("_failed_steps", size=N, dtype=np.int32)
except KeyError:
Expand Down
8 changes: 4 additions & 4 deletions brian2/codegen/optimisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ def evaluate_expr(expr, ns):
Example
-------
>>> assumptions = {'sin': DEFAULT_FUNCTIONS['sin'].pyfunc,
... 'pi': DEFAULT_CONSTANTS['pi'].value}
>>> assumptions = {'exp': DEFAULT_FUNCTIONS['exp'].pyfunc,
... 'inf': DEFAULT_CONSTANTS['inf'].value}
>>> evaluate_expr('1/2', assumptions)
(0.5, True)
>>> evaluate_expr('sin(pi/2)', assumptions)
(1.0, True)
>>> evaluate_expr('exp(-inf)', assumptions)
(0.0, True)
>>> evaluate_expr('sin(2*pi*freq*t)', assumptions)
('sin(2*pi*freq*t)', False)
>>> evaluate_expr('1/0', assumptions)
Expand Down
21 changes: 12 additions & 9 deletions brian2/core/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,9 @@ def __init__(self, name, value, dimensions=DIMENSIONLESS, owner=None):
def get_value(self):
return self.value

def item(self):
return self.value


class AuxiliaryVariable(Variable):
"""
Expand Down Expand Up @@ -503,6 +506,12 @@ def set_conditional_write(self, var):
def get_value(self):
return self.device.get_value(self)

def item(self):
if self.size == 1:
return self.get_value().item()
else:
raise ValueError("can only convert an array of size 1 to a Python scalar")

def set_value(self, value):
self.device.fill_with_array(self, value)

Expand Down Expand Up @@ -957,15 +966,9 @@ def set_item(self, item, value, level=0, namespace=None):
)
elif isinstance(item, str):
try:
float(value) # only checks for the exception
try:
# length-1 arrays are also convertible to float, but we
# don't want the repr used later to be something like
# array([...]).
value = value[0]
except (IndexError, TypeError):
# was scalar already apparently
pass
if isinstance(value, str):
raise TypeError # Will be dealt with below
value = np.asanyarray(value).item()
except (TypeError, ValueError):
if item != "True":
raise TypeError(
Expand Down
4 changes: 2 additions & 2 deletions brian2/groups/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def __call__(self, item=slice(None), index_var=None): # noqa: B008
if index_var == "0":
return 0
if index_var == "_idx":
start, stop, step = item.indices(int(self.N.get_value()))
start, stop, step = item.indices(self.N.item())
else:
start, stop, step = item.indices(index_var.size)
index_array = np.arange(start, stop, step, dtype=np.int32)
Expand Down Expand Up @@ -686,7 +686,7 @@ def _check_expression_scalar(self, expr, varname, level=0, run_namespace=None):
)

def __len__(self):
return int(self.variables["N"].get_value())
return self.variables["N"].item()


class Group(VariableOwner, BrianObject):
Expand Down
2 changes: 1 addition & 1 deletion brian2/monitors/spikemonitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def all_values(self):
"them."
)
indices = self.i[:]
sort_indices = np.argsort(indices)
sort_indices = np.argsort(indices, kind="mergesort")
used_indices, first_pos = np.unique(self.i[:][sort_indices], return_index=True)
all_values_dict = {}
for varname in self.record_variables - {"i"}:
Expand Down
8 changes: 4 additions & 4 deletions brian2/synapses/synapses.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,8 +510,8 @@ def slice_to_test(x):

def find_synapses(index, synaptic_neuron):
try:
index = int(index)
except TypeError:
index = index.item()
except (TypeError, ValueError):
pass

if isinstance(index, (int, slice)):
Expand Down Expand Up @@ -1770,8 +1770,8 @@ def _update_synapse_numbers(self, old_num_synapses):
source_offset = self.variables["_source_offset"].get_value()
target_offset = self.variables["_target_offset"].get_value()
# This resizing is only necessary if we are connecting to/from synapses
post_with_offset = int(self.variables["N_post"].get_value()) + target_offset
pre_with_offset = int(self.variables["N_pre"].get_value()) + source_offset
post_with_offset = self.variables["N_post"].item() + target_offset
pre_with_offset = self.variables["N_pre"].item() + source_offset
self.variables["N_incoming"].resize(post_with_offset)
self.variables["N_outgoing"].resize(pre_with_offset)
N_outgoing = self.variables["N_outgoing"].get_value()
Expand Down
4 changes: 4 additions & 0 deletions brian2/units/fundamentalunits.py
Original file line number Diff line number Diff line change
Expand Up @@ -1475,6 +1475,10 @@ def __getitem__(self, key):
"""
return Quantity(np.ndarray.__getitem__(self, key), self.dim)

def item(self, *args):
"""Overwritten to assure that the returned element retains its unit."""
return Quantity(np.ndarray.item(self, *args), self.dim)

def __setitem__(self, key, value):
fail_for_dimension_mismatch(self, value, "Inconsistent units in assignment")
return super().__setitem__(key, value)
Expand Down

0 comments on commit 98a30dd

Please sign in to comment.