BHAC Python tools
amrplot.py
Go to the documentation of this file.
1 '''2D plotting routines for vtu AMR data'''
2 
3 import numpy as np
4 import matplotlib.pyplot as plt
5 import matplotlib.colors as colors
6 from scipy.interpolate import griddata
7 import sys, time
8 from streamplot import streamplot
9 import read as read
10 from matplotlib.ticker import MaxNLocator
11 from scipy import ndimage
12 import copy
13 from scipy import interpolate
14 from mpl_toolkits.axes_grid1 import make_axes_locatable
15 from copy import deepcopy
16 
17 if sys.platform == "win32":
18 # On Windows, the best timer is time.clock()
19  default_timer = time.clock
20 else:
21 # On most other platforms the best timer is time.time()
22  default_timer = time.time
23 
24 #=============================================================================
25 class polyplot():
26 
27  """Simple 2D plotter class using matplotlib, plots every cell in one patch"""
28 
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,
33  swap=0,**kwargs):
34 
35  self.swap=swap
36  self.nlevels=nlevels
37  self.grid = grid
38  self.blocks = blocks
39  self.blockWidth = blockWidth
40  self.blockHeight = blockHeight
41  self.nlevel1 = nlevel1
42  self.cmap=cmap
43  self.orientation=orientation
44  self.right=right # If True, colorbar is at the right, if False it is at the left
45  self.cbarwidth=0.15
46  self.cbarpad=0.70
47  self.fixzoom=fixzoom
48  self.fixrange=fixrange
49  self.filenameout=filenameout
50  self.clear=clear # If True, the figure is cleared when initializing amrplot, preventing us e.g. for drawing on a different subplot.
51 
52  self.fontsize=10
53  self.fig_w=2.5
54  self.fig_h=4
55  self.dpi=300
56  self.maxXticks=None
57  self.maxYticks=None
58  self.cbarticks=None
59  self.edgecolor=edgecolor
60  self.smooth=smooth
61 
62  self.xrange=xrange
63  self.yrange=yrange
64  if xrange==None:
65  self.xrange=[data.getBounds()[0],data.getBounds()[1]]
66  if yrange==None:
67  self.yrange=[data.getBounds()[2],data.getBounds()[3]]
68 
69  self.setValue(value,min=min,max=max)
70 
71  # initialize for screen:
72  # If a figure and axis were not given, create new ones
73  if fig==None:
74  self.figure=plt.figure(figsize=(self.fig_w,self.fig_h),dpi=100)
75  else:
76  # else, use what was given
77  self.figure=fig
78 
79  if axis==None:
80  self.ax = self.figure.gca()
81  else:
82  self.ax = axis
83 
84  self.show(var=value,data=data,min=min,max=max)
85  if self.filenameout == None:
86  self.figure.canvas.mpl_connect('button_press_event', self.onkey)
87 
88 
89  def setValue(self,value,min=None,max=None):
90  '''Sets the min and max values of the data to saturate the display'''
91  self.value=value
92  self.min=min
93  self.max=max
94  if self.min==None:
95  self.min=value.min()
96  if self.max==None:
97  self.max=value.max()
98 
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'''
101  if var is not None:
102  newdata = np.any(var!=self.value)
103  else:
104  newdata = False
105 
106  if newdata:
107  self.value=var
108  if fixrange == None:
109  if min==None:
110  self.min=self.value.min()
111  if max==None:
112  self.max=self.value.max()
113  if data != None:
114  self.data=data
115  if reset != None:
116  self.min=self.value.min()
117  self.max=self.value.max()
118  if min != None:
119  self.min = min
120  if max != None:
121  self.max = max
122 
123  if filenameout != None:
124  self.filenameout=filenameout
125  self.figure.set_size_inches( (self.fig_w,self.fig_h) )
126 
127  self.ax.set_rasterization_zorder(-9)
128 
129  # save the view for later:
130  self.viewXrange=deepcopy( self.ax.xaxis.get_view_interval() )
131  self.viewYrange=deepcopy( self.ax.yaxis.get_view_interval() )
132 
133 
134  def info(self):
135  '''Print info to the console'''
136  print('=======================================================')
137  print('plotting range between %e and %e' % (self.min,self.max))
138  if self.fixzoom==None:
139  print('xrange = [%e,%e] yrange = [%e,%e]' % (self.xrange[0],self.xrange[1],self.yrange[0],self.yrange[1]))
140  else:
141  print('''Fixing zoomlevel to
142 xrange = [%e,%e] yrange = [%e,%e]''' % (
143  self.viewXrange[0],self.viewXrange[1],self.viewYrange[0],self.viewYrange[1]))
144  if self.nlevels<=1:
145  print('Need more than one color-level, resetting nlevels')
146  self.nlevels=256
147  print('colormap = %s; nlevels=%d; orientation=%s' % (self.cmap,self.nlevels,self.orientation))
148  if self.grid!=None:
149  print('Also showing gridlines')
150  if self.blocks!=None:
151  print('Also showing blocks')
152  print('=======================================================')
153 
154  def show(self,var=None,data=None,min=None,max=None,reset=None,fixrange=None,filenameout=None):
155  '''Draw the plotting-window'''
156  t0 = default_timer()
157 
158  self.update(var=var,data=data,min=min,max=max,reset=reset,fixrange=fixrange,filenameout=filenameout)
159 
160  if self.clear:
161  self.figure.clf()
162  self.ax = self.figure.gca()
163  self.info()
164 
165  colormap = plt.cm.get_cmap(self.cmap, self.nlevels)
166 
167  valueRange=self.max-self.min
168  if valueRange == 0.:
169  valueRange = 1
170 
171  self.valueClip = np.clip(self.value,self.min,self.max)
172 
173  tdata0= default_timer()
174  if (self.swap == 0):
175  [myxlist,myylist]=self.data.getPointList()
176  else:
177  [myylist,myxlist]=self.data.getPointList()
178  # List for regular cells with finite values (no infinitys or NaNs)
179  self.xlist = [[] for i in range(self.nlevels)]
180  self.ylist = [[] for i in range(self.nlevels)]
181  ilevel = ((self.nlevels-1)*(self.valueClip-self.min)/valueRange).astype(int)
182  # Special list to contain NaNs or other problematic cells
183  self.xlistspecial = []
184  self.ylistspecial = []
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)])
189  else:
190  self.xlistspecial.extend(myxlist[5*icell:5*(icell+1)])
191  self.ylistspecial.extend(myylist[5*icell:5*(icell+1)])
192  tdata1=default_timer()
193 
194  # Fill cells with finite values
195  for ilevel in range(self.nlevels):
196  self.ax.fill(self.xlist[ilevel],self.ylist[ilevel],
197  facecolor=colormap(ilevel/(self.nlevels-1.)), closed=False, edgecolor='none',antialiased=False,zorder=-10)
198 
199  # Fill cells with special values
200  if self.xlistspecial: # If the list of special cells is not empty
201  nancolor = 'magenta'
202  print('WARNING: There are NaNs or Inftys, NaN color:',nancolor)
203  self.ax.fill(self.xlistspecial,self.ylistspecial,
204  facecolor=nancolor, closed=False, edgecolor='none',antialiased=False,zorder=-10)
205 
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)
209 
210  if self.blocks != None:
211  [myxBlockList,myyBlockList] = self.data.getPieces(self.blockWidth,self.blockHeight,self.nlevel1)
212  self.ax.fill(myxBlockList,myyBlockList,
213  facecolor='none', edgecolor=self.edgecolor,aa=True,linewidth=0.2,alpha=0.8)
214 
215  if self.orientation != None:
216  self.colorbar()
217 
218  if self.fixzoom==None:
219  self.ax.set_xlim(self.xrange[0],self.xrange[1])
220  self.ax.set_ylim(self.yrange[0],self.yrange[1])
221  else:
222  self.ax.set_xlim(self.viewXrange)
223  self.ax.set_ylim(self.viewYrange)
224  self.ax.set_aspect('equal')
225 # ticks:
226  if self.maxXticks != None:
227  self.ax.xaxis.set_major_locator(MaxNLocator(self.maxXticks-1))
228  if self.maxYticks != None:
229  self.ax.yaxis.set_major_locator(MaxNLocator(self.maxYticks-1))
230 
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)
237 
238  tend = default_timer()
239  print('time for arranging the data= %f sec' % (tdata1-tdata0))
240  print('Execution time = %f sec' % (tend-t0))
241  print('=======================================================')
242  if self.filenameout == None:
243  plt.draw()
244 
245 # Make the main axis active:
246  plt.sca(self.ax)
247 
248 
249 
250  def colorbar(self,cax=None):
251  '''Draw the colorbar.
252  '''
253  colormap = plt.cm.get_cmap(self.cmap, self.nlevels)
254  m = plt.cm.ScalarMappable(cmap=colormap)
255  m.set_array(self.valueClip)
256  m.set_clim(vmin=self.min,vmax=self.max)
257 
258  if (cax==None):
259  divider = make_axes_locatable(self.ax)
260  if self.orientation == 'horizontal':
261  self.cax = divider.append_axes("bottom", self.cbarwidth, pad=self.cbarpad)
262  else:
263  if self.right:
264  self.cax = divider.append_axes("right", "4%", pad="6%")
265  else:
266  self.cax = divider.append_axes("left", "4%", pad="6%")
267  else:
268  self.cax=cax
269 
270  self.cbar=self.figure.colorbar(m, orientation=self.orientation,cax=self.cax)
271 
272  self.cbar.solids.set_rasterized(True)
273 
274  if self.cbarticks != None:
275  self.cbar.locator=MaxNLocator(nbins=self.cbarticks-1)
276  self.cbar.update_ticks()
277 
278 
279  for tick in self.cbar.ax.get_xticklabels():
280  tick.set_fontsize(self.fontsize)
281  for tick in self.cbar.ax.get_yticklabels():
282  tick.set_fontsize(self.fontsize)
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)
285 
286  def save(self,filenameout=None):
287  '''Save the figure'''
288  if filenameout != None:
289  self.filenameout=filenameout
290  print('saving plot to file %s' % (self.filenameout))
291  self.figure.set_size_inches( (self.fig_w,self.fig_h) )
292  self.figure.savefig(self.filenameout, transparent=False,aa=True,dpi=self.dpi,interpolation='bicubic',bbox_inches='tight')
293  self.filenameout=None
294 
295 
296  def onkey(self,event):
297  '''
298  Get data at mousepoint-location. Press middle button at location to activate,
299  press outside of plotting range to remove cross-hair.
300  '''
301  try:
302  if event.button !=2:
303  return True
304  except AttributeError:
305  return True
306  if event.xdata == None:
307  try:
308  self.selection.pop(0).remove()
309  plt.show()
310  except:
311  return True
312  return True
313 
314  icell=self.data.getIcellByPoint(event.xdata,event.ydata)
315  try:
316  self.selection.pop(0).remove()
317  except AttributeError:
318  print('first time defining selection, please wait for centerpoints...')
319  except ValueError:
320  pass
321  except IndexError:
322  pass
323  self.selection=self.ax.plot(self.data.getCenterPoints()[icell,0],self.data.getCenterPoints()[icell,1],'m+', markersize=20,markeredgewidth=3)
324  plt.show()
325  self.data.showValues(icell)
326  print('value=%e' %(self.value[icell]))
327  if self.value[icell] != self.valueClip[icell]:
328  print('exceeding plot range')
329  print('=======================================================')
330 
331 
332 #=============================================================================
333 class rgplot(polyplot):
334  '''
335  As polyplot, but use regridded data to display
336  '''
337 
338  def show(self,var=None,data=None,min=None,max=None,reset=None,fixrange=None,filenameout=None):
339  '''Draw the plotting-window'''
340 
341  t0 = default_timer()
342 
343  self.update(var=var,data=data,min=min,max=max,reset=reset,fixrange=fixrange,filenameout=filenameout)
344 
345  self.viewXrange=self.ax.xaxis.get_view_interval()
346  self.viewYrange=self.ax.yaxis.get_view_interval()
347  self.figure.clf()
348  self.ax = self.figure.gca()
349  self.ax.set_rasterization_zorder(-9)
350  self.info()
351 
352  if self.fixzoom==None:
353  self.ax.set_xlim(self.xrange[0],self.xrange[1])
354  self.ax.set_ylim(self.yrange[0],self.yrange[1])
355  else:
356  self.ax.set_xlim(self.viewXrange)
357  self.ax.set_ylim(self.viewYrange)
358  self.ax.set_aspect('equal')
359 
360 
361  valueRange=self.max-self.min
362  if valueRange == 0.:
363  valueRange = 1
364 
365  self.valueClip = np.clip(self.value,self.min,self.max)
366 
367 # Now regrid and imshow:
368  tdata0= default_timer()
369  xrange=[self.ax.get_xlim()[0],self.ax.get_xlim()[1]]
370  yrange=[self.ax.get_ylim()[0],self.ax.get_ylim()[1]]
371 
372  nregrid = [self.dpi*self.fig_w,self.dpi*self.fig_h]
373 
374  if (self.swap == 0):
375  CC=self.data.getCenterPoints()
376  else:
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]
381 
382 # regrid with linear interpolation and fall back to nearest neighbor at NaN, which should just be the borders.
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))
386 
387 # smooth the data slightly:
388  gridvar = ndimage.gaussian_filter(gridvar, sigma=self.smooth)
389 
390  extent = xrange[0], xrange[1], yrange[0], yrange[1]
391  gridvarClip = np.clip(gridvar,self.min,self.max)
392  self.image=gridvarClip
393  tdata1=default_timer()
394 
395 
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)
398  im2.set_norm(norm)
399 # Q=velovect(self.data.u1,self.data.u2,self.data,nvect=[20,20],scale=30,fig=self)
400 
401  if self.grid != None:
402  if (self.swap == 0):
403  [myxlist,myylist]=self.data.getPointList()
404  else:
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)
408 
409  if self.blocks != None:
410  [myxBlockList,myyBlockList] = self.data.getPieces(self.blockWidth,self.blockHeight,self.nlevel1)
411  self.ax.fill(myxBlockList,myyBlockList,
412  facecolor='none', edgecolor=self.edgecolor,aa=True,linewidth=0.4,alpha=0.5)
413 
414  if self.orientation != None:
415  self.colorbar()
416 
417 # ticks:
418  if self.maxXticks != None:
419  self.ax.xaxis.set_major_locator(MaxNLocator(self.maxXticks-1))
420  if self.maxYticks != None:
421  self.ax.yaxis.set_major_locator(MaxNLocator(self.maxYticks-1))
422 
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)
429 
430  tend = default_timer()
431  print('time for arranging the data= %f sec' % (tdata1-tdata0))
432  print('Execution time = %f sec' % (tend-t0))
433  print('=======================================================')
434  if self.filenameout == None:
435  plt.draw()
436 
437 # Make the main axis active:
438  plt.sca(self.ax)
439 
440 #=============================================================================
441 def velovect(u1,u2,d,nvect=None,scalevar=None,scale=100,color='k',ax=None,alpha=1.):
442  '''Plots normalized velocity vectors'''
443 
444  minvel=1e-40
445 
446  if ax==None:
447  ax=plt.gca()
448 
449  CC=d.getCenterPoints()
450  n=np.sqrt(u1**2+u2**2)
451  # remove zero velocity:
452  m=n<minvel
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:
456  vr = vr*scalevar
457  vz = vz*scalevar
458  if nvect==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)
461  else:
462  # regrid the data:
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)
470 
471  plt.draw()
472  return Q
473 
474 #=============================================================================
475 def contour(var,d,levels=None,nmax=600,colors='k',linestyles='solid',ax=None,linewidths=1,smooth=1.,alpha=1.):
476  if ax==None:
477  ax=plt.gca()
478 
479  xrange=[ax.get_xlim()[0],ax.get_xlim()[1]]
480  yrange=[ax.get_ylim()[0],ax.get_ylim()[1]]
481 
482  # Aspect ratio:
483  r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
484  if r<1:
485  ny=nmax
486  nx=int(r*nmax)
487  else:
488  nx=nmax
489  ny=int(nmax/r)
490  nregrid = [nx,ny]
491 
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')
499 
500 # smooth the data slightly:
501  blurred_gridvar = ndimage.gaussian_filter(gridvar, sigma=smooth)
502 
503 
504  if levels == None:
505  cs = ax.contour(grid_x,grid_y,blurred_gridvar,16,alpha=alpha)
506  else:
507  cs = ax.contour(grid_x,grid_y,blurred_gridvar,levels=levels,colors=colors,linestyles=linestyles,linewidths=linewidths,alpha=alpha)
508 
509  plt.draw()
510  return cs
511 
512 #=============================================================================
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.'''
515  if fig==None:
516  ax=plt.gca()
517  else:
518  ax=fig.ax
519 
520  xrange=[ax.get_xlim()[0],ax.get_xlim()[1]]
521  yrange=[ax.get_ylim()[0],ax.get_ylim()[1]]
522 
523  if nmax == 600 and fig != None:
524  nmax = fig.dpi * max([fig.fig_w,fig.fig_h])
525 
526 
527  # Aspect ratio:
528  r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
529  if r<1:
530  ny=nmax
531  nx=int(r*nmax)
532  else:
533  nx=nmax
534  ny=int(nmax/r)
535  nregrid = [nx,ny]
536  print(nregrid)
537 
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]
544 
545  u = griddata(CC, u1, (grid_x, grid_y), method='linear')
546  v = griddata(CC, u2, (grid_x, grid_y), method='linear')
547  uisnan=np.isnan(u)
548  visnan=np.isnan(v)
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')
553  u[uisnan]=un[uisnan]
554  v[visnan]=vn[visnan]
555 
556  if (smooth != 0):
557  u = ndimage.gaussian_filter(u, sigma=smooth)
558  v = ndimage.gaussian_filter(v, sigma=smooth)
559 
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)
565  else:
566  streamplot(x, y, u.transpose(), v.transpose(),
567  density=density, linewidth=linewidth,
568  INTEGRATOR='RK4', color=color, arrowsize=arrowsize,alpha=alpha)
569 
570 #=============================================================================
571 def streamline(u1,u2,d,x1_0,x2_0,dl=1.,fig=None,nmax=600):
572 
573  if fig==None:
574  ax=plt.gca()
575  else:
576  ax=fig.figure.gca()
577 
578  xrange=[ax.get_xlim()[0],ax.get_xlim()[1]]
579  yrange=[ax.get_ylim()[0],ax.get_ylim()[1]]
580 
581  if nmax == 600 and fig != None:
582  nmax = fig.dpi * max([fig.fig_w,fig.fig_h])
583 
584 
585  # Aspect ratio:
586  r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
587  if r<1:
588  ny=nmax
589  nx=int(r*nmax)
590  else:
591  nx=nmax
592  ny=int(nmax/r)
593  nregrid = [nx,ny]
594 
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]
601 
602  u = griddata(CC, u1, (grid_x, grid_y), method='linear')
603  v = griddata(CC, u2, (grid_x, grid_y), method='linear')
604  uisnan=np.isnan(u)
605  visnan=np.isnan(v)
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')
610  u[uisnan]=un[uisnan]
611  v[visnan]=vn[visnan]
612 # Normalize:
613  mag=np.sqrt(u**2+v**2)
614  u=u/mag
615  v=v/mag
616 
617  fu = interpolate.interp2d(grid_x, grid_y, u, kind='cubic')
618  fv = interpolate.interp2d(grid_x, grid_y, v, kind='cubic')
619  x1=[x1_0]
620  x2=[x2_0]
621  while(x1[-1] >= xrange[0] and x1[-1] <= xrange[1] and
622  x2[-1] >= yrange[0] and x2[-1] <= yrange[1]):
623  dt=dl
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)]
627 
628 #=============================================================================
629 def gridvar(var,d,xrange,yrange,nmax=600,smooth=0):
630 
631  # Aspect ratio:
632  r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
633  if r<1:
634  ny=nmax
635  nx=int(r*nmax)
636  else:
637  nx=nmax
638  ny=int(nmax/r)
639  nregrid = [nx,ny]
640 
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')
648 
649 # smooth the data slightly:
650  blurred_gridvar = ndimage.gaussian_filter(gridvar, sigma=smooth)
651 
652  return blurred_gridvar,grid_x,grid_y
def gridvar(var, d, xrange, yrange, nmax=600, smooth=0)
Definition: amrplot.py:629
def info(self)
Print info to the console.
Definition: amrplot.py:135
def setValue(self, value, min=None, max=None)
Sets the min and max values of the data to saturate the display.
Definition: amrplot.py:90
Simple 2D plotter class using matplotlib, plots every cell in one patch.
Definition: amrplot.py:26
default_timer
Definition: amrplot.py:19
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.
Definition: amrplot.py:514
def onkey(self, event)
Definition: amrplot.py:300
def contour(var, d, levels=None, nmax=600, colors='k', linestyles='solid', ax=None, linewidths=1, smooth=1., alpha=1.)
Definition: amrplot.py:475
def streamline(u1, u2, d, x1_0, x2_0, dl=1., fig=None, nmax=600)
Definition: amrplot.py:571
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)
Definition: amrplot.py:33
As polyplot, but use regridded data to display.
Definition: amrplot.py:336
def colorbar(self, cax=None)
Draw the colorbar.
Definition: amrplot.py:252
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.
Definition: amrplot.py:100
def save(self, filenameout=None)
Save the figure.
Definition: amrplot.py:287
def velovect(u1, u2, d, nvect=None, scalevar=None, scale=100, color='k', ax=None, alpha=1.)
Plots normalized velocity vectors.
Definition: amrplot.py:442
def show(self, var=None, data=None, min=None, max=None, reset=None, fixrange=None, filenameout=None)
Draw the plotting-window.
Definition: amrplot.py:339
def show(self, var=None, data=None, min=None, max=None, reset=None, fixrange=None, filenameout=None)
Draw the plotting-window.
Definition: amrplot.py:155