Numba - TypeError: 'type' object has no attribute '__getitem__ - typeerror

I am using Numba with Anaconda and wondering why
#jit(argtypes=[int16[:], int16[:]])
def index(ic, nc):
return ic[0] + nc[0] * (ic[1] + nc[1] * ic[2])
does not work:
TypeError: 'type' object has no attribute '__getitem__'
But if I use #autojit instead of #jit(..) everything is fine.

This is slightly confusing from reading the Numba examples, but you actually need to import int16 from the numba namespace.
The error you are seeing is consistent with importing int16 from NumPy. So if at the top of your file, your code looks like:
from numba import *
from numpy import *
Then you'll accidentally override int16 with the NumPy definition of it. There are two fixes. First, you could just swap the order of your imports:
from numpy import *
from numba import *
Or, more correctly, you could import the namespaces without the * and refer explicitly to what you need:
import numba as nb
#nb.jit(argtypes=[nb.int16[:], nb.int16[:]])

Related

Why import numpy doesn't automatically include matlib

I'm trying to repeat a numpy array x horizontally using a=numpy.matlib.repmat(x,1,3). However, directly typing this results in error. I must add import numpy.matlib in order for a=numpy.matlib.repmat(x,1,3) to work.
My question is, why do I need to explicitly import numpy.matlib? I thought import numpy should automatically import everything that appears in the form numpy.* just like numpy.zeros, numpy.array and numpy.mean.

System of second order ode

I am trying to solve an IVP, consisting of two second order ode. I use sympy. No problems to obtain general solution. But I don't understand how to plug in the IC:s.
MWE:
from sympy import *
import numpy as np
import matplotlib.pyplot as plt
x1,x2=symbols('x1,x2',cls=Function)
t,k1,k2,m1,m2=symbols('t k1 k2 m1 m2',real=True)
k1=1.0
k2=1.0
m1=1.0
m2=1.0
eq1=Eq(m1*diff(x1(t),t,2)+k1*x1(t)-k2*(x2(t)-x1(t)),0)
eq2=Eq(m2*diff(x2(t),t,2)+k2*(x2(t)-x1(t)),0)
eqs=[eq1,eq2]
IC1={x1(0):0,x1(t).diff().subs(t,0):0}
IC2={x2(0):1,x2(t).diff().subs(t,0):0}
sol=dsolve(eqs,[x1(t),x2(t)],ics=[IC1,IC2])
print(sol)
Error message:
for funcarg, value in ics.items():
AttributeError: 'list' object has no attribute 'items'

Plot Scipy ODE solution

I've been trying to solve a nonlinear ordinary differential equation numerically by using Scipy, in particular by the scipy.integrate.RK23 command. It returns <scipy.integrate._ivp.rk.RK23 at 0x7f2b1a908390>. How can I plot the solution?
Thank you in advance for your help!
EDIT:
As a simple example for testing:
import numpy
import scipy.integrate
t0=0;
tf=1;
x0=numpy.array([0]);
def F(t,x): return t**2;
x=scipy.integrate.RK23(F,t0,x0,tf)
RK23 is a class that implements a way to solve an ODE, that is, it is an OdeSolver so it should not be used directly but in other functions like solve_ivp:
import numpy
from scipy.integrate import solve_ivp, RK23
import matplotlib.pyplot as plt
t0=0
tf=1
x0=numpy.array([0])
def F(t,x): return t**2
sol = solve_ivp(F, [t0, tf], x0, RK23)
print(sol)
plt.plot(sol.t, sol.y[0])
plt.show()
OdeSolver allows the developer to add custom methods without the need to rewrite scipy, but since RK23 is a classic method already implemented by scipy, you could pass just the name and scipy search for the appropriate class:
...
sol = solve_ivp(F, [t0, tf], x0, "RK23")
...

The corresponding ctypes type of a numpy.dtype?

If I have a numpy ndarray with a certain dtype, how do I know what is the corresponding ctypes type?
For example, if I have a ndarray, I can do the following to convert it to a shared array:
import multiprocessing as mp
import numpy as np
import ctypes
x_np = np.random.rand(10, 10)
x_mp = mp.Array(ctypes.c_double, x_np)
However, I have to specify c_double here. It works if I don't specify the exact same type, but I would like to keep the type the same. How should I find out the ctypes type of the ndarray x_np automatically, at least for some common elementary data types?
This is now supported by numpy.ctypeslib.as_ctypes_type(dtype):
import numpy as np
x_np = np.random.rand(10, 10)
np.ctypeslib.as_ctypes_type(x_np.dtype)
Gives ctypes.c_double, as expected.
There is actually a way to do this that's built into Numpy:
x_np = np.random.rand(10, 10)
typecodes = np.ctypeslib._get_typecodes()
typecodes[x_np.__array_interface__['typestr']]
Output:
ctypes.c_double
The caveat is that the np.ctypeslib._get_typecodes function is marked as private (ie it's name starts with _). However, it doesn't seem like its implementation has changed in some time, so you can probably use it fairly reliably.
Alternatively, the implementation of _get_typecodes is pretty short, so you could just also copy the whole function over to your own code:
import ctypes
import numpy as np
def get_typecodes():
ct = ctypes
simple_types = [
ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong,
ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong,
ct.c_float, ct.c_double,
]
return {np.dtype(ctype).str: ctype for ctype in simple_types}

Dtype work in FROM but not IMPORT

I swear I read almost all the "FROM vs IMPORT" questions before asking this.
While going through the NumPy tutorial I was using:
import numpy as np
but ran into trouble when declaring dtype of a matrix like:
a = np.ones((2,3),dtype=int32)
I kept getting "NameError: name 'int32' is not defined." I am using Python v3.2, and am following the tentative tutorial that goes along with it. I used:
from numpy import *
a = ones((2,3),dtype=int32)
Which works. Any insight as to why this is would be much appreciated.
Thank you in advance!
import numpy as np
#this will work because int32 is defined inside the numpy module
a = np.ones((2,3), dtype=np.int32)
#this also works
b = np.ones((2,3), dtype = 'int32')
#python doesn't know what int32 is because you loaded numpy as np
c = np.ones((2,3), dtype=int32)
back to your example:
from numpy import *
#this will now work because python knows what int32 is because it is loaded with numpy.
d = np.ones((2,3), dtype=int32)
I tend to define the type using strings as in array b