-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathxgc_reader.py
1967 lines (1662 loc) · 74.9 KB
/
xgc_reader.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
"""Module of the XGC1 loader for regerating general plots using ADIOS2
Some parts are taken from Michael's xgc.py which is taken from Loic's load_XGC_local for BES.
It reads the data from the simulation especially 1D results and other small data output.
TODO
3D data are loaded only when it is specified.
"""
import numpy as np
import os
from matplotlib.tri import Triangulation, LinearTriInterpolator, CubicTriInterpolator
import matplotlib.pyplot as plt
from scipy.io import matlab
from scipy.optimize import curve_fit
from scipy.special import erfc
import scipy.sparse as sp
from tqdm.auto import trange, tqdm
from functools import singledispatchmethod
import adios2
adios2_version_minor = int(adios2.__version__[2:adios2.__version__.find('.',2)])
if adios2_version_minor < 10:
raise RuntimeError(f"Must use adios 2.10 or newer with the xgc_reader module, loaded 2.{adios2_version_minor}\n For 2.9.x version try adios_2_9_x branch")
def read_all_steps(f, var):
vars=f.available_variables()
stc=vars[var].get("AvailableStepsCount")
ct=vars[var].get("Shape")
stc=int(stc)
#print(var+':', ct, stc)
if ct!='':
c=[int(i) for i in ct.split(',')] #
if len(c)==1 :
return np.reshape(f.read(var,start=[0], count=c, step_selection=[0,stc]), [stc, c[0]])
elif len(c)==2 :
return np.reshape(f.read(var,start=[0,0], count=c, step_selection=[0,stc]), [stc, c[0], c[1]])
elif ( len(c)==3 ):
return np.reshape(f.read(var,start=[0,0,0],count=c, step_selection=[0,stc]), [stc, c[0], c[1], c[2]])
else:
return f.read(var, step_selection=[0,stc])
class xgc1(object):
class cnst:
echarge = 1.602E-19
protmass= 1.67E-27
mu0 = 4 * 3.141592 * 1E-7
def __init__(self, path='./'):
"""
initialize either cd to a directory to process many files later, or
open an Adios Campaign Archive now.
"""
if path.endswith(".aca"):
self.campaign = adios2.FileReader(path)
self.path='' # for self.path+filename to able to serve as name in campaign
# get all variable names and info at once and save for reuse
self.campaign_all_vars = self.campaign.available_variables()
else:
self.campaign=None
os.chdir(path)
self.path=os.getcwd()+'/'
self.campaign_all_vars = {} # not usable when reading individual files locally
@classmethod
def load_basic(cls, path='./'):
os.chdir(path)
cls.path=os.getcwd()+'/'
cls.load_units(cls)
cls.load_oned(cls)
cls.setup_mesh(cls)
cls.setup_f0mesh(cls)
cls.load_volumes(cls)
#for compatibility with older version
def load_unitsm(self):
self.load_units()
def load_units(self):
"""
read in xgc.units.bp file
"""
if self.campaign:
f = self.campaign
prefix = 'xgc.units.bp/'
else:
f = adios2.FileReader(self.path+"xgc.units.bp")
prefix = ''
self.unit_dic = {}
self.unit_dic['eq_x_psi'] = f.read(prefix+'eq_x_psi')
self.unit_dic['eq_x_r'] = f.read(prefix+'eq_x_r')
self.unit_dic['eq_x_z'] = f.read(prefix+'eq_x_z')
self.unit_dic['eq_axis_r'] = f.read(prefix+'eq_axis_r')
self.unit_dic['eq_axis_z'] = f.read(prefix+'eq_axis_z')
self.unit_dic['eq_axis_b'] = f.read(prefix+'eq_axis_b')
self.unit_dic['sml_dt'] = f.read(prefix+'sml_dt')
self.unit_dic['diag_1d_period'] = f.read(prefix+'diag_1d_period')
try:
self.unit_dic['e_ptl_charge_eu'] = f.read(prefix+'e_ptl_charge_eu')
self.unit_dic['e_ptl_mass_au'] = f.read(prefix+'e_ptl_mass_au')
except:
print('No electron particle charge/mass found in xgc.units.bp')
self.unit_dic['eq_den_v1'] = f.read(prefix+'eq_den_v1')
self.unit_dic['eq_tempi_v1'] = f.read(prefix+'eq_tempi_v1')
self.unit_dic['i_ptl_charge_eu'] = f.read(prefix+'i_ptl_charge_eu')
self.unit_dic['i_ptl_mass_au'] = f.read(prefix+'i_ptl_mass_au')
self.unit_dic['sml_dt'] = f.read(prefix+'sml_dt')
self.unit_dic['sml_totalpe'] = f.read(prefix+'sml_totalpe')
self.unit_dic['sml_tran'] = f.read(prefix+'sml_tran')
try:
self.unit_dic['sml_wedge_n'] = f.read(prefix+'sml_wedge_n')
except:
self.unit_dic['sml_wedge_n'] = 1 # XGCa
self.psix = self.unit_dic['eq_x_psi']
self.eq_x_r = self.unit_dic['eq_x_r']
self.eq_x_z = self.unit_dic['eq_x_z']
self.eq_axis_r = self.unit_dic['eq_axis_r']
self.eq_axis_z = self.unit_dic['eq_axis_z']
self.eq_axis_b = self.unit_dic['eq_axis_b']
self.sml_dt = self.unit_dic['sml_dt']
self.sml_wedge_n = self.unit_dic['sml_wedge_n']
self.diag_1d_period = self.unit_dic['diag_1d_period']
if not self.campaign:
f.close()
def load_oned(self, i_mass=2, i2mass=12):
"""
load xgc.oneddiag.bp and some post process
"""
if self.campaign:
self.od=self.data1(self.campaign, self.campaign_all_vars, "xgc.oneddiag.bp") #actual reading routine
else:
self.od=self.data1(self.path+"xgc.oneddiag.bp") #actual reading routine
self.od.psi=self.od.psi[0,:]
self.od.psi00=self.od.psi00[0,:]
try:
self.od.psi00n=self.od.psi00/self.psix #Normalize 0 - 1(Separatrix)
except:
print("psix is not defined - call load_units() to get psix to get psi00n")
# Temperatures
try:
Teperp=self.od.e_perp_temperature_df_1d
except:
print('No electron')
self.electron_on=False
else:
self.electron_on=True
Tepara=self.od.e_parallel_mean_en_df_1d #parallel flow ignored, correct it later
self.od.Te=(Teperp+Tepara)/3*2
#minority or impurity tempearture
try:
Ti2perp=self.od.i2perp_temperature_df_1d
except:
print('No Impurity')
self.ion2_on=False
else:
self.ion2_on=True
Ti2para=self.od.i2parallel_mean_en_df_1d - 0.5* i2mass * self.cnst.protmass * self.od.i2parallel_flow_df_1d**2 / self.cnst.echarge
self.od.Ti2=(Ti2perp+Ti2para)/3*2
Tiperp=self.od.i_perp_temperature_df_1d
Tipara=self.od.i_parallel_mean_en_df_1d - 0.5* i_mass * self.cnst.protmass * self.od.i_parallel_flow_df_1d**2 / self.cnst.echarge #parallel flow ignored, correct it later
self.od.Ti=(Tiperp+Tipara)/3*2
#ExB shear calculation
if(self.electron_on):
shear=self.od.d_dpsi(self.od.e_poloidal_ExB_flow_1d,self.od.psi_mks)
self.od.grad_psi_sqr = self.od.e_grad_psi_sqr_1d
else:
shear=self.od.d_dpsi(self.od.i_poloidal_ExB_flow_1d,self.od.psi_mks)
self.od.grad_psi_sqr = self.od.i_grad_psi_sqr_1d
self.od.shear_r=shear * np.sqrt(self.od.grad_psi_sqr) # assuming electron full-f is almost homogeneouse
if(self.electron_on):
self.od.density = self.od.e_gc_density_df_1d
else:
self.od.density = self.od.i_gc_density_df_1d
#gradient scale
self.od.Ln = self.od.density / self.od.d_dpsi(self.od.density, self.od.psi_mks) / np.sqrt(self.od.grad_psi_sqr)
self.od.Lti =self.od.Ti / self.od.d_dpsi(self.od.Ti , self.od.psi_mks) / np.sqrt(self.od.grad_psi_sqr)
if(self.electron_on):
self.od.Lte =self.od.Te / self.od.d_dpsi(self.od.Te , self.od.psi_mks) / np.sqrt(self.od.grad_psi_sqr)
#plasma beta (electron)
# (e n T) / (B^2/2mu0)
try:
self.od.beta_e= self.cnst.echarge *self.od.density*self.od.Te /(self.eq_axis_b**2*0.5/self.cnst.mu0)
except:
print ('electron beta calculation failed. No electron? units.m not loaded?')
#find tmask
d=self.od.step[1]-self.od.step[0]
st=self.od.step[0]/d
ed=self.od.step[-1]/d
st=st.astype(int)
ed=ed.astype(int)
idx=np.arange(st,ed, dtype=int)
self.od.tmask=idx #mem allocation
for i in idx:
tmp=np.argwhere(self.od.step==i*d)
#self.od.tmask[i-st/d]=tmp[-1,-1] #LFS zero based, RHS last element
try:
self.od.tmask[i-st]=tmp[-1,-1] #LFS zero based, RHS last element
except:
print ('failed to find tmaks', tmp)
"""
class for reading data file like xgc.oneddiag.bp
Trying to be general, but used only for xgc.onedidag.bp
"""
class data1(object):
@singledispatchmethod
def __init__(self, filename):
with adios2.FileReader(filename) as f:
vars=f.available_variables()
self.load_data(f, vars, 0)
# e.g. data1(adios2.FileReader, vars, 'xgc.oneddiag.bp')
# to read selected vars from already open file/campaign
@__init__.register(adios2.FileReader)
def _(self, f: adios2.FileReader, vars: dict, filename: str):
vs = {k:v for (k,v) in vars.items() if k.startswith(filename)}
self.load_data(f, vs, len(filename+"/"))
def load_data(self, f: adios2.FileReader, vars: dict, prefix_len: int):
for v in vars:
stc=vars[v].get("AvailableStepsCount")
ct=vars[v].get("Shape")
sgl=vars[v].get("SingleValue")
stc=int(stc)
if ct!='':
ct=int(ct)
data = f.read(v,start=[0], count=[ct], step_selection=[0, stc])
setattr(self,v[prefix_len:],np.reshape(data, [stc, ct]))
elif v!='gsamples' and v!='samples' :
setattr(self,v[prefix_len:],f.read(v,start=[], count=[], step_selection=[0, stc])) #null list for scalar
def d_dpsi(self,var,psi):
"""
radial derivative using psi_mks.
"""
dvdp=var*0; #memory allocation
dvdp[:,1:-1]=(var[:,2:]-var[:,0:-2])/(psi[:,2:]-psi[:,0:-2])
dvdp[:,0]=dvdp[:,1]
dvdp[:,-1]=dvdp[:,-2]
return dvdp
"""
class for head load diagnostic output.
Only psi space data currently?
"""
class datahlp(object):
def __init__(self,filename,irg, read_rz_all=False):
with adios2.FileReader(filename) as f:
#irg is region number 0,1 - outer, inner
#read file and assign it
self.vars=f.available_variables()
for v in self.vars:
stc=self.vars[v].get("AvailableStepsCount")
ct=self.vars[v].get("Shape")
sgl=self.vars[v].get("SingleValue")
stc=int(stc)
if ct!='':
c=[int(i) for i in ct.split(',')] #
if len(c)==1 : # time and step
setattr(self,v,f.read(v,start=[0], count=c, step_start=0, step_count=stc))
elif len(c)==2 : # c[0] is irg
setattr(self,v,np.squeeze(f.read(v,start=[irg,0], count=[1,c[1]], step_start=0, step_count=stc)))
elif ( len(c)==3 & read_rz_all ) : # ct[0] is irg, read only
setattr(self,v,np.squeeze(f.read(v,start=[irg,0,0], count=[1,c[1],c[2]], step_start=0, step_count=stc)))
elif ( len(c)==3 ) : # read_rz_all is false. ct[0] is irg, read only
setattr(self,v,np.squeeze(f.read(v,start=[irg,0,0], count=[1,c[1],c[2]], step_start=stc-1, step_count=1)))
elif v!='zsamples' and v!='rsamples':
setattr(self,v,f.read(v,start=[], count=[], step_start=0, step_count=stc)) #null list for scalar
#keep last time step
self.r=self.r[-1,:]
self.z=self.z[-1,:]
"""
get some parameters for plots of heat diag
"""
def post_heatdiag(self,ds):
#
"""
self.hl[i].rmid=np.interp(self.hl[i].psin,self.bfm.psino,self.bfm.rmido)
self.hl[i].drmid=self.hl[irg].rmid*0 # mem allocation
self.hl[i].drmid=[1:-1]=(self.hl[i].rmid[2:]-self.hl[i].rmid[0:-2])*0.5
self.hl[i].drmid[0]=self.hl[i].drmid[1]
self.hl[i].drmid[-1]=self.hl[i].drmid[-2]
"""
self.drmid=self.rmid*0 # mem allocation
self.drmid[1:-1]=(self.rmid[2:]-self.rmid[0:-2])*0.5
self.drmid[0]=self.drmid[1]
self.drmid[-1]=self.drmid[-2]
dt = np.zeros_like(self.time)
dt[1:] = self.time[1:] - self.time[0:-1]
dt[0] = dt[1]
rst=np.nonzero(dt<0) #index when restat happen
dt[rst]=dt[rst[0]+1]
self.dt = dt
#get separatrix r
self.rs=np.interp([1],self.psin,self.rmid)
self.rmidsepmm=(self.rmid-self.rs)*1E3 # dist from sep in mm
#get heat
self.qe=np.transpose(self.e_perp_energy_psi + self.e_para_energy_psi)/dt/ds
self.qi=np.transpose(self.i_perp_energy_psi + self.i_para_energy_psi)/dt/ds
self.ge=np.transpose(self.e_number_psi)/dt/ds
self.gi=np.transpose(self.i_number_psi)/dt/ds
self.qe = np.transpose(self.qe)
self.qi = np.transpose(self.qi)
self.ge = np.transpose(self.ge)
self.gi = np.transpose(self.gi)
if(self.ion2_on):
self.qi2=np.transpose(self.i2perp_energy_psi + self.i2para_energy_psi)/dt/ds
self.gi2=np.transpose(self.i2number_psi)/dt/ds
self.qi2 = np.transpose(self.qi2)
self.gi2 = np.transpose(self.gi2)
self.qt=self.qe+self.qi
if(self.ion2_on):
self.qt=self.qt+self.qi2
#imx=self.qt.argmax(axis=1)
mx=np.amax(self.qt,axis=1)
self.lq_int=mx*0 #mem allocation
for i in range(mx.shape[0]):
self.lq_int[i]=np.sum(self.qt[i,:]*self.drmid)/mx[i]
"""
getting total heat (radially integrated) to inner/outer divertor.
"""
def total_heat(self,wedge_n):
qe=wedge_n * (np.sum(self.e_perp_energy_psi,axis=1)+np.sum(self.e_para_energy_psi,axis=1))
qi=wedge_n * (np.sum(self.i_perp_energy_psi,axis=1)+np.sum(self.i_para_energy_psi,axis=1))
if(self.ion2_on):
qi2=wedge_n * (np.sum(self.i2perp_energy_psi,axis=1)+np.sum(self.i2para_energy_psi,axis=1))
#find restart point and remove --
# find dt in varying sml_dt after restart
self.qe_tot=qe/self.dt
self.qi_tot=qi/self.dt
if(self.ion2_on):
self.qi2tot=qi2/self.dt
#compare 2D data
#qe2=np.sum(self.e_perp_energy+self.e_para_energy,axis=2)
#qe2=np.sum(qe2,axis=1)
#self.qe_tot2=qe2*wedge_n/dt
#qi2=np.sum(self.i_perp_energy+self.i_para_energy,axis=2)
#qi2=np.sum(qi2,axis=1)
#self.qi_tot2=qi2*wedge_n/dt
"""
Functions for eich fit
q(x) =0.5*q0* exp( (0.5*s/lq)^2 - (x-dsep)/lq ) * erfc (0.5*s/lq - (x-dsep)/s)
"""
def eich(self,xdata,q0,s,lq,dsep):
return 0.5*q0*np.exp((0.5*s/lq)**2-(xdata-dsep)/lq)*erfc(0.5*s/lq-(xdata-dsep)/s)
"""
Eich fitting of one profile data
"""
def eich_fit1(self,ydata,pmask):
q0init=np.max(ydata)
sinit=2 # 2mm
lqinit=1 # 1mm
dsepinit=0.1 # 0.1 mm
p0=np.array([q0init, sinit, lqinit, dsepinit])
if(pmask==None):
popt,pconv = curve_fit(self.eich,self.rmidsepmm,ydata,p0=p0)
else:
popt,pconv = curve_fit(self.eich,self.rmidsepmm[pmask],ydata[pmask],p0=p0)
return popt, pconv
"""
Functions for 3 lambda fit: lp (lambda_q of private flux region), ln (lambda_q of near SOL), lf (lambda_q of far SOL)
q(x) = q0 * exp( (x-dsep)/lp) when x<dsep
=(q0-qf) * exp(-(x-dsep)/ln) + qf * exp(-(x-dsep)/lf) when x>dsep
"""
def lambda_q3(self,x,q0,qf,lp,ln,lf,dsep):
dsepl =0 # not using dsep --> dsepl=dsep to use
rtn = q0 * np.exp( (x-dsepl)/lp) # only x<dsep will be used.
ms=np.nonzero(x>=dsepl)
rtn[ms] = (q0-qf) * np.exp(-(x[ms]-dsepl)/ln) + qf * np.exp(-(x[ms]-dsepl)/lf)
return rtn
"""
3 lambda_q fitting of one profile data
"""
def lambda_q3_fit1(self,ydata,pmask):
q0init=np.max(ydata)
qfinit=0.01*q0init # 1 percent
lpinit=1 # 1mm
lninit=2 # 2mm
lfinit=4 # 4mm
dsepinit=0.01 # 0.01 mm
p0=np.array([q0init, qfinit, lpinit, lninit, lfinit, dsepinit])
if(pmask==None):
popt,pconv = curve_fit(self.lambda_q3,self.rmidsepmm,ydata,p0=p0)
else:
popt,pconv = curve_fit(self.lambda_q3,self.rmidsepmm[pmask],ydata[pmask],p0=p0)
return popt, pconv
"""
Smoothing qt before Eich fit
"""
def qt_smoothing(self,width,order):
from scipy.signal import savgol_filter
for i in range(self.time.size):
tmp = self.qt[i,:]
self.qt[i,:]= savgol_filter(tmp,width,order)
"""
Reset qt from qi and qe
"""
def qt_reset(self):
self.qt=self.qe+self.qi
if(self.ion2_on):
self.qt=self.qt+self.qi2
"""
perform fitting for all time steps.
"""
def eich_fit_all(self,**kwargs):
# need pmask for generalization?
pmask = kwargs.get('pmask', None)
self.lq_eich=np.zeros_like(self.lq_int) #mem allocation
self.S_eich=np.zeros_like(self.lq_eich)
self.dsep_eich=np.zeros_like(self.lq_eich)
for i in range(self.time.size):
try :
popt,pconv = self.eich_fit1(self.qt[i,:],pmask)
except:
popt=[0, 0, 0, 0]
self.lq_eich[i]= popt[2]
self.S_eich[i] = popt[1]
self.dsep_eich[i]= popt[3]
def lambda_q3_fit_all(self,**kwargs):
pmask = kwargs.get('pmask', None)
self.lp_lq3=np.zeros_like(self.lq_int) #mem allocation
self.ln_lq3=np.zeros_like(self.lp_lq3)
self.lf_lq3=np.zeros_like(self.lp_lq3)
self.dsep_eich=np.zeros_like(self.lp_lq3)
for i in range(self.time.size):
try :
popt,pconv = self.lambda_q3_fit1(self.qt[i,:],pmask)
except:
popt=[0, 0, 0, 0, 0, 0]
self.lp_lq3[i]= popt[2]
self.ln_lq3[i] = popt[3]
self.lf_lq3[i] = popt[4]
self.dsep_eich[i]= popt[5]
"""
data for bfieldm
"""
class databfm(object):
def __init__(self,path):
with adios2.FileReader(path+"xgc.bfieldm.bp") as f:
self.vars=f.available_variables()
if('rmajor' in self.vars):
v='rmajor'
else:
v='/bfield/rvec'
#ct=self.vars[v].get("Shape")
#c=int(ct)
self.rmid=f.read(v) #,start=[0],count=[c],step_selection=[0,1])
if('psi_n' in self.vars):
v='psi_n'
else:
v='/bfield/psi_eq_x_psi'
#ct=self.vars[v].get("Shape")
#c=int(ct)
self.psin=f.read(v) #,start=[0],count=[c],step_selection=[0,1])
def load_heatdiag(self, **kwargs):
"""
load xgc.heatdiag.bp and some post process
"""
read_rz_all = kwargs.get('read_rz_all',False) #read heat load in RZ
self.hl=[]
self.hl.append( self.datahlp(self.path+"xgc.heatdiag.bp",0,read_rz_all) ) #actual reading routine
self.hl.append( self.datahlp(self.path+"xgc.heatdiag.bp",1,read_rz_all) )#actual reading routine
for i in [0,1] :
try:
self.hl[i].e_perp_energy_psi
self.hl[i].electron_on=True
except:
self.hl[i].electron_on=False
try:
self.hl[i].i2perp_energy_psi
self.hl[i].ion2_on=True
except:
self.hl[i].ion2_on=False
for i in [0,1] :
try:
self.hl[i].psin=self.hl[i].psi[-1,:]/self.psix #Normalize 0 - 1(Separatrix)
except:
print("psix is not defined - call load_unitsm() to get psix to get psin")
#read bfieldm data if available
self.load_bfieldm()
#dt=self.unit_dic['sml_dt']*self.unit_dic['diag_1d_period']
wedge_n=self.unit_dic['sml_wedge_n']
for i in [0,1]:
dpsin=self.hl[i].psin[1]-self.hl[i].psin[0] #equal dist
#ds = dR* 2 * pi * R / wedge_n
ds=dpsin/self.bfm.dpndrs* 2 * 3.141592 * self.bfm.r0 /wedge_n #R0 at axis is used. should I use Rs?
self.hl[i].rmid=np.interp(self.hl[i].psin,self.bfm.psino,self.bfm.rmido)
self.hl[i].post_heatdiag(ds)
self.hl[i].total_heat(wedge_n)
#data class for each species data of heatdiag2
class datahl2_sp(object):
def __init__(self, prefix, f):
self.number = read_all_steps(f, prefix + '_number')[:,:,1:]
self.para_energy = read_all_steps(f, prefix + '_para_energy')[:,:,1:]
self.perp_energy = read_all_steps(f, prefix + '_perp_energy')[:,:,1:]
self.potential = read_all_steps(f, prefix + '_potential')[:,:,1:]
# data class for heatdiag2
class datahl2(object):
def __init__(self,filename, datahl2_sp):
prefix = ['e', 'i', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7', 'i8', 'i9']
with adios2.FileReader(filename) as f:
vars=f.available_variables()
self.time = read_all_steps(f, 'time')
self.step = read_all_steps(f, 'step')
self.tindex = read_all_steps(f, 'tindex')
self.ds = read_all_steps(f, 'ds')
self.psi = read_all_steps(f, 'psi')
self.r = read_all_steps(f, 'r')
self.z = read_all_steps(f, 'z')
self.strike_angle = read_all_steps(f, 'strike_angle')
# for each species read particle flux and energy flux as an array.
max_nsp = 10 # maximum number of species. Any larger integer should work.
self.sp=[]
for isp in range(max_nsp):
if(prefix[isp]+'_number' in vars):
self.sp.append( datahl2_sp(prefix[isp],f) )
else:
#print('No '+prefix[isp]+' species data in heatdiag2.')
break
if(isp==0):
print('No electron species data in heatdiag2. Nothing loaded.')
self.nsp = len(self.sp)
#set dt
self.dt = np.zeros_like(self.time)
self.dt[1:] = self.time[1:] - self.time[0:-1]
self.dt[0] = self.dt[1] # assume that the first time step is the same as the second one.
self.dt=self.dt[:,np.newaxis]
def get_midplane_conversion(self,psino,rmido, psix, wedge_n):
"""
get midplane conversion of each species
"""
self.rs = np.interp([1],psino,rmido)
self.rmidsepmm = (np.interp(self.psin,psino,rmido) - self.rs) * 1E3
def get_parallel_flux(self):
for isp in range(self.nsp):
# heat flux q and particle flux gammas(g)
self.sp[isp].q = np.squeeze(self.sp[isp].para_energy + self.sp[isp].perp_energy)/self.dt/self.area
self.sp[isp].g = np.squeeze(self.sp[isp].number)/self.dt/self.area
def update_total_flux(self):
"""
update total heat flux and particle flux
"""
self.g_total = 0
self.q_total = 0
for isp in range(self.nsp):
self.g_total += self.sp[isp].g
self.q_total += self.sp[isp].q
def get_divertor(self, outer=True, lower=True):
"""
get array index for inner and outer divertor
Assume the array index is conter-clockwise. --> need to consider the opposite cases
"""
# find minimum psi location
sign_z = 1 if lower else -1
mask = (self.z-self.eq_axis_z) * sign_z < 0
i0 = np.argmin(np.where(mask, self.psin, np.inf))
# find maximum psi location
sign_r = 1 if outer else -1
mask = (self.r-self.eq_axis_r) * sign_r > 0
i1 = np.argmax(np.where(mask, self.psin, -np.inf))
return i0,i1
"""
Functions for eich fit
q(x) =0.5*q0* exp( (0.5*s/lq)^2 - (x-dsep)/lq ) * erfc (0.5*s/lq - (x-dsep)/s)
"""
def eich(self,xdata,q0,s,lq,dsep):
return 0.5*q0*np.exp((0.5*s/lq)**2-(xdata-dsep)/lq)*erfc(0.5*s/lq-(xdata-dsep)/s)
"""
Eich fitting of one profile data
"""
def eich_fit1(self,ydata,pmask=None):
q0init=np.max(ydata)
sinit=2 # 2mm
lqinit=1 # 1mm
dsepinit=0.1 # 0.1 mm
p0=np.array([q0init, sinit, lqinit, dsepinit])
if(pmask is None):
popt,pconv = curve_fit(self.eich,self.rmidsepmm,ydata,p0=p0)
else:
popt,pconv = curve_fit(self.eich,self.rmidsepmm[pmask],ydata[pmask],p0=p0)
return popt, pconv
"""
perform fitting for all time steps.
"""
def eich_fit_all(self,pmask=None):
self.lq_eich=np.zeros_like(self.time) #mem allocation
self.S_eich=np.zeros_like(self.lq_eich)
self.dsep_eich=np.zeros_like(self.lq_eich)
for i in range(self.time.size):
try :
popt,pconv = self.eich_fit1(self.q_total[i,:],pmask=pmask)
except:
popt=[0, 0, 0, 0]
self.lq_eich[i]= popt[2]
self.S_eich[i] = popt[1]
self.dsep_eich[i]= popt[3]
"""
getting total heat (radially integrated) to inner/outer divertor.
"""
def total_heat(self,wedge_n, pmask=None):
if(pmask is None):
pmask=np.ones_like(self.rmidsepmm,dtype=bool)
for isp in range(self.nsp):
self.sp[isp].q_para_sum=np.sum(self.sp[isp].para_energy[:,:,pmask],axis=(1,2))[:,np.newaxis]*wedge_n/self.dt
self.sp[isp].q_perp_sum=np.sum(self.sp[isp].perp_energy[:,:,pmask],axis=(1,2))[:,np.newaxis]*wedge_n/self.dt
self.sp[isp].q_sum=self.sp[isp].q_para_sum+self.sp[isp].q_perp_sum
self.sp[isp].g_sum=np.sum(self.sp[isp].number[:,:,pmask],axis=(1,2))[:,np.newaxis]*wedge_n/self.dt
# load xgc.heatdiag2.bp and some postprocess
def load_heatdiag2(self):
self.hl2 = self.datahl2(self.path+"xgc.heatdiag2.bp", self.datahl2_sp)
#print('loading heatdiag2 done')
# post process
# calculate normalized psi and area at the target
wedge_n = self.unit_dic['sml_wedge_n']
it=-1 # keep the last one
self.hl2.psin=self.hl2.psi[it,:]/self.psix
#area of each segment with angle factor. 2pi * (r1+r2)/2 * ds / wedge_n * cos(angle)
self.hl2.area=np.pi*self.hl2.r[it,:]*self.hl2.ds[it,:]/wedge_n * np.cos(self.hl2.strike_angle[it,:])
self.hl2.area = self.hl2.area[np.newaxis,:]
# use bfieldm if loaded
if(hasattr(self, 'bfm')):
psino=self.bfm.psino
rmido=self.bfm.rmido
else: #get it from xgc.mesh.bp
psino, rmido = self.midplane_var(self.mesh.r)
# get midplane conversion
#plt.plot(psino,rmido)
self.hl2.get_midplane_conversion(psino, rmido, self.psix, wedge_n)
self.hl2.get_parallel_flux()
self.hl2.update_total_flux()
# get divertor index
self.hl2.eq_axis_r = self.eq_axis_r
self.hl2.eq_axis_z = self.eq_axis_z
# report basic analysis of heatdiag2.bp
# Need to specify the divertor region
# ndata is maximum number of data point to be considered.
# fit_mask is the mask for fitting. If None, all data will be used.
def report_heatdiag2(self, is_outer=True, is_lower=True, it=-1, xlim=[-5, 15], lq_ylim=[0, 10], ndata=1000000, fit_mask=None, sp_names=['e', 'i', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7', 'i8', 'i9']):
#select divertor
i0, i1 = self.hl2.get_divertor(outer=is_outer, lower=is_lower)
sign= 1 if (i0<i1) else -1
i1 = i0 + sign*ndata if np.abs(i1-i0)>ndata else i1
md = np.arange(i0,i1,sign)
fig, ax = plt.subplots()
plt.plot(self.hl2.r[0,:],self.hl2.z[0,:])
plt.plot(self.hl2.r[0,md],self.hl2.z[0,md],'r-',linewidth=4,label='Divertor')
plt.legend()
self.show_sep(ax, style=',')
plt.axis('equal')
#plot total heat flux
self.hl2.total_heat(self.sml_wedge_n, pmask=md)
plt.subplots()
for isp in range(4):
plt.plot(self.hl2.time*1E3, self.hl2.sp[isp].q_sum/1E6, '.',label=sp_names[isp])
plt.xlabel('Time (ms)')
plt.ylabel('Total Heat Flux (MW)')
plt.legend()
#heat flux profile
plt.subplots()
for isp in range(4):
plt.plot(self.hl2.rmidsepmm[md], self.hl2.sp[isp].q[it,md]/1E6,label=sp_names[isp])
plt.plot(self.hl2.rmidsepmm[md], self.hl2.q_total[it,md]/1E6,label='Total')
plt.xlim(xlim[0], xlim[1])
plt.ylabel('Parallel heat flux [MW/$m^2$] at the divertor')
plt.xlabel('Midplane distance from separatrix [mm]')
plt.legend()
#fitting one time step
if fit_mask is None:
fit_mask = md
popt,pconv = self.hl2.eich_fit1(self.hl2.q_total[it,:], pmask=fit_mask)
eich = self.hl2.eich(self.hl2.rmidsepmm[md], popt[0], popt[1], popt[2], popt[3])
plt.subplots()
plt.plot(self.hl2.rmidsepmm[md], self.hl2.q_total[it,md],label='XGC')
plt.plot(self.hl2.rmidsepmm[md], eich,label='Eich Fit')
plt.xlim(xlim[0], xlim[1])
plt.title('$\\lambda_q$ = %3.3f mm, S=%3.3f mm, t=%3.3f ms'%(popt[2],popt[1],self.hl2.time[it]*1E3))
plt.ylabel('Parallel heat flux [W/$m^2$] at the divertor')
plt.xlabel('Midplane distance from separatrix [mm]')
plt.legend()
self.hl2.eich_fit_all(pmask=fit_mask)
plt.subplots()
plt.plot(self.hl2.time*1E3, self.hl2.lq_eich, '.', label='$\\lambda_q$')
plt.plot(self.hl2.time*1E3, self.hl2.S_eich, '.', label='S')
plt.ylim(lq_ylim[0], lq_ylim[1])
plt.xlabel('Time [ms]')
plt.ylabel('$\\lambda_q$, S [mm]')
plt.legend()
return md
"""
Load xgc.bfieldm.bp -- midplane bfield info
"""
def load_bfieldm(self):
self.bfm = self.databfm(self.path)
self.bfm.r0=self.unit_dic['eq_axis_r']
plt.plot(self.bfm.rmid)
#get outside midplane only
msk=np.argwhere(self.bfm.rmid>self.bfm.r0)
print(msk)
n0=msk[0]
self.bfm.rmido=self.bfm.rmid[n0:]
self.bfm.psino=self.bfm.psin[n0:]
#find separtrix index and r
msk=np.argwhere(self.bfm.psino>1)
n0=msk[1]
self.bfm.rs = self.bfm.rmido[n0]
#get dpdr (normalized psi) at separatrix
self.bfm.dpndrs = (self.bfm.psino[n0]-self.bfm.psino[n0-1])/(self.bfm.rmido[n0]-self.bfm.rmido[n0-1])
self.bfm.rminor= self.bfm.rmido - self.bfm.r0
"""
Load xgc.bfield.bp -- equilibrium bfield
"""
def load_bfield(self):
with adios2.FileReader(self.path+"xgc.bfield.bp") as f:
try:
self.bfield = f.read('bfield')
except: # try older version of bfield
self.bfield = f.read('node_data[0]/values')
try:
self.jpar_bg = f.read('jpar_bg') # background current
except:
print('No jpar_bg in xgc.bfield.bp')
"""
load the whole .m file and return a dictionary contains all the entries.
"""
def load_m(self,fname):
f = open(fname,'r')
result = {}
for line in f:
words = line.split('=')
key = words[0].strip()
value = words[1].strip(' ;\n')
result[key]= float(value)
f.close()
return result
def plot1d_if(self,obj,**kwargs):
"""
plot 1D (psi) var of initial and final
with ylabel of varstr
Maybe it can be moved to data1 class -- but it might be possible to be used other data type??
"""
var=kwargs.get('var',None)
varstr = kwargs.get('varstr', None)
box = kwargs.get('box', None)
psi = kwargs.get('psi', None)
xlim = kwargs.get('xlim', None)
initial = kwargs.get('initial',True)
time_legend = kwargs.get('time_legend',True)
if(type(psi).__module__ != np.__name__): #None or not numpy data
psi=obj.psi #default psi is obj.psi
if(type(var).__module__ != np.__name__):
if(varstr==None):
print("Either var or varstr should be defined.")
else:
var=getattr(obj,varstr) #default var is from varstr
stc=var.shape[0]
fig, ax=plt.subplots()
it0=0 #0th time index
it1=stc-1 # last time index
tnorm=1E3
if(time_legend):
lbl=["t=%3.3f"%(obj.time[it0]*tnorm), "t=%3.3f"%(obj.time[it1]*tnorm)]
else:
lbl=["Initial","Final"]
if(xlim==None):
if(initial):
ax.plot(psi,var[it0,],label=lbl[0])
ax.plot(psi,var[it1,],label=lbl[1])
else:
msk=(psi >= xlim[0]) & (psi <= xlim[1])
if(initial):
ax.plot(psi[msk],var[it0,msk],label=lbl[0])
ax.plot(psi[msk],var[it1,msk],label=lbl[1])
ax.legend()
ax.set(xlabel='Normalized Pol. Flux')
if(varstr!=None):
ax.set(ylabel=varstr)
#add time stamp of final?
return fig, ax
"""
setup self.mesh
"""
def setup_mesh(self):
if self.campaign:
self.mesh = self.meshdata(self.campaign)
else:
self.mesh = self.meshdata(self.path)
#setup separatrix
self.mesh.isep = np.argmin(abs(self.mesh.psi_surf-self.psix))
isep=self.mesh.isep
length=self.mesh.surf_len[isep]
self.mesh.msep = self.mesh.surf_idx[isep,0:length]-1 # zero based
"""
setup f0mesh
"""
def setup_f0mesh(self):
if self.campaign:
self.f0 = self.f0meshdata(self.campaign)
else:
self.f0 = self.f0meshdata(self.path)
class meshdata(object):
"""
mesh data class for 2D contour plot
"""
@singledispatchmethod
def __init__(self,path):
with adios2.FileReader(path+"xgc.mesh.bp") as fm:
self.load_mesh(fm)
@__init__.register(adios2.FileReader)
def _(self, fm: adios2.FileReader):
self.load_mesh(fm, "xgc.mesh.bp/")
def load_mesh(self, fm: adios2.FileReader, prefix=''):
rz=fm.read(prefix+'rz')
self.cnct=fm.read(prefix+'nd_connect_list')
self.r=rz[:,0]
self.z=rz[:,1]
self.triobj = Triangulation(self.r,self.z,self.cnct)
try:
self.surf_idx=fm.read(prefix+'surf_idx')
except:
print("No surf_idx in xgc.mesh.bp")
else:
self.surf_len=fm.read(prefix+'surf_len')
self.psi_surf=fm.read(prefix+'psi_surf')
self.theta=fm.read(prefix+'theta')
self.m_max_surf=fm.read(prefix+'m_max_surf')
self.wall_nodes = fm.read(prefix+'grid_wall_nodes') -1 #zero based
self.node_vol=fm.read(prefix+'node_vol')
self.node_vol_nearest=fm.read(prefix+'node_vol_nearest')
self.qsafety=fm.read(prefix+'qsafety')
self.psi=fm.read(prefix+'psi')
self.epsilon=fm.read(prefix+'epsilon')
self.rmin=fm.read(prefix+'rmin')
self.rmaj=fm.read(prefix+'rmaj')
self.region=fm.read(prefix+'region')
self.wedge_angle=fm.read(prefix+'wedge_angle')
self.delta_phi=fm.read(prefix+'delta_phi')
self.nnodes = np.size(self.r) # same as n_n
class f0meshdata(object):
"""
mesh data class for 2D contour plot
"""
@singledispatchmethod
def __init__(self,path):
with adios2.FileReader(path+"xgc.f0.mesh.bp") as f:
self.load_f0mesh(f)
@__init__.register(adios2.FileReader)
def _(self, f: adios2.FileReader):
self.load_f0mesh(f, "xgc.f0.mesh.bp/")
def load_f0mesh(self, f: adios2.FileReader, prefix=''):
T_ev=f.read(prefix+'f0_T_ev')
den0=f.read(prefix+'f0_den')
flow=f.read(prefix+'f0_flow')
if(flow.size==0):
flow=np.zeros_like(den0) #zero flow when flow is not written
self.ni0=den0[-1,:]
self.ti0=T_ev[-1,:] # last species. need update for multi ion
self.ui0=flow[-1,:]
if(T_ev.shape[0]>=2):
self.te0=T_ev[0,:]
self.ne0=den0[0,:]
self.ue0=flow[0,:]
if(T_ev.shape[0]>=3):
print('multi species - ni0, ti0, ui0 are last species')
self.dsmu=f.read(prefix+'f0_dsmu')
self.dvp =f.read(prefix+'f0_dvp')
self.smu_max=f.read(prefix+'f0_smu_max')
self.vp_max=f.read(prefix+'f0_vp_max')
"""
flux surface average data structure
Not completed. Use fsa_simple
"""
class fluxavg(object):
def __init__(self,path):
with adios2.FileReader(path + "xgc.fluxavg.bp") as f:
eindex=f.read('eindex')
nelement=f.read('nelement')
self.npsi=f.read('npsi')
value=f.read('value')