1 '''2D plotting routines for vtu AMR data''' 4 import matplotlib.pyplot
as plt
5 import matplotlib.colors
as colors
6 from scipy.interpolate
import griddata
8 from streamplot
import streamplot
10 from matplotlib.ticker
import MaxNLocator
11 from scipy
import ndimage
13 from scipy
import interpolate
14 from mpl_toolkits.axes_grid1
import make_axes_locatable
15 from copy
import deepcopy
17 if sys.platform ==
"win32":
19 default_timer = time.clock
22 default_timer = time.time
27 """Simple 2D plotter class using matplotlib, plots every cell in one patch""" 29 def __init__(self,value,data,nlevels=256, grid=None, blocks=None, blockWidth = 8, blockHeight = 8, nlevel1=0,cmap='jet', min=None, max=None,
30 xrange=None, yrange=None, orientation='vertical', right=True, fixzoom=None, fixrange=None, fig=None, axis=None,
31 filenameout=None, clear=True,
32 edgecolor='k',smooth=0,
65 self.
xrange=[data.getBounds()[0],data.getBounds()[1]]
67 self.
yrange=[data.getBounds()[2],data.getBounds()[3]]
84 self.
show(var=value,data=data,min=min,max=max)
86 self.
figure.canvas.mpl_connect(
'button_press_event', self.
onkey)
89 def setValue(self,value,min=None,max=None):
90 '''Sets the min and max values of the data to saturate the display''' 99 def update(self,var=None,data=None,min=None,max=None,reset=None,fixrange=None,filenameout=None):
100 '''Prepare to re-draw the window, check if data was updated''' 102 newdata = np.any(var!=self.
value)
123 if filenameout !=
None:
127 self.
ax.set_rasterization_zorder(-9)
135 '''Print info to the console''' 136 print(
'=======================================================')
137 print(
'plotting range between %e and %e' % (self.
min,self.
max))
141 print(
'''Fixing zoomlevel to 142 xrange = [%e,%e] yrange = [%e,%e]''' % (
145 print(
'Need more than one color-level, resetting nlevels')
149 print(
'Also showing gridlines')
151 print(
'Also showing blocks')
152 print(
'=======================================================')
154 def show(self,var=None,data=None,min=None,max=None,reset=None,fixrange=None,filenameout=None):
155 '''Draw the plotting-window''' 158 self.
update(var=var,data=data,min=min,max=max,reset=reset,fixrange=fixrange,filenameout=filenameout)
165 colormap = plt.cm.get_cmap(self.
cmap, self.
nlevels)
167 valueRange=self.
max-self.
min 175 [myxlist,myylist]=self.
data.getPointList()
177 [myylist,myxlist]=self.
data.getPointList()
185 for icell
in range(self.
data.ncells):
186 if ilevel[icell] > -1
and ilevel[icell]<self.
nlevels:
187 self.
xlist[ilevel[icell]].extend(myxlist[5*icell:5*(icell+1)])
188 self.
ylist[ilevel[icell]].extend(myylist[5*icell:5*(icell+1)])
195 for ilevel
in range(self.
nlevels):
197 facecolor=colormap(ilevel/(self.
nlevels-1.)), closed=
False, edgecolor=
'none',antialiased=
False,zorder=-10)
202 print(
'WARNING: There are NaNs or Inftys, NaN color:',nancolor)
204 facecolor=nancolor, closed=
False, edgecolor=
'none',antialiased=
False,zorder=-10)
206 if self.
grid !=
None:
207 self.
ax.fill(myxlist,myylist,
208 facecolor=
'none', edgecolor=self.
edgecolor,aa=
True,linewidth=0.2,alpha=0.8)
212 self.
ax.fill(myxBlockList,myyBlockList,
213 facecolor=
'none', edgecolor=self.
edgecolor,aa=
True,linewidth=0.2,alpha=0.8)
224 self.
ax.set_aspect(
'equal')
227 self.
ax.xaxis.set_major_locator(MaxNLocator(self.
maxXticks-1))
229 self.
ax.yaxis.set_major_locator(MaxNLocator(self.
maxYticks-1))
231 for tick
in self.
ax.xaxis.get_major_ticks():
232 tick.label1.set_fontsize(self.
fontsize)
233 for tick
in self.
ax.yaxis.get_major_ticks():
234 tick.label1.set_fontsize(self.
fontsize)
235 self.
ax.xaxis.get_offset_text().set_fontsize(self.
fontsize-2)
236 self.
ax.yaxis.get_offset_text().set_fontsize(self.
fontsize-2)
239 print(
'time for arranging the data= %f sec' % (tdata1-tdata0))
240 print(
'Execution time = %f sec' % (tend-t0))
241 print(
'=======================================================')
251 '''Draw the colorbar. 253 colormap = plt.cm.get_cmap(self.
cmap, self.
nlevels)
254 m = plt.cm.ScalarMappable(cmap=colormap)
256 m.set_clim(vmin=self.
min,vmax=self.
max)
259 divider = make_axes_locatable(self.
ax)
264 self.
cax = divider.append_axes(
"right",
"4%", pad=
"6%")
266 self.
cax = divider.append_axes(
"left",
"4%", pad=
"6%")
272 self.
cbar.solids.set_rasterized(
True)
276 self.
cbar.update_ticks()
279 for tick
in self.
cbar.ax.get_xticklabels():
281 for tick
in self.
cbar.ax.get_yticklabels():
283 self.
cbar.ax.xaxis.get_offset_text().set_fontsize(self.
fontsize-2)
284 self.
cbar.ax.yaxis.get_offset_text().set_fontsize(self.
fontsize-2)
286 def save(self,filenameout=None):
287 '''Save the figure''' 288 if filenameout !=
None:
290 print(
'saving plot to file %s' % (self.
filenameout))
292 self.
figure.savefig(self.
filenameout, transparent=
False,aa=
True,dpi=self.
dpi,interpolation=
'bicubic',bbox_inches=
'tight')
296 def onkey(self,event):
298 Get data at mousepoint-location. Press middle button at location to activate, 299 press outside of plotting range to remove cross-hair. 304 except AttributeError:
306 if event.xdata ==
None:
314 icell=self.
data.getIcellByPoint(event.xdata,event.ydata)
317 except AttributeError:
318 print(
'first time defining selection, please wait for centerpoints...')
323 self.
selection=self.
ax.plot(self.
data.getCenterPoints()[icell,0],self.
data.getCenterPoints()[icell,1],
'm+', markersize=20,markeredgewidth=3)
325 self.
data.showValues(icell)
326 print(
'value=%e' %(self.
value[icell]))
328 print(
'exceeding plot range')
329 print(
'=======================================================')
335 As polyplot, but use regridded data to display 338 def show(self,var=None,data=None,min=None,max=None,reset=None,fixrange=None,filenameout=None):
339 '''Draw the plotting-window''' 343 self.
update(var=var,data=data,min=min,max=max,reset=reset,fixrange=fixrange,filenameout=filenameout)
349 self.
ax.set_rasterization_zorder(-9)
358 self.
ax.set_aspect(
'equal')
361 valueRange=self.
max-self.
min 369 xrange=[self.
ax.get_xlim()[0],self.
ax.get_xlim()[1]]
370 yrange=[self.
ax.get_ylim()[0],self.
ax.get_ylim()[1]]
375 CC=self.
data.getCenterPoints()
377 CC=self.
data.getCenterPoints()[:,[1,0]]
378 tmp0=np.complex(0,nregrid[0])
379 tmp1=np.complex(0,nregrid[1])
380 grid_x, grid_y = np.mgrid[xrange[0]:xrange[1]:tmp0, yrange[0]:yrange[1]:tmp1]
383 gridvar = griddata(CC, self.
valueClip, (grid_x, grid_y), method=
'cubic',fill_value=float(np.NaN))
384 isnan=np.isnan(gridvar)
385 gridvar[isnan] = griddata(CC, self.
value, (grid_x[isnan], grid_y[isnan]), method=
'nearest',fill_value=float(np.NaN))
388 gridvar = ndimage.gaussian_filter(gridvar, sigma=self.
smooth)
390 extent = xrange[0], xrange[1], yrange[0], yrange[1]
391 gridvarClip = np.clip(gridvar,self.
min,self.
max)
396 im2 = self.
ax.imshow(gridvarClip.transpose(), cmap=plt.cm.get_cmap(self.
cmap, self.
nlevels), interpolation=
'bicubic',extent=extent,origin=
'lower',zorder=-10)
397 norm = colors.Normalize(vmin=self.
min, vmax=self.
max)
401 if self.
grid !=
None:
403 [myxlist,myylist]=self.
data.getPointList()
405 [myylist,myxlist]=self.
data.getPointList()
406 self.
ax.fill(myxlist,myylist,
407 facecolor=
'none', edgecolor=self.
edgecolor,aa=
True,linewidth=0.2,alpha=0.8)
411 self.
ax.fill(myxBlockList,myyBlockList,
412 facecolor=
'none', edgecolor=self.
edgecolor,aa=
True,linewidth=0.4,alpha=0.5)
419 self.
ax.xaxis.set_major_locator(MaxNLocator(self.
maxXticks-1))
421 self.
ax.yaxis.set_major_locator(MaxNLocator(self.
maxYticks-1))
423 for tick
in self.
ax.xaxis.get_major_ticks():
424 tick.label1.set_fontsize(self.
fontsize)
425 for tick
in self.
ax.yaxis.get_major_ticks():
426 tick.label1.set_fontsize(self.
fontsize)
427 self.
ax.xaxis.get_offset_text().set_fontsize(self.
fontsize-2)
428 self.
ax.yaxis.get_offset_text().set_fontsize(self.
fontsize-2)
431 print(
'time for arranging the data= %f sec' % (tdata1-tdata0))
432 print(
'Execution time = %f sec' % (tend-t0))
433 print(
'=======================================================')
441 def velovect(u1,u2,d,nvect=None,scalevar=None,scale=100,color='k',ax=None,alpha=1.):
442 '''Plots normalized velocity vectors''' 449 CC=d.getCenterPoints()
450 n=np.sqrt(u1**2+u2**2)
453 vr=np.ma.filled(np.ma.masked_array(u1/n,m),0.)
454 vz=np.ma.filled(np.ma.masked_array(u2/n,m),0.)
455 if scalevar
is not None:
459 Q=ax.quiver(CC[:,0],CC[:,1],vr,vz,pivot=
'middle',width=1e-3,minlength=0.,scale=scale,
460 headwidth=6,alpha=alpha)
463 tmp0=np.complex(0,nvect[0])
464 tmp1=np.complex(0,nvect[1])
465 grid_r, grid_z = np.mgrid[ax.get_xlim()[0]:ax.get_xlim()[1]:tmp0, ax.get_ylim()[0]:ax.get_ylim()[1]:tmp1]
466 grid_vr = griddata(CC, vr, (grid_r, grid_z), method=
'nearest')
467 grid_vz = griddata(CC, vz, (grid_r, grid_z), method=
'nearest')
468 Q=ax.quiver(grid_r,grid_z,grid_vr,grid_vz,pivot=
'middle',width=2e-3,minlength=minvel,scale=scale,
469 headwidth=10,headlength=10,color=color,edgecolor=color,rasterized=
True,alpha=alpha)
475 def contour(var,d,levels=None,nmax=600,colors='k',linestyles='solid',ax=None,linewidths=1,smooth=1.,alpha=1.):
479 xrange=[ax.get_xlim()[0],ax.get_xlim()[1]]
480 yrange=[ax.get_ylim()[0],ax.get_ylim()[1]]
483 r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
492 CC=d.getCenterPoints()
493 tmp0=np.complex(0,nregrid[0])
494 tmp1=np.complex(0,nregrid[1])
495 grid_x, grid_y = np.mgrid[xrange[0]:xrange[1]:tmp0, yrange[0]:yrange[1]:tmp1]
496 gridvar = griddata(CC, var, (grid_x, grid_y), method=
'linear')
497 isnan=np.isnan(gridvar)
498 gridvar[isnan] = griddata(CC, var, (grid_x[isnan], grid_y[isnan]), method=
'nearest')
501 blurred_gridvar = ndimage.gaussian_filter(gridvar, sigma=smooth)
505 cs = ax.contour(grid_x,grid_y,blurred_gridvar,16,alpha=alpha)
507 cs = ax.contour(grid_x,grid_y,blurred_gridvar,levels=levels,colors=colors,linestyles=linestyles,linewidths=linewidths,alpha=alpha)
513 def streamlines(u1,u2,d,x0=None,y0=None,nmax=600,density=1,fig=None,color='b',linewidth=1,arrowsize=1,alpha=1.,smooth=0):
514 '''plots streamlines from a vector field. Use density=[densx,densy] to control how close streamlines are allowed to get.''' 520 xrange=[ax.get_xlim()[0],ax.get_xlim()[1]]
521 yrange=[ax.get_ylim()[0],ax.get_ylim()[1]]
523 if nmax == 600
and fig !=
None:
524 nmax = fig.dpi * max([fig.fig_w,fig.fig_h])
528 r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
538 CC=d.getCenterPoints()
539 tmp0=np.complex(0,nregrid[0])
540 tmp1=np.complex(0,nregrid[1])
541 x=np.linspace(xrange[0],xrange[1],nregrid[0])
542 y=np.linspace(yrange[0],yrange[1],nregrid[1])
543 grid_x, grid_y = np.mgrid[xrange[0]:xrange[1]:tmp0, yrange[0]:yrange[1]:tmp1]
545 u = griddata(CC, u1, (grid_x, grid_y), method=
'linear')
546 v = griddata(CC, u2, (grid_x, grid_y), method=
'linear')
549 un = np.empty(np.shape(u))
550 vn = np.empty(np.shape(v))
551 un[uisnan] = griddata(CC, u1, (grid_x[uisnan], grid_y[uisnan]), method=
'nearest')
552 vn[visnan] = griddata(CC, u2, (grid_x[visnan], grid_y[visnan]), method=
'nearest')
557 u = ndimage.gaussian_filter(u, sigma=smooth)
558 v = ndimage.gaussian_filter(v, sigma=smooth)
560 if (x0 !=
None and y0!=
None):
561 for myx
in zip(x0,y0):
562 streamplot(x, y, u.transpose(), v.transpose(), x_0=myx[0],
563 y_0=myx[1], density=density, linewidth=linewidth,
564 INTEGRATOR=
'RK4', color=color, arrowsize=arrowsize,alpha=alpha)
566 streamplot(x, y, u.transpose(), v.transpose(),
567 density=density, linewidth=linewidth,
568 INTEGRATOR=
'RK4', color=color, arrowsize=arrowsize,alpha=alpha)
578 xrange=[ax.get_xlim()[0],ax.get_xlim()[1]]
579 yrange=[ax.get_ylim()[0],ax.get_ylim()[1]]
581 if nmax == 600
and fig !=
None:
582 nmax = fig.dpi * max([fig.fig_w,fig.fig_h])
586 r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
595 CC=d.getCenterPoints()
596 tmp0=np.complex(0,nregrid[0])
597 tmp1=np.complex(0,nregrid[1])
598 x=np.linspace(xrange[0],xrange[1],nregrid[0])
599 y=np.linspace(yrange[0],yrange[1],nregrid[1])
600 grid_x, grid_y = np.mgrid[xrange[0]:xrange[1]:tmp0, yrange[0]:yrange[1]:tmp1]
602 u = griddata(CC, u1, (grid_x, grid_y), method=
'linear')
603 v = griddata(CC, u2, (grid_x, grid_y), method=
'linear')
606 un = np.empty(np.shape(u))
607 vn = np.empty(np.shape(v))
608 un[uisnan] = griddata(CC, u1, (grid_x[uisnan], grid_y[uisnan]), method=
'nearest')
609 vn[visnan] = griddata(CC, u2, (grid_x[visnan], grid_y[visnan]), method=
'nearest')
613 mag=np.sqrt(u**2+v**2)
617 fu = interpolate.interp2d(grid_x, grid_y, u, kind=
'cubic')
618 fv = interpolate.interp2d(grid_x, grid_y, v, kind=
'cubic')
621 while(x1[-1] >= xrange[0]
and x1[-1] <= xrange[1]
and 622 x2[-1] >= yrange[0]
and x2[-1] <= yrange[1]):
624 x1.append(x1[-1]+fu(x1[-1],x2[-1])*dt)
625 x2.append(x2[-1]+fv(x1[-1],x2[-1])*dt)
626 return [np.array(x1),np.array(x2)]
629 def gridvar(var,d,xrange,yrange,nmax=600,smooth=0):
632 r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
641 CC=d.getCenterPoints()
642 tmp0=np.complex(0,nregrid[0])
643 tmp1=np.complex(0,nregrid[1])
644 grid_x, grid_y = np.mgrid[xrange[0]:xrange[1]:tmp0, yrange[0]:yrange[1]:tmp1]
645 gridvar = griddata(CC, var, (grid_x, grid_y), method=
'linear')
646 isnan=np.isnan(gridvar)
647 gridvar[isnan] = griddata(CC, var, (grid_x[isnan], grid_y[isnan]), method=
'nearest')
650 blurred_gridvar = ndimage.gaussian_filter(gridvar, sigma=smooth)
652 return blurred_gridvar,grid_x,grid_y
def gridvar(var, d, xrange, yrange, nmax=600, smooth=0)
def info(self)
Print info to the console.
def setValue(self, value, min=None, max=None)
Sets the min and max values of the data to saturate the display.
Simple 2D plotter class using matplotlib, plots every cell in one patch.
def streamlines(u1, u2, d, x0=None, y0=None, nmax=600, density=1, fig=None, color='b', linewidth=1, arrowsize=1, alpha=1., smooth=0)
plots streamlines from a vector field.
def contour(var, d, levels=None, nmax=600, colors='k', linestyles='solid', ax=None, linewidths=1, smooth=1., alpha=1.)
def streamline(u1, u2, d, x1_0, x2_0, dl=1., fig=None, nmax=600)
def __init__(self, value, data, nlevels=256, grid=None, blocks=None, blockWidth=8, blockHeight=8, nlevel1=0, cmap='jet', min=None, max=None, xrange=None, yrange=None, orientation='vertical', right=True, fixzoom=None, fixrange=None, fig=None, axis=None, filenameout=None, clear=True, edgecolor='k', smooth=0, swap=0, kwargs)
As polyplot, but use regridded data to display.
def colorbar(self, cax=None)
Draw the colorbar.
def update(self, var=None, data=None, min=None, max=None, reset=None, fixrange=None, filenameout=None)
Prepare to re-draw the window, check if data was updated.
def save(self, filenameout=None)
Save the figure.
def velovect(u1, u2, d, nvect=None, scalevar=None, scale=100, color='k', ax=None, alpha=1.)
Plots normalized velocity vectors.
def show(self, var=None, data=None, min=None, max=None, reset=None, fixrange=None, filenameout=None)
Draw the plotting-window.
def show(self, var=None, data=None, min=None, max=None, reset=None, fixrange=None, filenameout=None)
Draw the plotting-window.