rasbt / python-machine-learning-book

The "Python Machine Learning (1st edition)" book code repository and info resource

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ValueError: operands could not be broadcast together with shapes (200,) (30000,)

donet3088 opened this issue · comments

I am working on a finite element code in python. It is originally for the diffusion equation but I want to modify it for the wave equation and include a ricker source term. I tried adding the source term and it produces an error. Below is the code and error

from IPython import display
from matplotlib.tri import Triangulation, LinearTriInterpolator

deltat = 0.001
numIterations = 30
mass = numpy.zeros((NPOINTS,NPOINTS))
stiffness = numpy.zeros((NPOINTS,NPOINTS))
phi = numpy.zeros((NPOINTS,))
phi_old = numpy.zeros((NPOINTS,))

f0= 5 # Center frequency Ricker-wavelet
q0= 100 # Maximum amplitude Ricker-Wavelet
t=np.arange(0,numIterations,deltat) # Time vector

tau=np.pif0(t-1.5/f0)
q=q0*(1.0-2.0*tau2.0)*np.exp(-tau2)

xi = np.linspace(0, L, 200)
yi = np.linspace(0, H, 200)
Xi, Yi = np.meshgrid(xi, yi)

updateMatrix(mass,stiffness,phi)
mat = mass/deltat + stiffness
triang = Triangulation(points[:,0], points[:,1])

for iteration in range(1,numIterations+1):
phi_old = phi

rhs = numpy.dot(mass/deltat, phi_old)
rhs = rhs + q
phi = numpy.linalg.solve(mat,rhs)

interpolator = LinearTriInterpolator(triang, phi)
zi = interpolator(Xi, Yi)
fig1 = pylab.figure(1)
pylab.imshow(zi)

fig2 = pylab.figure(2)
xanal, yanal = analytical(numIterations*deltat)
pylab.plot(xanal,yanal,"-")
pylab.plot(Xi[100,:],zi[100,:])
fig2.savefig("comparison.png",format="PNG")


ValueError Traceback (most recent call last)
in
29
30 rhs = numpy.dot(mass/deltat, phi_old)
---> 31 rhs = rhs + q
32 phi = numpy.linalg.solve(mat,rhs)
33 interpolator = LinearTriInterpolator(triang, phi)

ValueError: operands could not be broadcast together with shapes (200,) (30000,)

The error message means that rhs is a 200-element vector, and q is a 30000-element vector. The problem is that the vectors should have the same size in order to add them via rhs = rhs + q.

I suggest checking (e.g. printing) the values of some of the variables computed earlier to track down where the dimension issue occurs so that you can fix it.