matplotlib streamplot error for a specific number of gridpoints - python

The following minimal code snippet fails when n=29 but works when n=28 or n=30.
import numpy
import matplotlib.pyplot as plt
x = np.linspace(0,1,n)
plt.streamplot(x,x,np.meshgrid(x,x)[0],np.meshgrid(x,x)[1])
plt.show()
The error given when n=29 is
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~/.local/lib/python3.6/site-packages/matplotlib/streamplot.py in _integrate_rk12(x0, y0, dmap, f, maxlength)
526 try:
--> 527 k1x, k1y = f(xi, yi)
528 k2x, k2y = f(xi + ds * k1x,
~/.local/lib/python3.6/site-packages/matplotlib/streamplot.py in backward_time(xi, yi)
434 def backward_time(xi, yi):
--> 435 dxi, dyi = forward_time(xi, yi)
436 return -dxi, -dyi
~/.local/lib/python3.6/site-packages/matplotlib/streamplot.py in forward_time(xi, yi)
425 def forward_time(xi, yi):
--> 426 ds_dt = interpgrid(speed, xi, yi)
427 if ds_dt == 0:
~/.local/lib/python3.6/site-packages/matplotlib/streamplot.py in interpgrid(a, xi, yi)
619 a00 = a[y, x]
--> 620 a01 = a[y, xn]
621 a10 = a[yn, x]
~/.local/lib/python3.6/site-packages/numpy/ma/core.py in __getitem__(self, indx)
3196 # So it's easier to stick to the current version
-> 3197 dout = self.data[indx]
3198 _mask = self._mask
IndexError: index 29 is out of bounds for axis 1 with size 29
This has been driving me crazy for a while. The plots are generated when n=28 or n=30. I even checked the code on google collab to make sure that I did not screw up my libraries somehow.
Here's the link
Any idea as to why this is happening?

This is because of an indexing error in the matplotlib 2.2.x series. Solved in matplotlib 3.x with this patch. The github issue for the bug I created is here. The patch might get backported to 2.2.x

Related

How to plot a windrose when the wind direction is a categorical value

From Dataset Australia Rainfall, I'm trying to predict RainTomorrow. Here is my code given below :
Downloading dataset directly from Kaggle using opendatasets library
import opendatasets as od
dataset_url = 'https://www.kaggle.com/jsphyg/weather-dataset-rattle-package'
od.download(dataset_url)
Importing necessary libraries
import os
import pandas as pd
import numpy as np
import plotly.express as px
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_style('darkgrid')
matplotlib.rcParams['font.size'] = 14
matplotlib.rcParams['figure.figsize'] = (10,6)
matplotlib.rcParams['figure.facecolor'] = '#00000000'
Loading Dataset
data_dir = './weather-dataset-rattle-package'
os.listdir(data_dir)
train_csv = data_dir + '/weatherAUS.csv'
raw_df = pd.read_csv(train_csv)
Explore WindGustDir variable
print('WindGustDir contains', len(raw_df['WindGustDir'].unique()), 'labels')
raw_df['WindGustDir'].unique()
raw_df.WindGustDir.value_counts()
pd.get_dummies(raw_df.WindGustDir, drop_first=True, dummy_na=True).head()
pd.get_dummies(raw_df.WindGustDir, drop_first=True, dummy_na=True).sum(axis=0)
Plotting Windrose
from windrose import WindroseAxes
ax = WindroseAxes.from_ax()
ax.bar(raw_df.WindGustDir, raw_df.Rainfall, normed=True, opening=0.8,
edgecolor='white')
ax.set_legend()
I am unable to figure out which columns should use with WindGustDir or if their is any other option of compare RainTomorrow and WindGustDir .
Error Message
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
57 try:
---> 58 return bound(*args, **kwds)
59 except TypeError:
TypeError: '<' not supported between instances of 'float' and 'str'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-253-1a1f0fa6bf7a> in <module>
1 ax = WindroseAxes.from_ax()
----> 2 ax.bar(direction=df.WindGustDir, var=df.Rainfall, normed=True, opening=0.8, edgecolor='white')
3 ax.set_legend()
e:\Anaconda3\lib\site-packages\windrose\windrose.py in bar(self, direction, var, **kwargs)
547 """
548
--> 549 bins, nbins, nsector, colors, angles, kwargs = self._init_plot(
550 direction, var, **kwargs
551 )
e:\Anaconda3\lib\site-packages\windrose\windrose.py in _init_plot(self, direction, var, **kwargs)
359
360 # Set the global information dictionnary
--> 361 self._info["dir"], self._info["bins"], self._info["table"] = histogram(
362 direction, var, bins, nsector, normed, blowto
363 )
e:\Anaconda3\lib\site-packages\windrose\windrose.py in histogram(direction, var, bins, nsector, normed, blowto)
746 direction[direction >= 360.] = direction[direction >= 360.] - 360
747
--> 748 table = histogram2d(x=var, y=direction, bins=[var_bins, dir_bins], normed=False)[0]
749 # add the last value to the first to have the table of North winds
750 table[:, 0] = table[:, 0] + table[:, -1]
<__array_function__ internals> in histogram2d(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\lib\twodim_base.py in histogram2d(x, y, bins, range, normed, weights, density)
742 xedges = yedges = asarray(bins)
743 bins = [xedges, yedges]
--> 744 hist, edges = histogramdd([x, y], bins, range, normed, weights, density)
745 return hist, edges[0], edges[1]
746
<__array_function__ internals> in histogramdd(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\lib\histograms.py in histogramdd(sample, bins, range, normed, weights, density)
1071
1072 # Compute the bin number each sample falls into.
-> 1073 Ncount = tuple(
1074 # avoid np.digitize to work around gh-11022
1075 np.searchsorted(edges[i], sample[:, i], side='right')
e:\Anaconda3\lib\site-packages\numpy\lib\histograms.py in <genexpr>(.0)
1073 Ncount = tuple(
1074 # avoid np.digitize to work around gh-11022
-> 1075 np.searchsorted(edges[i], sample[:, i], side='right')
1076 for i in _range(D)
1077 )
<__array_function__ internals> in searchsorted(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in searchsorted(a, v, side, sorter)
1346
1347 """
-> 1348 return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
1349
1350
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
65 # Call _wrapit from within the except clause to ensure a potential
66 # exception has a traceback chain.
---> 67 return _wrapit(obj, method, *args, **kwds)
68
69
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapit(obj, method, *args, **kwds)
42 except AttributeError:
43 wrap = None
---> 44 result = getattr(asarray(obj), method)(*args, **kwds)
45 if wrap:
46 if not isinstance(result, mu.ndarray):
TypeError: '<' not supported between instances of 'float' and 'str'
It seems that the direction parameter must be numeric.
Create a dict where each key is a each direction in 'WindGustDir' and the corresponding value is a float in degrees.
.map the dict to df.WindGustDir and plot
Alternatively, create and plot a new column
df.insert(loc=8, column='WindGustDirDeg', value=df.WindGustDir.map(wind_dir_deg))
import pandas as pd
from windrose import WindroseAxes
import numpy as np
# load the downloaded data and dropna
df = pd.read_csv('weatherAUS/weatherAUS.csv').dropna(subset=['WindGustDir'])
# create a dict for WindGustDir to numeric values
wind_dir = ['E', 'ENE', 'NE', 'NNE', 'N', 'NNE', 'NW', 'WNW', 'W', 'WSW', 'SW', 'SSW', 'S', 'SSE', 'SE', 'ESE']
degrees = np.arange(0, 360, 22.5)
wind_dir_deg = dict((zip(wind_dir, degrees)))
# plot and map WindGustDir to the dict
ax = WindroseAxes.from_ax()
ax.bar(direction=df.WindGustDir.map(wind_dir_deg), var=df.Rainfall, normed=True, opening=0.8, edgecolor='white')
ax.set_legend()

3D graph error: "The truth value of an array with more than one element is ambiguous"

I am trying to plot a 3D graph, using a re-existing function to generate the Z values. However, this is yielding the error "The truth value of an array with more than one element is ambiguous". This seems strange, as I am able to generate a list of Z values using the same function and y,x values, but once I include the 3D graphing code the error occurs.
My graphing code is:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm
def f(tau,tau_b): #re-use society welfare function of tau & tau_b, using corr=0.6
Z = society_welfare2 (0.6, tau, tau_b)
return Z
xgrid=np.linspace(1e-5, 1-1e-5,100) #tau grid
ygrid=np.linspace(1e-5, 1-1e-5,100) #tau_b grid
tau,tau_b=np.meshgrid(xgrid,ygrid)
fig=plt.figure(figsize=(8,6))
ax=fig.add_subplot(111,projection='3d')
ax.plot_surface(tau,
tau_b,
f(tau,tau_b),
rstride=2,cstride=2,
cmap=cm.jet,
alpha=0.7,
linewidth=0.25)
ax.set_zlim(-0.5,1.0)
plt.show()
My society_welfare2 function code:
def society_welfare2 (corr, tau, tau_b):
cov = [[1,corr], [corr,1]] #covariance
epsilon_start,b_start = np.random.multivariate_normal(mean, cov, sample_N).T
epsilon = np.exp(epsilon_start) #to ensure epsilon positive
b = np.exp(b_start) #to ensure b positive
indv_welfares = []
def GBC (t_o):
taxes_paid = []
for i in range(sample_N): #loop over all agents to find their C1,C2,L
def consumption_functions(Lguess,epsilon=epsilon,b=b):
C2 = (((1-tau)*epsilon[i]*w*Lguess) +(1-tau_b)*b[i] + ((t_o)/(1+r)))/((1/((beta**(1/gamma))*((1+r)**(1/gamma)))) + (1/(1+r)))
C1 = C2 /((beta**(1/gamma))*(1+r)**(1/gamma))
return -Utility(C1,C2,Lguess)
result = minimize_scalar(consumption_functions,bounds=(0,1),method='bounded', args=(epsilon, b))
opt_L = result.x
opt_C1=(((1-tau)*(epsilon[i])*w)/(opt_L**sigma))**(1/gamma)
opt_C2=(opt_C1)*((beta**(1/gamma))*(1+r)**(1/gamma))
income_tax = tau*(epsilon[i])*w*opt_L
bequest_tax = tau_b*(b[i])
taxes_paid.append(income_tax)
taxes_paid.append(bequest_tax)
welfare_func = opt_C1**(1-gamma)/(1-gamma)-opt_L**(1+sigma)/(1+sigma) + beta*(opt_C2**(1-gamma)/(1-gamma))
indv_welfares.append(welfare_func)
total_tax_revenue = sum(taxes_paid)
return total_tax_revenue - (10000*t_o)
result1 = minimize_scalar(GBC,bounds=(1e-5, 100000),method='bounded')
opt_t_o = result1.x
total_welfare = sum(indv_welfares)
return total_welfare
The full traceback error code:
ValueError Traceback (most recent call last)
<ipython-input-19-3633f4a9db76> in <module>
18 ax.plot_surface(tau,
19 tau_b,
---> 20 f(tau,tau_b),
21 rstride=2,cstride=2,
22 cmap=cm.jet,
<ipython-input-19-3633f4a9db76> in f(tau, tau_b)
7
8 def f(tau,tau_b): #re-use society welfare function of tau & tau_b, using corr=0.6
----> 9 Z = society_welfare2 (0.6, tau, tau_b)
10 return Z
11
<ipython-input-17-321a709b9684> in society_welfare2(corr, tau, tau_b)
61 return total_tax_revenue - (10000*t_o)
62
---> 63 result1 = minimize_scalar(GBC,bounds=(1e-5, 100000),method='bounded')
64
65 opt_t_o = result1.x
/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/_minimize.py in minimize_scalar(fun, bracket, bounds, args, method, tol, options)
798 if isinstance(disp, bool):
799 options['disp'] = 2 * int(disp)
--> 800 return _minimize_scalar_bounded(fun, bounds, args, **options)
801 elif meth == 'golden':
802 return _minimize_scalar_golden(fun, bracket, args, **options)
/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/optimize.py in _minimize_scalar_bounded(func, bounds, args, xatol, maxiter, disp, **unknown_options)
1956 rat = e = 0.0
1957 x = xf
-> 1958 fx = func(x, *args)
1959 num = 1
1960 fmin_data = (1, xf, fx)
<ipython-input-17-321a709b9684> in GBC(t_o)
41 return -Utility(C1,C2,Lguess)
42
---> 43 result = minimize_scalar(consumption_functions,bounds=(0,1),method='bounded', args=(epsilon, b))
44
45 opt_L = result.x
/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/_minimize.py in minimize_scalar(fun, bracket, bounds, args, method, tol, options)
798 if isinstance(disp, bool):
799 options['disp'] = 2 * int(disp)
--> 800 return _minimize_scalar_bounded(fun, bounds, args, **options)
801 elif meth == 'golden':
802 return _minimize_scalar_golden(fun, bracket, args, **options)
/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/optimize.py in _minimize_scalar_bounded(func, bounds, args, xatol, maxiter, disp, **unknown_options)
2015 print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)))
2016
-> 2017 if fu <= fx:
2018 if x >= xf:
2019 a = xf
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The lowest point the trace back is
if fu <= fx:
That's comparing two variables in an if. That will work if fu and fx are scalars, or single value arrays. But if either is a multivalue array if will raise this error.
Our task at this point is to trace those variables back to your code. I suspect you are providing arrays for some parameter, where they/is should be a scalar.
Looking at the top. It occurs when you ask for the plot, but a parameter is a function call:
f(tau,tau_b)
and on through a function calls to the minimize on the GBC function. I think that GBC is the func in:
fx = func(x, *args)
Which raises the question, what exactly does GBC return? It's being used in a _minimize_scalar, so it should return exactly one value.
What is its return expression?
return total_tax_revenue - (10000*t_o)
Do you think you can take the analysis from there?
Now do you see why we insist on seeing the traceback. The error is in your code, but the sequence getting there is long, and not obvious from simply reading the code.
edit
Oops, I see another level of minimize, one that uses
consumption_functions
It has several parameters, epsilon and b. I suppose we can deduce what those are. But what is
Utility
The fu <= fx appears to be testing the fx return value against a bound fu. Assuming the bound is scalar, then the value fx must be an array. Is it???

Problems interpolating and evaluating numpy array at arbitrary points with Scipy

I am trying to replicate some of the functionality of Matlab's interp2. I know somewhat similar questions have been asked before, but none apply to my specific case.
I have a distance map (available at this Google drive location):
https://drive.google.com/open?id=0B6acq_amk5e3X0Q5UG1ya1VhSlE&authuser=0
Values are normalized in the range 0-1. Size is 200 rows by 300 columns.
I can load it up with this code snippet:
import numpy as np
dstnc1=np.load('dstnc.npy')
Coordinates are defined by the next snippet:
xmin = 0.
xmax = 9000.
ymin = 0.
ymax = 6000.
r1,c1 = dstnc1.shape
x = np.linspace(xmin,xmax,c1)
y = np.linspace(ymin, ymax,r1)
I have three map points defined by vectors xnew1, ynew1 with this snippet:
xnew1=[3700.540199,3845.940199,3983.240199]
ynew1=[1782.8611,1769.862,1694.862]
I check their location with respect to the distance map with this:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 16))
ax = fig.add_subplot(1, 1, 1)
plt.imshow(dstnc1, cmap=my_cmap_r,vmin=0,vmax=0.3,
extent=[0, 9000, 0, 6000], origin='upper')
plt.scatter(xnew1, ynew1, s=50, linewidths=0.15)
plt.show()
They plot in the correct location. Now I would like to extract the
distance value at those three points. I tried first interp2d.
from scipy.interpolate import interp2d
x1 = np.linspace(xmin,xmax,c1)
y1 = np.linspace(ymin,ymax,r1)
f = interp2d(x1, y1, dstnc1, kind='cubic')
but when I try to evaluate with:
test=f(xnew1,ynew1)
I get this error:
--------------------
ValueError Traceback (most recent call last)
<ipython-input-299-d0f42e609b23> in <module>()
----> 1 test=f(xnew1,ynew1)
C:\...\AppData\Local\Continuum\Anaconda\lib\site-packages\scipy\interpolate\interpolate.pyc
in __call__(self, x, y, dx, dy)
270 (self.y_min, self.y_max)))
271
--> 272 z = fitpack.bisplev(x, y, self.tck, dx, dy)
273 z = atleast_2d(z)
274 z = transpose(z)
C:\...\AppData\Local\Continuum\Anaconda\lib\site-packages\scipy\interpolate\fitpack.pyc
in bisplev(x, y, tck, dx, dy)
1027 z,ier = _fitpack._bispev(tx,ty,c,kx,ky,x,y,dx,dy)
1028 if ier == 10:
-> 1029 raise ValueError("Invalid input data")
1030 if ier:
1031 raise TypeError("An error occurred")
ValueError: Invalid input data
If I try RectBivariateSpline:
from scipy.interpolate import RectBivariateSpline
x2 = np.linspace(xmin,xmax,r1)
y2 = np.linspace(ymin,ymax,c1)
f = RectBivariateSpline(x2, y2, dstnc1)
I get this error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-302-d0f42e609b23> in <module>()
----> 1 test=f(xnew1,ynew1)
C:\...\AppData\Local\Continuum\Anaconda\lib\site-packages\scipy\interpolate\fitpack2.pyc
in __call__(self, x, y, mth, dx, dy, grid)
643 z,ier = dfitpack.bispev(tx,ty,c,kx,ky,x,y)
644 if not ier == 0:
--> 645 raise ValueError("Error code returned by
bispev: %s" % ier)
646 else:
647 # standard Numpy broadcasting
ValueError: Error code returned by bispev: 10
Any suggestion as to whether I am using the wrong functions or the right
function with wrong syntax, and how I may fix it is appreciated. Thank you.
UPDATE
I am running Python 2.7.9 and Scipy 0.14.0 (on Continuum Anaconda)
As posted on the Scipy mailing list here the documentation seems confusing, being a mix of Scipy 0.14.0, and the next version. Can anybody suggest a workaround or the correct syntax for version 0.14.0.
UPDATE 2
tried
xnew1=np.array([3700.540199,3845.940199,3983.240199])
ynew1=np.array([1782.8611,1769.862,1694.862])
as suggested inj a comment but the error remains.
This syntax worked with RectBivariateSpline
x2 = np.linspace(xmin,xmax,c1)
y2 = np.linspace(ymin,ymax,r1)
f2 = sp.interpolate.RectBivariateSpline(x2, y2, dstnc1.T,kx=1, ky=1)
I can then evaluate at new points with this:
out2 = f2.ev(xnew1,ynew1)
For interp2d I am stuck as I am not able to bypass firewall at my office to update Anaconda (Windows). I may be able at home on a Mac installation, in which case, if I get the syntax right, I will add to thsi answer.

How to pass date array to pcolor plot?

I have matrix-data where one axis relates to dates. However, I'm having problems passing this data on as an axis to pcolor. My dummy data is as follows:
In [219]: X = [datetime.date.today() + datetime.timedelta(days=i) for i in range(4)]
In [220]: Y = arange(5)
In [221]: Z = arange(4*5).reshape(4, 5)
The naive attemp pcolor(Y, X, Z) fails because pcolor does not like to get a list object:
In [222]: pcolor(Y, X, Z)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-222-1ece18b4bc13> in <module>()
----> 1 pcolor(Y, X, Z)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/pyplot.py in pcolor(*args, **kwargs)
2926 ax.hold(hold)
2927 try:
-> 2928 ret = ax.pcolor(*args, **kwargs)
2929 draw_if_interactive()
2930 finally:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in pcolor(self, *args, **kwargs)
7545 shading = kwargs.pop('shading', 'flat')
7546
-> 7547 X, Y, C = self._pcolorargs('pcolor', *args, allmatch=False)
7548 Ny, Nx = X.shape
7549
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in _pcolorargs(funcname, *args, **kw)
7357
7358 Nx = X.shape[-1]
-> 7359 Ny = Y.shape[0]
7360 if len(X.shape) != 2 or X.shape[0] == 1:
7361 x = X.reshape(1, Nx)
AttributeError: 'list' object has no attribute 'shape'
Converting it to an array containing datetime.date fails with TypeError: float() argument must be a string or a number, not 'datetime.date':
In [223]: pcolor(Y, numpy.array(X), Z)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-223-a00423a6d479> in <module>()
----> 1 pcolor(Y, numpy.array(X), Z)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/pyplot.py in pcolor(*args, **kwargs)
2926 ax.hold(hold)
2927 try:
-> 2928 ret = ax.pcolor(*args, **kwargs)
2929 draw_if_interactive()
2930 finally:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in pcolor(self, *args, **kwargs)
7606 kwargs['antialiaseds'] = False
7607
-> 7608 collection = mcoll.PolyCollection(verts, **kwargs)
7609
7610 collection.set_alpha(alpha)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/collections.py in __init__(self, verts, sizes, closed, **kwargs)
743 Collection.__init__(self, **kwargs)
744 self._sizes = sizes
--> 745 self.set_verts(verts, closed)
746
747 def set_verts(self, verts, closed=True):
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/collections.py in set_verts(self, verts, closed)
763 codes[0] = mpath.Path.MOVETO
764 codes[-1] = mpath.Path.CLOSEPOLY
--> 765 self._paths.append(mpath.Path(xy, codes))
766 else:
767 self._paths.append(mpath.Path(xy))
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/path.py in __init__(self, vertices, codes, _interpolation_steps, closed, readonly)
131 vertices = vertices.astype(np.float_).filled(np.nan)
132 else:
--> 133 vertices = np.asarray(vertices, np.float_)
134
135 if codes is not None:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
460
461 """
--> 462 return array(a, dtype, copy=False, order=order)
463
464 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number, not 'datetime.date'
Finally, converting it to a proper numpy.datetime64 object does not resolve the situation either, failing with Invalid type promotion:
In [224]: pcolor(Y, numpy.array(X, dtype="datetime64[D]"), Z)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-224-0ac06cfafa35> in <module>()
----> 1 pcolor(Y, numpy.array(X, dtype="datetime64[D]"), Z)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/pyplot.py in pcolor(*args, **kwargs)
2926 ax.hold(hold)
2927 try:
-> 2928 ret = ax.pcolor(*args, **kwargs)
2929 draw_if_interactive()
2930 finally:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in pcolor(self, *args, **kwargs)
7577 X4[:, newaxis], Y4[:, newaxis],
7578 X1[:, newaxis], Y1[:, newaxis]),
-> 7579 axis=1)
7580 verts = xy.reshape((npoly, 5, 2))
7581
TypeError: invalid type promotion
What would be the correct way to proceed here? In the
Note that the answer to the question plotting date data with pcolor uses scatter, not pcolor, and therefore does not help in my situation.
Matplotlib uses simple floats to represent datetimes. Hence you have to convert them first and then tell the axis that is has to format the labels as dates. Matplotlib provides the function date2num for that:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import numpy as np
# Your original data (with adapted sizes)
x = [datetime.date.today() + datetime.timedelta(days=i) for i in range(4)]
y = np.arange(5)
z = np.arange(3*4).reshape(3, 4).T
# Convert to numbers
x = mdates.date2num(x)
# Create the figure
fig, ax = plt.subplots(1,1)
plt.pcolor(x,y,z)
# Setup the DateFormatter for the x axis
date_format = mdates.DateFormatter('%D')
ax.xaxis.set_major_formatter(date_format)
# Rotates the labels to fit
fig.autofmt_xdate()
plt.show()
Some other remarks:
For pcolor the x and y vectors represent the corner points of the tiles. So they need to be 1 element longer than the data.
The documentation provides a nice overview of how to handle dates in matplotlib.
Result:

Cannot do mpmath.sqrtm() in sympy

I have the following code to extract the square root of a symmetric second-order tensor.
from sympy import symbols, Matrix, mpmath
import numpy as np
F11, F12, F13, F21, F22, F23, F31, F32, F33 = symbols('F11, F12, F13, F21, F22, F23, F31, F32, F33', real=True)
F = np.array([[F11, F12, F13], [F21, F22, F23], [F31, F32, F33]])
B = F.dot(F.T)
mpmath.sqrtm(Matrix(B))
However, it gave me the error:
TypeError Traceback (most recent call last)
<ipython-input-14-439fed475a57> in <module>()
5 F = np.array([[F11, F12, F13], [F21, F22, F23], [F31, F32, F33]])
6 B = F.dot(F.T)
----> 7 mpmath.sqrtm(Matrix(B))
X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\matrices\calculus.py in sqrtm(ctx, A, _may_rotate)
308
309 """
--> 310 A = ctx.matrix(A)
311 # Trivial
312 if A*0 == A:
X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\matrices\matrices.py in __init__(self, *args, **kwargs)
326 A[i,j] = convert(A[i,j])
327 elif hasattr(args[0], 'tolist'):
--> 328 A = self.ctx.matrix(args[0].tolist())
329 self.__data = A._matrix__data
330 self.__rows = A._matrix__rows
X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\matrices\matrices.py in __init__(self, *args, **kwargs)
299 for i, row in enumerate(A):
300 for j, a in enumerate(row):
--> 301 self[i, j] = convert(a)
302 else:
303 # interpret list as row vector
X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\ctx_mp_python.py in convert(ctx, x, strings)
660 if hasattr(x, '_mpmath_'):
661 return ctx.convert(x._mpmath_(prec, rounding))
--> 662 return ctx._convert_fallback(x, strings)
663
664 def isnan(ctx, x):
X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\ctx_mp.py in _convert_fallback(ctx, x, strings)
612 else:
613 raise ValueError("can only create mpf from zero-width interval")
--> 614 raise TypeError("cannot create mpf from " + repr(x))
615
616 def mpmathify(ctx, *args, **kwargs):
TypeError: cannot create mpf from F11**2 + F12**2 + F13**2
May I ask why that is happening? Is this a limitation of sympy or that I am doing something wrong?
Thank you!
Shawn
mpmath.sqrtm is expecting a square matrix of numbers; if you want to take the sqrt of each element in B symbolically try:
>>> B.applyfunc(sqrt)
Don't use NumPy to do symbolic calculations. NumPy only works with numerical arrays.
To take the square root of a matrix, use B**(Rational(1, 2)) (sqrt(B) ought to work too, but it looks like it remains unevaluated by default).
In this case, though, SymPy hangs, because it computes the square root by diagonalizing, and the eigenvalues don't simplify (or at least SymPy doesn't know how to simplify them), so they are huge cubic equations. Take a look at B.eigenvals(). Thus, the square root of this matrix is quite huge. Are you expecting the square root matrix to be a relatively simple expression?

Categories

Resources