BHAC Python tools
read.py
Go to the documentation of this file.
1 '''Modules used for reading AMRVAC data'''
2 #=============================================================================
3 import numpy as np
4 import vtk as v
5 from numpy import loadtxt as pylabload
6 import numpy_support as ah
7 import sys, time
8 import struct
9 #import piece2poly as he
10 
11 
12 if sys.platform == "win32":
13 # On Windows, the best timer is time.clock()
14  default_timer = time.clock
15 else:
16 # On most other platforms the best timer is time.time()
17  default_timer = time.time
18 
19 
20 #=============================================================================
21 def extract(data,varname,attribute_mode='cell'):
22  '''Extracts variable "varname" from vtk datastructure "data"'''
23  if attribute_mode == 'cell':
24  vtk_values = data.GetCellData().GetArray(varname)
25  elif attribute_mode == 'point':
26  if data.GetPointData().GetNumberOfArrays() > 0:
27  vtk_values = data.GetPointData().GetArray(varname)
28  else:
29  # Convert to pointdata first
30  c2p = v.vtkCellDataToPointData()
31  c2p.SetInput(data)
32  pointdata=c2p.GetOutput()
33  pointdata.Update()
34  vtk_values = pointdata.GetPointData().GetScalars(varname)
35  elif attribute_mode == 'topoint':
36  c2p = v.vtkCellDataToPointData()
37  c2p.SetInput(data)
38  pointdata=c2p.GetOutput()
39  pointdata.Update()
40  vtk_values = pointdata.GetPointData().GetScalars(varname)
41  else:
42  print("attribute_mode is either 'cell' or 'point'")
43 
44  return ah.vtk2array(vtk_values)
45 
46 #=============================================================================
47 class load:
48  """
49  Loader class for vtu and pvtu files.
50  """
51  def __init__(self,offset,get=1,file='data',type='vtu',mirrorPlane=None,
52  rotateX=0,rotateY=0,rotateZ=0,
53  scaleX=1,scaleY=1,scaleZ=1,
54  silent=0):
55  self.offset=offset
56  self.filenameout = file
57  self.type = type
58  self.isLoaded = False
59  self.mirrorPlane=mirrorPlane
60  self.silent = silent
61 
62  self.rotateX = rotateX
63  self.rotateY = rotateY
64  self.rotateZ = rotateZ
65 
66  self.scaleX = scaleX
67  self.scaleY = scaleY
68  self.scaleZ = scaleZ
69 
70  if type == 'vtu':
71  self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vtu'])
72  self.datareader = v.vtkXMLUnstructuredGridReader()
73  elif type == 'pvtu':
74  self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.pvtu'])
75  self.datareader = v.vtkXMLPUnstructuredGridReader()
76  elif type == 'vti':
77  self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vti'])
78  self.datareader = v.vtkXMLImageDataReader()
79  else:
80  print('Unknown filetype')
81 
82  if (self.silent == 0): print('========================================')
83  if (self.silent == 0): print('loading file %s' % (self.filename))
84 
85  if get != None:
86  self.getAll()
87 
88 
89  def getTime(self):
90  try:
91  self.time=ah.vtk2array(self.data.GetFieldData().GetArray(0))[0]
92  except AttributeError:
93  self.time = np.nan
94  return self.time
95 
96 
97  def getVar(self,varname):
98  try:
99  exec("tmp=self.%s" % (varname))
100  return tmp
101  except AttributeError:
102  print("Unknown variable", varname)
103 
104  def getData(self):
105  self.datareader.SetFileName(self.filename)
106  self.datareader.Update()
107  self.data = self.datareader.GetOutput()
108  self.ncells = self.data.GetNumberOfCells()
109  self.isLoaded = True
110 
111  if (self.rotateX != 0 or self.rotateY != 0 or self.rotateZ != 0
112  or self.scaleX != 1 or self.scaleY != 1 or self.scaleZ != 1):
113  transform = v.vtkTransform()
114  transform.RotateX(self.rotateX)
115  transform.RotateY(self.rotateY)
116  transform.RotateZ(self.rotateZ)
117  transform.Scale(self.scaleX, self.scaleY, self.scaleZ)
118  transfilter = v.vtkTransformFilter()
119  transfilter.SetTransform(transform)
120  transfilter.SetInputData(self.data)
121  self.data = transfilter.GetOutput()
122  transfilter.Update()
123 
124 
125  def getPointData(self):
126  self.getData()
127  if self.data.GetPointData().GetNumberOfArrays() == 0:
128  c2p = v.vtkCellDataToPointData()
129  # vtk 4,5:
130 # c2p.SetInput(self.data)
131  # vtk 6:
132  c2p.SetInputData(self.data)
133  self.pointdata=c2p.GetOutput()
134  # vtk 4,5:
135 # self.pointdata.Update()
136  # vtk 6:
137  c2p.Update()
138  else:
139  self.pointdata=self.data
140 
141 
142  def getVars(self):
143  nvars= self.data.GetCellData().GetNumberOfArrays()
144  for i in range(nvars):
145  varname = self.data.GetCellData().GetArrayName(i)
146  if (self.silent == 0): print("Assigning variable:", varname)
147  vtk_values = self.data.GetCellData().GetArray(varname)
148  exec("self.%s = ah.vtk2array(vtk_values)[0:self.ncells]" % (varname))
149 
150 
151  def getVarnames(self):
152  nvars= self.data.GetCellData().GetNumberOfArrays()
153  varnames=[]
154  for i in range(nvars):
155  varnames.append(self.data.GetCellData().GetArrayName(i))
156  return varnames
157 
158 
159  def getBounds(self):
160  return self.data.GetBounds()
161 
162 
163  def getVert(self,icell):
164  if self.data.GetCell(icell).GetCellType() == 8 :
165  pts=ah.vtk2array(self.data.GetCell(icell).GetPoints().GetData())
166  return np.array((pts[0][0:2],pts[1][0:2],pts[3][0:2],pts[2][0:2]))
167  if self.data.GetCell(icell).GetCellType() == 3 :
168  pts=ah.vtk2array(self.data.GetCell(icell).GetPoints().GetData())
169  return np.array((pts[0][0],pts[1][0]))
170  else:
171  if (self.silent == 0): print("Can handle only type 3 or type 8")
172 
173 
174  def getPointList(self):
175  tstart = default_timer()
176  try:
177  self.data
178  except AttributeError:
179  self.getData()
180  try:
181  [self.xlist,self.ylist]
182  except AttributeError:
183  if self.data.GetCell(0).GetCellType() != 8 :
184  if (self.silent == 0): print("Can handle pixel types only")
185  pass
186  self.xlist = []
187  self.ylist = []
188  for icell in range(self.ncells):
189  pts=ah.vtk2array(self.data.GetCell(icell).GetPoints().GetData())
190  self.xlist.extend((pts[0][0],pts[1][0],pts[3][0],pts[2][0],None))
191  self.ylist.extend((pts[0][1],pts[1][1],pts[3][1],pts[2][1],None))
192  tend = default_timer()
193  if (self.silent == 0): print('Getting formatted pointlist time=%f sec' % (tend-tstart))
194  return [self.xlist,self.ylist]
195 
196 
197  def getCenterPoints(self):
198  tstart = default_timer()
199  firstget = False
200  try:
201  self.data
202  except AttributeError:
203  self.getData()
204  firstget = True
205  try:
206  self.centerpoints
207  except AttributeError:
208  if self.getNdim() == 2 or self.getNdim() == 3:
209  self.centerpoints=np.empty((self.ncells,2))
210  for icell in range(self.ncells):
211  vert=self.getVert(icell)
212  self.centerpoints[icell,0]=vert[:,0].mean()
213  self.centerpoints[icell,1]=vert[:,1].mean()
214  if self.getNdim() == 1 :
215  self.centerpoints=np.empty((self.ncells))
216  for icell in range(self.ncells):
217  vert=self.getVert(icell)
218  self.centerpoints[icell]=vert.mean()
219  tend = default_timer()
220  if firstget:
221  if (self.silent == 0): print('Getting cell center coordiantes time=%f sec' % (tend-tstart))
222  return self.centerpoints
223 
224 
225  def getSurface(self):
226  def calcSurface(icell):
227  vert=self.getVert(icell)
228  return np.sqrt(((vert[0][0]-vert[1][0])**2+(vert[0][1]-vert[1][1])**2)*
229  ((vert[1][0]-vert[2][0])**2+(vert[1][1]-vert[2][1])**2))
230 
231  tstart = default_timer()
232  try:
233  self.data
234  except AttributeError:
235  self.getData()
236  try:
237  self.surface
238  except AttributeError:
239  # Assuming cells are rectangles here.
240  surface=list(map(calcSurface,list(range(self.ncells))))
241  self.surface=np.array(surface)
242  tend = default_timer()
243  if (self.silent == 0): print('Getting cell surface (assuming rectangles) time=%f sec' % (tend-tstart))
244  return self.surface
245 
246  def getPieces(self,nBWidth,nBHeight,nIgnore):
247  tstart = default_timer()
248  try:
249  self.data
250  except AttributeError:
251  self.getData()
252  try:
253  [self.xBlockList,self.yBlockList]
254  except AttributeError:
255 
256  self.xBlockList=[]
257  self.yBlockList=[]
258 
259  pts=self.getPoints()
260  nPoints = np.shape(pts)[0]
261 
262  # Calculate number of blocks
263 
264  nBSize=(nBWidth+1)*(nBHeight+1)
265 
266  nBlocks=int(nPoints/nBSize)
267 
268  # For all blocks, draw the perimeter
269  for iBlock in range(nBlocks):
270  start=iBlock*nBSize
271  end =(iBlock+1)*nBSize-1
272  # Side 1
273  for i in range(start,start+nBWidth+1):
274  self.xBlockList.append(pts[i][0])
275  self.yBlockList.append(pts[i][1])
276  # Side 2
277  for i in range(start+nBWidth,end+1,nBWidth+1):
278  self.xBlockList.append(pts[i][0])
279  self.yBlockList.append(pts[i][1])
280  # Side 3
281  for i in range(end,end-nBWidth-1,-1):
282  self.xBlockList.append(pts[i][0])
283  self.yBlockList.append(pts[i][1])
284  # Side 4
285  for i in range(end-nBWidth,start-1,-nBWidth-1):
286  self.xBlockList.append(pts[i][0])
287  self.yBlockList.append(pts[i][1])
288 
289  self.xBlockList.append(None)
290  self.yBlockList.append(None)
291 
292 
327 
328  tend = default_timer()
329  if (self.silent == 0): print('Getting formatted blocklist time=%f sec' % (tend-tstart))
330  return [self.xBlockList,self.yBlockList]
331 
332  def showValues(self,icell):
333  if (self.silent == 0): print('=======================================================')
334  if (self.silent == 0): print('icell= %d; x=%e; y=%e' % (icell,self.getCenterPoints()[icell,0],self.getCenterPoints()[icell,1]))
335  for varname in self.getVarnames():
336  exec("if (self.silent == 0): print '%s =', self.%s[icell]" % (varname,varname))
337 
338 
339  def getIcellByPoint(self,x,y):
340  radii2 = (self.getCenterPoints()[:,0]-x)**2 + (self.getCenterPoints()[:,1]-y)**2
341  icell=radii2.argmin()
342  return icell
343 
344 
345  def getPoints(self):
346  try:
347  self.data
348  except AttributeError:
349  self.getData()
350  try:
351  self.points
352  except AttributeError:
353  vtk_points=self.data.GetPoints().GetData()
354  self.points=ah.vtk2array(vtk_points)
355  return self.points
356 
357 
358  def mirror(self):
359  """
360  Called when mirrorPlane != None
361  The reflection plane is labeled as follows: From the vtk documentation:
362  ReflectionPlane {
363  USE_X_MIN = 0, USE_Y_MIN = 1, USE_Z_MIN = 2, USE_X_MAX = 3,
364  USE_Y_MAX = 4, USE_Z_MAX = 5, USE_X = 6, USE_Y = 7,
365  USE_Z = 8
366  }
367  """
368 
369  vr=v.vtkReflectionFilter()
370  vr.SetInputData(self.data)
371  vr.SetPlane(self.mirrorPlane)
372  self.data=vr.GetOutput()
373  vr.Update()
374  #self.data.Update()
375  self.ncells = self.data.GetNumberOfCells()
376 
377 
378  def reflectVar(self,var):
379  if self.mirrorPlane == 0:
380  CC=self.getCenterPoints()
381  im = CC[:,0] < 0
382  var[im] = -var[im]
383  else:
384  if (self.silent == 0): print('reflection of this plane not yet implemented, sorry')
385 
386  return var
387 
388 
389  def getNdim(self):
390  smalldouble = 1e-10
391  self.ndim = 3
392  if abs(self.data.GetBounds()[1] - self.data.GetBounds()[0]) <= smalldouble:
393  self.ndim=self.ndim - 1
394  if abs(self.data.GetBounds()[3] - self.data.GetBounds()[2]) <= smalldouble:
395  self.ndim=self.ndim - 1
396  if abs(self.data.GetBounds()[5] - self.data.GetBounds()[4]) <= smalldouble:
397  self.ndim=self.ndim - 1
398  return self.ndim
399 
400 
401  def getAll(self):
402  t0 = default_timer()
403 
404  self.getData()
405  tdata = default_timer()
406  if (self.silent == 0): print('Reading data time= %f sec' % (tdata-t0))
407 
408  if self.mirrorPlane != None:
409  if (self.silent == 0): print('========== Mirror about plane ',self.mirrorPlane,' ... ============')
410  self.mirror()
411 
412 
413  if (self.silent == 0): print('========== Initializing ... ============')
414 
415 
416  self.getVars()
417  tvars = default_timer()
418  if (self.silent == 0): print('Getting vars time= %f sec' % (tvars-tdata))
419 
420  self.getPoints()
421  tpoints = default_timer()
422  if (self.silent == 0): print('Getting points time= %f sec' % (tpoints-tvars))
423 
424  self.getTime()
425 
426  tend = default_timer()
427  if (self.silent == 0): print('========== Finished loading %d cells in %f sec, have a nice day! ===========' % (self.ncells, (tend-t0) ))
428 
429 #=============================================================================
430 class loadvti(load):
431  """Loader class for vti data"""
432  def __init__(self,offset,get=1,file='data',mirrorPlane=None,silent=0,
433  rotateX=0,rotateY=0,rotateZ=0,
434  scaleX=1,scaleY=1,scaleZ=1):
435  self.offset=offset
436  self.filenameout = file
437  self.isLoaded = False
438  self.mirrorPlane=mirrorPlane
439  self.silent = silent
440 
441  self.rotateX = rotateX
442  self.rotateY = rotateY
443  self.rotateZ = rotateZ
444 
445  self.scaleX = scaleX
446  self.scaleY = scaleY
447  self.scaleZ = scaleZ
448 
449  self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vti'])
450  self.datareader = v.vtkXMLImageDataReader()
451 
452  if (self.silent == 0): print('========================================')
453  if (self.silent == 0): print('loading file %s' % (self.filename))
454 
455  if get != None:
456  self.getAll()
457 
458  def getNdim(self):
459  self.ndim = 3
460  if self.data.GetExtent()[1] - self.data.GetExtent()[0] == 0.:
461  self.ndim=self.ndim - 1
462  if self.data.GetExtent()[3] - self.data.GetExtent()[2] == 0.:
463  self.ndim=self.ndim - 1
464  if self.data.GetExtent()[5] - self.data.GetExtent()[4] == 0.:
465  self.ndim=self.ndim - 1
466  return self.ndim
467 
468  def getX(self):
469  self.dx=self.data.GetSpacing()[0]
470  self.nx=self.data.GetExtent()[1]-self.data.GetExtent()[0]
471  self.x=self.data.GetOrigin()[0] + np.arange(self.data.GetExtent()[0],self.data.GetExtent()[1])*self.dx+self.dx/2.
472 
473  def getY(self):
474  self.dy=self.data.GetSpacing()[1]
475  self.ny=self.data.GetExtent()[3]-self.data.GetExtent()[2]
476  self.y=self.data.GetOrigin()[1] + np.arange(self.data.GetExtent()[2],self.data.GetExtent()[3])*self.dy+self.dy/2.
477 
478  def getZ(self):
479  self.dz=self.data.GetSpacing()[2]
480  self.nz=self.data.GetExtent()[5]-self.data.GetExtent()[4]
481  self.z=self.data.GetOrigin()[2] + np.arange(self.data.GetExtent()[4],self.data.GetExtent()[5])*self.dz+self.dz/2.
482 
483 
484  def getVars(self):
485  nvars= self.data.GetCellData().GetNumberOfArrays()
486  for i in range(nvars):
487  varname = self.data.GetCellData().GetArrayName(i)
488  if (self.silent == 0): print("Assigning variable:", varname)
489  # vtk_values = self.pointdata.GetPointData().GetArray(varname)
490  vtk_values = self.data.GetCellData().GetArray(varname)
491  if self.getNdim() == 1:
492  exec("self.%s = ah.vtk2array(vtk_values)[0:self.ncells].reshape((self.nx),order='F')" % (varname))
493  if self.getNdim() == 2:
494  exec("self.%s = ah.vtk2array(vtk_values)[0:self.ncells].reshape((self.nx,self.ny),order='F')" % (varname))
495  if self.getNdim() == 3:
496  exec("self.%s = ah.vtk2array(vtk_values)[0:self.ncells].reshape((self.nx,self.ny,self.nz),order='F')" % (varname))
497 
498 
499  def getAll(self):
500  t0 = default_timer()
501 
502  self.getData()
503  tdata = default_timer()
504  if (self.silent == 0): print('Reading data time= %f sec' % (tdata-t0))
505 
506  self.getNdim()
507 
508  self.getX()
509  self.getY()
510  self.getZ()
511 
512  if self.mirrorPlane != None:
513  if (self.silent == 0): print('========== Mirror about plane ',self.mirrorPlane,' ... ============')
514  self.mirror()
515 
516 
517  if (self.silent == 0): print('========== Initializing ... ============')
518 
519 
520  self.getVars()
521  tvars = default_timer()
522  if (self.silent == 0): print('Getting vars time= %f sec' % (tvars-tdata))
523 
524  self.getTime()
525 
526  tend = default_timer()
527  if (self.silent == 0): print('========== Finished loading %d cells in %f sec, have a nice day! ===========' % (self.ncells, (tend-t0) ))
528 
529 #=============================================================================
530 class loadcsv():
531  '''Load 1D comma separated list from a cut'''
532  def __init__(self,offset,get=1,file='data',dir=1,coord=0.,silent=0):
533  self.silent = silent
534  self.offset=offset
535  self.filenameout = file
536  self.coord = coord
537  self.dir = dir
538  self.isLoaded = False
539  self.makefilename()
540 
541  if (self.silent == 0): print('========================================')
542  if (self.silent == 0): print('loading file %s' % (self.filename))
543 
544  if get != None:
545  self.getAll()
546 
547 
548  def makefilename(self):
549  number='%+.2e' % self.coord
550  if self.coord >= 0. and abs(self.coord) >1.:
551  self.filename = self.filenameout+'_d'+str(self.dir)+'_x+'+'0.'+number[1]+number[3]+'D+'+str(int(np.log10(abs(self.coord)))+1).zfill(2)+'_n'+str(self.offset).zfill(4)+'.csv'
552  if self.coord < 0. and abs(self.coord) >1.:
553  self.filename = self.filenameout+'_d'+str(self.dir)+'_x-'+'0.'+number[1]+number[3]+'D+'+str(int(np.log10(abs(self.coord)))+1).zfill(2)+'_n'+str(self.offset).zfill(4)+'.csv'
554  if self.coord > 0. and abs(self.coord) <=1.:
555  self.filename = self.filenameout+'_d'+str(self.dir)+'_x+'+'0.'+number[1]+number[3]+'D+'+str(int(np.log10(abs(self.coord)))).zfill(2)+'_n'+str(self.offset).zfill(4)+'.csv'
556  if self.coord < 0. and abs(self.coord) <=1.:
557  self.filename = self.filenameout+'_d'+str(self.dir)+'_x-'+'0.'+number[1]+number[3]+'D+'+str(int(np.log10(abs(self.coord)))).zfill(2)+'_n'+str(self.offset).zfill(4)+'.csv'
558  if self.coord == 0.:
559  self.filename = self.filenameout+'_d'+str(self.dir)+'_x+'+'0.'+number[1]+number[3]+'D+'+str(0).zfill(2)+'_n'+str(self.offset).zfill(4)+'.csv'
560 
561 
562  def getHeader(self):
563  self.file.seek(0)
564  self.header=self.file.readline().split(',')
565  self.header[-1]=self.header[-1].rstrip('\n')
566 
567  return self.header
568 
569 
570  def getAll(self):
571  t0 = default_timer()
572  self.file = open(self.filename, 'r')
573  if (self.silent == 0): print('========== Initializing ... ============')
574  self.getHeader()
575  self.getData()
576  self.file.close()
577  tdata = default_timer()
578  if (self.silent == 0): print('Reading data time= %f sec' % (tdata-t0))
579 
580 
581  def getData(self):
582  i=0
583  for var in self.header:
584  exec("self.%s = pylabload(self.filename,usecols=[i],skiprows=1, delimiter=',')" % (var))
585  i=i+1
586  exec("self.ncells = len(self.%s)" % (self.getHeader()[0]))
587 
588 #=============================================================================
589 class particles():
590  """Load binary particles data"""
591 
592  def __init__(self,offset,file='data',components=3):
593  self.offset=offset
594  self.filenameout = file
595  self.isLoaded = False
596  self.components = components
597 
598  self.data=[]
599  self.mynparticles = 0
600 
601  self.makefilename()
602  self.openfile()
603  self.read()
604  self.closefile()
605 
606 
607  def makefilename(self):
608  self.filename = self.filenameout+'_particles'+str(self.offset).zfill(4)+'.dat'
609 
610 
611  def openfile(self):
612  self.file = open(self.filename,'rb')
613  self.isLoaded = True
614 
615 
616  def closefile(self):
617  self.file.close()
618  self.isLoaded = False
619 
620 
621  def readheader(self):
622  self.file.seek(0)
623  (self.nparticles,) = struct.unpack('i',self.file.read(4))
624  (self.itparticles,) = struct.unpack('i',self.file.read(4))
625  (self.npayload,) = struct.unpack('i',self.file.read(4))
626 
627 
629  x = np.empty(self.components)
630  u = np.empty(self.components)
631  payload = np.empty(self.npayload)
632 
633  (index,) = struct.unpack('i',self.file.read(4))
634 
635  (ifollow,) = struct.unpack('i',self.file.read(4))
636  if (ifollow == -1):
637  follow = True
638  else:
639  follow = False
640 
641  (q,) = struct.unpack('d',self.file.read(8))
642  (m,) = struct.unpack('d',self.file.read(8))
643  (t,) = struct.unpack('d',self.file.read(8))
644  (dt,) = struct.unpack('d',self.file.read(8))
645 
646  for icomp in range(self.components):
647  (x[icomp],) = struct.unpack('d',self.file.read(8))
648 
649  for icomp in range(self.components):
650  (u[icomp],) = struct.unpack('d',self.file.read(8))
651 
652  for ipayload in range(self.npayload):
653  (payload[ipayload],) = struct.unpack('d',self.file.read(8))
654 
655  self.data.append({'index':index, 'q':q,
656  'follow':follow, 'm':m, 't':t,
657  'dt':dt, 'x':x, 'u':u, 'payload':payload})
658 
659  self.mynparticles= self.mynparticles + 1
660 
661 
662  def read(self):
663  self.readheader()
664  while (self.mynparticles < self.nparticles):
665  self.read_next_particle()
666 
667 
668  def particle(self,index):
669  for particle in self.data:
670  if particle['index'] == index :
671  return particle
672  return False
673 
674 
675  def get_sorted(self,i):
676  try:
677  self.sorted
678  except AttributeError:
679  self.index=np.array(self.nparticles)
680  index=[]
681  for particle in self.data:
682  index.append(particle['index'])
683  index=np.array(index)
684  self.sorted=index.argsort()
685  return self.sorted[i-1]
686 
687 #=============================================================================
688 class ensemble():
689  '''Load particle ensemble .csv files'''
690 
691  def __init__(self,offset,file='data0000',npayload=1,components=3,delimiter=','):
692  self.offset=offset
693  self.filenameout = file
694  self.isLoaded = False
695  self.components = components
696  self.npayload = npayload
697  self.delimiter = delimiter
698 
699  self.data=[]
700 
701  self.makefilename()
702  self.read()
703 
704 
705  def makefilename(self):
706  self.filename = self.filenameout+'_ensemble'+str(self.offset).zfill(6)+'.csv'
707 
708 
709  def read(self):
710  x = pylabload(self.filename, comments='#', delimiter=self.delimiter)
711 
712  t_ = 0
713  dt_ = 1
714  x1_ = 2
715  u1_ = x1_+self.components
716  payload_ = u1_+self.components
717  ipe_ = payload_+self.npayload
718  iteration_ = ipe_+1
719  index_ = iteration_+1
720 
721  if x.shape[1] == index_+1 :
722 
723  for particle in x:
724  self.data.append({'t':particle[t_],
725  'dt':particle[dt_], 'x':np.array(particle[x1_:x1_+self.components]),
726  'u':np.array(particle[u1_:u1_+self.components]),
727  'payload':np.array(particle[payload_:payload_+self.npayload]),
728  'ipe':particle[ipe_].astype(np.int), 'iteration':particle[iteration_].astype(np.int), 'index':particle[index_].astype(np.int)})
729 
730  else:
731  print('File inconsistent, assuming iteration counter overflow')
732  for particle in x:
733  self.data.append({'t':particle[t_],
734  'dt':particle[dt_], 'x':np.array(particle[x1_:x1_+self.components]),
735  'u':np.array(particle[u1_:u1_+self.components]),
736  'payload':np.array(particle[payload_:payload_+self.npayload]),
737  'garbage':particle[ipe_].astype(np.int), 'index':particle[index_-1].astype(np.int)})
738 
739 
740  self.isLoaded = True
741 
742 
743  def particle(self,index):
744  for particle in self.data:
745  if particle['index'] == index :
746  return particle
747  return False
748 #=============================================================================
749 class postrad():
750  """Load binary postrad data"""
751 
752  def __init__(self,offset,file='data',headersize=256,nvars=8):
753  self.offset=offset
754  self.filenameout = file
755  self.headersize = headersize
756  self.nvars =8
757 
758  self.indices={'r':0,'theta':1,'phi':2,'rho':0,'vr':1,'vtheta':2,'vphi':3,'p':4,'br':5,'btheta':6,'bphi':7}
759 
760  self.data=-1
761  self.grid=-1
762  self.header=-1
763 
764  self.__makefilenames()
765  self.__openfiles()
766  self.__read()
767  self.__closefiles()
768 
769  def __makefilenames(self):
770  self.filename_vars = self.filenameout+str(self.offset).zfill(4)+'.blk'
771  self.filename_grid = self.filenameout+'_grid.blk'
772 
773  def __openfiles(self):
774  self.file_vars = open(self.filename_vars,'rb')
775  self.file_grid = open(self.filename_grid,'rb')
776 
777  def __closefiles(self):
778  self.file_vars.close()
779  self.file_grid.close()
780 
781  def __read(self):
782  self.__read_header()
783  self.__set_dtype()
784  self.__read_grid()
785  self.__read_data()
786 
787  def __read_header(self):
788  file_vars = self.file_vars
789  file_vars.seek(0)
790  nr = struct.unpack('i',file_vars.read(4)) [0]
791  ntheta = struct.unpack('i',file_vars.read(4)) [0]
792  nphi = struct.unpack('i',file_vars.read(4)) [0]
793  t = struct.unpack('d',file_vars.read(8)) [0]
794  a = struct.unpack('d',file_vars.read(8)) [0]
795  r_in = struct.unpack('d',file_vars.read(8)) [0]
796  theta_in = struct.unpack('d',file_vars.read(8)) [0]
797  phi_in = struct.unpack('d',file_vars.read(8)) [0]
798  r_out = struct.unpack('d',file_vars.read(8)) [0]
799  theta_out = struct.unpack('d',file_vars.read(8)) [0]
800  phi_out = struct.unpack('d',file_vars.read(8)) [0]
801  gammahat = struct.unpack('d',file_vars.read(8)) [0]
802  # hslope = struct.unpack('d',file_vars.read(8)) [0]
803  hslope = 0.25 # was incorrectly set in codeComparison files
804  imetric = struct.unpack('i',file_vars.read(4)) [0]
805  dummy = struct.unpack('i',file_vars.read(4)) [0]
806  dim = struct.unpack('i',file_vars.read(4)) [0]
807  isp = struct.unpack('i',self.file_vars.read(4)) [0]
808  if (isp == -1):
809  single_precision = True
810  else:
811  single_precision = False
812 
813  self.header = {'nr':nr, 'ntheta':ntheta, 'nphi':nphi,'t':t,'a':a,'r_in':r_in,'theta_in':theta_in,'phi_in':phi_in,'r_out':r_out,'theta_out':theta_out,'phi_out':phi_out,'gammahat':gammahat,'hslope':hslope,'imetric':imetric,'dim':dim,'single_precision':single_precision}
814 
815  def __set_dtype(self):
816  if (self.header['single_precision']):
817  self.__dtype_str = 'f'
818  else:
819  self.__dtype_str = 'd'
820 
821  def __read_data(self):
822  file_vars = self.file_vars
823  header = self.header
824  file_vars.seek(self.headersize)
825 
826  len_bytes = header['nphi']*header['ntheta']*header['nr']*self.nvars
827  data = np.array(struct.unpack(self.__dtype_str*len_bytes,file_vars.read())).reshape(header['nphi'],header['ntheta'],header['nr'],self.nvars)
828 
829  self.data = data
830 
831  def __read_grid(self):
832  file_grid = self.file_grid
833  header = self.header
834  file_grid.seek(0)
835  len_bytes = header['nphi']*header['ntheta']*header['nr']*3
836  data = np.array(struct.unpack(self.__dtype_str*len_bytes,file_grid.read())).reshape(header['nphi'],header['ntheta'],header['nr'],3)
837 
838  self.grid = data
839 #=============================================================================
840 #if __name__ == "__main__":
841 # print("read.py is being run directly.")
842 #else:
843 # print("read.py is being imported.")
def __init__(self, offset, file='data', components=3)
Definition: read.py:592
def __set_dtype(self)
Definition: read.py:815
Loader class for vti data.
Definition: read.py:431
def getData(self)
Definition: read.py:104
def read(self)
Definition: read.py:709
def __read_data(self)
Definition: read.py:821
def reflectVar(self, var)
Definition: read.py:378
filename
Definition: read.py:71
rotateY
Definition: read.py:63
silent
Definition: read.py:60
def mirror(self)
Definition: read.py:367
filename_vars
Definition: read.py:770
def getVarnames(self)
Definition: read.py:151
surface
Definition: read.py:241
def getPointList(self)
Definition: read.py:174
offset
Definition: read.py:55
pointdata
Definition: read.py:133
def extract(data, varname, attribute_mode='cell')
Extracts variable "varname" from vtk datastructure "data&#39;.
Definition: read.py:22
time
Definition: read.py:91
scaleX
Definition: read.py:66
def getPointData(self)
Definition: read.py:125
def getCenterPoints(self)
Definition: read.py:197
def __init__(self, offset, get=1, file='data', mirrorPlane=None, silent=0, rotateX=0, rotateY=0, rotateZ=0, scaleX=1, scaleY=1, scaleZ=1)
Definition: read.py:434
def getData(self)
Definition: read.py:581
def get_sorted(self, i)
Definition: read.py:675
def getY(self)
Definition: read.py:473
centerpoints
Definition: read.py:209
type
Definition: read.py:57
def __closefiles(self)
Definition: read.py:777
def makefilename(self)
Definition: read.py:607
Loader class for vtu and pvtu files.
Definition: read.py:50
def getVar(self, varname)
Definition: read.py:97
Load binary particles data.
Definition: read.py:590
def getVert(self, icell)
Definition: read.py:163
Definition: read.py:1
rotateX
Definition: read.py:62
filenameout
Definition: read.py:56
rotateZ
Definition: read.py:64
points
Definition: read.py:354
def getPoints(self)
Definition: read.py:345
def __init__(self, offset, get=1, file='data', dir=1, coord=0., silent=0)
Definition: read.py:532
scaleZ
Definition: read.py:68
def getVars(self)
Definition: read.py:484
def getBounds(self)
Definition: read.py:159
def __init__(self, offset, file='data', headersize=256, nvars=8)
Definition: read.py:752
def getHeader(self)
Definition: read.py:562
def makefilename(self)
Definition: read.py:548
def __init__(self, offset, get=1, file='data', type='vtu', mirrorPlane=None, rotateX=0, rotateY=0, rotateZ=0, scaleX=1, scaleY=1, scaleZ=1, silent=0)
Definition: read.py:54
def __makefilenames(self)
Definition: read.py:769
def getZ(self)
Definition: read.py:478
isLoaded
Definition: read.py:58
def getIcellByPoint(self, x, y)
Definition: read.py:339
Load 1D comma separated list from a cut.
Definition: read.py:531
def openfile(self)
Definition: read.py:611
def getPieces(self, nBWidth, nBHeight, nIgnore)
Definition: read.py:246
def showValues(self, icell)
Definition: read.py:332
def getAll(self)
Definition: read.py:401
Load particle ensemble .csv files.
Definition: read.py:689
default_timer
Definition: read.py:14
xBlockList
Definition: read.py:256
def getAll(self)
Definition: read.py:570
def getSurface(self)
Definition: read.py:225
yBlockList
Definition: read.py:257
scaleY
Definition: read.py:67
def read(self)
Definition: read.py:662
def getNdim(self)
Definition: read.py:458
def __read_header(self)
Definition: read.py:787
ncells
Definition: read.py:108
def readheader(self)
Definition: read.py:621
Load binary postrad data.
Definition: read.py:750
def getX(self)
Definition: read.py:468
mirrorPlane
Definition: read.py:59
def read_next_particle(self)
Definition: read.py:628
def makefilename(self)
Definition: read.py:705
def closefile(self)
Definition: read.py:616
def __openfiles(self)
Definition: read.py:773
def particle(self, index)
Definition: read.py:743
def __init__(self, offset, file='data0000', npayload=1, components=3, delimiter=')
Definition: read.py:691
def getAll(self)
Definition: read.py:499
datareader
Definition: read.py:72
def __read_grid(self)
Definition: read.py:831
def __read(self)
Definition: read.py:781
def getNdim(self)
Definition: read.py:389
filename_grid
Definition: read.py:771
def getTime(self)
Definition: read.py:89
def particle(self, index)
Definition: read.py:668
def getVars(self)
Definition: read.py:142