Subtle bug about vector copy in python

Suggestions for improvements to the NEURON Forum.
Post Reply
hhshih
Posts: 5
Joined: Fri Nov 02, 2012 11:05 am

Subtle bug about vector copy in python

Post by hhshih » Sat Nov 17, 2012 5:31 pm

Code: Select all

from neuron import h

v1 = h.Vector(1)
v1.x[0]=10

v2 = v1.c
v2.x[0]=5

print v1.x[0] == v2.x[0]    # true
print v1.x == v2.x            # false
print v1==v2                    # false

In python, v1 and v2 are said to be different, but in fact they point to the same vector in hoc.
This problem won't occur if we use v2 = v1.c()

hines
Site Admin
Posts: 1449
Joined: Wed May 18, 2005 3:32 pm

Re: Subtle bug about vector copy in python

Post by hines » Sun Nov 18, 2012 5:38 pm

This is definitely a surprise.
v2 = v1.c
is a callable to the clone function for v1. You mean
v2 = v1.c()
in which v2 is a clone of v1 (not a reference to v1). If you use the latter then everything will make sense.
The surprise is the third hname below since one would expect a callable not to have a method 'x'.
>>> v1.hname()
'Vector[0]'
>>> v2.hname()
'Vector[0].c()'
v2.x.hname()
'Vector[0].x[?]'
This is a side effect of everything being a hoc.HocObject

>>> from neuron import h
>>> v1 = h.Vector(1)
>>> v1
<hoc.HocObject object at 0x7f183acb8ed0>
>>> v1.hname()
'Vector[0]'
>>> v2 = v1.c
>>> v2
<hoc.HocObject object at 0x7f183acb83d8>
>>> v2.hname()
'Vector[0].c()'
>>> v3 = v2.x
>>> v3
<hoc.HocObject object at 0x7f183acb8f18>
>>> v3.hname()
'Vector[0].x[?]'
>>>
Looks like everything that does not actually get resolved into a new vector always refers to the old vector.

hhshih
Posts: 5
Joined: Fri Nov 02, 2012 11:05 am

Re: Subtle bug about vector copy in python

Post by hhshih » Sun Nov 18, 2012 11:22 pm

Thanks for your detailed explanation!

hines
Site Admin
Posts: 1449
Joined: Wed May 18, 2005 3:32 pm

Re: Subtle bug about vector copy in python

Post by hines » Mon Nov 19, 2012 7:02 am

For easier debugging, I will look into having
h.Vector(1).c.x[0]
raise an exception indicating x is not a valid method for a callable.
h.Vector(1).c().x[0] would be valid.

hines
Site Admin
Posts: 1449
Joined: Wed May 18, 2005 3:32 pm

Re: Subtle bug about vector copy in python

Post by hines » Tue Nov 20, 2012 8:26 am

http://www.neuron.yale.edu/hg/neuron/nr ... b867b1a597
now produces the error

Code: Select all

from neuron import h
v1 = h.Vector(1)
v1.x[0]=10
v2 = v1.c
v2.x[0]=5
Traceback (most recent call last):
  File "stdin", line 1, in <module>
TypeError: No hoc method for a callable. Missing parentheses before the '.'?
v2.hname() and other standard python idioms continue to do the right thing.

Post Reply