forked from coolastro/pyPLUTO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyPLUTO.py
executable file
·1782 lines (1370 loc) · 64.9 KB
/
pyPLUTO.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import os
import sys
import array
import numpy as np
import scipy.ndimage
import scipy.interpolate
from scipy.interpolate import UnivariateSpline
from matplotlib.pyplot import *
from matplotlib.mlab import *
####### Check for h5py to Read AMR data ######
try:
import h5py as h5
hasH5 = True
except ImportError:
hasH5 = False
def curdir():
""" Get the current working directory.
"""
curdir = os.getcwd()+'/'
return curdir
def get_nstepstr(ns):
""" Convert the float input *ns* into a string that would match the data file name.
**Inputs**:
ns -- Integer number that represents the time step number. E.g., The ns for data.0001.dbl is 1.\n
**Outputs**:
Returns the string that would be used to complete the data file name. E.g., for data.0001.dbl, ns = 1 and pyPLUTO.get_nstepstr(1) returns '0001'
"""
nstepstr = str(ns)
while len(nstepstr) < 4:
nstepstr= '0'+nstepstr
return nstepstr
def nlast_info(w_dir=None,datatype=None):
""" Prints the information of the last step of the simulation as obtained from out files
**Inputs**:
w_dir -- path to the directory which has the dbl.out(or flt.out) and the data\n
datatype -- If the data is of 'float' type then datatype = 'float' else by default the datatype is set to 'double'.
**Outputs**:
This function returns a dictionary with following keywords - \n
nlast -- The ns for the last file saved.\n
time -- The simulation time for the last file saved.\n
dt -- The time step dt for the last file. \n
Nstep -- The Nstep value for the last file saved.
**Usage**:
In case the data is 'float'.
``wdir = /path/to/data/directory``\n
``import pyPLUTO as pp``\n
``A = pp.nlast_info(w_dir=wdir,datatype='float')``
"""
if w_dir is None: w_dir=curdir()
if datatype == 'float':
fname_v = w_dir+"flt.out"
elif datatype == 'vtk':
fname_v = w_dir+"vtk.out"
else:
fname_v = w_dir+"dbl.out"
last_line = file(fname_v,"r").readlines()[-1].split()
nlast = int(last_line[0])
SimTime = float(last_line[1])
Dt = float(last_line[2])
Nstep = int(last_line[3])
print("------------TIME INFORMATION--------------")
print('nlast =',nlast)
print('time =',SimTime)
print('dt =', Dt)
print('Nstep =',Nstep)
print("-------------------------------------------")
return {'nlast':nlast,'time':SimTime,'dt':Dt,'Nstep':Nstep}
class pload(object):
def __init__(self, ns, w_dir=None, datatype=None, level = 0, x1range=None, x2range=None, x3range=None, stdout=True):
"""Loads the data.
**Inputs**:
ns -- Step Number of the data file\n
w_dir -- path to the directory which has the data files\n
datatype -- Datatype (default = 'double')
**Outputs**:
pyPLUTO pload object whose keys are arrays of data values.
"""
self.NStep = ns
self.Dt = 0.0
self.n1 = 0
self.n2 = 0
self.n3 = 0
self.x1 = []
self.x2 = []
self.x3 = []
self.dx1 = []
self.dx2 = []
self.dx3 = []
self.x1range = x1range
self.x2range = x2range
self.x3range = x3range
self.NStepStr = str(self.NStep)
while len(self.NStepStr) < 4:
self.NStepStr = '0'+self.NStepStr
if datatype is None:
datatype = "double"
self.datatype = datatype
if ((not hasH5) and (datatype == 'hdf5')):
print('To read AMR hdf5 files with python')
print('Please install h5py (Python HDF5 Reader)')
return
self.level = level
if w_dir is None:
w_dir = os.getcwd() + '/'
self.wdir = w_dir
self.stdout=stdout # should we print a message with the filename that was opened?
Data_dictionary = self.ReadDataFile(self.NStepStr)
for keys in Data_dictionary:
object.__setattr__(self, keys, Data_dictionary.get(keys))
def ReadTimeInfo(self, timefile):
""" Read time info from the outfiles.
**Inputs**:
timefile -- name of the out file which has timing information.
"""
if (self.datatype == 'hdf5'):
fh5 = h5.File(timefile,'r')
self.SimTime = fh5.attrs.get('time')
#self.Dt = 1.e-2 # Should be erased later given the level in AMR
fh5.close()
else:
ns = self.NStep
f_var = open(timefile, "r")
tlist = []
for line in f_var.readlines():
tlist.append(line.split())
self.SimTime = float(tlist[ns][1])
self.Dt = float(tlist[ns][2])
def ReadVarFile(self, varfile):
""" Read variable names from the outfiles.
**Inputs**:
varfile -- name of the out file which has variable information.
"""
if (self.datatype == 'hdf5'):
fh5 = h5.File(varfile,'r')
self.filetype = 'single_file'
self.endianess = '>' # not used with AMR, kept for consistency
self.vars = []
for iv in range(fh5.attrs.get('num_components')):
self.vars.append(fh5.attrs.get('component_'+str(iv)))
fh5.close()
else:
vfp = open(varfile, "r")
varinfo = vfp.readline().split()
self.filetype = varinfo[4]
self.endianess = varinfo[5]
self.vars = varinfo[6:]
vfp.close()
def ReadGridFile(self, gridfile):
""" Read grid values from the grid.out file.
**Inputs**:
gridfile -- name of the grid.out file which has information about the grid.
"""
xL = []
xR = []
nmax = []
gfp = open(gridfile, "r")
for i in gfp.readlines():
if len(i.split()) == 1:
try:
int(i.split()[0])
nmax.append(int(i.split()[0]))
except:
pass
if len(i.split()) == 3:
try:
int(i.split()[0])
xL.append(float(i.split()[1]))
xR.append(float(i.split()[2]))
except:
if (i.split()[1] == 'GEOMETRY:'):
self.geometry=i.split()[2]
pass
self.n1, self.n2, self.n3 = nmax
n1 = self.n1
n1p2 = self.n1 + self.n2
n1p2p3 = self.n1 + self.n2 + self.n3
self.x1 = np.asarray([0.5*(xL[i]+xR[i]) for i in range(n1)])
self.dx1 = np.asarray([(xR[i]-xL[i]) for i in range(n1)])
self.x2 = np.asarray([0.5*(xL[i]+xR[i]) for i in range(n1, n1p2)])
self.dx2 = np.asarray([(xR[i]-xL[i]) for i in range(n1, n1p2)])
self.x3 = np.asarray([0.5*(xL[i]+xR[i]) for i in range(n1p2, n1p2p3)])
self.dx3 = np.asarray([(xR[i]-xL[i]) for i in range(n1p2, n1p2p3)])
# Stores the total number of points in '_tot' variable in case only
# a portion of the domain is loaded. Redefine the x and dx arrays
# to match the requested ranges
self.n1_tot = self.n1 ; self.n2_tot = self.n2 ; self.n3_tot = self.n3
if (self.x1range != None):
self.n1_tot = self.n1
self.irange = range(abs(self.x1-self.x1range[0]).argmin(),abs(self.x1-self.x1range[1]).argmin()+1)
self.n1 = len(self.irange)
self.x1 = self.x1[self.irange]
self.dx1 = self.dx1[self.irange]
else:
self.irange = range(self.n1)
if (self.x2range != None):
self.n2_tot = self.n2
self.jrange = range(abs(self.x2-self.x2range[0]).argmin(),abs(self.x2-self.x2range[1]).argmin()+1)
self.n2 = len(self.jrange)
self.x2 = self.x2[self.jrange]
self.dx2 = self.dx2[self.jrange]
else:
self.jrange = range(self.n2)
if (self.x3range != None):
self.n3_tot = self.n3
self.krange = range(abs(self.x3-self.x3range[0]).argmin(),abs(self.x3-self.x3range[1]).argmin()+1)
self.n3 = len(self.krange)
self.x3 = self.x3[self.krange]
self.dx3 = self.dx3[self.krange]
else:
self.krange = range(self.n3)
self.Slice=(self.x1range != None) or (self.x2range != None) or (self.x3range != None)
# Create the xr arrays containing the edges positions
# Useful for pcolormesh which should use those
self.x1r = np.zeros(len(self.x1)+1) ; self.x1r[1:] = self.x1 + self.dx1/2.0 ; self.x1r[0] = self.x1r[1]-self.dx1[0]
self.x2r = np.zeros(len(self.x2)+1) ; self.x2r[1:] = self.x2 + self.dx2/2.0 ; self.x2r[0] = self.x2r[1]-self.dx2[0]
self.x3r = np.zeros(len(self.x3)+1) ; self.x3r[1:] = self.x3 + self.dx3/2.0 ; self.x3r[0] = self.x3r[1]-self.dx3[0]
prodn = self.n1*self.n2*self.n3
if prodn == self.n1:
self.nshp = (self.n1)
elif prodn == self.n1*self.n2:
self.nshp = (self.n2, self.n1)
else:
self.nshp = (self.n3, self.n2, self.n1)
def DataScanVTK(self, fp, n1, n2, n3, endian, dtype):
""" Scans the VTK data files.
**Inputs**:
fp -- Data file pointer\n
n1 -- No. of points in X1 direction\n
n2 -- No. of points in X2 direction\n
n3 -- No. of points in X3 direction\n
endian -- Endianess of the data\n
dtype -- datatype
**Output**:
Dictionary consisting of variable names as keys and its values.
"""
ks = []
vtkvar = []
while True:
l = fp.readline()
try:
l.split()[0]
except IndexError:
pass
else:
if l.split()[0] == 'SCALARS':
ks.append(l.split()[1])
elif l.split()[0] == 'LOOKUP_TABLE':
A = array.array(dtype)
fmt = endian+str(n1*n2*n3)+dtype
nb = np.dtype(fmt).itemsize
A.fromstring(fp.read(nb))
if (self.Slice):
darr = np.zeros((n1*n2*n3))
indxx = np.sort([n3_tot*n2_tot*k + j*n2_tot + i for i in self.irange for j in self.jrange for k in self.krange])
if (sys.byteorder != self.endianess):
A.byteswap()
for ii,iii in enumerate(indxx):
darr[ii] = A[iii]
vtkvar_buf = [darr]
else:
vtkvar_buf = np.frombuffer(A,dtype=np.dtype(fmt))
vtkvar.append(np.reshape(vtkvar_buf,self.nshp).transpose())
else:
pass
if l == '':
break
vtkvardict = dict(zip(ks,vtkvar))
return vtkvardict
def DataScanHDF5(self, fp, myvars, ilev):
""" Scans the Chombo HDF5 data files for AMR in PLUTO.
**Inputs**:
fp -- Data file pointer\n
myvars -- Names of the variables to read\n
ilev -- required AMR level
**Output**:
Dictionary consisting of variable names as keys and its values.
**Note**:
Due to the particularity of AMR, the grid arrays loaded in ReadGridFile are overwritten here.
"""
# Read the grid information
dim = fp['Chombo_global'].attrs.get('SpaceDim')
nlev = fp.attrs.get('num_levels')
il = min(nlev-1,ilev)
lev = []
for i in range(nlev):
lev.append('level_'+str(i))
freb = np.zeros(nlev,dtype='int')
for i in range(il+1)[::-1]:
fl = fp[lev[i]]
if (i == il):
pdom = fl.attrs.get('prob_domain')
dx = fl.attrs.get('dx')
dt = fl.attrs.get('dt')
ystr = 1. ; zstr = 1. ; logr = 0
try:
geom = fl.attrs.get('geometry')
logr = fl.attrs.get('logr')
if (dim == 2):
ystr = fl.attrs.get('g_x2stretch')
elif (dim == 3):
zstr = fl.attrs.get('g_x3stretch')
except:
print('Old HDF5 file, not reading stretch and logr factors')
freb[i] = 1
x1b = fl.attrs.get('domBeg1')
if (dim == 1):
x2b = 0
else:
x2b = fl.attrs.get('domBeg2')
if (dim == 1 or dim == 2):
x3b = 0
else:
x3b = fl.attrs.get('domBeg3')
jbeg = 0 ; jend = 0 ; ny = 1
kbeg = 0 ; kend = 0 ; nz = 1
if (dim == 1):
ibeg = pdom[0] ; iend = pdom[1] ; nx = iend-ibeg+1
elif (dim == 2):
ibeg = pdom[0] ; iend = pdom[2] ; nx = iend-ibeg+1
jbeg = pdom[1] ; jend = pdom[3] ; ny = jend-jbeg+1
elif (dim == 3):
ibeg = pdom[0] ; iend = pdom[3] ; nx = iend-ibeg+1
jbeg = pdom[1] ; jend = pdom[4] ; ny = jend-jbeg+1
kbeg = pdom[2] ; kend = pdom[5] ; nz = kend-kbeg+1
else:
rat = fl.attrs.get('ref_ratio')
freb[i] = rat*freb[i+1]
dx0 = dx*freb[0]
## Allow to load only a portion of the domain
if (self.x1range != None):
if logr == 0:
self.x1range = self.x1range-x1b
else:
self.x1range = [log(self.x1range[0]/x1b),log(self.x1range[1]/x1b)]
ibeg0 = min(self.x1range)/dx0 ; iend0 = max(self.x1range)/dx0
ibeg = max([ibeg, int(ibeg0*freb[0])]) ; iend = min([iend,int(iend0*freb[0]-1)])
nx = iend-ibeg+1
if (self.x2range != None):
self.x2range = (self.x2range-x2b)/ystr
jbeg0 = min(self.x2range)/dx0 ; jend0 = max(self.x2range)/dx0
jbeg = max([jbeg, int(jbeg0*freb[0])]) ; jend = min([jend,int(jend0*freb[0]-1)])
ny = jend-jbeg+1
if (self.x3range != None):
self.x3range = (self.x3range-x3b)/zstr
kbeg0 = min(self.x3range)/dx0 ; kend0 = max(self.x3range)/dx0
kbeg = max([kbeg, int(kbeg0*freb[0])]) ; kend = min([kend,int(kend0*freb[0]-1)])
nz = kend-kbeg+1
## Create uniform grids at the required level
if logr == 0:
x1 = x1b + (ibeg+np.array(range(nx))+0.5)*dx
else:
x1 = x1b*(exp((ibeg+np.array(range(nx))+1)*dx)+exp((ibeg+np.array(range(nx)))*dx))*0.5
x2 = x2b + (jbeg+np.array(range(ny))+0.5)*dx*ystr
x3 = x3b + (kbeg+np.array(range(nz))+0.5)*dx*zstr
if logr == 0:
dx1 = np.ones(nx)*dx
else:
dx1 = x1b*(exp((ibeg+np.array(range(nx))+1)*dx)-exp((ibeg+np.array(range(nx)))*dx))
dx2 = np.ones(ny)*dx*ystr
dx3 = np.ones(nz)*dx*zstr
# Create the xr arrays containing the edges positions
# Useful for pcolormesh which should use those
x1r = np.zeros(len(x1)+1) ; x1r[1:] = x1 + dx1/2.0 ; x1r[0] = x1r[1]-dx1[0]
x2r = np.zeros(len(x2)+1) ; x2r[1:] = x2 + dx2/2.0 ; x2r[0] = x2r[1]-dx2[0]
x3r = np.zeros(len(x3)+1) ; x3r[1:] = x3 + dx3/2.0 ; x3r[0] = x3r[1]-dx3[0]
NewGridDict = dict([('n1',nx),('n2',ny),('n3',nz),\
('x1',x1),('x2',x2),('x3',x3),\
('x1r',x1r),('x2r',x2r),('x3r',x3r),\
('dx1',dx1),('dx2',dx2),('dx3',dx3),\
('Dt',dt)])
# Variables table
nvar = len(myvars)
vars = np.zeros((nx,ny,nz,nvar))
LevelDic = {'nbox':0,'ibeg':ibeg,'iend':iend,'jbeg':jbeg,'jend':jend,'kbeg':kbeg,'kend':kend}
AMRLevel = []
AMRBoxes = np.zeros((nx,ny,nz))
for i in range(il+1):
AMRLevel.append(LevelDic.copy())
fl = fp[lev[i]]
data = fl['data:datatype=0']
boxes = fl['boxes']
nbox = len(boxes['lo_i'])
AMRLevel[i]['nbox'] = nbox
ncount = 0
AMRLevel[i]['box']=[]
for j in range(nbox): # loop on all boxes of a given level
AMRLevel[i]['box'].append({'x0':0.,'x1':0.,'ib':0,'ie':0,\
'y0':0.,'y1':0.,'jb':0,'je':0,\
'z0':0.,'z1':0.,'kb':0,'ke':0})
# Box indexes
ib = boxes[j]['lo_i'] ; ie = boxes[j]['hi_i'] ; nbx = ie-ib+1
jb = 0 ; je = 0 ; nby = 1
kb = 0 ; ke = 0 ; nbz = 1
if (dim > 1):
jb = boxes[j]['lo_j'] ; je = boxes[j]['hi_j'] ; nby = je-jb+1
if (dim > 2):
kb = boxes[j]['lo_k'] ; ke = boxes[j]['hi_k'] ; nbz = ke-kb+1
szb = nbx*nby*nbz*nvar
# Rescale to current level
kb = kb*freb[i] ; ke = (ke+1)*freb[i] - 1
jb = jb*freb[i] ; je = (je+1)*freb[i] - 1
ib = ib*freb[i] ; ie = (ie+1)*freb[i] - 1
# Skip boxes lying outside ranges
if ((ib > iend) or (ie < ibeg) or \
(jb > jend) or (je < jbeg) or \
(kb > kend) or (ke < kbeg)):
ncount = ncount + szb
else:
### Read data
q = data[ncount:ncount+szb].reshape((nvar,nbz,nby,nbx)).T
### Find boxes intersections with current domain ranges
ib0 = max([ibeg,ib]) ; ie0 = min([iend,ie])
jb0 = max([jbeg,jb]) ; je0 = min([jend,je])
kb0 = max([kbeg,kb]) ; ke0 = min([kend,ke])
### Store box corners in the AMRLevel structure
if logr == 0:
AMRLevel[i]['box'][j]['x0'] = x1b + dx*(ib0)
AMRLevel[i]['box'][j]['x1'] = x1b + dx*(ie0+1)
else:
AMRLevel[i]['box'][j]['x0'] = x1b*exp(dx*(ib0))
AMRLevel[i]['box'][j]['x1'] = x1b*exp(dx*(ie0+1))
AMRLevel[i]['box'][j]['y0'] = x2b + dx*(jb0)*ystr
AMRLevel[i]['box'][j]['y1'] = x2b + dx*(je0+1)*ystr
AMRLevel[i]['box'][j]['z0'] = x3b + dx*(kb0)*zstr
AMRLevel[i]['box'][j]['z1'] = x3b + dx*(ke0+1)*zstr
AMRLevel[i]['box'][j]['ib'] = ib0 ; AMRLevel[i]['box'][j]['ie'] = ie0
AMRLevel[i]['box'][j]['jb'] = jb0 ; AMRLevel[i]['box'][j]['je'] = je0
AMRLevel[i]['box'][j]['kb'] = kb0 ; AMRLevel[i]['box'][j]['ke'] = ke0
AMRBoxes[ib0-ibeg:ie0-ibeg+1, jb0-jbeg:je0-jbeg+1, kb0-kbeg:ke0-kbeg+1] = il
### Extract the box intersection from data stored in q
cib0 = (ib0-ib)/freb[i] ; cie0 = (ie0-ib)/freb[i]
cjb0 = (jb0-jb)/freb[i] ; cje0 = (je0-jb)/freb[i]
ckb0 = (kb0-kb)/freb[i] ; cke0 = (ke0-kb)/freb[i]
q1 = np.zeros((cie0-cib0+1, cje0-cjb0+1, cke0-ckb0+1,nvar))
q1 = q[cib0:cie0+1,cjb0:cje0+1,ckb0:cke0+1,:]
# Remap the extracted portion
if (dim == 1):
new_shape = (ie0-ib0+1,1)
elif (dim == 2):
new_shape = (ie0-ib0+1,je0-jb0+1)
else:
new_shape = (ie0-ib0+1,je0-jb0+1,ke0-kb0+1)
stmp = list(new_shape)
while stmp.count(1) > 0:
stmp.remove(1)
new_shape = tuple(stmp)
myT = Tools()
for iv in range(nvar):
vars[ib0-ibeg:ie0-ibeg+1,jb0-jbeg:je0-jbeg+1,kb0-kbeg:ke0-kbeg+1,iv] = \
myT.congrid(q1[:,:,:,iv].squeeze(),new_shape,method='linear',minusone=True).reshape((ie0-ib0+1,je0-jb0+1,ke0-kb0+1))
ncount = ncount+szb
h5vardict={}
for iv in range(nvar):
h5vardict[myvars[iv]] = vars[:,:,:,iv].squeeze()
AMRdict = dict([('AMRBoxes',AMRBoxes),('AMRLevel',AMRLevel)])
OutDict = dict(NewGridDict)
OutDict.update(AMRdict)
OutDict.update(h5vardict)
return OutDict
def DataScan(self, fp, n1, n2, n3, endian, dtype, off=None):
"""
Scans the data files in all formats.
**Inputs**:
fp -- Data file pointer\n
n1 -- No. of points in X1 direction\n
n2 -- No. of points in X2 direction\n
n3 -- No. of points in X3 direction\n
endian -- Endianess of the data\n
dtype -- datatype, eg : double, float, vtk, hdf5\n
off -- offset (for avoiding staggered B fields)
**Output**:
Dictionary consisting of variable names as keys and its values.
"""
if off is not None:
off_fmt = endian+str(off)+dtype
nboff = np.dtype(off_fmt).itemsize
fp.read(nboff)
n1_tot = self.n1_tot ; n2_tot = self.n2_tot; n3_tot = self.n3_tot
A = array.array(dtype)
fmt = endian+str(n1_tot*n2_tot*n3_tot)+dtype
nb = np.dtype(fmt).itemsize
A.fromstring(fp.read(nb))
if (self.Slice):
darr = np.zeros((n1*n2*n3))
indxx = np.sort([n3_tot*n2_tot*k + j*n2_tot + i for i in self.irange for j in self.jrange for k in self.krange])
if (sys.byteorder != self.endianess):
A.byteswap()
for ii,iii in enumerate(indxx):
darr[ii] = A[iii]
darr = [darr]
else:
darr = np.frombuffer(A,dtype=np.dtype(fmt))
return np.reshape(darr[0],self.nshp).transpose()
def ReadSingleFile(self, datafilename, myvars, n1, n2, n3, endian,
dtype, ddict):
"""Reads a single data file, data.****.dtype.
**Inputs**:
datafilename -- Data file name\n
myvars -- List of variable names to be read\n
n1 -- No. of points in X1 direction\n
n2 -- No. of points in X2 direction\n
n3 -- No. of points in X3 direction\n
endian -- Endianess of the data\n
dtype -- datatype\n
ddict -- Dictionary containing Grid and Time Information
which is updated
**Output**:
Updated Dictionary consisting of variable names as keys and its values.
"""
if self.datatype == 'hdf5':
fp = h5.File(datafilename,'r')
else:
fp = open(datafilename, "rb")
if self.stdout==True:
print("Reading Data file : %s"%datafilename)
if self.datatype == 'vtk':
vtkd = self.DataScanVTK(fp, n1, n2, n3, endian, dtype)
ddict.update(vtkd)
elif self.datatype == 'hdf5':
h5d = self.DataScanHDF5(fp,myvars,self.level)
ddict.update(h5d)
else:
for i in range(len(myvars)):
if myvars[i] == 'bx1s':
ddict.update({myvars[i]: self.DataScan(fp, n1, n2, n3, endian,
dtype, off=n2*n3)})
elif myvars[i] == 'bx2s':
ddict.update({myvars[i]: self.DataScan(fp, n1, n2, n3, endian,
dtype, off=n3*n1)})
elif myvars[i] == 'bx3s':
ddict.update({myvars[i]: self.DataScan(fp, n1, n2, n3, endian,
dtype, off=n1*n2)})
else:
ddict.update({myvars[i]: self.DataScan(fp, n1, n2, n3, endian,
dtype)})
fp.close()
def ReadMultipleFiles(self, nstr, dataext, myvars, n1, n2, n3, endian,
dtype, ddict):
"""Reads a multiple data files, varname.****.dataext.
**Inputs**:
nstr -- File number in form of a string\n
dataext -- Data type of the file, e.g., 'dbl', 'flt' or 'vtk' \n
myvars -- List of variable names to be read\n
n1 -- No. of points in X1 direction\n
n2 -- No. of points in X2 direction\n
n3 -- No. of points in X3 direction\n
endian -- Endianess of the data\n
dtype -- datatype\n
ddict -- Dictionary containing Grid and Time Information
which is updated.
**Output**:
Updated Dictionary consisting of variable names as keys and its values.
"""
for i in range(len(myvars)):
datafilename = self.wdir+myvars[i]+"."+nstr+dataext
fp = open(datafilename, "rb")
if self.datatype == 'vtk':
ddict.update(self.DataScanVTK(fp, n1, n2, n3, endian, dtype))
else:
ddict.update({myvars[i]: self.DataScan(fp, n1, n2, n3, endian,
dtype)})
fp.close()
def ReadDataFile(self, num):
"""Reads the data file generated from PLUTO code.
**Inputs**:
num -- Data file number in form of an Integer.
**Outputs**:
Dictionary that contains all information about Grid, Time and
variables.
"""
gridfile = self.wdir+"grid.out"
if self.datatype == "float":
dtype = "f"
varfile = self.wdir+"flt.out"
dataext = ".flt"
elif self.datatype == "vtk":
dtype = "f"
varfile = self.wdir+"vtk.out"
dataext=".vtk"
elif self.datatype == 'hdf5':
dtype = 'd'
dataext = '.hdf5'
nstr = num
varfile = self.wdir+"data."+nstr+dataext
else:
dtype = "d"
varfile = self.wdir+"dbl.out"
dataext = ".dbl"
self.ReadVarFile(varfile)
self.ReadGridFile(gridfile)
self.ReadTimeInfo(varfile)
nstr = num
if self.endianess == 'big':
endian = ">"
elif self.datatype == 'vtk':
endian = ">"
else:
endian = "<"
D = [('NStep', self.NStep), ('SimTime', self.SimTime), ('Dt', self.Dt),
('n1', self.n1), ('n2', self.n2), ('n3', self.n3),
('x1', self.x1), ('x2', self.x2), ('x3', self.x3),
('dx1', self.dx1), ('dx2', self.dx2), ('dx3', self.dx3),
('endianess', self.endianess), ('datatype', self.datatype),
('filetype', self.filetype)]
ddict = dict(D)
if self.filetype == "single_file":
datafilename = self.wdir+"data."+nstr+dataext
self.ReadSingleFile(datafilename, self.vars, self.n1, self.n2,
self.n3, endian, dtype, ddict)
elif self.filetype == "multiple_files":
self.ReadMultipleFiles(nstr, dataext, self.vars, self.n1, self.n2,
self.n3, endian, dtype, ddict)
else:
print("Wrong file type : CHECK pluto.ini for file type.")
print("Only supported are .dbl, .flt, .vtk, .hdf5")
sys.exit()
return ddict
class Tools(object):
"""
This Class has all the functions doing basic mathematical
operations to the vector or scalar fields.
It is called after pyPLUTO.pload object is defined.
"""
def deriv(self,Y,X=None):
"""
Calculates the derivative of Y with respect to X.
**Inputs:**
Y : 1-D array to be differentiated.\n
X : 1-D array with len(X) = len(Y).\n
If X is not specified then by default X is chosen to be an equally spaced array having same number of elements
as Y.
**Outputs:**
This returns an 1-D array having the same no. of elements as Y (or X) and contains the values of dY/dX.
"""
n = len(Y)
n2 = n-2
if X==None : X = np.arange(n)
Xarr = np.asarray(X,dtype='float')
Yarr = np.asarray(Y,dtype='float')
x12 = Xarr - np.roll(Xarr,-1) #x1 - x2
x01 = np.roll(Xarr,1) - Xarr #x0 - x1
x02 = np.roll(Xarr,1) - np.roll(Xarr,-1) #x0 - x2
DfDx = np.roll(Yarr,1) * (x12 / (x01*x02)) + Yarr * (1./x12 - 1./x01) - np.roll(Yarr,-1) * (x01 / (x02 * x12))
# Formulae for the first and last points:
DfDx[0] = Yarr[0] * (x01[1]+x02[1])/(x01[1]*x02[1]) - Yarr[1] * x02[1]/(x01[1]*x12[1]) + Yarr[2] * x01[1]/(x02[1]*x12[1])
DfDx[n-1] = -Yarr[n-3] * x12[n2]/(x01[n2]*x02[n2]) + Yarr[n-2]*x02[n2]/(x01[n2]*x12[n2]) - Yarr[n-1]*(x02[n2]+x12[n2])/(x02[n2]*x12[n2])
return DfDx
def Grad(self,phi,x1,x2,dx1,dx2,polar=False):
""" This method calculates the gradient of the 2D scalar phi.
**Inputs:**
phi -- 2D scalar whose gradient is to be determined.\n
x1 -- The 'x' array\n
x2 -- The 'y' array\n
dx1 -- The grid spacing in 'x' direction.\n
dx2 -- The grid spacing in 'y' direction.\n
polar -- The keyword should be set to True inorder to estimate the Gradient in polar co-ordinates. By default it is set to False.
**Outputs:**
This routine outputs a 3D array with shape = (len(x1),len(x2),2), such that [:,:,0] element corresponds to the gradient values of phi wrt to x1 and [:,:,1] are the gradient values of phi wrt to x2.
"""
(n1, n2) = phi.shape
grad_phi = np.zeros(shape=(n1,n2,2))
h2 = np.ones(shape=(n1,n2))
if polar == True:
for j in range(n2):
h2[:,j] = x1
for i in range(n1):
scrh1 = phi[i,:]
grad_phi[i,:,1] = self.deriv(scrh1,x2)/h2[i,:]
for j in range(n2):
scrh2 = phi[:,j]
grad_phi[:,j,0] = self.deriv(scrh2,x1)
return grad_phi
def Div(self,u1,u2,x1,x2,dx1,dx2,geometry=None):
""" This method calculates the divergence of the 2D vector fields u1 and u2.
**Inputs:**
u1 -- 2D vector along x1 whose divergence is to be determined.\n
u2 -- 2D vector along x2 whose divergence is to be determined.\n
x1 -- The 'x' array\n
x2 -- The 'y' array\n
dx1 -- The grid spacing in 'x' direction.\n
dx2 -- The grid spacing in 'y' direction.\n
geometry -- The keyword *geometry* is by default set to 'cartesian'. It can be set to either one of the following : *cartesian*, *cylindrical*, *spherical* or *polar*. To calculate the divergence of the vector fields, respective geometric corrections are taken into account based on the value of this keyword.
**Outputs:**
A 2D array with same shape as u1(or u2) having the values of divergence.
"""
(n1, n2) = u1.shape
Divergence = np.zeros(shape=(n1,n2))
du1 = np.zeros(shape=(n1,n2))
du2 = np.zeros(shape=(n1,n2))
A1 = np.zeros(shape=n1)
A2 = np.zeros(shape=n2)
dV1 = np.zeros(shape=(n1,n2))
dV2 = np.zeros(shape=(n1,n2))
if geometry == None : geometry = 'cartesian'
#------------------------------------------------
# define area and volume elements for the
# different coordinate systems
#------------------------------------------------
if geometry == 'cartesian' :
A1[:] = 1.0
A2[:] = 1.0
dV1 = np.outer(dx1,A2)
dV2 = np.outer(A1,dx2)
if geometry == 'cylindrical' :
A1 = x1
A2[:] = 1.0
dV1 = np.meshgrid(x1*dx1,A2)[0].T*np.meshgrid(x1*dx1,A2)[1].T
for i in range(n1) : dV2[i,:] = dx2[:]
if geometry == 'polar' :
A1 = x1
A2[:] = 1.0
dV1 = np.meshgrid(x1,A2)[0].T*np.meshgrid(x1,A2)[1].T
dV2 = np.meshgrid(x1,dx2)[0].T*np.meshgrid(x1,dx2)[1].T
if geometry == 'spherical' :
A1 = x1*x1
A2 = np.sin(x2)
for j in range(n2): dV1[:,j] = A1*dx1
dV2 = np.meshgrid(x1,np.sin(x2)*dx2)[0].T*np.meshgrid(x1,np.sin(x2)*dx2)[1].T
# ------------------------------------------------
# Make divergence
# ------------------------------------------------
for i in range(1,n1-1):
du1[i,:] = 0.5*(A1[i+1]*u1[i+1,:] - A1[i-1]*u1[i-1,:])/dV1[i,:]
for j in range(1,n2-1):
du2[:,j] = 0.5*(A2[j+1]*u2[:,j+1] - A2[j-1]*u2[:,j-1])/dV2[:,j]
Divergence = du1 + du2
return Divergence
def RTh2Cyl(self,R,Th,X1,X2):
""" This method does the transformation from spherical coordinates to cylindrical ones.
**Inputs:**
R - 2D array of spherical radius coordinates.\n
Th - 2D array of spherical theta-angle coordinates.\n
X1 - 2D array of radial component of given vector\n
X2 - 2D array of thetoidal component of given vector\n
**Outputs:**
This routine outputs two 2D arrays after transformation.
**Usage:**
``import pyPLUTO as pp``\n
``import numpy as np``\n
``D = pp.pload(0)``\n
``ppt=pp.Tools()``\n
``TH,R=np.meshgrid(D.x2,D.x1)``\n
``Br,Bz=ppt.RTh2Cyl(R,TH,D.bx1,D.bx2)``
D.bx1 and D.bx2 should be vectors in spherical coordinates. After transformation (Br,Bz) corresponds to vector in cilindrical coordinates.
"""
Y1=X1*np.sin(Th)+X2*np.cos(Th)
Y2=X1*np.cos(Th)-X2*np.sin(Th)
return Y1,Y2
def myInterpol(self,RR,N):
""" This method interpolates (linear interpolation) vector 1D vector RR to 1D N-length vector. Useful for stretched grid calculations.
**Inputs:**
RR - 1D array to interpolate.\n
N - Number of grids to interpolate to.\n
**Outputs:**
This routine outputs interpolated 1D array to the new grid (len=N).
**Usage:**
``import pyPLUTO as pp``\n
``import numpy as np``\n
``D = pp.pload(0)``\n
``ppt=pp.Tools()``\n
``x=linspace(0,1,10) #len(x)=10``\n
``y=x*x``\n
``Ri,Ni=ppt.myInterpol(y,100) #len(Ri)=100``
Ri - interpolated numbers;
Ni - grid for Ri
"""
NN=np.linspace(0,len(RR)-1,len(RR))
spline_fit=UnivariateSpline(RR,NN,k=3,s=0)
RRi=np.linspace(RR[0],RR[-1],N)
NNi=spline_fit(RRi)
NNi[0]=NN[0]+0.00001
NNi[-1]=NN[-1]-0.00001
return RRi,NNi
def getUniformGrid(self,r,th,rho,Nr,Nth):
""" This method transforms data with non-uniform grid (stretched) to uniform. Useful for stretched grid calculations.
**Inputs:**
r - 1D vector of X1 coordinate (could be any, e.g D.x1).\n
th - 1D vector of X2 coordinate (could be any, e.g D.x2).\n
rho- 2D array of data.\n
Nr - new size of X1 vector.\n
Nth- new size of X2 vector.\n
**Outputs:**
This routine outputs 2D uniform array Nr x Nth dimension
**Usage:**
``import pyPLUTO as pp``\n
``import numpy as np``\n
``D = pp.pload(0)``\n
``ppt=pp.Tools()``\n
``X1new, X2new, res = ppt.getUniformGrid(D.x1,D.x2,D.rho,20,30)``
X1new - X1 interpolated grid len(X1new)=20
X2new - X2 interpolated grid len(X2new)=30
res - 2D array of interpolated variable
"""
Ri,NRi=self.myInterpol(r,Nr)
Ra=np.int32(NRi);Wr=NRi-Ra
YY=np.ones([Nr,len(th)])
for i in range(len(th)):
YY[:,i]=(1-Wr)*rho[Ra,i] + Wr*rho[Ra+1,i]