Python throws error when I call integrate( vector expression, t ) - python

I wrote a Python program to calculate the Magnetic Field from a given time-varying Electric field. I used CoordSys3d from sympy.vector
I got it working this afternoon. It was giving correct answers. Then, I upgraded to the newest version of Anaconda (which updated the SymPy library), and now it throws an error when I call integrate().
Here is the error traceback:
>>> integrate( jimmy, t )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/integrals.py", line 1573, in integrate
new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/integrals.py", line 1573, in <listcomp>
new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/integrals.py", line 597, in doit
antideriv = self._eval_integral(
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/integrals.py", line 941, in _eval_integral
result, i = risch_integrate(f, x, separate_integral=True,
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/risch.py", line 1831, in risch_integrate
ans, i, b = integrate_hyperexponential(fa, fd, DE, conds=conds)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/risch.py", line 1564, in integrate_hyperexponential
qa, qd, b = integrate_hyperexponential_polynomial(pp, DE, z)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/risch.py", line 1516, in integrate_hyperexponential_polynomial
va, vd = rischDE(iDta, iDtd, Poly(aa, DE.t), Poly(ad, DE.t), DE)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/rde.py", line 774, in rischDE
_, (fa, fd) = weak_normalizer(fa, fd, DE)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/integrals/rde.py", line 126, in weak_normalizer
r = (a - Poly(z, DE.t)*derivation(d1, DE)).as_poly(DE.t).resultant(
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/polytools.py", line 65, in wrapper
return func(f, g)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/polytools.py", line 4104, in __sub__
return f.sub(g)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/polytools.py", line 1464, in sub
_, per, F, G = f._unify(g)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/polytools.py", line 465, in _unify
dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens) - 1
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/domains/domain.py", line 686, in unify
return K0.unify_with_symbols(K1, symbols)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/domains/domain.py", line 666, in unify_with_symbols
return K0.unify(K1)
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/domains/domain.py", line 725, in unify
domain = domain.get_ring()
File "/opt/anaconda3/lib/python3.8/site-packages/sympy/polys/domains/complexfield.py", line 98, in get_ring
raise DomainError("there is no ring associated with %s" % self)
sympy.polys.polyerrors.DomainError: there is no ring associated with CC
Here is the code:
import numpy as np
import sympy as smp
import matplotlib.pyplot as plt
from sympy import *
from sympy import symbols
from sympy.vector import divergence
from sympy.vector import curl
from sympy import diff
from sympy import exp
from sympy import integrate
from sympy.vector import CoordSys3D
R = CoordSys3D('R')
# Variables
X, Y, Z = symbols('X Y Z')
X = R.x
Y = R.y
Z = R.z
# Basis Unit Vectors
i,j,k = symbols('i j k')
i = R.i
j = R.j
k = R.k
# Symbols
x,t = symbols('x t')
Ex = smp.Function('Ex')(x,t)
Ey = smp.Function('Ey')(x,t)
Ez = smp.Function('Ez')(x,t)
wavenumber = symbols('k')
E_0 = symbols('E_0') # Amplitude of E field
w = symbols('w' , real=True, positive=True)
# Define Ey(x,t)
Ey = E_0 * smp.exp( 1j * (wavenumber*X - w*t ))
# The Electric Field
E = Ex*i + Ey*j + Ez*k
init_printing(use_unicode=True, wrap_line=False)
# curl E = - dB/dt
# integrate( (curl E) , t ) = - B
jimmy = curl( E )
B = -integrate( jimmy, t )
pprint( B )
B = -integrate( jimmy, t ).doit()
pprint( B )

Usually we ask users to include the full traceback when asking about errors.
In a sympy context I expect to see "won't integrate" description when result is an expression containing the integral sign. Similarly for "can't solve" results, where the result is the original expression, or a barely simplified one.
Your case is an actual error.
In [6]: jimmy = curl( E, R )
In [7]: jimmy
Out[7]:
1.0⋅ⅈ⋅(Rₓ⋅k - t⋅w)
1.0⋅ⅈ⋅E₀⋅k⋅ℯ r_z
In [8]: smp.integrate( jimmy, t )
/usr/local/lib/python3.8/dist-packages/sympy/core/sympify.py:456: SymPyDeprecationWarning:
String fallback in sympify has been deprecated since SymPy 1.6. Use
sympify(str(obj)) or sympy.core.sympify.converter or obj._sympy_
instead. See https://github.com/sympy/sympy/issues/18066 for more
info.
SymPyDeprecationWarning(
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
ValueError: Error from parse_expr with transformed code: "Float ('1.0' )*I *Symbol ('E_0' )*Symbol ('k' )*exp (Float ('1.0' )*I *(Symbol ('R_x' )*Symbol ('k' )-Symbol ('t' )*Symbol ('w' )))*Symbol ('R' ).z "
The above exception was the direct cause of the following exception:
AttributeError Traceback (most recent call last)
<ipython-input-8-8d40c4ce949f> in <module>
----> 1 smp.integrate( jimmy, t )
/usr/local/lib/python3.8/dist-packages/sympy/integrals/integrals.py in integrate(meijerg, conds, risch, heurisch, manual, *args, **kwargs)
1566 'manual': manual
1567 }
-> 1568 integral = Integral(*args, **kwargs)
1569
1570 if isinstance(integral, Integral):
/usr/local/lib/python3.8/dist-packages/sympy/integrals/integrals.py in __new__(cls, function, *symbols, **assumptions)
89 useinstead="the as_expr or integrate methods of Poly").warn()
90
---> 91 obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
92 return obj
93
/usr/local/lib/python3.8/dist-packages/sympy/concrete/expr_with_limits.py in __new__(cls, function, *symbols, **assumptions)
496
497 def __new__(cls, function, *symbols, **assumptions):
--> 498 pre = _common_new(cls, function, *symbols, **assumptions)
499 if type(pre) is tuple:
500 function, limits, orientation = pre
/usr/local/lib/python3.8/dist-packages/sympy/concrete/expr_with_limits.py in _common_new(cls, function, *symbols, **assumptions)
23 (function, limits, orientation). This code is common to
24 both ExprWithLimits and AddWithLimits."""
---> 25 function = sympify(function)
26
27 if isinstance(function, Equality):
/usr/local/lib/python3.8/dist-packages/sympy/core/sympify.py in sympify(a, locals, convert_xor, strict, rational, evaluate)
477 try:
478 a = a.replace('\n', '')
--> 479 expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
480 except (TokenError, SyntaxError) as exc:
481 raise SympifyError('could not parse %r' % a, exc)
....
AttributeError: 'Symbol' object has no attribute 'z'
So while:
In [9]: R.z
Out[9]: r_z
it has replaced that with:
In [10]: parse_expr(Symbol ('R' ).z)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-60a85cf12db4> in <module>
----> 1 parse_expr(Symbol ('R' ).z)
AttributeError: 'Symbol' object has no attribute 'z'
I don't know enough sympy to understand the issue, but it is more informative than "won't integrate".

I discovered the problem was being caused by me using "1j" for "i". I changed it to "I" and now it works.
Causes error:
Ey = E_0 * smp.exp( 1j * (wavenumber*X - w*t ))
Works fine:
Ey = E_0 * smp.exp( I * (wavenumber*X - w*t ))

Related

Error: _print_LambertW() got an unexpected keyword argument 'exp'

I am trying multiply the following equation with its derivative using Python, I made the following code
from sympy.abc import x, y, z, a,b
from sympy import *
a, b, n, t,N_0,x = symbols('a b n t N_0 x')
f=-LambertW(-N_0*b**(-a)*log(b)*log(t + 1))/((t + 1)*log(b)*log(t + 1))
f_a=diff(f,a)
d=f*f_a
d
When I try to run the code:
TypeError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/IPython/core/formatters.py in __call__(self, obj)
336 method = get_real_method(obj, self.print_method)
337 if method is not None:
--> 338 return method()
339 return None
340 else:
10 frames
/usr/local/lib/python3.7/dist-packages/sympy/printing/printer.py in _print(self, expr, **kwargs)
327 printmethod = '_print_' + cls.__name__
328 if hasattr(self, printmethod):
--> 329 return getattr(self, printmethod)(expr, **kwargs)
330 # Unknown object, fall back to the emptyPrinter.
331 return self.emptyPrinter(expr)
TypeError: _print_LambertW() got an unexpected keyword argument 'exp'
This error is no longer raised in the most recent version of SymPy (or at least the development version).

How to return boolean array in numba.njit?

import numpy as np
from numba import njit, float64
from numba.experimental import jitclass
#njit(fastmath=True)
def compare(values1, values2):
shape = values1.shape[0]
res = np.zeros(shape, dtype=bool)
for i in range(shape):
res[i] = x[i] > y[i]
return res
spce = [("x", float64[:]),
("y", float64[:]),
("z", float64[:]),]
#jitclass(spce)
class Math:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def calculate(self):
i = compare(self.x, self.y)
return self.z[i]
If I testing like this:
x = np.random.rand(10)
y = np.random.rand(10)
compare(x, y)
It will return:
Traceback (most recent call last):
File "<ipython-input-25-586dc5d173c7>", line 3, in <module>
compare(x, y)
File "C:\Users\Option00\Anaconda3\envs\bot\lib\site-packages\numba\core\dispatcher.py", line 415, in _compile_for_args
error_rewrite(e, 'typing')
File "C:\Users\Option00\Anaconda3\envs\bot\lib\site-packages\numba\core\dispatcher.py", line 358, in error_rewrite
reraise(type(e), e, None)
File "C:\Users\Option00\Anaconda3\envs\bot\lib\site-packages\numba\core\utils.py", line 80, in reraise
raise value.with_traceback(tb)
TypingError: No implementation of function Function(<built-in function zeros>) found for signature:
zeros(int64, dtype=Function(<class 'bool'>))
There are 2 candidate implementations:
- Of which 2 did not match due to:
Overload of function 'zeros': File: numba\core\typing\npydecl.py: Line 504.
With argument(s): '(int64, dtype=Function(<class 'bool'>))':
No match.
During: resolving callee type: Function(<built-in function zeros>)
During: typing of call at <ipython-input-24-69a4f907fb89> (4)
Finally I need to use it in the jitclass:
x = np.random.rand(10)
y = np.random.rand(10)
z = np.random.rand(10)
m = Math(x, y, z)
m.calculate()
Actually the output is just z[x>y] in numpy, but how i can use in njit & jitclass?
I need both of them for speed up my others code.
If the compare function can be return boolean array, the problem should be solved.
You have to use Numba's special bool_ type for that:
import numpy as np
from numba.types import bool_, int_, float32
#njit(bool_[:,:](float32[:,:,:],float32[:,:,:],int_))
def test(im1, im2, j_delta=1):
diff = ((im1 - im2)**2).sum(axis=2)/3
mask = np.zeros_like(diff, bool_) # <--- like so
for i in range(diff.shape[0]):
for j in range(diff.shape[1]):
mask[i,j] = diff[i,j] > 1.0
return mask
If you replace bool_ by bool or even np.bool, you'll get a compile error.

shapes (401,1) and (401,1) not aligned: 1 (dim 1) != 401 (dim 0)

I am implementing the one vs all classifier, however, I got the error "shapes (401,1) and (401,1) not aligned: 1 (dim 1) != 401 (dim 0)",and the traceback is below :
Traceback (most recent call last):
File "<ipython-input-1-682bb50c2435>", line 1, in <module>
runfile('/Users/alvin/Documents/GitDemo/ML_Basic_Imple/Coursera_ML_Python/ex3/Multi_classify_oneVSall.py', wdir='/Users/alvin/Documents/GitDemo/ML_Basic_Imple/Coursera_ML_Python/ex3')
File "/Users/alvin/Documents/tools/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "/Users/alvin/Documents/tools/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/alvin/Documents/GitDemo/ML_Basic_Imple/Coursera_ML_Python/ex3/Multi_classify_oneVSall.py", line 124, in <module>
trained_theta = training_OnevsAll_theta(X,y,10,0.1)
File "/Users/alvin/Documents/GitDemo/ML_Basic_Imple/Coursera_ML_Python/ex3/Multi_classify_oneVSall.py", line 119, in training_OnevsAll_theta
theta,cost = opt_Cost(initial_theta,X,y,lamada)
File "/Users/alvin/Documents/GitDemo/ML_Basic_Imple/Coursera_ML_Python/ex3/Multi_classify_oneVSall.py", line 96, in opt_Cost
res = optimize.fmin_bfgs(LR_Costfunction, theta, fprime=Gradient, args=(X,y,lamada) )
File "/Users/alvin/Documents/tools/anaconda3/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 859, in fmin_bfgs
res = _minimize_bfgs(f, x0, args, fprime, callback=callback, **opts)
File "/Users/alvin/Documents/tools/anaconda3/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 934, in _minimize_bfgs
old_fval, old_old_fval, amin=1e-100, amax=1e100)
File "/Users/alvin/Documents/tools/anaconda3/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 765, in _line_search_wolfe12
**kwargs)
File "/Users/alvin/Documents/tools/anaconda3/lib/python3.6/site-packages/scipy/optimize/linesearch.py", line 97, in line_search_wolfe1
derphi0 = np.dot(gfk, pk)
ValueError: shapes (401,1) and (401,1) not aligned: 1 (dim 1) != 401 (dim 0)e
Could you find any problem in my below code?
Thank you for your patient!
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.io
import scipy.misc
import matplotlib.cm as cm # Used to display images in a specific colormap
import random
from scipy.special import expit
datapath = 'data/ex3data1.mat'
data = scipy.io.loadmat(datapath)
X = data['X']
y = data['y']
print(X.shape)
print(y.shape)
def _display_data():
all_fig = np.zeros((10*20,10*20))
index_of_samples = random.sample(range(X.shape[0]),100)
row, col = 0, 0
for i in index_of_samples:
if col == 10:
row += 1
col = 0
fig = X[i].reshape(20,20).T
all_fig[row * 20:(row+1)*20,col * 20:(col+1)*20] = fig
col += 1
plt.figure(figsize=(8,8))
img = scipy.misc.toimage(all_fig)
plt.imshow(img, cmap = plt.cm.gray_r)
_display_data()
# ============ Part 2a: Vectorize Logistic Regression ============
def hpy_sigmod_fucntion(X_inter,theta_inter):
return expit(np.dot(X_inter,theta_inter))
def LR_Costfunction(theta_inter,X_inter,y,lamada=0.):
m = X_inter.shape[0]
hyp = hpy_sigmod_fucntion(X_inter,theta_inter)
reg = np.dot(theta_inter.T,theta_inter) * (lamada / (2 * m))
J = np.dot(y.T,np.log(hyp))+np.dot((1 - y.T),np.log(1 - hyp))
return J + reg
def Gradient(theta_inter,X_inter,y,lamada=0.):
m = X_inter.shape[0]
hyp = hpy_sigmod_fucntion(X_inter,theta_inter)
hyp = np.asarray(hyp).reshape(hyp.shape[0],1)
h_y = hyp - y # 5000 * 1
reg = theta_inter[1:] * (lamada / m)
reg = np.asarray(reg).reshape(reg.shape[0],1)
grad = (1 / m) * np.dot(X_inter.T,h_y) # 401 * 1
grad[1:] = grad[1:] + reg
return grad # 401 * 1
def opt_Cost(theta,X,y,lamada=0.):
from scipy import optimize
res = optimize.fmin_bfgs(LR_Costfunction, theta, fprime=Gradient, args=(X,y,lamada) )
return result[0], result[1]
This function below maybe catch the problem.
Are there any restrictions when using fmin functions?
def training_OnevsAll_theta(X,y,num_labels,lamada=0.):
m = X.shape[0]
n = X.shape[1]
all_theta = np.zeros((num_labels,n+1))
X = np.hstack((np.ones((m,1)),X))
for c in range(num_labels):
print("Training theta for class %d" %c)
initial_theta = np.zeros((n+1,1))
theta,cost = opt_Cost(initial_theta,X,y,lamada)
all_theta[c] = theta
print("Finished!")
trained_theta = training_OnevsAll_theta(X,y,10,0.1)
Thank you!
Aha , I found the answer on matrices are not aligned Error: Python SciPy fmin_bfgs
Actually, the incorrect input gradient makes the problem occur, so I followed the answer up and add below code before 'return grad'
grad = np.ndarray.flatten(grad)
And It works!

call matlab neural network function from matlab python engine

I am trying to use the matlab neural network toolbox from matlab python engine.
Suppose for example I want to emulate the following example http://uk.mathworks.com/help/nnet/ref/fitnet.html
net = fitnet(10);
net = train(net,x,t);
view(net)
y = net(x);
perf = perform(net,y,t)
Then I have the following python code:
import numpy as np
import sys
sys.path.insert(0, '/home/donbeo/myApp/matlab_python_engine/installdir/lib/python3.4/site-packages/')
n = 100
x = np.linspace(-10, 10, n)
y = x**3 + x*2 + x + np.random.normal(0, .1, n)
plt.plot(x, y)
plt.show()
import matlab.engine
eng = matlab.engine.start_matlab()
eng.net = eng.fitnet(10.);
eng.net = eng.train(eng.net,x,t);
y_est = eng.net(x);
eng.quit()
When I run the line eng.net = eng.fitnet(10.);
I get the following error:
In [24]: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-cc577dcdc93c> in <module>()
----> 1 eng.net = eng.fitnet(10.);
/home/donbeo/myApp/matlab_python_engine/installdir/lib/python3.4/site-packages/matlab/engine/matlabengine.py in __call__(self, *args, **kwargs)
77 else:
78 return FutureResult(self._engine(), future, nargs, _stdout,
---> 79 _stderr).result()
80
81 def __validate_engine(self):
/home/donbeo/myApp/matlab_python_engine/installdir/lib/python3.4/site-packages/matlab/engine/futureresult.py in result(self, timeout)
105
106 self._result = pythonengine.getFEvalResult(
--> 107 self._future,self._nargout, None, out=self._out, err=self._err)
108 self._retrieved = True
109 return self._result
TypeError: Unsupported datatype returned from MATLAB.
In [25]:
How can I solve?
EDIT:
The command eng.net = eng.fitnet(10);
returns :
Error using network/subsasgn>network_subsasgn (line 553)
"layers{1}.size" must be a positive integer.
Error in network/subsasgn (line 13)
net = network_subsasgn(net,subscripts,v,netname);
Error in feedforwardnet>create_network (line 116)
net.layers{i}.size = param.hiddenSizes(i);
Error in feedforwardnet (line 69)
net = create_network(param);
Error in fitnet>create_network (line 98)
net = feedforwardnet(param.hiddenSizes,param.trainFcn);
Error in fitnet (line 70)
net = create_network(param);
---------------------------------------------------------------------------
MatlabExecutionError Traceback (most recent call last)
<ipython-input-29-480a6805679e> in <module>()
----> 1 eng.net = eng.fitnet(10);
/home/donbeo/myApp/matlab_python_engine/installdir/lib/python3.4/site-packages/matlab/engine/matlabengine.py in __call__(self, *args, **kwargs)
77 else:
78 return FutureResult(self._engine(), future, nargs, _stdout,
---> 79 _stderr).result()
80
81 def __validate_engine(self):
/home/donbeo/myApp/matlab_python_engine/installdir/lib/python3.4/site-packages/matlab/engine/futureresult.py in result(self, timeout)
105
106 self._result = pythonengine.getFEvalResult(
--> 107 self._future,self._nargout, None, out=self._out, err=self._err)
108 self._retrieved = True
109 return self._result
MatlabExecutionError:
File /home/donbeo/myApp/MatlabR2015a/toolbox/nnet/nnet/#network/subsasgn.p, line 553, in network_subsasgn
File /home/donbeo/myApp/MatlabR2015a/toolbox/nnet/nnet/#network/subsasgn.p, line 13, in subsasgn
File /home/donbeo/myApp/MatlabR2015a/toolbox/nnet/nnet/nnnetwork/feedforwardnet.m, line 116, in create_network
File /home/donbeo/myApp/MatlabR2015a/toolbox/nnet/nnet/nnnetwork/feedforwardnet.m, line 69, in feedforwardnet
File /home/donbeo/myApp/MatlabR2015a/toolbox/nnet/nnet/nnnetwork/fitnet.m, line 98, in create_network
File /home/donbeo/myApp/MatlabR2015a/toolbox/nnet/nnet/nnnetwork/fitnet.m, line 70, in fitnet
"layers{1}.size" must be a positive integer.
In [30]:
The best thing to do in this circumstances is to create a matlab function that can perform your required actions and then return to python variables, that it can understand. With matlab objects that python cant understand it is best to control the objects in matlab, Load them and save them in matlab every time you call matlab engine to operate. Other solution is to use handle objects but that's not a perfect solution, each solution has its ups and downs.

ValueError: x and y must have same first dimension

I get an error message
ValueError: x and y must have same first dimension.
Here is the code:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
date,bid,ask = np.loadtxt('GBPUSD1d.txt', unpack=True,
delimiter =',',converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})
avgLine = ((bid+ask)/2)
patternAr = []
performanceAr = []
patForRec = []
eachPattern = []
def percentChange(startPoint, currentPoint):
return ((float(currentPoint)- startPoint)/abs(startPoint))*100.00
def patternStorage():
patStartTime = time.time()
x = (len(avgLine))-30
y = 11
while y < x:
pattern = []
p1 = percentChange(avgLine[y-10], avgLine[y-9])
...
p10 = percentChange(avgLine[y-10], avgLine[y])
outcomeRange = avgLine[y+20:y+30]
currentPoint = avgLine[y]
try:
avgOutcome = reduce(lambda x, y: x + y, outcomeRange) / len(outcomeRange)
except Exception, e:
print str(e)
avgOutcome = 0
futureOutcome = percentChange(currentPoint, avgOutcome)
pattern.append(p1)
pattern.append(p2)
pattern.append(p3)
pattern.append(p3)
pattern.append(p4)
pattern.append(p5)
pattern.append(p6)
pattern.append(p7)
pattern.append(p8)
pattern.append(p9)
pattern.append(p10)
patternAr.append(pattern)
performanceAr.append(futureOutcome)
y += 1
patEndTime = time.time()
print len (patternAr)
print len (performanceAr)
print 'Patten storage took:', patEndTime - patStartTime, 'seconds'
def currentPattern():
cp1 = percentChange(avgLine[-11], avgLine[-10])
...
cp10 = percentChange(avgLine[-11], avgLine[-1])
patForRec.append(cp1)
...
patForRec.append(cp10)
print patForRec
def patternRecognition():
for eachPattern in patternAr:
sim1 = 100.00 - abs(percentChange(eachPattern[0], patForRec[0]))
...
sim10 = 100.00 - abs(percentChange(eachPattern[9], patForRec[9]))
howSim =((sim1+sim2+sim3+sim4+sim5+sim6+sim7+sim8+sim9+sim10))/float(10)
if howSim > 70:
patdex = patternAr.index(eachPattern)
print 'predicted outcome',performanceAr[patdex]
xp = [1,2,3,4,5,6,7,8,9,10]
fig = plt.figure()
plt.plot(xp, patForRec)
plt.plot(xp, eachPattern)
plt.show()
patternStorage()
currentPattern()
patternRecognition()
print (len(patForRec))
print (len(eachPattern))
Full error message
Traceback (most recent call last):
File "C:\Python27\ANN.py", line 165, in <module>
patternRecognition()
File "C:\Python27\ANN.py", line 131, in patternRecognition
plt.plot(xp, eachPattern)
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 3093, in plot
ret = ax.plot(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\axes\_axes.py", line 1373, in plot
for line in self._get_lines(*args, **kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 303, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 281, in _plot_args
x, y = self._xy_from_xy(x, y)
File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 223, in _xy_from_xy
raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension
The problem is that eachPattern has a 11 elements in it, whereas all xp has 10. The reason for this is probably on lines 52 and 53 in the patternStorage function of your code where you append p3 to your list twice:
pattern.append(p3)
pattern.append(p3)
if you get rid of one of these the graph plots fine. Though it is stored in a loop to plot multiple times, don't know if you wanted to do that...
If you try and do more things inside loops, so you have to write less code, this sort of problem where you accidentally do something twice will happen less.

Categories

Resources