i am struggling with the quiver function in python.
I want to create a 2D vector field of a given 2D array containing the two components of the vectors using quiver.
Given the array b:
>>> b
VigraArray(shape=(512, 512, 2), axistags=x y c, dtype=float32, data=
[[[ 0.59471679 0.51902866 0.38904327 ..., -0.56878477 -0.50834674
-0.48382956]
[ 0.58222073 0.50713873 0.37990916 ..., -0.56091702 -0.50057167
-0.47613338]
[ 0.53815156 0.46551338 0.34787226 ..., -0.54245669 -0.48314109
-0.45911735]
...,
and using quiver:
>>> X,Y = meshgrid(range(b.shape[0]),range(b.shape[1]))
>>> quiver(X,Y,b[...,0],b[...,1])
returns:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2892, in quiver
ret = ax.quiver(*args, **kw)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 6641, in quiver
q = mquiver.Quiver(self, *args, **kw)
File "/usr/lib/pymodules/python2.7/matplotlib/quiver.py", line 419, in __init__
self.set_UVC(U, V, C)
File "/usr/lib/pymodules/python2.7/matplotlib/quiver.py", line 463, in set_UVC
U = ma.masked_invalid(U, copy=False).ravel()
File "/usr/lib/python2.7/dist-packages/numpy/ma/core.py", line 3969, in ravel
r._mask = ndarray.ravel(self._mask).reshape(r.shape)
File "/usr/lib/python2.7/dist-packages/vigra/arraytypes.py", line 1308, in reshape
res = numpy.ndarray.reshape(self, shape, order)
TypeError: an integer is required
I never had problems using VigraArray with matplotlib, so i don't think this is the problem. Thanks for help!
As a matter of fact it seems that pylab.quiver does not handle vigra.VigraArray correctly. The following substitution worked for me:
b[...,0] = numpy.array(b[...,0])
b[...,1] = numpy.array(b[...,1])
Related
I want to calculate the exponential of a 200x200 matrix (expm(B)) and get the following problem. Thanks a lot for your help.
exp_matrix2 = expm(B)
File ".../python2.7/site-packages/scipy/linalg/matfuncs.py", line
261, in expm
return scipy.sparse.linalg.expm(A)
File ".../python2.7/site-packages/scipy/sparse/linalg/matfuncs.py",
line 582, in expm
return _expm(A, use_exact_onenorm='auto')
File ".../python2.7/site-packages/scipy/sparse/linalg/matfuncs.py",
line 618, in _expm
eta_1 = max(h.d4_loose, h.d6_loose)
File ".../python2.7/site-packages/scipy/sparse/linalg/matfuncs.py",
line 457, in d4_loose
structure=self.structure)**(1/4.)
File ".../python2.7/site-packages/scipy/sparse/linalg/matfuncs.py",
line 301, in _onenormest_matrix_power
MatrixPowerOperator(A, p, structure=structure))
File ".../python2.7/site-packages/scipy/sparse/linalg/_onenormest.py",
line 95, in onenormest
est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax)
File "/python2.7/site-packages/scipy/sparse/linalg/_onenormest.py",
line 424, in _onenormest_core
Z = np.asarray(AT_linear_operator.matmat(S))
File ".../python2.7/site-packages/scipy/sparse/linalg/interface.py",
line 326, in matmat
Y = self._matmat(X)
File ".../python2.7/site-packages/scipy/sparse/linalg/interface.py",
line 468, in _matmat
return super(_CustomLinearOperator, self)._matmat(X)
File ".../python2.7/site-packages/scipy/sparse/linalg/interface.py",
line 174, in _matmat
return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T])
File
"/home/dk2518/anaconda2/lib/python2.7/site-packages/scipy/sparse/linalg/interface.py",
line 219, in matvec
y = self._matvec(x)
File ".../python2.7/site-packages/scipy/sparse/linalg/interface.py",
line 471, in _matvec
return self.__matvec_impl(x)
File ".../python2.7/site-packages/scipy/sparse/linalg/interface.py",
line 266, in rmatvec
y = self._rmatvec(x)
File ".../python2.7/site-packages/scipy/sparse/linalg/matfuncs.py",
line 203, in _rmatvec
x = A_T.dot(x)
ValueError: shapes (207,207) and (1,207) not aligned: 207 (dim 1) != 1
(dim 0)
As discussed in #TomNash's link, a large np.matrix is the problem.
ndarray and sparse matrix work fine:
In [309]: slg.expm(np.ones((200,200)));
In [310]: slg.expm(sparse.csc_matrix(np.ones((200,200))));
In [311]: slg.expm(np.matrix(np.ones((200,200))));
ValueError: shapes (200,200) and (1,200) not aligned: 200 (dim 1) != 1 (dim 0)
Not every np.matrix gives problems:
In [313]: slg.expm(np.matrix(np.eye(200)));
Turning the np.matrix back into ndarray works:
In [315]: slg.expm(np.matrix(np.ones((200,200))).A);
This uses slg.matfuncs._expm(A, use_exact_onenorm='auto')
which has an test, early one, for:
if use_exact_onenorm == "auto":
# Hardcode a matrix order threshold for exact vs. estimated one-norms.
use_exact_onenorm = A.shape[0] < 200
That explains, in part, why we get the problem with a (200,200) matrix, but not a (199,199).
This works:
slg.matfuncs._expm(M, use_exact_onenorm=True);
It fails with False. But from there I get lost in the details of how it sets up _ExpmPadeHelper and attempts a Pade order 3.
In short - avoid np.matrix, especially if (200,200) or larger.
I'm trying to extract tonnetz from the harmonic components of my audio. My code is basically a copy paste from the tutorial https://librosa.github.io/librosa/generated/librosa.feature.tonnetz.html
My code:
import librosa
def extract_feature(file_name):
y, sr = librosa.load(file_name)
y = librosa.effects.harmonic(y)
tonnetz = librosa.feature.tonnetz(y=y, sr=sr)
return tonnetz
print extract_feature("out.wav")
Here's the stack trace:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/pitch.py:160: DeprecationWarning: object of type <type 'numpy.float64'> cannot be safely interpreted as an integer.
bins = np.linspace(-0.5, 0.5, np.ceil(1./resolution), endpoint=False)
Traceback (most recent call last):
File "test_python.py", line 10, in <module>
print extract_feature("out.wav")
File "test_python.py", line 6, in extract_feature
tonnetz = librosa.feature.tonnetz(y=y, sr=sr)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/feature/spectral.py", line 1157, in tonnetz
chroma = chroma_cqt(y=y, sr=sr)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/feature/spectral.py", line 936, in chroma_cqt
real=False))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/constantq.py", line 251, in cqt
cqt_resp.append(__cqt_response(my_y, n_fft, my_hop, fft_basis))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/constantq.py", line 531, in __cqt_response
D = stft(y, n_fft=n_fft, hop_length=hop_length, window=np.ones)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/spectrum.py", line 167, in stft
y_frames = util.frame(y, frame_length=n_fft, hop_length=hop_length)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/util/utils.py", line 102, in frame
strides=(y.itemsize, hop_length * y.itemsize))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/stride_tricks.py", line 102, in as_strided
array = np.asarray(DummyArray(interface, base=x))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/numeric.py", line 531, in asarray
return array(a, dtype, copy=False, order=order)
TypeError: 'float' object cannot be interpreted as an index
Any idea how to fix this?
I rolled back to numpy 1.10.1 to fix this issue (although I was running chroma_cqt and getting this error).
Numpy > 1.11 as_strided makes a dummyarray and asarray does not handle the float array properly. 1.10.1 numpy has better stride_tricks, apparently.
I have following codes to plot a gassian-2d contour,but I get this Error:
Traceback (most recent call last):
File "question.py", line 15, in <module>
Z0=gaussian_2d(X0,Y0,2,3,cov)
File "question.py", line 4, in gaussian_2d
return exp(-0.5*mat([x-x0,y-y0])*sigmaMatrix.I*mat([x-x0,y-y0]).T)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/matrixlib/defmatrix.py", line 96, in asmatrix
return matrix(data, dtype=dtype, copy=False)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/matrixlib/defmatrix.py", line 272, in __new__
raise ValueError("matrix must be 2-dimensional")
ValueError: matrix must be 2-dimensional
This my code:
import matplotlib.pyplot as plt
from numpy import *
def gaussian_2d(x, y, x0, y0, sigmaMatrix):
return exp(-0.5*mat([x-x0,y-y0])*sigmaMatrix.I*mat([x-x0,y-y0]).T)
cov=mat([[1,0],[0,2]])
delta=0.025
xgrid=arange(-2, 6, delta)
ygrid=arange(-2, 6, delta)
X0, Y0 = meshgrid(xgrid, ygrid)
Z0=gaussian_2d(X0,Y0,2,3,cov)
Can anyone tell me what am i doing wrong here?
Error starts from the concatenation but also your matrix dimensions don't match.
You are performing a quadratic form multiplication x^T A x but your meshgrid variables are square matrices of 320x320. Your A matrix cov is 2x2 hence you get an error.
If the sizes matches you can column concatenate mat(c_[x-x0,y-y0]) or use any other stacking option.
I want to make a 2d histogramme by putting two 2D array as argument, Tx and alt_array, same size (56000,40)
def histo_2D(alt, Tx):
u,v = 56000,40
Tx = np.zeros((u,v))
alt_array = np.zeros((u,v))
alt,tx = np.zeros((v)), np.zeros((v))
for i in range(0,v):
alt[i] = i
tx[i] = i
alt_array[:][:] = alt
Tx[:][:] = tx
alt_array[:][:] = alt
print np.shape(Tx), np.shape(alt_array)
plt.hist2d(Tx , alt_array)
But when i try to execute my program, i get this error message :
Traceback (most recent call last):
File "goccp.py", line 516, in <module>
histo_2D(alt,Tx)
File "goccp.py", line 376, in histo_2D
plt.hist2d(Tx , alt_array)
File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2847, in hist2d
weights=weights, cmin=cmin, cmax=cmax, **kwargs)
File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 8628, in hist2d
normed=normed, weights=weights)
File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/twodim_base.py", line 650, in histogram2d
hist, edges = histogramdd([x, y], bins, range, normed, weights)
File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py", line 288, in histogramdd
N, D = sample.shape
ValueError: too many values to unpack
I've tried to use flattened array, but the result is not really good...
The documentation for hist2d states:
matplotlib.pyplot.hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, cmax=None, hold=None, **kwargs)
Parameters: x, y: array_like, shape (n, ) :
Thus x and y need to be one dimensional; your values are two dimensional.
Have a look at the example as well, given at the end of the documentation.
I am using matplotlib's contourf function to display z data as function of x and y. I am able to use a numpy array of datetime objects as the x-axis if x and y are 1-d arrays. However, When I make my x and y arrays 2-dimensional, contourf breaks on 2-d array of datetime objects. Example follows:
import numpy as np
from datetime import datetime,timedelta
import matplotlib.pyplot as plt
x = np.array([datetime(2012,12,12),datetime(2012,12,13),datetime(2012,12,14)])
y = np.arange(10)
z = np.random.random((10,3))
plt.contourf(x,y,z)
This example works and produces an expected result. However, if I do this:
x = np.tile(np.reshape(x,( 1,3)),(10,1))
y = np.tile(np.reshape(y,(10,1)),( 1,3))
so that x, y, and z are all of shape (10,3), contourf(x,y,z) yields this traceback:
Traceback (most recent call last):
File "./test_2d_datetime.py", line 14, in <module>
plt.contourf(x,y,z)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2206, in contourf
ret = ax.contourf(*args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/axes.py", line 7322, in contourf
return mcontour.QuadContourSet(self, *args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1106, in __init__
ContourSet.__init__(self, ax, *args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 700, in __init__
self._process_args(*args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1119, in _process_args
x, y, z = self._contour_args(args, kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1166, in _contour_args
x,y,z = self._check_xyz(args[:3], kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1194, in _check_xyz
x = np.asarray(x, dtype=np.float64)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/numpy/core/numeric.py", line 235, in asarray
return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number
If I use a 2-d array of matplotlib.dates.date2num() values instead of datetime objects, contourf() works as expected.
Is there a remedy for the problem I am encountering? I am using Python 2.7.3 with matplotlib 1.1.0 on 64-bit Linux.