def __init__(self, shot, trange=None): self.shot = shot try: LiBD = dd.shotfile('LIN', shot, experiment='AUGD') except: LiBD = dd.shotfile('LIN', shot, experiment='LIBE') ne = LiBD('ne').data time = LiBD('ne').time rhoP = LiBD('ne').area LiBD.close # limit to the part in trange if given if trange: _idx = np.where(((time >= trange[0]) & (time <= trange[1])))[0] ne = ne[_idx, :] time = time[_idx] rhoP = rhoP[_idx, :] # load the equilibrium self.eq = eqtools.AUGDDData(self.shot) self.eq.remapLCFS() # now build your own basis on the same rhoPoloidal # outsize the separatrix self.neraw = ne[:, ::-1] self.rhoraw = rhoP.data[:, ::-1] self.rho = np.linspace(0.9, 1.1, 50) self.ne = np.zeros((time.size, self.rho.size)) self.neNorm = np.zeros((time.size, self.rho.size)) self.time = time # now compute the UnivariateSpline for t in range(time.size): S = UnivariateSpline(self.rhoraw[t, :], self.neraw[t, :], s=0) self.ne[t, :] = S(self.rho) self.neNorm[t, :] = S(self.rho) / S(1)
def __init__(self, shot): self.shot = shot # load the geometry self._geometry() # open the shotfile self.Ioc = dd.shotfile('IOC', self.shot) # read and create the attribute dictionary self._read() # close all the stuff self.Ioc.close() # open and read available gas information self.Uvs = dd.shotfile('UVS', self.shot) self._valves() self._readGas() self.Uvs.close() # now the directory where eventually the neutrals resides try: _path = os.path.abspath( os.path.join( os.path.join(__file__, '../../../..'), 'Experiments/AUG/analysis/data/neutrals/%5i' % self.shot)) data = numpy.load(_path + '/n0_avg.npy') self.n0 = data[:, 0] self.n0Err = data[:, 1] self.n0Time = numpy.loadtxt(_path + '/time_brillanza.txt') except: logging.warning('File not found') pass # now also the equilibrium since it will be useful for # the plot of gauges and valves location self.Eq = equilibrium.equilibrium(device='AUG', time=2, shot=self.shot) self.rg, self.zg = map_equ.get_gc()
def load_all_ECRH(shot, output=False): ECS = dd.shotfile("ECS", int(shot), experiment="AUGD") ECN = dd.shotfile("ECN", int(shot), experiment="AUGD") gy_list = [] for N in range(1, 9): gy_list.append(gyrotron(shot, N, ECS, ECN, False)) # if(gy_list[-1].avail): # print(np.mean(gy_list[-1].PW)) # print(np.mean(gy_list[-1].theta_pol)) # print(np.mean(gy_list[-1].phi_tor)) return gy_list
def test_close(self): sf = dd.shotfile() sf.open('DCN', 30336) self.assertTrue(sf.status) sf.close() self.assertFalse(sf.status) del sf
def test_int_sgr_noTB(self): sf = dd.shotfile() sf.open('CFR', 30407) a = sf.getSignalGroup('CCD_DATA') sf.close() self.assertFalse(sf.status) del sf
def getsig(shotnr, diag, sig, tBegin=0.0, tEnd=10.0, exper='AUGD', edition=0): """Returns an object with the shotfile data Parameters ----------- shotnr: int Number of the discharge diag: str Three letter code for the diagnostic sig: str Name of signal or signal group. tBegin: float Beginning of analysis window tEnd: float End of analysis window exper: str Experiment where to read the data. For private shotfiles it is the username in question. edition: int Version of the shotfile to be opened Returns ----------- An object with the data respective to the signal or signal group. Look for more info in the DD library wrapper. """ shtfl = dd.shotfile(diag, shotnr, experiment=exper, edition=edition) dta = shtfl(sig, tBegin=tBegin, tEnd=tEnd) shtfl.close() return dta
def test_char_sgr(self): sf = dd.shotfile() sf.open('EQI', 28053) a = sf.getSignalGroup('SSQnam') sf.close() self.assertFalse(sf.status) del sf print a
def test_getrelations(self): sf = dd.shotfile() sf.open('CEZ', 30407) rel = sf.GetRelations('Ti') sf.close() self.assertFalse(sf.status) del sf self.assertEqual(rel.txt[0],'time') self.assertEqual(rel.txt[1],'R_time')
def test_getShotfileCreationDate(self): sf = dd.shotfile('MAG', 30774) test_date = datetime.datetime( year=2014, month=5, day=13, hour=14, minute=33, second=41 ) self.assertEqual( (test_date-sf.getShotfileCreationDate()).total_seconds(), 0.0 ) del sf
def get_ric_profile(shotnumber, antenna, time, accuracy=1e-4): """ Script to read the RIC profiles from data base Input: shotnumber: int, Number of the requiring shot antenna: int, Number of requiring antenna. Note: there are 3 antennas in RIC with following numbers: 1 : upper plane, 4 : mid plane, 8 : lower plane. time: float, Time instance of a profile in [s] accuracy: float, time accuracy to find a value in a time base in order to get the index Output: p: dictionary, Dictionary, that contains the following keys: time: float time instance of a profile area: numpy array, float rho poloidal base of a profile data: numpy array, float electron density array persistance: float, number of frequency sweeps that was used to calculate the profile """ # Antenna name antenna = "Ne_Ant" + str(antenna) # Getting data routin shotfile = dd.shotfile('RIC', shotnumber) ne = shotfile(antenna) shotfile.close() # Find time index (indx1, indy) = findindx.findin(ne.time, time, accuracy) # Generating the time, area and data time = ne.time[indx1] area = ne.area[indx1,:] data = ne.data[indx1,:] # Constructing dictionary p = {"time":time,"area":area, "data":data} return p
def test_getParameter(self): sf = dd.shotfile() sf.open('NIS', 30133) tol = 1e-4 spec1 = sf.getParameter('INJ1', 'SPEC') self.assertTrue(numpy.abs(spec1.data[0] - 20.214462) < tol) sf.open('TTH', 30133) law = sf.getParameter('scal_par', 'descript') self.assertEqual(law.data[0].rstrip(), 'ITERL-89P(tot), Wtot/Ptot')
def test_getrelations(self): sf = dd.shotfile() sf.open('CEZ', 30407) rel = sf.getRelations('Ti') sf.close() self.assertFalse(sf.status) del sf self.assertEqual(rel.txt[0], 'time') self.assertEqual(rel.txt[1], 'R_time')
def SIFData2(shot, filename="SIF", data="DataSIF", offset=0, rev=True): shotfile = dd.shotfile(filename,shot) temp = shotfile(data) temp.data = temp.data[:,:1024] temp.data = temp.data[:,::-1] #flip axis for wavelength data temp.wavelength = (scipy.arange(temp.data.shape[1]) + offset + calib)/disp temp.wavelength = temp.wavelength[:1024] return temp #send it out into the wild
def test_char_sgr(self): sf = dd.shotfile() sf.open('EQI', 28053) a = sf.getSignalGroup('SSQnam') sf.close() self.assertFalse(sf.status) del sf mystr = "".join(a[:,0]).strip() self.assertEqual(mystr,'Rsquad')
def test_getParameter(self): sf = dd.shotfile() sf.open('NIS', 30133) tol = 1e-4 spec1 = sf.getParameter('INJ1','SPEC') self.assertTrue(numpy.abs(spec1.data[0] - 20.214462) < tol) sf.open('TTH', 30133) law = sf.getParameter('scal_par','descript') self.assertEqual(law.data[0].rstrip(), 'ITERL-89P(tot), Wtot/Ptot')
def test_char_sgr(self): sf = dd.shotfile() sf.open('EQI', 28053) a = sf.getSignalGroup('SSQnam') sf.close() self.assertFalse(sf.status) del sf mystr = "".join(a[0]).strip() self.assertEqual(mystr, 'Rsquad')
def _loadeq(self): # loading the equilibrium self.Eqm = map_equ.equ_map() status = self.Eqm.Open(self.shot, diag='EQH') self.Eqm._read_scalars() self.Eqm._read_profiles() self.Eqm._read_pfm() # load the wall for aug self.rg, self.zg = map_equ.get_gc() self._psi = self.Eqm.pfm.transpose() self._time_array = self.Eqm.t_eq nr = self._psi.shape[0] nz = self._psi.shape[1] self._r = self.Eqm.Rmesh self._z = self.Eqm.Zmesh self._psi_axis = self.Eqm.psi0 self._psi_bnd = self.Eqm.psix # get the fpol in similar way # as done in eqtools self._jpol = self.Eqm.jpol # these are the lower xpoints self._rxpl = self.Eqm.ssq['Rxpu'] self._zxpl = self.Eqm.ssq['Zxpu'] # read also the upper xpoint self._rxpu = self.Eqm.ssq['Rxpo'] self._zxpu = self.Eqm.ssq['Zxpo'] # R magnetic axis self._axisr = self.Eqm.ssq['Rmag'] # Z magnetic axis self._axisz = self.Eqm.ssq['Zmag'] # eqm does not load the RBphi on axis Mai = dd.shotfile('MAI', self.shot) self.Rcent = 1.65 # we want to interpolate on the same time basis Spl = UnivariateSpline(Mai('BTF').time, Mai('BTF').data, s=0) self._bphi = Spl(self._time_array) * self.Rcent Mai.close() Mag = dd.shotfile('MAG', self.shot) Spl = UnivariateSpline(Mag('Ipa').time, Mag('Ipa').data, s=0) self._cplasma = Spl(self._time_array) # we want to load also the plasma curent # now define the psiN self._psiN = (self._psi-self._psi_axis[:, np.newaxis, np.newaxis])/ \ (self._psi_bnd[:, np.newaxis, np.newaxis]-self._psi_axis[:, np.newaxis, np.newaxis])
def test_getSignalGroupSlice(self): sf = dd.shotfile('MSX', 28053) sig = sf('SG-1', index=6, tEnd=0.1) tol = 1e-6 self.assertTrue(numpy.abs(sig.data[0] + 1.6354893) < tol) self.assertTrue(numpy.abs(sig.data[-1] + 0.0094636055) < tol) sigraw = sf('SG-2', index=2, tEnd=0.1, calibrated=0) self.assertTrue(sigraw.data[0] == 8195) self.assertTrue(sigraw.data[-1] == 8193) del sf
def test_getSignal(self): sf = dd.shotfile() sf.open('DCN', 29708) self.assertEqual(sf.getSignal('H-1').dtype, numpy.int16) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float32).dtype, numpy.float32) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float64).dtype, numpy.float64) self.assertEqual(sf.getSignal('H-1').size, 100000) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float32).size, 100000) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float64).size, 100000) del sf
def test_sig_calib(self): sf = dd.shotfile() sf.open('DCN', 28053) a = sf.getSignal('H-1') b = sf.getSignalCalibrated('H-1') sf.close() self.assertFalse(sf.status) del sf print a print b
def test_getSignalGroupSlice(self): sf = dd.shotfile('MSX', 28053) sig = sf('SG-1', index=6, tEnd=0.1 ) tol = 1e-6 self.assertTrue(numpy.abs(sig.data[0] + 1.6354893) < tol) self.assertTrue(numpy.abs(sig.data[-1] + 0.0094636055) < tol) sigraw = sf('SG-2', index=2, tEnd=0.1, calibrated=0 ) self.assertTrue(sigraw.data[0] == 8195) self.assertTrue(sigraw.data[-1] == 8193) del sf
def test_getShotfileCreationDate(self): sf = dd.shotfile('MAG', 30774) test_date = datetime.datetime(year=2014, month=5, day=13, hour=14, minute=33, second=41) self.assertEqual( (test_date - sf.getShotfileCreationDate()).total_seconds(), 0.0) del sf
def SIFData(shot, filename="SIF", data="DataSIF", offset=0, rev=True): shotfile = dd.shotfile(filename, shot) temp = shotfile(data) temp.data = temp.data[:, :1024] temp.data = temp.data[:, ::-1] #flip axis for wavelength data temp.wavelength = (scipy.arange(temp.data.shape[1]) + offset + calib) / disp temp.wavelength = temp.wavelength[:1024] #temp.wavelength = (scipy.arange(1250) - 34334.5 + offset)/(-85650.6) #give it a wavelength parameter. This is hardcoded and derived from Sertoli's work in /u/csxr/sif/sif.pro return temp #send it out into the wild
def init_read_from_shotfile(self): self.equ = equ_map() self.state = 0 if(not self.equ.Open(self.shot, diag=self.EQ_diag, exp=self.EQ_exp, ed=self.EQ_ed)): print("Failed to open shotfile") self.state = -1 return self.EQ_ed = self.equ.ed if(self.EQ_diag == "EQH"): self.GQH = dd.shotfile("GQH", int(self.shot), experiment=self.EQ_exp, edition=self.EQ_ed) self.FPC = dd.shotfile("FPC", int(self.shot)) elif(self.EQ_diag == "IDE"): self.GQH = dd.shotfile("IDG", int(self.shot), experiment=self.EQ_exp, edition=self.EQ_ed) self.IDF = dd.shotfile("IDF", int(self.shot), experiment=self.EQ_exp, edition=self.EQ_ed) self.FPC = None else: print("EQ diagnostic {0:s} not supported - only EQH and IDE are currently supported!".format(self.EQ_diag)) self.MBI_shot = dd.shotfile('MBI', int(self.shot)) self.equ.read_scalars() self.shotfile_ready = True
def check_Bt_vac_source(shot): try: MBI_shot = dd.shotfile('MBI', int(shot)) except: print("No MBI shotfile. No Bt source!") return False, 1.0 try: MBI_shot.getSignal("BTFABB") return True, 1.005 except: return True, 1.01
def test_tb_calib(self): # a=Integer TB in [ns], b="calibrated" in float,[s] sf = dd.shotfile() sf.open('MSX', 28053) a = sf.getTimeBase('TIME-AD0',dtype=numpy.int64) b = sf.getTimeBase('TIME-AD0',dtype=numpy.float32) sf.close() self.assertFalse(sf.status) del sf print a print b
def test_getSignal(self): sf = dd.shotfile() sf.open('DCN', 29708) self.assertEqual(sf('H-1', tBegin=0, tEnd=0).data[0], numpy.float32(4.1904756e+17)) self.assertEqual(sf.getSignal('H-1').dtype, numpy.int16) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float32).dtype, numpy.float32) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float64).dtype, numpy.float64) self.assertEqual(sf.getSignal('H-1').size, 100000) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float32).size, 100000) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float64).size, 100000) del sf
def test_tb_calib(self): # a=Integer TB in [ns], b="calibrated" in float,[s] sf = dd.shotfile() sf.open('MSX', 28053) # Gives segmentation fault b = sf.getTimeBase('TIME-AD0', dtype=numpy.float32) sf.close() self.assertFalse(sf.status) del sf tol = 1e-5 self.assertTrue(numpy.abs(b[0] + 0.6550321) < tol) self.assertTrue(numpy.abs(b[-1] - 11.34496403) < tol)
def test_tb_calib(self): # a=Integer TB in [ns], b="calibrated" in float,[s] sf = dd.shotfile() sf.open('MSX', 28053) # Gives segmentation fault b = sf.getTimeBase('TIME-AD0',dtype=numpy.float32) sf.close() self.assertFalse(sf.status) del sf tol = 1e-5 self.assertTrue(numpy.abs(b[0] + 0.6550321) < tol) self.assertTrue(numpy.abs(b[-1] -11.34496403) < tol)
def get_shot_title(shotnr, with_shotnr=True): """Returns the shot title as it is stored in the JOU diagnostic""" jou = dd.shotfile('JOU', shotnr) umb = jou.getParameter('REMARKS', 'REMARKS') jou.close() ##Remove first characters umb2 = umb.data[4:] umb3 = umb2.tostring() if with_shotnr: title = '\#' + str(shotnr) + ' ' + umb3.splitlines()[0] else: title = umb3.splitlines()[0] return str(title)
def test_getSignal(self): sf = dd.shotfile() sf.open('DCN', 29708) self.assertEqual( sf('H-1', tBegin=0, tEnd=0).data[0], numpy.float32(4.1904756e+17)) self.assertEqual(sf.getSignal('H-1').dtype, numpy.int16) self.assertEqual( sf.getSignal('H-1', dtype=numpy.float32).dtype, numpy.float32) self.assertEqual( sf.getSignal('H-1', dtype=numpy.float64).dtype, numpy.float64) self.assertEqual(sf.getSignal('H-1').size, 100000) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float32).size, 100000) self.assertEqual(sf.getSignal('H-1', dtype=numpy.float64).size, 100000) del sf
def test_sig_calib(self): sf = dd.shotfile() sf.open('DCN', 28053) a = sf.getSignal('H-1') b = sf.getSignalCalibrated('H-1') sf.close() self.assertFalse(sf.status) del sf tol = 1e-5 self.assertTrue(numpy.abs(a[0] + 1) < tol) self.assertTrue(numpy.abs(a[-1] -11) < tol) tol *= 1e17 self.assertTrue(numpy.abs(b[0][0] - 1.39682516e+17) < tol) self.assertTrue(numpy.abs(b[0][-1] + 1.53650771e+18) < tol)
def test_sig_calib(self): sf = dd.shotfile() sf.open('DCN', 28053) a = sf.getSignal('H-1') b = sf.getSignalCalibrated('H-1') sf.close() self.assertFalse(sf.status) del sf tol = 1e-5 self.assertTrue(numpy.abs(a[0] + 1) < tol) self.assertTrue(numpy.abs(a[-1] - 11) < tol) tol *= 1e17 self.assertTrue(numpy.abs(b[0][0] - 1.39682516e+17) < tol) self.assertTrue(numpy.abs(b[0][-1] + 1.53650771e+18) < tol)
def test_getSignalCalibrated(self): sf = dd.shotfile() sf.open('DCN', 29708) data, unit = sf.getSignalCalibrated('H-1') self.assertEqual(data.dtype, numpy.float32) self.assertEqual(data.size, 100000) self.assertEqual(unit, '1/m^3') data, unit = sf.getSignalCalibrated('H-1', dtype=numpy.float32) self.assertEqual(data.dtype, numpy.float32) self.assertEqual(data.size, 100000) self.assertEqual(unit, '1/m^3') data, unit = sf.getSignalCalibrated('H-1', dtype=numpy.float64) self.assertEqual(data.dtype, numpy.float64) self.assertEqual(data.size, 100000) self.assertEqual(unit, '1/m^3') del sf
def SIFData(shot, filename="SIF", data="DataSIF", offset=0, rev=True): """This yanks data for the analysis (for fitting gaussians)""" shotfile = dd.shotfile(filename,shot) temp = shotfile(data) temp.data = temp.data[:,:1024] temp.data = temp.data[:,::-1] #flip axis for wavelength data temp.wavelength = (scipy.arange(temp.data.shape[1]) + offset + calib)/disp temp.wavelength = temp.wavelength[:1024] if len(temp.data)*1.5 < len(temp.time): #this corrects an error where the timebase of the SIF data is incorrect (x2 too many points) temp.time = temp.time[::2] #timebase issue correction #if len(temp.data) != len(temp.time): # raise dd.PyddError #timebase problem #temp.wavelength = (scipy.arange(1250) - 34334.5 + offset)/(-85650.6) #give it a wavelength parameter. This is hardcoded and derived from Sertoli's work in /u/csxr/sif/sif.pro return temp #send it out into the wild
def loadPosition(self, trange=None): """ Load the position and compute for each of the pin the corresponding rho values taking into account the (R, Z) position Parameters ---------- trange 2d array to eventually load in a given time window Returns ------- None Attributes ---------- Add to the self.RZgrid dictionary the time basis of the rhopoloidal and the corresponding values of rhop """ Lsm = dd.shotfile('LSM', self.shot) sPos = np.abs(Lsm('S-posi').data - Lsm('S-posi').data.min()) tPos = Lsm('S-posi').time # convert into absolute value according to transformation R = ((2188. - (self.Xprobe - self.Xlim) - sPos + 100.)/1.e3) # smooth it R = self.smooth(R, window_len=100) # check if trange exist or not if not trange: # convert in Rhopoloidal self.rhoProbe = np.zeros(R.size) for r, t, i in zip(R, tPos, list(range(R.size))): self.rhoProbe[i] = self.Eq.rz2psinorm(r, self.Zmem * 1e-3, t, sqrt=True) self.tPos = tPos else: _idx = np.where(((tPos >= trange[0]) & (tPos <= trange[1])))[0] _R = R[_idx] _t = tPos[_idx] self.rhoProbe = np.zeros(_R.size) for r, t, i in zip(_R, _t, list(range(_R.size))): self.rhoProbe[i] = self.Eq.rz2psinorm(r, self.Zmem * 1e-3, t, sqrt=True) self.tPos = _t
def test_getInfo(self): sf = dd.shotfile() sf.open('CEC', 30133) info = sf.getInfo('Trad-A') sf.close() self.assertFalse(sf.status) del sf self.assertEqual(dd.__obj__[info.objtyp], 'Sig_Group') self.assertEqual(info.level, 1) self.assertEqual(info.status, 0) self.assertEqual(info.error, 0) self.assertEqual(info.bytlen, 62914560) self.assertEqual(dd.__dataformat__[info.fmt], numpy.float32) self.assertEqual(info.units, 'eV') self.assertEqual(info.ind[0], 114685) self.assertEqual(info.ind[1], 60) self.assertEqual(info.ind[2], 1) self.assertEqual(info.ind[3], 1) self.assertEqual(info.rels, ['time-A', 'parms-A'])
def test_GetInfo(self): sf = dd.shotfile() sf.open('CEC', 30133) info = sf.GetInfo('Trad-A') sf.close() self.assertFalse(sf.status) del sf self.assertEqual(dd.__obj__[info.objtyp], 'Sig_Group') self.assertEqual(info.level, 1) self.assertEqual(info.status, 0) self.assertEqual(info.error, 0) self.assertEqual(info.bytlen,62914560) self.assertEqual(dd.__dataformat__[info.fmt], numpy.float32) self.assertEqual(info.units, 'eV') self.assertEqual(info.ind[0], 114685) self.assertEqual(info.ind[1], 60) self.assertEqual(info.ind[2], 1) self.assertEqual(info.ind[3], 1) self.assertEqual(info.rels,['time-A', 'parms-A'])
def test_init(self): sf = dd.shotfile('DCN', 30336, 'AUGD', 0) self.assertTrue(sf.status) del sf
def ddelmsync(shotnr, diag, signal, experiment='AUGD', edition=0, tBegin=0.0, tEnd=10.0, preft=0.001, suft=0.004, felm_min=0, felm_max=1000, elm_exper="AUGD", elm_edition=0): """Gets a selected 1-D signal and syncs it to the ELMs in the desired time interval Parameters ------------ shotnr: int Number of the shot to analyse. diag: str Name of the shotfile containing the data. signal: str Name of the signal in 'diag' to analyse. experiment: str Naame of the experiment (username) containing the shotfile. edition: int Edition of the shotfile. tBegin: float Initial time of analysis. tEnd: float Final time for analysis. preft: float 'Prefix time' to consider before ELM onset. suft: float 'Suffix time' to consider after ELM ends. felm_min: float Minimum ELM frequency to include in analysis. Default value 0Hz considers all ELMs. felm_max : float Maximum ELM frequency to include in analysis. Default value 1000Hz considers all ELMs. elm_exper: str User of the experiment. Default is public shotfile 'AUGD'. elm_edition: int Edition of the ELM shotfile. Default is latest edition, 0. Returns ------------ synctime: np.array(float) Array of times resetted to the closest ELM. syncsig: np.array(float) 1D or 2D array of data ordered according to the sychronized times. """ ################################# ##Flag to check if data came from a signal group sgrp = False ###### Gets ELM data ############ ELM = dd.shotfile("ELM", shotnr, experiment=elm_exper, edition=elm_edition) elmd = ELM("t_endELM", tBegin=tBegin, tEnd=tEnd) freq_ELM = ELM("f_ELM", tBegin=tBegin, tEnd=tEnd) t_endELM = elmd.data t_begELM = elmd.time ELM.close() ################################ ################################ ###### Get the signal in cause signal = getsig(shotnr, diag, signal, tBegin=tBegin, tEnd=tEnd, edition=edition) #################### Syncs the timebase to the ELM timebase ########################### ###### Signal group ########################### syncsig = []#np.zeros_like(signal.data) synctime = []#np.zeros_like(signal.time) for elm in range(t_begELM.size): #Only accept ELMs at the chosen frequency window if (freq_ELM.data[elm]>=felm_min)&(freq_ELM.data[elm]<=felm_max): t1, t2 =t_begELM[elm]-preft, t_endELM[elm]+suft #Re-adjust ELM times so no overlap between consecutive ELMs occurs if (elm >=1 ) : tendprev = t_endELM[elm-1] t1 = np.max([t1,tendprev]) if (elm<t_begELM.size-1): tstartnext = t_begELM[elm+1] t2 = np.min([t2,tstartnext]) elmind = np.where((signal.time >= t1) & (signal.time <=t2)) synctime.append(signal.time[elmind]-t_begELM[elm]) #Distinguish between 1D (signal) and 2D array (Signal group) if len(signal.data.shape)==1: syncsig.append(signal.data[elmind]) elif len(signal.data.shape)==2: syncsig.append(signal.data[elmind,:]) else: raise Exception('Array format not supported!') else:#Space left open for possible analysis a=0 #Finally, return is again dependent on array dimensions if len(signal.data.shape)==1: synctime_return = np.concatenate(synctime) syncsig_return = np.concatenate(syncsig) if len(signal.data.shape)==2: synctime_return = np.concatenate(synctime) syncsig_return = np.concatenate(syncsig, axis=1)[0,:,:] return synctime_return, syncsig_return
def _maskElm(self, usedda=False, threshold=3000, trange=[2, 3], check=False): """ Provide an appropriate mask where we identify both the ELM and inter-ELM regime Parameters ---------- usedda : :obj: `bool` Boolean, if True use the default ELM diagnostic ELM in the shotfile threshold : :obj: `float` If we choose to detect as threshold in the SOL current then this is the threshold chosen Returns ------- None Attributes ---------- Define the class hidden attributes self._elm self._interelm which are the indexes of the ELM and inter ELM intervals """ if usedda: logging.warning("Using ELM dda") ELM = dd.shotfile("ELM", self.shot, experiment='AUGD') elmd = ELM("t_endELM", tBegin=trange[0], tEnd=trange[1]) # limit to the ELM included in the trange _idx = np.where((elmd.time >= trange[0]) & (elmd.time <= trange[1]))[0] self.tBegElm = eldm.time[_idx] self.tEndElm = elmd.data[_idx] ELM.close() else: logging.warning("Using IpolSolI") Mac = dd.shotfile("MAC", self.shot, experiment='AUGD') Ipol = Mac('Ipolsoli') _idxT = np.where( ((Ipol.time >= trange[0]) & (Ipol.time <= trange[1])))[0] # now create an appropriate savgolfile IpolS = savgol_filter(Ipol.data[_idxT], 301, 3) IpolT = Ipol.time[_idxT] IpolO = Ipol.data[_idxT] # we generate an UnivariateSpline object _dummyTime = self.time[np.where((self.time >= trange[0]) & (self.time <= trange[1]))[0]] IpolSp = UnivariateSpline(IpolT, IpolS, s=0)(_dummyTime) # on these we choose a threshold # which can be set as also set as keyword self._Elm = np.where(IpolSp > threshold) # generate a fake interval ElmMask = np.zeros(IpolSp.size, dtype='bool') ElmMask[self._Elm] = True self._interElm = np.where(ElmMask == False)[0] if check: fig, ax = mpl.pylab.subplots(nrows=1, ncols=1, figsize=(6, 4)) fig.subplots_adjust(bottom=0.15, left=0.15) ax.plot(IpolT, IpolO, color='gray', alpha=0.5) ax.plot(IpolT, IpolS, 'k', lw=1.2, alpha=0.5) ax.plot(_dummyTime[self._interElm], IpolSp[self._interElm], 'g', lw=1.5) ax.set_xlabel(r't[s]') ax.set_ylabel(r'Ipol SOL I') ax.axhline(threshold, ls='--', color='#d62728')
def findTime(shot): shotfile = dd.shotfile('EQH',shot) time = shotfile('time').data del(shotfile) return [time[0],time[-1]]
def GIWData(shot, filename="GIW", data="c_W"): shotfile = dd.shotfile(filename,shot) return shotfile(data)
def starkelmsync(shotnr, tBegin=0.0, tEnd=10.0, item='nev', side='in', preft=0.004, suft=0.008, felm_min=0.0, felm_max=1000.0, elm_exper='AUGD', elm_edition=0, file=None): """Synchronizes DIVERTOR data to ELMs Data must be saved in a file that is output from DIVERTOR. Parameters ------------ shotnr: int Number of the shot to analyse. tBegin: float Initial time of analysis. tEnd: float Final time of analysis. item: str side: str preft: float 'Prefix time' to consider before ELM onset. suft: float 'Suffix time' to consider after ELM ends. felm_min: float Minimum ELM frequency to include in analysis. Default value 0Hz considers all ELMs. felm_max: float Maximum ELM frequency to include in analysis. Default value 1000Hz considers all ELMs. elm_exper: str User of the experiment. Default is public shotfile 'AUGD'. elm_edition: int Edition of the ELM shotfile. Default is latest edition, 0. file: str DIVERTOR data file. Default of 'None' will try to read a file stored in '$HOME/Divertor/#shotnr/'. Returns ------------ synctime: np.array(float) deltas: np.array(float) syncmat: np.array(float, float) Example: import matplotlib.pyplot as plt t, s, m = starkelmsync(30554, ti=2.0, tf=3.0, item="jsat", side="in", suft=0.004, preft=0.002) plt.pcolormesh(t, s, m, shading='goraud') plt.show() """ #Gets the filename where DIVERTOR data is stored if file is None: divertor_fname = getDivFname(shotnr, item, side) else: divertor_fname = file try: sdata = readDivData(divertor_fname) if (len(sdata.deltas) <= 2 | len(sdata.time) <= 2): print "Returning dummy data from starkelmsync!" return sdata.time, sdata.deltas, sdata.data except: print "No such file!" raise analysis_mask = np.where((sdata.time >= tBegin) & (sdata.time <= tEnd)) time_stark = sdata.time[analysis_mask] dummy = sdata.data[:, analysis_mask] ##MAS PORQUE CRLLLL!!!!!!??????? mat = dummy[:, 0, :] ######## READ THE ELMS ######## ELM = dd.shotfile("ELM", shotnr, experiment=elm_exper, edition=elm_edition) elmd = ELM("t_endELM", tBegin=tBegin, tEnd=tEnd) f_ELM = ELM('f_ELM') t_endELM = elmd.data t_begELM = elmd.time ELM.close() ############################### synctime = [] dslen = len(sdata.deltas) syncmat = [[]] * dslen matT = mat.T for elm in range(t_begELM.size): #Only accept ELMs at the chosen frequency window if ((f_ELM.data[elm] >= felm_min) & (f_ELM.data[elm] <= felm_max)): t1, t2 = t_begELM[elm] - preft, t_endELM[elm] + suft #Re-adjust ELM times so no overlap between consecutive ELMs occurs if (elm >= 1): tendprev = t_endELM[elm - 1] t1 = np.max([t1, tendprev]) if (elm < t_begELM.size - 1): tstartnext = t_begELM[elm + 1] t2 = np.min([t2, tstartnext]) elmind = np.where((time_stark >= t_begELM[elm] - preft) & (time_stark <= t_endELM[elm] + suft)) synctime.append(time_stark[elmind] - t_begELM[elm]) for s in range(dslen): syncmat[s] = np.append(syncmat[s], [matT[elmind, s][0]]) #dummy = np.append(mat[:, elmind], axis=0) #syncmat.append(dummy[:,0,:]) synctime = np.concatenate(synctime) syncmat = np.array(syncmat) indt = np.argsort(synctime) return synctime[indt], sdata.deltas, syncmat[:, indt]