Pass data array to interact function? - python

Is it possible to pass data arrays (numpy arrays) to the interact function ?
My data are loaded from a csv file bad.csv and stored into numpy arrays: u, v, w and uNorm for example.
I've tried to use the following code snippet without luck:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np
from IPython.html.widgets import interact, fixed
fileName = './bad.csv'
p,u,v,w,x,y,z = np.loadtxt(fileName,delimiter=',',skiprows=1,usecols=(0,1,2,3,4,5,6),unpack=True)
uNorm = np.sqrt(u**2 + v**2 + w**2)
r = np.sqrt(y**2 + x**2)
tang = (y / x)
aux_tri = mtri.Triangulation(r/np.max(r), tang/np.max(tang))
triang = mtri.Triangulation(x, y, aux_tri.triangles)
triang.set_mask(mtri.TriAnalyzer(aux_tri).get_flat_tri_mask())
def plotContour(data=w, legendName='Legend', gridOn=True, edgeColors='black'):
plt.gca().set_aspect('equal')
plt.tripcolor(triang,data,NbLevels,cmap=cm.hot_r,edgecolors=edgeColors)
plt.grid(gridOn)
cbar = plt.colorbar()
cbar.set_label(legendName,labelpad=10)
interact(plotContour, data={'u':fixed(u),'v':fixed(v),'w':fixed(w),'Magnitude':fixed(uNorm)}, edgeColors=('Black','None'));
The first time this snippet is run everything works correctly as the default value for data is w.
But when I try to use the dropdown menus I got the following error:
/usr/local/lib/python2.7/dist-packages/matplotlib/tri/tripcolor.pyc in tripcolor(ax, *args, **kwargs)
74 # length of C whether it refers to points or faces.
75 # Do not do this for gouraud shading.
---> 76 if (facecolors is None and len(C) == len(tri.triangles) and
77 len(C) != len(tri.x) and shading != 'gouraud'):
78 facecolors = C
TypeError: len() of unsized object
So how to pass numpy arrays in a dropdown menus ?

Related

Implementation of NLMS for a one dimensional array with padasip

I am trying to implement an NLMS filter per the Padasipexample:
https://matousc89.github.io/padasip/sources/filters/nlms.html
I need to filter a one dimensional array. I adjusted the code but I'm getting an error
File "C:\Python310\lib\site-packages\padasip\filters\base_filter.py", line 194, in run
self.n = len(x[0])
TypeError: object of type 'numpy.float64' has no len()
I understand that a int doesn't have a length, however I'm not clear how do implement NLMS with a single array.
Full Code:
import numpy as np
import matplotlib.pylab as plt
import padasip as pa
# creation of data
N = 10000
x = np.random.normal(0, 1, N) # input matrix
v = np.random.normal(0, 0.1, N) # noise
d = x + v
# identification
TAP=5000
f = pa.filters.FilterNLMS(n=TAP, mu=0.1, w="random")
y, e, w = f.run(d, x)
# show results
plt.figure(figsize=(15,9))
plt.subplot(211);plt.title("Adaptation");plt.xlabel("samples - k")
plt.plot(d,"b", label="d - target")
plt.plot(y,"g", label="y - output");plt.legend()
plt.subplot(212);plt.title("Filter error");plt.xlabel("samples - k")
plt.plot(10*np.log10(e**2),"r", label="e - error [dB]");plt.legend()
plt.tight_layout()
plt.show()

int() argument must be a string, a bytes-like object or a number, not 'list'

I am trying to plot a graph using matplotlib.pyplot in Python but getting an error:
int() argument must be a string, a bytes-like object or a number, not
'list'
in the second-to-last line.
Here is the code:
import numpy as np
import random
import matplotlib.pyplot as plt
#constants
mUn0 = 1350
Vcat = 18000000
n = 2 * pow(10,16)
e = 1.6 * pow(10,-19)
#variable
E = 1000
d = []
f = []
for i in range(1,E):
j = log(n*e*mUn0) + log(i) - 0.5 * log(1+pow((mUn0*i/Vcat),2))
f.append(j)
d.append(log(i))
plt.xlabel('E')
plt.ylabel('V')
plt.subplot(2,1,2)
plt.subplot(f,d,'bo')
plt.show()
Thank you
pyplot.subplot() requires subplot(nrows, ncols, plot_number), all three options are integers.
Matplotlib is trying to cast your f and d lists to integer type and failing.
Just a couple of small issues. You have to use plt.plot() to plot, and you can't just use log, you need np.log() or to import the math module and then use math.log(). I noted the lines I changed with #FIXED
import numpy as np
import random
import matplotlib.pyplot as plt
#constants
mUn0 = 1350
Vcat = 18000000
n = 2 * pow(10,16)
e = 1.6 * pow(10,-19)
#variable
E = 1000
d = []
f = []
for i in range(1,E):
j = np.log(n*e*mUn0) + np.log(i) - 0.5 * np.log(1+pow((mUn0*i/Vcat),2)) #FIXED
f.append(j)
d.append(np.log(i)) #FIXED
plt.xlabel('E')
plt.ylabel('V')
plt.subplot(2,1,2) #not needed, but maybe a holdover from full code
plt.plot(f,d,'bo') #FIXED
plt.show()
That takes care of the syntax errors. Using a subplot works with one plot but you don't need it, so I don't know what type of logic error that is (do you want two plots?)

Solving nonlinear differential first order equations using Python

I would like to solve a nonlinear first order differential equation using Python.
For instance,
df/dt = f**4
I wrote the following program, but I have an issue with matplotlib, so I don't know if the method I used with scipy is correct.
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
derivate=lambda f,t: f**4
f0=10
t=np.linspace(0,2,100)
f_numeric=scipy.integrate.odeint(derivate,f0,t)
print(f_numeric)
plt.plot(t,f_numeric)
plt.show()
Which results in the following error:
AttributeError: 'float' object has no attribute 'rint'
In this case, you might be better of using Sympy, which allows you to obtain the closed form solutions:
from IPython.display import display
import sympy as sy
from sympy.solvers.ode import dsolve
import matplotlib.pyplot as plt
import numpy as np
sy.init_printing() # LaTeX like pretty printing for IPython
t = sy.symbols("t", real=True)
f = sy.symbols("f", function=True)
eq1 = sy.Eq(f(t).diff(t), f(t)**4) # the equation
sls = dsolve(eq1) # solvde ODE
# print solutions:
print("For ode")
display(eq1)
print("the solutions are:")
for s in sls:
display(s)
# plot solutions:
x = np.linspace(0, 2, 100)
fg, axx = plt.subplots(2, 1)
axx[0].set_title("Real part of solution of $\\frac{d}{dt}f(t)= (f(t))^4$")
axx[1].set_title("Imag. part of solution of $\\frac{d}{dt}f(t)= (f(t))^4$")
fg.suptitle("$C_1=0.1$")
for i, s in enumerate(sls, start=1):
fn1 = s.rhs.subs("C1", .1) # C_1 -> 1
fn2 = sy.lambdify(t, fn1, modules="numpy") # make numpy function
y = fn2(x+0j) # needs to be called with complex number
axx[0].plot(x, np.real(y), label="Sol. %d" % i)
axx[1].plot(x, np.imag(y), label="Sol. %d" % i)
for ax in axx:
ax.legend(loc="best")
ax.grid(True)
axx[0].set_ylabel("Re$\\{f(t)\\}$")
axx[1].set_ylabel("Im$\\{f(t)\\}$")
axx[-1].set_xlabel("$t$")
fg.canvas.draw()
plt.show()
In an IPython shell, you should see the following:

Mathieu Characteristics Cross When Plotted

I need to plot the mathieu characteristic parameters for various q. The plot should show 'flute' shapes going from wide on the left, to very narrow on the right. The code below does this, but it also introduces a handful of inter-band jumps (obvious from the plotted figure). How can I fix this?
Thank you!
AM
import numpy as np
import scipy as sp
import scipy.special as spfun
from matplotlib import pyplot as plt
uplim =120#E_rec
Npts =1000
Nstates =8
q = np.linspace(0, uplim/4.0, Npts)
EA = np.zeros([Npts,Nstates])
EB = np.zeros([Npts,Nstates])
U = 4*q
print np.shape(EA) #plt.fill_between(U, EA[:,i], EB[:,i]) #plt.plot(U,Ea,U,Eb)
for i in range(Nstates):
a = spfun.mathieu_a(i,q)
b = spfun.mathieu_b(i+1,q)
EA[:,i] = a + 2*q
EB[:,i] = b + 2*q
plt.fill_between(U, EA[:,i], EB[:,i]) #plt.plot(U,Ea,U,Eb)
print np.shape(EA) #plt.fill_between(U, EA[:,i], EB[:,i]) #plt.plot(U,Ea,U,Eb)
plt.show()
EDIT As DSM and pv have pointed out, this is a scipy bug. The glitches get worse as you go out further. What I ended up doing was exporting tables of values that I wanted from Mathematica, and importing them into python and interpolating. Not great, but works.
I tried computing this with the latest release of the NAG Library for Python which included a new Mathieu function routine.
I pushed a little harder -- more states and a higher value of uplim.
%matplotlib inline
import numpy as np
import scipy as sp
import scipy.special as spfun
from naginterfaces.library import specfun
from matplotlib import pyplot as plt
uplim =150#E_rec
Npts = 4000
Nstates = 10
q = np.linspace(0, uplim/4.0, Npts)
EA = np.zeros([Npts,Nstates])
EB = np.zeros([Npts,Nstates])
U = 4*q
plt.figure(figsize=(15,8))
plt.subplot(1,2,1)
plt.title('Using SciPy')
for i in range(Nstates):
a = spfun.mathieu_a(i,q)
b = spfun.mathieu_b(i+1,q)
EA[:,i] = a + 2*q
EB[:,i] = b + 2*q
plt.fill_between(U, EA[:,i], EB[:,i]) #plt.plot(U,Ea,U,Eb)
plt.subplot(1,2,2)
plt.title('Using NAG')
for i in range(Nstates):
a = [specfun.mathieu_ang_periodic_real(ordval=i, q=qi, parity=0, mode=3)[2] for qi in q]
b = [specfun.mathieu_ang_periodic_real(ordval=i+1, q=qi, parity=1, mode=3)[2] for qi in q]
EA[:,i] = a + 2*q
EB[:,i] = b + 2*q
plt.fill_between(U, EA[:,i], EB[:,i])
plt.show()
This uses Mark 27 of the NAG Library and version 1.2.1 of ScipPy

How do you loop through an array, perform calculations on the arrays and plot the results?

I am very new to programming, and would appreciate some assistance with my program. I'm trying to read in arrays through a for loop, do some calculations on them and plot the result on a 3D graph, but it gives me the error:
IndexError: index 753 is out of bounds for axis 0 with size 753
Here's the code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import math
from itertools import product, combinations
from numpy import *
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
ra_day = loadtxt("RA Days.txt")
ra_minute = loadtxt("RA Minutes.txt")
ra_second = loadtxt("RA Seconds.txt")
ra = ra_day + (ra_minute/60) + (ra_second/3600)
dec_day = loadtxt("DEC Days.txt")
dec_minute = loadtxt("DEC Minutes.txt")
dec_second = loadtxt("DEC Seconds.txt")
dec = dec_day + (dec_minute/60) + (dec_second/3600)
dist = loadtxt("Distance.txt")
for i in range(len(ra)):
x = math.cos(ra[i]) * (dist[i] * math.cos(dec[i]))
y = math.sin(ra[i]) * (dist[i] * math.cos(dec[i]))
z = dist * math.sin(dec[i])
ax.scatter([0],[0],[0],color="b",s=100)
ax.scatter([x],[y],[z],color="k",s=100)
plt.show()
I don't know the language but generally an index out of bounds is when the starting and ending indexes are incorrect. Starting at zero until length instead of length-1 etc. Might be worth looking at that in particular until someone posts an answer who knows the language. Hope I may have helped

Categories

Resources