Exemplo n.º 1
0
    def setCleanedIVDFS(self, fwin = 1500):
        '''This routine takes the self.di_ivdf and self.dye_ivdf files and
        generates a cleaned (fft - zerod) IVDF in self.di_ivdf_clean and
        self.dye_ivdf_clean.
        
        Optional Inputs:
        fwin = 1500     :   Wavenumber outside which to set the spec to 0.

        '''
        #First the dye.
        d = np.loadtxt(self.dye_ivdf, skiprows=1)
        R = np.sqrt(d[:,2]**2 + d[:,3]**2)
        wl = d[:,0]
        (wlc, rc) = clean.clean(wl, R)
        [f, g] = spec.spec(rc, wlc[1] - wlc[0])
        g[np.where(np.abs(f) > fwin)] = 0
        [t, rcf] = spec.ispec(g, f[1] - f[0])
        self.dye_ivdf_c = (wlc, rcf)
        #Then the diode.
        if self.di_ivdf == '':
            #The Diode file is missing.
            return
        else:
            d = np.loadtxt(self.dye_ivdf, skiprows=1)
            R = np.sqrt(d[:,2]**2 + d[:,3]**2)
            wl = d[:,0]
            (wlc, rc) = clean.clean(wl, R)
            [f, g] = spec.spec(rc, wlc[1] - wlc[0])
            g[np.where(np.abs(f) > fwin)] = 0
            [t, rcf] = spec.ispec(g, f[1] - f[0])
            self.diode_ivdf_c = (wlc, rcf)
        return
Exemplo n.º 2
0
	def __call__(self,u,v,w,bx,by,bz):
		q = 4

		d = (self.sim.zmx, self.sim.ymx, self.sim.xmx)
		vspec = spec(u,v,w,dims=d)
		bspec = spec(bx,by,bz,dims=d)

		plt.subplot(221)
		plt.plot(vspec)
		plt.semilogy()
		plt.title('v-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])

		plt.subplot(222)
		plt.plot(vspec)
		plt.loglog()
		plt.title('v-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])

		plt.subplot(223)
		plt.plot(bspec)
		plt.semilogy()
		plt.title('b-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])

		plt.subplot(224)
		plt.plot(bspec)
		plt.loglog()
		plt.title('b-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])
Exemplo n.º 3
0
def ZeemanFitFunc_VaryV(RSi, RSf, Ei, Ef, P, V, tls, wavelengths, s):
    """
        Function which takes a Zeeman spectrum, deconvolves it with the natural
        Zeeman linewidth according to B and P, and returns the deconvolved
        spectrum. This is to be used with an optimization problem.

        See also: ZeemanFit_VaryB, which postulates that there is a magnetic
        field other than 1kG in the plasma.
        
        INPUTS:
        RSi     -   Russel Saunders term for the initial energy level.
        RSf     -   Russel Saunders term for the final energy level.
        Ei      -   Energy for the initial energy level.
        Ef      -   Energy for the final energy level.
        P       -   Polarization of Zeeman lines to fit (-1, 0, 1).
        V       -   Streaming flow. cm/s defined to be positive towards the
                    observer (laser).
        tls     -   Tuple of (ti, tf) for the mean lifetimes of the starting
                    and ending state. Just one entry in the tuple is fine.
        wavelengths -   Wvelengths of data.
        spec    -   Measured LIF spectrum.
        OUTPUTS
        x       -   Cleaned wavelengths.
        yn      -   Cleaned and normalized spectrum.
        lns_clnn-   Cleaned and normalized natural lines.
        ivdf    -   Resulting deconvolved spectrum.
    """
    #Try deconvolving using the usual process.
    #Normalize:
    (x, y) = clean.clean(wavelengths, s)
    yn = y / np.sqrt(np.dot(y, y))
    B = 1e3
    lns_cln = Zeeman_Lines(RSi, RSf, Ei, Ef, x, P, B, tls, velocity=V)
    lns_clnn = lns_cln / np.sqrt(np.dot(lns_cln, lns_cln))
    [f, gl] = spec.spec(lns_clnn, x[1] - x[0])
    [f, gs] = spec.spec(yn, x[1] - x[0])
    fi = np.where(np.abs(f) > freq_end)
    fni = np.where((np.abs(f) > fnoise_start) - (np.abs(f) > fnoise_end))
    fwi = np.where(np.abs(f) <= freq_end)
    gdc = np.abs(gs) / np.abs(gl)
    gdc[fi] = 0
    [trash, ivdf] = spec.ispec(gdc, f[1] - f[0])
    ivdf = sp.fftpack.fftshift(ivdf)
    #Get the errors too.
    err = np.mean(np.abs(gs[fi]))
    sig_real = np.sqrt(err**2 / np.size(fwi) * np.sum(1 / gl[fwi]**2) *
        np.size(fwi) / np.size(f))
    errs = np.abs(sig_real)
    return (x, yn, lns_clnn, ivdf, errs)
Exemplo n.º 4
0
def getCleanedDiodeIVDFS(fwin = 1500):
    '''
        Acuires and returns cleaned Dye IVDFS. Default f window size of 1500
        nm^-1.
        INPUTS:
        fwin=1500    :  Chooses the range outside of which to zero the
        spectrum.   
        OUTPUTS:
        diode_cleanedivdfs        :   Tuple of (wavelength, data).
    '''
    rels = getDyeIVDFRels()
    di_civdfs = []
    di_days = []
    fl = getDyeIVDFFiles()
    for x in rels:
        if 'Apr8' in fl[x]:
            di_civdfs.append(np.array([[],[]]))
            continue
        d = np.loadtxt(fl[x].replace('DYE','DIODE'), skiprows=1)
        R = np.sqrt(d[:,2]**2 + d[:,3]**2)
        wl = d[:,0]
        (wlc, rc) = clean.clean(wl, R)
        #Get rid of high freq noise too
        [f, g] = spec.spec(rc, wlc[1] - wlc[0])
        fi = np.where(np.abs(f) > 1500)
        g[fi] = 0
        [t, rcf] = spec.ispec(g, f[1] - f[0])
        di_civdfs.append((wlc, rcf))
    return di_civdfs
Exemplo n.º 5
0
def getCleanedDyeIVDFS(fwin = 1500):
    '''
        Acuires and returns cleaned Dye IVDFS. Default f window size of 1500
        nm^-1.
        INPUTS:
        fwin=1500    :  Chooses the range outside of which to zero the
        spectrum.   
        OUTPUTS:
        (dye_dyes, dye_cleanedivdfs)
        dye_days    :   Corresponding data file for the output data.
        dye_cleanedivdfs        :   Tuple of (wavelength, data).
    '''
    rels = getDyeIVDFRels()
    dye_cleanedivdfs = []
    dye_days = []
    fl = getDyeIVDFFiles()
    for x in rels:
        dye_days.append(fl[x])
        d = np.loadtxt(fl[x], skiprows=1)
        R = np.sqrt(d[:,2]**2 + d[:,3]**2)
        wl = d[:,0]
        (wlc, rc) = clean.clean(wl, R)
        [f, g] = spec.spec(rc, wlc[1]- wlc[0])
        fi = np.where(np.abs(f) > fwin)
        g[fi] = 0
        [t, rcf] = spec.ispec(g, f[1]- f[0])
        dye_cleanedivdfs.append((wlc, rcf))
    return (dye_days, dye_cleanedivdfs)
Exemplo n.º 6
0
	def spec(self,iteration, magnetic=False, cutDim=None, slices=0):
    """Gives you a power spectrum of an iteration of your data.  magnetic 
       controls if you do it for the magnetic variables or the velocity
       variables.  If neither cutDim nor slices are specified, then it will
       give you the power spectrum for the full box averaged over spheres. 
       Otherwise, cutDim specifies which dimension you want horizontal slices
       of and slices specifies which slices you want, and for each slice you 
       will be returned a spectrum for that slice averaged over circles.
    """
		if magnetic == True:
			temp = self.get_b(iteration)
		else:
			temp = self.get_v(iteration)

		a=temp[0]
		b=temp[1]
		c=temp[2]

		ret  = []
		if cutDim == 0:
			a = a[slices,:,:]
			b = b[slices,:,:]
			c = c[slices,:,:]
			dims = (self.ymx,self.xmx)
			for i in range(len(slices)):
				ret.append(spec(a[i,:,:],b[i,:,:],c[i,:,:],dims=dims))
		elif cutDim == 1:
			a = a[:,slices,:]
			b = b[:,slices,:]
			c = c[:,slices,:]
			dims = (self.zmx,self.xmx)
			for i in range(len(slices)):
				ret.append(spec(a[:,i,:],b[:,i,:],c[:,i,:],dims=dims))
		elif cutDim == 2:
			a = a[:,:,slices]
			b = b[:,:,slices]
			c = c[:,:,slices]
			dims = (self.zmx,self.ymx)
			for i in range(len(slices)):
				ret.append(spec(a[:,:,i],b[:,:,i],c[:,:,i],dims=dims))
		elif cutDim == None:
			dims = (self.zmx,self.ymx,self.xmx)
			return spec(a,b,c,dims)
		else:
			print "nonsensical cutDim! ",cutDim

		return ret
Exemplo n.º 7
0
	def __call__(self,u,v,w,bx,by,bz):
		q = 4

		u = u[:,0,:]
		v = v[:,0,:]
		w = w[:,0,:]
		bx = bx[:,0,:]
		by = by[:,0,:]
		bz = bz[:,0,:]

		d = (self.sim.xmz, self.sim.xmx)
		vspec = spec(u,v,w,dims=d)
		bspec = spec(bx,by,bz,dims=d)

		plt.subplot(221)
		plt.plot(vspec)
		plt.semilogy()
		plt.title('v-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])

		plt.subplot(222)
		plt.plot(vspec)
		plt.loglog()
		plt.title('v-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])

		plt.subplot(223)
		plt.plot(bspec)
		plt.semilogy()
		plt.title('b-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])

		plt.subplot(224)
		plt.plot(bspec)
		plt.loglog()
		plt.title('b-spec')
		plt.axis("tight")
		plt.ylim([1e-12,1e-2])
Exemplo n.º 8
0
def deconvolve(wl, R, linevals, amps, B, P, pad):
    '''
    Quick return which deconvolves an f0 with the laser information given by linevals.
    :param wl:
    :param R:
    :return:
    '''
    [gsp, wlp, zp] = ZeemanSpec_Padded(wl, R, P, B, *linevals, amps =amps, padx=pad)
    [f, g] = spec.spec(R, 1)
    gdc = g / gsp
    [t, Rdc] = spec.ispec(gdc, 1)
    return (fp.fftshift(Rdc), (gsp, wlp, zp))
Exemplo n.º 9
0
	def spec(self,iteration, magnetic=False, cutDim=None, slices=0):
		if magnetic == True:
			temp = self.get_b(iteration)
		else:
			temp = self.get_v(iteration)

		a=temp[0]
		b=temp[1]
		c=temp[2]

		ret  = []
		if cutDim == 0:
			a = a[slices,:,:]
			b = b[slices,:,:]
			c = c[slices,:,:]
			dims = (self.ymx,self.xmx)
			for i in range(len(slices)):
				ret.append(spec(a[i,:,:],b[i,:,:],c[i,:,:],dims=dims))
		elif cutDim == 1:
			a = a[:,slices,:]
			b = b[:,slices,:]
			c = c[:,slices,:]
			dims = (self.zmx,self.xmx)
			for i in range(len(slices)):
				ret.append(spec(a[:,i,:],b[:,i,:],c[:,i,:],dims=dims))
		elif cutDim == 2:
			a = a[:,:,slices]
			b = b[:,:,slices]
			c = c[:,:,slices]
			dims = (self.zmx,self.ymx)
			for i in range(len(slices)):
				ret.append(spec(a[:,:,i],b[:,:,i],c[:,:,i],dims=dims))
		elif cutDim == None:
			dims = (self.zmx,self.ymx,self.xmx)
			return spec(a,b,c,dims)
		else:
			print "nonsensical cutDim! ",cutDim

		return ret
Exemplo n.º 10
0
    def xcSpec(self, tw = 0.01):
        '''
            Takes the spectrum of the xcorr array - along the long (time) axis.
            Uses the untrimmed array for the actual spectrum.

            INPUTS:
            tw     :       (float) Width of Gaussian window to use (if any).
        '''
        win = np.exp(-(self.t / tw)**2/2)
        #We have to make a grid of windowing functions.
        [xxwin, yy] = np.meshgrid(win, range(self.xcorrs.shape[0]))
        #xxwin is now a 2d array which has each row corresponding to a
        #windowing function, ready to be pointwise multiplied by xcorrs.
        [self.f, self.g] = spec.spec(xxwin * self.xcorrs, self.t[1] -
                self.t[0], axis=1)
        return
Exemplo n.º 11
0
def ZeemanSpec_Padded(wld, s, P, B, RSi, RSf, Ei, Ef, ts, roll=0, amps = 1, padx=10):
    """
        Creates a padded Zeeman array with padx * n + 1 the number of elements of
        the original wavelength array, finds a spectrum, then returns the
        spectrum with the original number of points. This is so that
        undersampling the Zeeman spectrum is not a problem in deconvolution.
        INPUTS:
        wld     -   Wavelengths. The first and last values are used to generate
            the padded array, while the length is used to cut down the spectrum.
        s       -   Spectrum. Used to scale the zeeman profile.
        P       -   tuple of desired polarizations.
        B       -   magnetic field.
        RSi     -   RS term for upper level of transition.
        RSf     -   RS term for lower level of transition.
        Ei      -   Energy for upper level of transition.
        Ef      -   Energy for lower level of transition.
        ts      -   Tuple of mean lifetimes for upper and lower states. A one
                    element tuple is fine.
        roll    -   (Optional) # to roll the padded wavelength array.
        amp_scale   -   (float, tuple, Optional) Tuple of relative scalings for the groups of
                         amplitudes. Each element corresponds to the tuple elements of P.
        padx = 10   -   Scaling factor for padded array wavelength array to make.
        OUTPUTS:
        (ZPSC, wldp, ZP)
        ZPSC    -   Zeeman spectrum reduced back to wld size.
        wldp    -   Padded wavelength array.
        ZP      -   Padded Zeeman profile.
    """
    wldp = np.linspace(wld[0], wld[-1], padx * (np.size(wld) - 1) + np.size(wld))
    lns = wldp * 0 
    even = 1 - np.size(wld) % 2
    if amps == 1:
        for p in P:
            lns += Zeeman_Lines(RSi, RSf, Ei, Ef, wldp, p, B, ts)
    else:
        for x in zip(P, amps):
            lns += x[1] * Zeeman_Lines(RSi, RSf, Ei, Ef, wldp, x[0], B, ts)
    lns = lns / np.max(lns) * np.max(np.abs(s))
    [f, gl] = spec.spec(lns, wldp[1] - wldp[0])
    gl = gl * np.sqrt(float(np.size(gl)) / float(np.size(wld)))
    #Grab the middle n elements. Adjust the indices for whether the size of 
    #wld is odd or even.
    #NB: np.size(x) / 2 is truncated if x is odd.
    glc = gl[np.floor((np.size(gl) / 2)) - np.floor((np.size(wld)) / 2) :
            np.floor((np.size(gl) / 2) - (1 - np.size(wld) % 2)) + np.floor((np.size(wld)) / 2) + 1]
    return (glc, wldp, lns)
Exemplo n.º 12
0
	def spec(self,iteration, mag=False,heights=0):
		if type(heights) is not list: heights = [heights]

		if (mag):
			a,b,c,trash = self.get_b(iteration)
		else:
			a,b,c,d,trash = self.get_v(iteration)

		ret = []
		dims = (self.ymx,self.xmx)

		if(mag):
			for i in heights:
				ret.append(spec(a[i,:,:],b[i,:,:],c[i,:,:],dims=dims))
		else:
			for i in heights:
				ret.append(spec_comp(a[i,:,:],b[i,:,:],c[i,:,:],d[i,:,:],dims=dims))

		return ret
Exemplo n.º 13
0
fn = 'Fri_Apr_03_20_08_31_num5_2p5e-4torr_RP29WF_Diode_668p6114024_Dye611p659794.h5'
# Afaict, my phase max finding routine is working properly. So use it.

d = np.array(h5py.File(dir + fn, 'r')['PMT_DATA_8BIT'])

(p1, p2) = lifxcmeans.findMaxPhase(dir + fn, 8, 1e6, 1e5, plots=True, duty=0.5)

phases = lifxcmeans.genBasePhase(8, 1e6, 1e5)

sq1 = sig.square(p1 + phases)
sq2 = sig.square(p2 + phases)

s1 = np.sum(d[:, 0:16], 1)
s2 = np.sum(d[:, 16:], 1)

su1 = s1 * (sq1 + 1) / 2
sb1 = s1 * (-sq1 + 1) / 2

[f, gu1] = spec.spec(su1, 1e-6)
[f, gb1] = spec.spec(sb1, 1e-6)

cut = np.where(np.abs(f) > 5e4)

gu1[cut] = 0
gb1[cut] = 0

[t, su1_c] = spec.ispec(gu1, f[1] - f[0])
[t, sb1_c] = spec.ispec(gb1, f[1]- f[0])

top1 = resample(su1_c, 0.1, 'sinc_best')
bot1 = resampel(sb1_c, 0.1, 'sinc_best')
Exemplo n.º 14
0
def response(xcm, a1, a2, tc, tw, dt):
    """Calculates and returns the linear response function corresponding to Cr
    and Cl, the folded cross correlation functions.

    (Hxy, Hyx, t) = response(xcm, a1, a2, tc, tw, dt)

    This method assumes that xcm was created with the matlab command xcorr as
    follows:
    xcm = xcorr(a1, a2, 'unbisaed');
    This results in Cr corresponding to the linear response of X to Y and Cl
    corresponding to the linear response of Y to X.

    This method uses a gaussian windowing function in order to clean up the
    signal before taking spectra. tc is a parameter to allow tuning of this window.

    Parameters:
    xcm : array_like
        Cross correlation of a1 and a2.
    a1 : array_like
        Autocorrelation of time series one.
    a2 : array_like
        Autocorelation of times series two.
    tc : float64
        Window width to use. Goes like win = exp(-(t/tc)**2/2)
    tw : float64
        Maximum time to include in data. All time points larger will be cut
        out. A typical value for a tc = 0.01 is 0.04.
    Returns:
    Hxy : array_like
        Linear response of X to Y.
    Hyx: array_like
        Linear response of Y to X.
    t : array_like
        Time axis of the linear response functions.
    """
    N = (np.size(xcm) + 1) / 2
    CR = np.append(xcm[N-1:][::-1], xcm[N:])
    CL = np.append(xcm[0:N-1], xcm[0:N][::-1])
    t = np.linspace(-(N-1),(N-1), 2 * N - 1) / 1e5
    win = np.exp(-(t/tc)**2/2)
    #Window functions
    CRw = CR * win
    CLw = CL * win
    a1w = a1 * win
    a2w = a2 * win
    #Get the middle points according to tw
    tc = np.where(abs(t) < tw)
    CRw = CRw[tc]
    CLw = CLw[tc]
    a1w = a1w[tc]
    a2w = a2w[tc]
    #fftshift + reverse so that t = 0 is at the beginning (rather than the end)
    CRw = fp.fftshift(CRw)[::-1]
    CLw = fp.fftshift(CLw)[::-1]
    a1w = fp.fftshift(a1w)[::-1]
    a2w = fp.fftshift(a2w)[::-1]
    #take spectra
    [f, gCRw] = spec.spec(CRw, dt)
    [f, gCLw] = spec.spec(CLw, dt)
    [f, ga1w] = spec.spec(a1w, dt)
    [f, ga2w] = spec.spec(a2w, dt)
    #Get k space response functions
    #Really, using the reals here is kind of redundant since CR, CL, a1w, and
    #a2w are all symmetric by construction. Shifting it to t = 0 and taking
    #real() is just another way of getting abs(), only by making sure the
    #fft vector is on the real line. w/e
    gHxy = np.real(gCRw) / np.real(ga2w)
    gHyx = np.real(gCLw) / np.real(ga1w)
    gHxyHT = signal.hilbert(gHxy)
    gHyxHT = signal.hilbert(gHyx)
    [t, Hxy] = spec.ispec(gHxyHT, f[1] - f[0])
    [t, Hyx] = spec.ispec(gHyxHT, f[1] - f[0])
    return (Hxy[::-1], Hyx[::-1], t)
Exemplo n.º 15
0
def ZeemanFitFunc_VaryB(RSi, RSf, Ei, Ef, P, B, tls, wavelengths, s):
    """
        Function which takes a Zeeman spectrum, deconvolves it with the natural
        Zeeman linewidth according to B and P, and returns the deconvolved
        spectrum. This is to be used with an optimization problem.

        See also: ZeemanFit_VaryV, which postulates that there is a streaming
        flow in the plasma.
        
        INPUTS:
        RSi     -   Russel Saunders term for the initial energy level.
        RSf     -   Russel Saunders term for the final energy level.
        Ei      -   Energy for the initial energy level.
        Ef      -   Energy for the final energy level.
        P       -   Polarization of Zeeman lines to fit (-1, 0, 1).
        B0      -   Initial guess for magnetic field in Gauss.
        tls     -   Tuple of (ti, tf) for the mean lifetimes of the starting
                    and ending state. Just one entry in the tuple is fine.
        wavelengths -   Wvelengths of data.
        spec    -   Measured LIF spectrum.
        OUTPUTS
        x       -   Cleaned wavelengths.
        yn      -   Cleaned and normalized spectrum.
        lns_clnn-   Cleaned and normalized natural lines.
        ivdf    -   Resulting deconvolved spectrum.
    """
    #Try deconvolving using the usual process.
    #Normalize:
    (x, y) = clean.clean(wavelengths, s)
    yn = y / np.sqrt(np.dot(y, y))
    #Pad the Zeeman array so that the Zeeman lines aren't
    #truncated by numerical errors.
    #Do this by adding high frequency elements to the FFT
    #of the original data array.
    pad_length = 5000
    [f, gs] = spec.spec(yn, x[1] - x[0])
    gs = np.pad(gs, pad_length, mode='constant', constant_values=0)
    xp = linspace(x[0], x[-1], np.size(gs))
    lns_cln = Zeeman_Lines(RSi, RSf, Ei, Ef, xp, P, B, tls)
    lns_clnn = lns_cln / np.sqrt(np.dot(lns_cln, lns_cln))
    lns_clnn = lns_clnn * np.max(yn) / np.max(lns_clnn)
    [junk, gl] = spec.spec(lns_clnn, x[1] - x[0])
    #remove the HF padding.
    gs = gs[pad_length:-pad_length]
    gl = gl[pad_length:-pad_length]
    [junk, lns_clnn] = spec.ispec(gl, f[1] - f[0])
    #fi = find outside of window.
    fi = np.where(np.abs(f) > freq_end)
    #fni = noise estimation interval
    fni = np.where((np.abs(f) > fnoise_start) - (np.abs(f) > fnoise_end))
    #fwi = indices of window to keep.
    fwi = np.where(np.abs(f) <= freq_end)
    gdc = np.abs(gs) / np.abs(gl)
    gdc[fi] = 0
    [trash, ivdf] = spec.ispec(gdc, f[1] - f[0])
    ivdf = sp.fftpack.fftshift(ivdf)
    #Get the errors too.
    err = np.mean(np.abs(gs[fi]))
    sig_real = np.sqrt(err**2 / np.size(fwi) * np.sum(1 / gl[fwi]**2) *
        np.size(fwi) / np.size(f))
    errs = np.abs(sig_real)
    return (x, yn, lns_clnn, ivdf, errs)
Exemplo n.º 16
0
emsys = ['ElES_LowPt', 'ElES_PS', 'ElES_R12', 'ElES_Zee',
         'ElEnResSys']  # branches
JES = [
    'JER', 'JES_Detector1', 'JES_EtaMethod', 'JES_EtaModelling',
    'JES_FlavComp', 'JES_FlavResp', 'JES_Modelling1', 'JES_PUNPV', 'JES_PURho'
]  # branch
MET = ['METResSys', 'METScaleSys', 'METRESOSOFT', 'METSCALESOFT']  # branches
PU = ['PU_rescaling']

################################################################
# Standard Event Selection
################################################################
el_fit = spec(streams.el,
              DIR='prod4/el_fit',
              regions=['SR'],
              control=['WCR', 'QCD'],
              reg_entries=[upsilon_20],
              cr_entries=[upsilon_CR],
              syst=emsys + JES + MET,
              SFsys=tausys + lepsys + PU)

mu_fit = spec(streams.mu,
              DIR='prod4/mu_fit',
              regions=['SR'],
              control=['WCR', 'QCD'],
              reg_entries=[upsilon_20],
              cr_entries=[upsilon_CR],
              syst=emsys + JES + MET,
              SFsys=tausys + lepsys + PU)

mu_theory = spec(
    streams.mutheory,
Exemplo n.º 17
0
    def run(self):
        """
        Run SPEC, if needed.
        """
        if not self.need_to_run_code:
            logger.info("run() called but no need to re-run SPEC.")
            return
        logger.info("Preparing to run SPEC.")
        self.counter += 1

        si = self.inputlist  # Shorthand

        # nfp must be consistent between the surface and SPEC. The surface's value trumps.
        si.nfp = self.boundary.nfp
        si.istellsym = int(self.boundary.stellsym)

        # Convert boundary to RZFourier if needed:
        boundary_RZFourier = self.boundary.to_RZFourier()

        # Transfer boundary data to fortran:
        si.rbc[:, :] = 0.0
        si.zbs[:, :] = 0.0
        si.rbs[:, :] = 0.0
        si.zbc[:, :] = 0.0
        mpol_capped = np.min([boundary_RZFourier.mpol, si.mmpol])
        ntor_capped = np.min([boundary_RZFourier.ntor, si.mntor])
        stellsym = bool(si.istellsym)
        print("In run, si.istellsym=", si.istellsym, " stellsym=", stellsym)
        for m in range(mpol_capped + 1):
            for n in range(-ntor_capped, ntor_capped + 1):
                si.rbc[n + si.mntor, m + si.mmpol] = boundary_RZFourier.get_rc(m, n)
                si.zbs[n + si.mntor, m + si.mmpol] = boundary_RZFourier.get_zs(m, n)
                if not stellsym:
                    si.rbs[n + si.mntor, m + si.mmpol] = boundary_RZFourier.get_rs(m, n)
                    si.zbc[n + si.mntor, m + si.mmpol] = boundary_RZFourier.get_zc(m, n)

        # Set the coordinate axis using the lrzaxis=2 feature:
        si.lrzaxis = 2
        # lrzaxis=2 only seems to work if the axis is not already set
        si.ras[:] = 0.0
        si.rac[:] = 0.0
        si.zas[:] = 0.0
        si.zac[:] = 0.0

        # Another possible way to initialize the coordinate axis: use
        # the m=0 modes of the boundary.
        # m = 0
        # for n in range(2):
        #     si.rac[n] = si.rbc[n + si.mntor, m + si.mmpol]
        #     si.zas[n] = si.zbs[n + si.mntor, m + si.mmpol]

        filename = self.extension + '_{:03}_{:06}'.format(self.mpi.group, self.counter)
        logger.info("Running SPEC using filename " + filename)
        self.allglobal.ext = filename
        try:
            # Here is where we actually run SPEC:
            if self.mpi.proc0_groups:
                logger.debug('About to call check_inputs')
                spec.allglobal.check_inputs()
            logger.debug('About to call broadcast_inputs')
            spec.allglobal.broadcast_inputs()
            logger.debug('About to call preset')
            spec.preset()
            logger.debug(f'About to call init_outfile')
            spec.sphdf5.init_outfile()
            logger.debug('About to call mirror_input_to_outfile')
            spec.sphdf5.mirror_input_to_outfile()
            if self.mpi.proc0_groups:
                logger.debug('About to call wrtend')
                spec.allglobal.wrtend()
            logger.debug('About to call init_convergence_output')
            spec.sphdf5.init_convergence_output()
            logger.debug(f'About to call spec')
            spec.spec()
            logger.debug('About to call diagnostics')
            spec.final_diagnostics()
            logger.debug('About to call write_grid')
            spec.sphdf5.write_grid()
            if self.mpi.proc0_groups:
                logger.debug('About to call wrtend')
                spec.allglobal.wrtend()
            logger.debug('About to call hdfint')
            spec.sphdf5.hdfint()
            logger.debug('About to call finish_outfile')
            spec.sphdf5.finish_outfile()
            logger.debug('About to call ending')
            spec.ending()

        except:
            if self.verbose:
                traceback.print_exc()
            raise ObjectiveFailure("SPEC did not run successfully.")

        logger.info("SPEC run complete.")
        # Barrier so workers do not try to read the .h5 file before it is finished:
        self.mpi.comm_groups.Barrier()

        try:
            self.results = py_spec.SPECout(filename + '.sp.h5')
        except:
            if self.verbose:
                traceback.print_exc()
            raise ObjectiveFailure("Unable to read results following SPEC execution")

        logger.info("Successfully loaded SPEC results.")
        self.need_to_run_code = False

        # Group leaders handle deletion of files:
        if self.mpi.proc0_groups:

            # If the worker group is not 0, delete all wout files, unless
            # keep_all_files is True:
            if (not self.keep_all_files) and (self.mpi.group > 0):
                os.remove(filename + '.sp.h5')
                os.remove(filename + '.sp.end')

            # Delete the previous output file, if desired:
            for file_to_delete in self.files_to_delete:
                os.remove(file_to_delete)
            self.files_to_delete = []

            # Record the latest output file to delete if we run again:
            if (self.mpi.group == 0) and (self.counter > 0) and (not self.keep_all_files):
                self.files_to_delete.append(filename + '.sp.h5')
                self.files_to_delete.append(filename + '.sp.end')