Page 1 of 1

Subtle bug about vector copy in python

Posted: Sat Nov 17, 2012 5:31 pm
by hhshih

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()

Re: Subtle bug about vector copy in python

Posted: Sun Nov 18, 2012 5:38 pm
by hines
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.

Re: Subtle bug about vector copy in python

Posted: Sun Nov 18, 2012 11:22 pm
by hhshih
Thanks for your detailed explanation!

Re: Subtle bug about vector copy in python

Posted: Mon Nov 19, 2012 7:02 am
by hines
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.

Re: Subtle bug about vector copy in python

Posted: Tue Nov 20, 2012 8:26 am
by hines
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.