Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numexpr: How to use "local_dict" and "global_dict"?

I have been experimenting and trying to learn the Numexpr package. Examples on how to use it are sparse at best. Can someone please give me a quick example on how to use the "local_dict" and "global_dict" arguments?

like image 519
Noob Saibot Avatar asked Jan 29 '13 01:01

Noob Saibot


1 Answers

The following examples may clarify it a little. First set up the scene like this:

import numpy as np
import numexpr as ne

a = np.arange(10)
b = np.arange(10, 20)
c = np.arange(20, 30)

No dict

>>> def f0(a, b) :
...     a, b = 2 * a, 3 * b
...     return ne.evaluate('2*a + 3*b + c')
...
>>> f0(a, b)
array([110, 124, 138, 152, 166, 180, 194, 208, 222, 236])
>>> 4 * a + 9 * b + c
array([110, 124, 138, 152, 166, 180, 194, 208, 222, 236])

When you run it like this, a and bare the local variables, and cis the global variable, as expected.

local_dict

>>> def f1(a, b) :
...     a, b = 2 * a, 3 * b
...     return ne.evaluate('2*a + 3*b + c',
...                        local_dict={'c' : np.arange(30, 40)})
...
>>> f1(a, b)
array([ 60,  66,  72,  78,  84,  90,  96, 102, 108, 114])
>>> 2*a + 3 * b + np.arange(30, 40)
array([ 60,  66,  72,  78,  84,  90,  96, 102, 108, 114])

Because we have redefined local_dict, a and b no longer show up there as local variables, so the value of the global ones is used instead. And because c now is defined as a local variable, the value of the global one is ignored.

global_dict

>>> def f2(a, b) :
...     a, b = 2 * a, 3 * b
...     return ne.evaluate('2*a + 3*b + c',
...                        global_dict= {'c' : np.arange(30, 40)})
...
>>> f2(a, b)
array([120, 134, 148, 162, 176, 190, 204, 218, 232, 246])
>>> 4 * a + 9 * b + np.arange(30, 40)
array([120, 134, 148, 162, 176, 190, 204, 218, 232, 246])

In this case, a and b are taken from the default local dictionary, and the new c is taken in place of the original global one.

like image 179
Jaime Avatar answered Oct 01 '22 22:10

Jaime