Exporting arrays of shared properties

I’m trying to export some properties of a network to a numpy array. This works fine for most properties, but I noticed I got a “setting an array element with a sequence” error for some. Looking a little closer this seems to happen with (shared) properties, perhaps because of the VariableView that’s returned?

Is there a simple way to convert a list of VariableViews (of scalars) to a standard python list?

Minimal Code:
ffrom brian2 import *
import numpy as np

eqs = '''
    v0 : 1
    sigma : 1 (shared)
    dv/dt = (v0 - v)/tau + sigma*xi*(tau**-0.5) :1
    '''
    
tau = 10*ms
G1 = NeuronGroup(10, eqs)
G2 = NeuronGroup(5, eqs)
Gs = [G1,G2]

#%%
nonshared_list = [G.v0[0] for G in Gs] 
shared_list = [G.sigma for G in Gs]

simple_list = [.1,.2,.3]

print('brian lists:')
print(nonshared_list)
print(shared_list)

print('\nsimple list → numpy array:')
print(np.array(simple_list))

print('\nnon-shared list → numpy array:')
print(np.array(nonshared_list))

print('\nshared list → numpy array')
try:
    shared_np = np.array(shared_list)
    print('success!')
except ValueError as err:
    'results in "cannot set array with sequence"'
    print('ERROR:',err)

#%% EXAMPLE OUTPUT:

# brian lists:
# [0.0, 0.0]
# [<neurongroup_5.sigma: 0.0>, <neurongroup_6.sigma: 0.0>]
# 
# simple list → numpy array:
# [0.1 0.2 0.3]
# 
# non-shared list → numpy array:
# [0. 0.]
# 
# shared list → numpy array
# ERROR: setting an array element with a sequence.

a hacky workaround which seems to work for now is to multiply the value by 1.0

shared_np_array = np.array([G.sigma*1.0 for G in Gs])

Hi @adam . A general way to get a normal numpy array (or Quantity for values with units) instead of a VariableView (which we only need so that more complex indexing, e.g. with string expressions, works) is to use [:] as an index. For shared variables, this will return a numpy scalar, which should work fine in lists, etc. So in sum, if you replace the shared_list definition by:

shared_list = [G.sigma[:] for G in Gs]

all should work as expected. All that said, I will have a look why it does not transparently work with VariableView as in your example. We try to make it automatically convert into a normal array whenever necessary so that it does not raise errors like that.

1 Like