writable_array

odl.util.utility.writable_array(obj, \*\*kwargs)[source]

Context manager that casts obj to a numpy.array and saves changes.

Parameters
objarray-like

Object that should be made available as writable array. It must be valid as input to numpy.asarray and needs to support the syntax obj[:] = arr.

kwargs :

Keyword arguments that should be passed to numpy.asarray.

Examples

Convert list to array and use with numpy:

>>> lst = [1, 2, 3]
>>> with writable_array(lst) as arr:
...    arr *= 2
>>> lst
[2, 4, 6]

Usage with ODL vectors:

>>> space = odl.uniform_discr(0, 1, 3)
>>> x = space.element([1, 2, 3])
>>> with writable_array(x) as arr:
...     arr += [1, 1, 1]
>>> x
uniform_discr(0.0, 1.0, 3).element([ 2.,  3.,  4.])

Additional keyword arguments are passed to numpy.asarray:

>>> lst = [1, 2, 3]
>>> with writable_array(lst, dtype='complex') as arr:
...     print(arr)
[ 1.+0.j  2.+0.j  3.+0.j]

Note that the changes are only saved upon exiting the context manger exits. Before, the input object is unchanged:

>>> lst = [1, 2, 3]
>>> with writable_array(lst) as arr:
...     arr *= 2
...     print(lst)
[1, 2, 3]
>>> print(lst)
[2, 4, 6]