Exemple #1
0
 def ReIter(self):
     [a, b] = ipVar.poptDir(self.RePath)
     z = np.where(np.diff(np.sign(a)))[0]
     i = z[0]
     r1 = b[i]
     r2 = b[i + 1]
     print(r1)
     print(r2)
     print("the value of the ")
     while (abs(r1 - r2) > 20):
         self.ReList = []
         ReCr = funcs.calcReC(a, b)
         self.ReList.append(ReCr + 0.3 * abs(r1 - r2))
         self.ReList.append(ReCr - 0.3 * abs(r1 - r2))
         self.CritRe()
         print(r1)
         print(r2)
         [a, b] = ipVar.poptDir(self.RePath)
         z = np.where(np.diff(np.sign(a)))[0]
         r1 = b[z[0]]
         r2 = b[z[0] + 1]
     [a, b] = ipVar.poptDir(self.RePath)
     if (len(a) > 3): func = InterpolatedUnivariateSpline(b, a, k=3)
     ReC = func.roots()
     return ReC
Exemple #2
0
def attenuation_dead_zone(f, s1, s2):
    DZ = []
    pat1 = re.compile(s1 + '(.*?)' + s2, re.S)  ### used for otdr 1
    for element in f:
        filename = element.split('/')[-1].split('.')[0]
        cond = filename.split('_')[2]
        if float(cond) != 8:
            data = open(element)
            lines = data.read()
            new_data = pat1.findall(lines)
            x = []
            y = []
            for line in new_data:
                line = line.split()
                n = len(line)
                for i in range(1, int(n * 0.5), 1):
                    newline = line[i].split(',')
                    x.append(float(newline[0]))
                    y.append(float(newline[1]))
            spl = InterpolatedUnivariateSpline(x, y)
            x_new_1 = np.linspace(0.15, 0.25, 100)
            y_new_1 = spl(x_new_1)
            left = np.average(abs(y_new_1))
            n = len(y)
            y_new = []
            for i in range(n):
                y_new.append(float(y[i]) - left)
            spl1 = InterpolatedUnivariateSpline(x, y_new)
            root = InterpolatedUnivariateSpline.roots(spl1)
            error = (abs(root[-1] - root[-2])) * 500
            DZ.append(error)
        else:
            DZ.append(0)
    return DZ
def find_cell_interceps(u_par_grid, u_perp_grid, cur_BDOP, irhop):
    u_par_interceps = u_par_grid[np.logical_and(
        u_par_grid > np.min(cur_BDOP.u_par[irhop]),
        u_par_grid < np.max(cur_BDOP.u_par[irhop]))]
    u_perp_spl = InterpolatedUnivariateSpline(cur_BDOP.u_par[irhop],
                                              cur_BDOP.u_perp[irhop])
    u_perp_at_u_par_interceps = u_perp_spl(u_par_interceps)
    u_perp_interceps = []
    u_par_at_u_perp_inteceps = []
    for u_perp_intercep in u_perp_grid:
        u_perp_interceps_spl = InterpolatedUnivariateSpline(
            cur_BDOP.u_par[irhop], cur_BDOP.u_perp[irhop] - u_perp_intercep)
        roots = u_perp_interceps_spl.roots()
        if (len(roots) > 0):
            for root in roots:
                if (root >= np.min(u_par_grid) and root <= np.max(u_par_grid)):
                    u_perp_interceps.append(u_perp_intercep)
                    u_par_at_u_perp_inteceps.append(root)
    # Now create list of all intercep points (u_par, u_perp) sorted by ascending u_par
    intercep_list = np.array([
        np.concatenate([u_par_interceps, u_par_at_u_perp_inteceps]),
        np.concatenate([u_perp_at_u_par_interceps, u_perp_interceps])
    ])
    sortarray = np.argsort(intercep_list[0])
    return intercep_list.T[sortarray]
Exemple #4
0
    def ReIter2(self, FT):
        [a, b] = ipVar.poptDir(self.RePath)
        z = np.where(np.diff(np.sign(a)))[0]
        r1 = b[z[0]]
        r2 = b[z[0] + 1]
        while (abs(r1 - r2) > 11):
            [a, b] = ipVar.poptDir(self.RePath)
            ReCr = funcs.calcReC(a, b)
            self.ReList.append(ReCr + 5)
            self.ReList.append(ReCr - 5)
            self.CritRe(FT)
            [a, b] = ipVar.poptDir(self.RePath)
            ReCr = funcs.calcReC(a, b)
            z = np.where(np.diff(np.sign(a)))[0]
            r1 = b[z[0]]
            r2 = b[z[0] + 1]

        if (abs(r1 - r2) < 11):
            [a, b] = ipVar.poptDir(self.RePath)
            ReCr = funcs.calcReC(a, b)
            self.ReList.append(ReCr)
            self.CritRe(FT)

        [a, b] = ipVar.poptDir(self.RePath)
        if (len(a) > 3): func = InterpolatedUnivariateSpline(b, a, k=3)
        ReC = func.roots()
        return ReC
Exemple #5
0
    def ReIter2(self,FT):
        [a,b]=ipVar.poptDir(self.RePath);
        z=np.where(np.diff(np.sign(a)))[0];
        r1=b[z[0]];r2=b[z[0]+1];
        while(abs(r1-r2)>11):
            [a,b]=ipVar.poptDir(self.RePath);
            ReCr=funcs.calcReC(a,b);
            self.ReList.append(ReCr+5);
            self.ReList.append(ReCr-5);
            self.CritRe(FT);
            [a,b]=ipVar.poptDir(self.RePath);
            ReCr=funcs.calcReC(a,b);
            z=np.where(np.diff(np.sign(a)))[0];
            r1=b[z[0]];r2=b[z[0]+1];

        if(abs(r1-r2)< 11):
            [a,b]=ipVar.poptDir(self.RePath);
            ReCr=funcs.calcReC(a,b);
            self.ReList.append(ReCr);
            self.CritRe(FT);

        [a,b]=ipVar.poptDir(self.RePath);
        if(len(a)>3):func=InterpolatedUnivariateSpline(b,a,k=3);
        ReC=func.roots();
        return ReC;
Exemple #6
0
def get_key_points(t, x):
    """
    Basic function used in ZeroKeypointsGenerator
    finding t: x(t)=0 and filtering the outliers
    """
    spl = InterpolatedUnivariateSpline(t, x)
    roots = spl.roots()
    key_points = roots[1::2]
    if len(key_points) < 3:
        return key_points, np.zeros_like(key_points)

    outlier_scores = np.abs(
        (key_points[2:] + key_points[:-2] - 2 * key_points[1:-1]) /
        key_points[1:-1])
    np.pad(np.abs((key_points[2:] + key_points[:-2] - 2 * key_points[1:-1]) /
                  key_points[1:-1]), (2, 2),
           mode='constant',
           constant_values=1)

    threshold = 3 * np.percentile(outlier_scores, 75) - 2 * np.percentile(
        outlier_scores, 25)
    outliers = (np.convolve(
        np.pad(outlier_scores > threshold, (2, 2),
               mode='constant',
               constant_values=1), [1, 1, 1]) == 3)[2:-2]
    return key_points, outliers
def parsec_locus_jhjk(x0, y0, cer, feh, age, isochrones):
    '''
    Find the where a star would be located on the stellar locus in (J - K)-(J - H) color space.
    (J - K) is the abscissa and (J - H) is the ordinate.
    
    Inputs:
    ------
        x0: J - K color of star
        y0: J - H color of star
        cer: color excess ratio [E(J - H)/E(J - K)]
        feh: metallicity of star
        age: age in Gyr
        isochrones: set of parsec isochrones
    
    Outputs:
    -------
        jk_cross: J - K of intersection point
        jh_cross: J - H of intersection point
    '''
    single = isochrones[np.where((isochrones['logAge'] == closest(
        np.log10(age * 10**9), isochrones['logAge'])) & (
            isochrones['MH'] == closest(feh, isochrones['MH'])))]
    xs = (single['Jmag'] - single['Ksmag'])
    ys = (single['Jmag'] - single['Hmag'])

    bins = np.arange(np.min(xs), np.max(xs), 0.005)
    binned_color = binned_statistic(xs, ys, statistic='median',
                                    bins=bins).statistic

    fin = np.where((np.isfinite(bins[:-1]) == True)
                   & (np.isfinite(binned_color) == True))

    bins = bins[:-1][fin]
    binned_color = binned_color[fin]

    # Interpolate Isochrone
    spline = InterpolatedUnivariateSpline(bins, binned_color, ext=0)
    y_spl = spline(bins)

    # Find the crossing point
    if y0 - spline(x0) > 0:
        # what to do if star is above isochrone in color-color space
        return np.squeeze([-9999.0, -9999.0])

    else:
        # Find roots in difference between the ccline and isochrone
        func = y_spl - ccline(bins, cer, x0, y0)
        func_spl = InterpolatedUnivariateSpline(bins, func, ext=0)
        jk_cross = func_spl.roots()
        jh_cross = spline(jk_cross)

        if len(jk_cross) == 0:
            # If cross12 is empty
            return np.squeeze([-9999.0, -9999.0])

        else:
            # Return Cartesian coordinates of crossing point in color-color space
            return np.squeeze(list(zip(jk_cross, jh_cross)))
Exemple #8
0
def crossings(series, value):
    """Find the labels where the series passes through value.
    The labels in series must be increasing numerical values.
    series: Series
    value: number
    returns: sequence of labels
    """
    interp = InterpolatedUnivariateSpline(series.index, series-value)
    return interp.roots()
Exemple #9
0
def find_FWHM(x, y):
    """
    Find FWHM (full width at half maximum) of the waveform.
    """
    xmax = x[np.argmax(y)]
    yn = y/np.max(y)
    spl = InterpolatedUnivariateSpline(x=x, y=yn-0.5)
    roots = spl.roots()
    x1 = roots[roots<xmax][-1]
    x2 = roots[roots>xmax][0]
    return x2-x1
Exemple #10
0
def crossings(series, value):
    """Find the labels where the series passes through value.

    The labels in series must be increasing numerical values.

    series: Series
    value: number

    returns: sequence of labels
    """
    interp = InterpolatedUnivariateSpline(series.index, series-value)
    return interp.roots()
Exemple #11
0
def fwhm(x, y):
    """Calculate the FWHM and peak height of a vector y with corresponding coordinates x."""
    i_max_y = np.argmax(y)
    y_norm = y - y[i_max_y] / 2
    max_x = x[i_max_y]
    spline = InterpolatedUnivariateSpline(x, y_norm, k=3, ext='raise')

    # FWHM
    r = spline.roots()
    if len(r) < 2:
        return np.nan
    center = r[np.argsort(np.abs(r - max_x))[0:2]]
    fwhm = np.abs(center[1] - center[0])
    return fwhm
Exemple #12
0
def CalculateHWHM(GF_A):
	''' calculates the half-width at half-maximum of the Kondo resonance 
	and the maximum of the spectral function '''
	N = len(En_A)
	IntMin = int((N+1)/2-int(0.5/dE))
	IntMax = int((N+1)/2+int(0.5/dE))
	DOSmaxPos = sp.argmax(-sp.imag(GF_A[IntMin:IntMax])/sp.pi)
	DOSmax    = -sp.imag(GF_A[IntMin+DOSmaxPos])/sp.pi # maximum of DoS
	wmax      = En_A[IntMin+DOSmaxPos]                 # position of the maximum at energy axis
	DOS = InterpolatedUnivariateSpline(En_A-1e-12,-sp.imag(GF_A)/sp.pi-DOSmax/2.0) 
	## 1e-12 breaks symmetry for half-filling, otherway DOS.roots() loses one solution.
	DOSroots_A = sp.sort(sp.fabs(DOS.roots()))
	try:
		HWHM = (DOSroots_A[0] + DOSroots_A[1])/2.0
	except IndexError:
		HWHM = 0.0
	return [HWHM,DOSmax,wmax]
Exemple #13
0
def CalculateHWHM(GF_A):
	''' calculates the half-width at half-maximum of the Kondo resonance 
	and the maximum of the spectral function '''
	N = len(En_A)
	IntMin = int((N+1)/2-int(0.5/dE))
	IntMax = int((N+1)/2+int(0.5/dE))
	DOSmaxPos = sp.argmax(-sp.imag(GF_A[IntMin:IntMax])/sp.pi)
	DOSmax    = -sp.imag(GF_A[IntMin+DOSmaxPos])/sp.pi # maximum of DoS
	wmax      = En_A[IntMin+DOSmaxPos]                 # position of the maximum at energy axis
	DOS = InterpolatedUnivariateSpline(En_A-1e-12,-sp.imag(GF_A)/sp.pi-DOSmax/2.0) 
	## 1e-12 breaks symmetry for half-filling, otherway DOS.roots() loses one solution.
	DOSroots_A = sp.sort(sp.fabs(DOS.roots()))
	try:
		HWHM = (DOSroots_A[0] + DOSroots_A[1])/2.0
	except IndexError:
		HWHM = 0.0
	return [HWHM,DOSmax,wmax]
Exemple #14
0
def retreat_terminus(profile, verbose=False):
    """
    Retreats terminus position with interpolation to satisfy height above flotation criterion.

    Parameters
    ----------
    profile: Profile
        Profile to advance.
    verobse: bool, optional
        Print out diagnostic messages. Default: False.
       
    Returns
    -------
    new_profile: Profile
        New Profile instance.
    """
    # Create spline representation of HAF
    spline = InterpolatedUnivariateSpline(profile.x, profile.HAF)

    # Find roots
    roots = spline.roots()
    if len(roots) > 1:
        raise ValueError('Found multiple zero crossings of HAF')
    x_zero = roots[0]

    # Compute rough number of grid points to remove
    n_remove = int(np.round((profile.x[-1] - x_zero) / profile.dx))
    if verbose:
        print('Retreating %d cells' % n_remove)

    # Create new grid of x points
    x_new = np.linspace(profile.x[0], x_zero, profile.N - n_remove)

    # Check if we need to remove an extra point
    dx_thresh = profile.dx - 0.05 * profile.dx
    if (x_new[1] - x_new[0]) < dx_thresh:
        x_new = np.linspace(profile.x[0], x_zero, profile.N - n_remove - 1)

    # Create new profile
    new_profile = profile.update_coordinates(x_new, extrapolate=False)
    new_profile.t = profile.t
    if verbose:
        print('New spacing:', new_profile.dx)

    return new_profile
Exemple #15
0
    def ReIter(self, FT):
        [a, b] = ipVar.poptDir(self.RePath)
        while (all(i > 0 for i in a)):
            self.ReList = []
            ReNew = float(b[0]) - 0.2 * float(b[0])
            self.ReList.append(ReNew)
            self.CritRe(FT)
            [a, b] = ipVar.poptDir(self.RePath)

        while (all(i < 0 for i in a)):
            self.ReList = []
            ReNew = float(b[-1]) + 0.3 * float(b[-1])
            self.ReList.append(ReNew)
            self.CritRe(FT)
            [a, b] = ipVar.poptDir(self.RePath)
        [a, b] = ipVar.poptDir(self.RePath)
        z = np.where(np.diff(np.sign(a)))[0]
        i = z[0]
        r1 = b[i]
        r2 = b[i + 1]
        print(r1)
        print(r2)
        print("the value of the ")
        temp = [0]
        ReCr = funcs.calcReC(a, b)
        temp.append(ReCr)
        while (abs(temp[-1] - temp[-2]) > 1):
            self.ReList = []
            ReCr = funcs.calcReC(a, b)
            self.ReList.append(ReCr + 0.1 * abs(r1 - r2))
            self.ReList.append(ReCr - 0.1 * abs(r1 - r2))
            self.CritRe(FT)
            print(r1)
            print(r2)
            ReCr = funcs.calcReC(a, b)
            temp.append(ReCr)
            [a, b] = ipVar.poptDir(self.RePath)
            z = np.where(np.diff(np.sign(a)))[0]
            r1 = b[z[0]]
            r2 = b[z[0] + 1]

        [a, b] = ipVar.poptDir(self.RePath)
        if (len(a) > 3): func = InterpolatedUnivariateSpline(b, a, k=3)
        ReC = func.roots()
        return ReC
Exemple #16
0
def score_from_efficiency_array(y_truth,
                                y_score,
                                efficiency_selected,
                                keep_lower=False):
    """
    Return the score array corresponding to an external fixed efficiency
    array.

    Parameters
    -----------------------------------------------
    y_truth: array
        Training or test set labels. The candidates for each
        class should be labeled with 0, ..., N.
        In case of binary classification, 0 should
        correspond to the background while 1 to the signal

    y_score: array
        Estimated probabilities or decision function.

    keep_lower: bool
        If True compute the efficiency using the candidates with
        score lower than the score threshold; otherwise using the
        candidates with score higher than the score threshold.

    efficiency_selected: list or array
        Efficiency array along which calculate
        the corresponding score array

    Returns
    -----------------------------------------------
    out: numpy array
        Score array corresponding to efficiency_selected
    """
    score_list = []
    eff, score = bdt_efficiency_array(y_truth,
                                      y_score,
                                      n_points=1000,
                                      keep_lower=keep_lower)
    for eff_val in efficiency_selected:
        interp = InterpolatedUnivariateSpline(score, eff - eff_val)
        score_list.append(interp.roots()[0])
    score_array = np.array(score_list)
    return score_array
Exemple #17
0
def FindABS(Det_A):
	"""	determines ABS energies as zeroes of GF determinant """
	DetG = InterpolatedUnivariateSpline(En_A[EdgePos1+1:EdgePos2],sp.real(Det_A[:]))
	RootsG_A = DetG.roots()
	NABS = len(RootsG_A)
	ABSpos_A = sp.zeros(2)
	Diff_A = sp.zeros(2)
	if NABS == 0:	
		## assumes ABS states too close to gap edges
		## this also happens when using brentq to calculate densities and
		## it starts from wrong initial guess
		print("# - Warning: FindABS: no ABS found: Probably too close to band edges.")
		ABS_A = sp.array([-Delta+2.0*dE,Delta-2.0*dE])
		ABSpos_A = sp.array([EdgePos1+1,EdgePos2-1])
		Diff_A = sp.array([DetG.derivatives(ABS_A[0])[1],DetG.derivatives(ABS_A[1])[1]])
	elif NABS == 1: 
		## ABS too close to each other?
		print("# - Warning: FindABS: only one ABS found: {0: .6e}".format(RootsG_A[0]))
		print("# -          Assuming they are too close to Fermi energy.")
		print("# -          Using mirroring to get the other ABS, please check the result.")
		ABS_A = [-sp.fabs(RootsG_A[0]),sp.fabs(RootsG_A[0])]
		for i in range(2):
			ABSpos_A[i] = FindInEnergies(ABS_A[i],En_A)
			Diff_A[i] = DetG.derivatives(ABS_A[i])[1]
	elif NABS == 2:	
		## two ABS states, ideal case
		ABS_A = sp.copy(RootsG_A)
		for i in range(2):
			ABSpos_A[i] = FindInEnergies(RootsG_A[i],En_A)
			Diff_A[i] = DetG.derivatives(RootsG_A[i])[1]
	else:
		print("# - Error: FindABS: Too many zeroes of the determinant.")
		exit()
	if sp.fabs(ABS_A[0]+ABS_A[1]) > 1e-6:
		print("# - Warning: FindABS: positive and negative ABS energies don't match, diff = {0: .6e}"\
		.format(sp.fabs(ABS_A[0]-ABS_A[1])))
	if sp.fabs(ABS_A[0])<dE:
		## ABS energy smaller than the energy resolution
		print("# - Warning: FindABS: ABS energies smaller than energy resolution")
		print("# -          We put the poles to lowest possible energies.")
		ABSpos_A = [Nhalf-1,Nhalf+1]
	return [ABS_A,Diff_A,ABSpos_A]
Exemple #18
0
    def filter_fwhm(self):
        """
        Returns
        -------
        float
            Filter full width at half maximum (micron).
        """

        data = self.get_filter()

        spline = InterpolatedUnivariateSpline(
            data[0, :], data[1, :] - np.max(data[1, :]) / 2.)
        root = spline.roots()

        diff = root - self.mean_wavelength()

        root1 = np.amax(diff[diff < 0.])
        root2 = np.amin(diff[diff > 0.])

        return root2 - root1
Exemple #19
0
    def ReIter(self,FT):
        [a,b]=ipVar.poptDir(self.RePath);
        while(all(i > 0 for i in a)):
            self.ReList=[];
            ReNew=float(b[0])- 0.2*float(b[0]);
            self.ReList.append(ReNew);
            self.CritRe(FT);
            [a,b]=ipVar.poptDir(self.RePath);

        while(all(i < 0 for i in a)):
            self.ReList=[];
            ReNew=float(b[-1])+0.3*float(b[-1]);
            self.ReList.append(ReNew);
            self.CritRe(FT);
            [a,b]=ipVar.poptDir(self.RePath); 
        [a,b]=ipVar.poptDir(self.RePath);
        z=np.where(np.diff(np.sign(a)))[0];
        i=z[0];
        r1=b[i];r2=b[i+1];
        print(r1);print(r2);
        print("the value of the ");
        temp=[0];
        ReCr=funcs.calcReC(a,b);
        temp.append(ReCr);
        while(abs(temp[-1]-temp[-2])>1):
            self.ReList=[];
            ReCr=funcs.calcReC(a,b);
            self.ReList.append(ReCr+0.1*abs(r1-r2));
            self.ReList.append(ReCr-0.1*abs(r1-r2));
            self.CritRe(FT);
            print(r1);print(r2);
            ReCr=funcs.calcReC(a,b);
            temp.append(ReCr);
            [a,b]=ipVar.poptDir(self.RePath);
            z=np.where(np.diff(np.sign(a)))[0];
            r1=b[z[0]];r2=b[z[0]+1];

        [a,b]=ipVar.poptDir(self.RePath);
        if(len(a)>3):func=InterpolatedUnivariateSpline(b,a,k=3);
        ReC=func.roots();
        return ReC;
Exemple #20
0
 def ReIter(self):
     [a,b]=ipVar.poptDir(self.RePath);
     z=np.where(np.diff(np.sign(a)))[0];
     i=z[0];
     r1=b[i];r2=b[i+1];
     print(r1);print(r2);
     print("the value of the ");
     while(abs(r1-r2)>20):
         self.ReList=[];
         ReCr=funcs.calcReC(a,b);
         self.ReList.append(ReCr+0.3*abs(r1-r2));
         self.ReList.append(ReCr-0.3*abs(r1-r2));
         self.CritRe();
         print(r1);print(r2);
         [a,b]=ipVar.poptDir(self.RePath);
         z=np.where(np.diff(np.sign(a)))[0];
         r1=b[z[0]];r2=b[z[0]+1];
     [a,b]=ipVar.poptDir(self.RePath);
     if(len(a)>3):func=InterpolatedUnivariateSpline(b,a,k=3);
     ReC=func.roots();
     return ReC;
Exemple #21
0
    def filter_fwhm(self) -> float:
        """
        Calculate the full width at half maximum (FWHM) of the filter profile.

        Returns
        -------
        float
            Filter full width at half maximum (um).
        """

        data = self.get_filter()

        spline = InterpolatedUnivariateSpline(
            data[:, 0], data[:, 1] - np.max(data[:, 1]) / 2.)
        root = spline.roots()

        diff = root - self.mean_wavelength()

        root1 = np.amax(diff[diff < 0.])
        root2 = np.amin(diff[diff > 0.])

        return root2 - root1
Exemple #22
0
def refl_dead_zone(f, s1, s2):
    DZ = []
    pat1 = re.compile(s1 + '(.*?)' + s2, re.S)  ### used for otdr 1
    for element in f:
        filename = element.split('/')[-1].split('.')[0]
        cond = filename.split('_')[2]
        if float(cond) != 8:
            data = open(element)
            lines = data.read()
            new_data = pat1.findall(lines)
            x = []
            y = []
            for line in new_data:
                line = line.split()
                n = len(line)
                for i in range(1, n, 1):
                    newline = line[i].split(',')
                    x.append(float(newline[0]))
                    y.append(float(newline[1]))
            refl_peak = max(y)
            refl_under_peak_1 = refl_peak - 1.5
            index = y.index(refl_peak)
            index_low = index - 50
            index_high = index + 20
            x_new = []
            y_new = []
            for i in range(index_low, index_high, 1):
                x_new.append(float(x[i]))
                y_new.append(float(y[i]) - refl_under_peak_1)
            spl = InterpolatedUnivariateSpline(x_new, y_new)
            root = InterpolatedUnivariateSpline.roots(spl)
            pos_gap = (abs(root[0] - root[1])) * 1000
            DZ.append(pos_gap)
        else:
            DZ.append(0)
    return DZ
Exemple #23
0
 def find_contours(self, h):
     # Contour for single level
     # Sign changes of Z-h are recoreded in pen_points
     # The recorded points are always above or left the penetration point
     # Negative indices indicate a horizontal sign change
     self.pen_points = []
     #horizontal
     # The zeroth x entry can never be a horizontal penetration point
     for i in range(1, self.nx-1):
         for j in range(0, self.ny):
             if((self.Z[i,j] -h) * (self.Z[i + 1,j] - h) < 0.0):
                 self.pen_points.append(-np.array([i,j]))
     # Edge
     for i in range(self.nx-1, self.nx):
         for j in range(0, self.ny):
             if((self.Z[i,j] -h) * (self.Z[i - 1,j] - h) < 0.0):
                 if(np.all(np.sum(np.abs(self.pen_points - (-np.array([i - 1,j]))),axis=1) > 0)):
                     self.pen_points.append(-np.array([i - 1,j]))
     #Vertical
     for i in range(0, self.nx):
         # The zeroth xy entry can never be a vertical penetration point
         for j in range(1, self.ny-1):
             if((self.Z[i,j] - h) * (self.Z[i,j + 1] - h) < 0.0):
                 self.pen_points.append(np.array([i,j]))
     #Edge
     for i in range(0, self.nx):
         for j in range(self.ny-1, self.ny):
             if((self.Z[i,j] - h) * (self.Z[i,j - 1] - h) < 0.0):
                 if(np.all(np.sum(np.abs(self.pen_points - (-np.array([i,j-1]))),axis=1) > 0)):
                     self.pen_points.append(np.array([i,j-1]))
     if(len(self.pen_points) == 0):
         self.contours_found = False
         return
     # Convert the pen_points to complex values which makes the index search much faster
     # Also remove any duplicates we might have picked up
     self.pen_points = list(np.unique(np.array(self.pen_points).T[0] + 1.j * np.array(self.pen_points).T[1]))
     self.contours_found = True
     self.finished_points = []
     self.contour_lines = [[]]
     self.contour_indices = [[]]
     self.contour_closed = []
     next_point = self.pen_points.pop(0)
     Z_spl = RectBivariateSpline(self.x, self.y, self.Z - h)
     N_int = 10
     x_int = np.zeros(N_int)
     y_int = np.zeros(N_int)
     # Open contourlines are reversed to avoid bad starting points
     contour_reversed = False
     # Assemble contours
     while True:
         i_next = int(np.real(next_point))
         j_next = int(np.imag(next_point))
         if(i_next < 0 or j_next < 0):
             # Horiontal penetration point
             x_int[:] = np.linspace(self.x[-i_next], self.x[-i_next + 1], N_int)
             y_int[:] = self.y[-j_next]
             Z_int = Z_spl(x_int, y_int, grid=False)
             root_spl = InterpolatedUnivariateSpline(x_int, Z_int)
             roots = root_spl.roots()
             if(len(roots) == 0):
                 print("Found no roots for this penetration point")
                 fig = plt.figure()
                 ax = fig.add_subplot(111)
                 ax.contour(self.x, self.y, self.Z.T - h, levels=[0.0])
                 ax.vlines(self.x, np.min(self.y), np.max(self.y), linewidths=0.2)
                 ax.hlines(self.y, np.min(self.x), np.max(self.x), linewidths=0.2)
                 ax.plot(x_int, y_int, "r--", linewidth=4)
                 fig2 = plt.figure()
                 ax2 = fig2.add_subplot(111)
                 ax2.plot(x_int, Z_int)
                 plt.show()
                 raise ValueError("Found  no roots for this penetration point")
             for root in roots:
                 self.contour_lines[-1].append([root, y_int[0]])
         else:
             # Horiontal penetration point
             x_int[:] = self.x[i_next]
             y_int[:] = np.linspace(self.y[j_next], self.y[j_next + 1], N_int)
             Z_int = Z_spl(x_int, y_int, grid=False)
             root_spl = InterpolatedUnivariateSpline(y_int, Z_int)
             roots = root_spl.roots()
             if(len(roots) == 0):
                 print("Found no roots for this penetration point")
                 fig = plt.figure()
                 ax = fig.add_subplot(111)
                 ax.contour(self.x, self.y, self.Z.T - h, levels=[0.0])
                 ax.vlines(self.x, np.min(self.y), np.max(self.y), linewidths=0.2)
                 ax.hlines(self.y, np.min(self.x), np.max(self.x), linewidths=0.2)
                 ax.plot(x_int, y_int, "r--", linewidth=4)
                 fig2 = plt.figure()
                 ax2 = fig2.add_subplot(111)
                 ax2.plot(y_int, Z_int)
                 plt.show()
                 raise ValueError("Found no roots for this penetration point")
             for root in roots:
                 self.contour_lines[-1].append([x_int[0], root])
         self.contour_indices[-1].append(next_point)
         self.finished_points.append(next_point)
         # Find the next point
         found_next, isclosed, next_point = self._find_next(next_point)
         if(not found_next):
             if(isclosed and len(self.contour_lines[-1]) > 2):
                 # Close the contour
                 self.contour_lines[-1].append(self.contour_lines[-1][0])
                 self.contour_indices[-1].append(self.contour_indices[-1][0])
             elif(not contour_reversed):
                 self.contour_lines[-1] = self.contour_lines[-1][::-1]
                 self.contour_indices[-1] = self.contour_indices[-1][::-1]
                 contour_reversed = True
                 found_next, isclosed, next_point = self._find_next(self.contour_indices[-1][-1])
             if(not found_next):
                 contour_reversed = False
                 self.contour_closed.append(isclosed)
                 self.contour_lines[-1] = np.array(self.contour_lines[-1])
                 self.contour_indices[-1] = np.array(self.contour_indices[-1])
                 if(len(self.pen_points) == 0):
                     break
                 next_point = self.pen_points.pop(0)
                 self.contour_lines.append([])
                 self.contour_indices.append([])
Exemple #24
0
    def integrate_flux(
        self,
        wavel_int: Tuple[float, float],
        interp_kind: str = "linear",
        plot_filename: Optional[str] = "int_line.pdf",
    ) -> Union[np.float64, np.float64]:
        """
        Method for calculating the integrated line flux and error. The
        spectrum is first interpolated to :math:`R = 100000` and then
        integrated across the specified wavelength range with the
        composite trapezoidal rule of ``np.trapz``. The error is
        estimated with a Monte Carlo approach from 1000 samples.

        Parameters
        ----------
        wavel_int : tuple(float, float)
            Wavelength range (um) across which the flux
            will be integrated.
        interp_kind : str
            Kind of interpolation kind for
            ``scipy.interpolate.interp1d`` (default: 'linear').
        plot_filename : str, None
            Filename for the plot with the interpolated line profile.
            The plot is shown in an interface window if the argument
            is set to ``None``.

        Returns
        -------
        float
            Integrated line flux (W m-2).
        float
            Flux error (W m-2).
        """

        if plot_filename is None:
            print("Plotting integrated line...", end="", flush=True)
        else:
            print(f"Plotting integrated line: {plot_filename}...", end="", flush=True)

        n_samples = 1000

        wavel_high_res = read_util.create_wavelengths(wavel_int, 1e5)

        # Creating plot

        mpl.rcParams["font.serif"] = ["Bitstream Vera Serif"]
        mpl.rcParams["font.family"] = "serif"

        plt.rc("axes", edgecolor="black", linewidth=2)
        plt.rcParams["axes.axisbelow"] = False

        plt.figure(1, figsize=(6, 3))
        gs = mpl.gridspec.GridSpec(1, 1)
        gs.update(wspace=0, hspace=0, left=0, right=1, bottom=0, top=1)

        ax1 = plt.subplot(gs[0, 0])
        ax2 = ax1.twiny()

        ax1.tick_params(
            axis="both",
            which="major",
            colors="black",
            labelcolor="black",
            direction="in",
            width=1,
            length=5,
            labelsize=12,
            top=False,
            bottom=True,
            left=True,
            right=True,
        )

        ax1.tick_params(
            axis="both",
            which="minor",
            colors="black",
            labelcolor="black",
            direction="in",
            width=1,
            length=3,
            labelsize=12,
            top=False,
            bottom=True,
            left=True,
            right=True,
        )

        ax2.tick_params(
            axis="both",
            which="major",
            colors="black",
            labelcolor="black",
            direction="in",
            width=1,
            length=5,
            labelsize=12,
            top=True,
            bottom=False,
            left=False,
            right=True,
        )

        ax2.tick_params(
            axis="both",
            which="minor",
            colors="black",
            labelcolor="black",
            direction="in",
            width=1,
            length=3,
            labelsize=12,
            top=True,
            bottom=False,
            left=False,
            right=True,
        )

        ax1.set_xlabel("Wavelength (µm)", fontsize=16)
        ax1.set_ylabel("Flux (W m$^{-2}$ µm$^{-1}$)", fontsize=16)
        ax2.set_xlabel("Velocity (km s$^{-1}$)", fontsize=16)

        ax1.get_xaxis().set_label_coords(0.5, -0.12)
        ax1.get_yaxis().set_label_coords(-0.1, 0.5)
        ax2.get_xaxis().set_label_coords(0.5, 1.12)

        ax1.plot(
            self.spectrum[:, 0],
            self.spectrum[:, 1],
            color="black",
            label=self.spec_name,
        )
        ax2.plot(self.spec_vrad, self.spectrum[:, 1], ls="-", lw=0.0)

        flux_sample = np.zeros(n_samples)
        fwhm_sample = np.zeros(n_samples)
        mean_sample = np.zeros(n_samples)
        vrad_sample = np.zeros(n_samples)
        lum_sample = np.zeros(n_samples)

        for i in range(n_samples):
            # Sample fluxes from random errors
            spec_rand = np.random.normal(self.spectrum[:, 1], self.spectrum[:, 2])

            # Interpolate sampled spectrum
            spec_interp = interp1d(
                self.spectrum[:, 0], spec_rand, kind=interp_kind, bounds_error=False
            )

            # Resample to high-resolution wavelengths
            flux_rand = spec_interp(wavel_high_res)

            # Integrate line flux (W m-2)
            flux_sample[i] = np.trapz(flux_rand, wavel_high_res)

            # Line luminosity (Lsun)
            lum_sample[i] = (
                4.0 * np.pi * (1e3 * constants.PARSEC / self.parallax) ** 2 * flux_sample[i]
            )
            lum_sample[i] /= constants.L_SUN  # (Lsun)

            # Weighted (with flux) mean wavelength (um)
            mean_sample[i] = np.trapz(
                wavel_high_res * flux_rand, wavel_high_res
            ) / np.trapz(flux_rand, wavel_high_res)

            # Radial velocity (km s-1)
            vrad_sample[i] = (
                1e-3
                * constants.LIGHT
                * (mean_sample[i] - self.lambda_rest)
                / self.lambda_rest
            )

            # Find full width at half maximum

            spline = InterpolatedUnivariateSpline(
                wavel_high_res, flux_rand - np.max(flux_rand) / 2.0
            )
            root = spline.roots()

            diff = root - mean_sample[i]

            root1 = np.amax(diff[diff < 0.0])
            root2 = np.amin(diff[diff > 0.0])

            fwhm_sample[i] = 1e-3 * constants.LIGHT * (root2 - root1) / mean_sample[i]

            # Add 30 samples to the plot

            if i == 0:
                ax1.plot(
                    wavel_high_res,
                    flux_rand,
                    ls="-",
                    lw=0.5,
                    color="gray",
                    alpha=0.4,
                    label="Random samples",
                )

            elif i < 30:
                ax1.plot(
                    wavel_high_res, flux_rand, ls="-", lw=0.5, color="gray", alpha=0.4
                )

        # Line flux from original, interpolated spectrum

        spec_interp = interp1d(
            self.spectrum[:, 0],
            self.spectrum[:, 1],
            kind=interp_kind,
            bounds_error=False,
        )

        flux_high_res = spec_interp(wavel_high_res)

        line_flux = np.trapz(flux_high_res, wavel_high_res)

        ax1.plot(
            wavel_high_res, flux_high_res, color="tab:blue", label="High resolution"
        )

        ax1.legend(loc="upper right", frameon=False, fontsize=12.0)

        print(" [DONE]")

        if plot_filename is None:
            plt.show()
        else:
            plt.savefig(plot_filename, bbox_inches="tight")

        plt.clf()
        plt.close()

        wavel_mean, wavel_std = np.mean(mean_sample), np.std(mean_sample)
        print(f"Mean wavelength (nm): {1e3*wavel_mean:.2f} +/- {1e3*wavel_std:.2f}")

        fwhm_mean, fwhm_std = np.mean(fwhm_sample), np.std(fwhm_sample)
        print(f"FWHM (km s-1): {fwhm_mean:.2f} +/- {fwhm_std:.2f}")

        vrad_mean, vrad_std = np.mean(vrad_sample), np.std(vrad_sample)
        print(f"Radial velocity (km s-1): {vrad_mean:.1f} +/- {vrad_std:.1f}")

        line_error = np.std(flux_sample)
        print(f"Line flux (W m-2): {line_flux:.2e} +/- {line_error:.2e}")

        lum_mean, lum_std = np.mean(lum_sample), np.std(lum_sample)
        print(f"Line luminosity (Lsun): {lum_mean:.2e} +/- {lum_std:.2e}")

        return line_flux, line_error
Exemple #25
0
def SpecHWHM(GFint_A):
	''' Half-width at half-maximum of the spectral function '''
	N = len(En_A)
	DOSF = -sp.imag(GFint_A[N/2])/sp.pi	# value at Fermi energy
	DOS = InterpolatedUnivariateSpline(En_A,-sp.imag(GFint_A)/sp.pi-DOSF/2.0)
	return sp.amin(sp.fabs(DOS.roots()))
Exemple #26
0
def SpecHWHM(GFint_A):
	''' Half-width at half-maximum of the spectral function '''
	N = len(En_A)
	DOSF = -sp.imag(GFint_A[N/2])/sp.pi	# value at Fermi energy
	DOS = InterpolatedUnivariateSpline(En_A,-sp.imag(GFint_A)/sp.pi-DOSF/2.0)
	return sp.amin(sp.fabs(DOS.roots()))
Exemple #27
0
def calc_fwhm(x, y):
    """Return FWHM calculated by fitting a spline to y vs. x"""
    y = N.array(y)
    sp = InterpolatedUnivariateSpline(x, y - y.max() / 2)
    lo, hi = sp.roots()
    return hi - lo
Exemple #28
0
    
    	x0 = [seed[0], seed[1], seed[2], seed[4]]
    	res = optimize.minimize(chi2_rel, x0, method='Nelder-Mead')
	chi2vals.append(res.fun)

fig = plt.figure(figsize=(7, 6), dpi=200)
ax = plt.axes()
ax.plot(means, chi2vals, "k-")
ax.set_ylabel('$\\Delta\\chi^2$', position=(0., 1.), va='top', ha='right')
ax.set_xlabel('mean [keV]', position=(1., 0.), va='bottom', ha='right')
ax.yaxis.set_label_coords(-0.12, 1.)
ax.xaxis.set_label_coords(1.0, -0.1)
plt.savefig("chi2.png")

# find roots numerically via interpolation
from scipy.interpolate import InterpolatedUnivariateSpline
spline = InterpolatedUnivariateSpline(means, numpy.asarray(chi2vals)-1.)
roots = spline.roots()
print "best fit:", result.x[3], "+", roots[1]-result.x[3], "-", result.x[3]-roots[0]

 
    

      






def parsec_locus(x0, y0, mag1, mag2, mag3, mag4, cer, feh, age, parsec):
    '''
    Find the where a star would be located on the stellar locus in (1 - 2)-(3 - 4) color space.
    (1 - 2) is the abscissa and (3 - 4) is the ordinate.
    
    Inputs:
    ------
        x0: (1 - 2) color of star off locus
        y0: (3 - 4) color of star off locus
        mag1: [str] first magnitude in (1 - 2) color
        mag2: [str] second magnitude in (1 - 2) color
        mag3: [str] first magnitude in (3 - 4) color
        mag4: [str] second magnitude in (3 - 4) color
        cer: color excess ratio [E(3 - 4)/E(1 - 2)]
        feh: metallicity of star
        age: age in Gyr
        parsec: set of parsec isochrones
    
    Outputs:
    -------
        cross12: (1 - 2) of intersection point
        cross34: (3 - 4) of intersection point
    '''

    single = parsec[np.where(
        (parsec['logAge'] == closest(np.log10(age * 10**9), parsec['logAge']))
        & (parsec['MH'] == closest(feh, parsec['MH'])))]
    xs = (single[mag1] - single[mag2])
    ys = (single[mag3] - single[mag4])

    bins = np.arange(np.min(xs), np.max(xs), 0.005)
    binned_color = binned_statistic(xs, ys, statistic='median',
                                    bins=bins).statistic

    fin = np.where((np.isfinite(bins[:-1]) == True)
                   & (np.isfinite(binned_color) == True))

    bins = bins[:-1][fin]
    binned_color = binned_color[fin]

    # Interpolate Isochrone
    spline = InterpolatedUnivariateSpline(bins, binned_color, ext=0)
    y_spl = spline(bins)

    # Find the crossing point
    if y0 - spline(x0) > 0:
        # what to do if star is above isochrone in color-color space
        return np.squeeze([-9999.0, -9999.0])

    else:
        # Find roots in difference between the ccline and isochrone
        func = y_spl - ccline(bins, cer, x0, y0)
        func_spl = InterpolatedUnivariateSpline(bins, func, ext=0)
        cross12 = func_spl.roots()
        cross34 = spline(cross12)

        if len(cross12) == 0:
            # If cross12 is empty
            return np.squeeze([-9999.0, -9999.0])

        else:
            # Return Cartesian coordinates of crossing point in color-color space
            return np.squeeze(list(zip(cross12, cross34)))
Exemple #30
0
    def upperlimit(self, printlevel=1):
        """
        Returns the upper limit of the parameter of interest.
        """

        pvalues = self.pvalues()
        poinull = self.poinull
        poivalues = poinull.value
        poiname = poinull.name
        poiparam = poinull.parameter

        bestfitpoi = self.calculator.config.bestfit.params[poiparam]["value"]
        sel = poivalues > bestfitpoi

        if self.CLs:
            k = "cls"
        else:
            k = "clsb"

        values = {}
        if isinstance(self.calculator, AsymptoticCalculator):
            keys = [k]
        else:
            keys = [k, "exp", "exp_p1", "exp_m1", "exp_p2", "exp_m2"]

        for k_ in keys:
            p_ = pvalues[k_]
            pvals = poivalues
            if k_ not in ["exp_m1", "exp_m2"]:
                p_ = p_[sel]
                pvals = pvals[sel]
            p_ = p_ - self.alpha

            s = InterpolatedUnivariateSpline(pvals, p_)
            val = s.roots()

            if len(val) > 0:
                poiul = val[0]
            else:
                poiul = None
            if k_ == k:
                k_ = "observed"

            values[k_] = poiul

        if isinstance(self.calculator, AsymptoticCalculator):
            poiul = POI(poiparam, poiul)
            exp_poi = self.calculator.expected_poi
            sigmas = [0.0, 1.0, 2.0, -1.0, -2.0]
            kwargs = dict(poinull=poiul,
                          poialt=self.poialt,
                          nsigma=sigmas,
                          alpha=self.alpha,
                          CLs=self.CLs)

            results = exp_poi(**kwargs)
            keys = ["exp", "exp_p1", "exp_p2", "exp_m1", "exp_m2"]

            for r, k_ in zip(results, keys):
                values[k_] = r

        if printlevel > 0:

            msg = "\nObserved upper limit: {0} = {1}"
            print(msg.format(poiname, values["observed"]))
            msg = "Expected upper limit: {0} = {1}"
            print(msg.format(poiname, values["exp"]))
            msg = "Expected upper limit +1 sigma: {0} = {1}"
            print(msg.format(poiname, values["exp_p1"]))
            msg = "Expected upper limit -1 sigma: {0} = {1}"
            print(msg.format(poiname, values["exp_m1"]))
            msg = "Expected upper limit +2 sigma: {0} = {1}"
            print(msg.format(poiname, values["exp_p2"]))
            msg = "Expected upper limit -2 sigma: {0} = {1}"
            print(msg.format(poiname, values["exp_m2"]))

        return values
def get_half_energy(p_spectrum, f, idx, prev_idx, next_idx):
    a_spectrum = np.sqrt(p_spectrum)
    p_value = a_spectrum[idx]
    q_value = p_value / 2
    ius = InterpolatedUnivariateSpline(f, a_spectrum - q_value)
    p_ius = InterpolatedUnivariateSpline(f, p_spectrum)
    roots = ius.roots()
    if len(roots) == 0:
        l_limit = find_minima(p_spectrum, f, prev_idx, idx, idx)
        r_limit = find_minima(p_spectrum, f, idx, next_idx, idx)
    elif len(roots) == 1:
        #check the root if it lies on the left side or the right side
        if roots[0] < f[prev_idx]:
            l_limit = find_minima(p_spectrum, f, prev_idx, idx, idx)
            r_limit = find_minima(p_spectrum, f, idx, next_idx, idx)
        elif roots[0] >= f[prev_idx] and roots[0] < f[idx]:
            l_limit = roots[0]
            #find minina on the right side
            r_limit = find_minima(p_spectrum, f, idx, next_idx, idx)
        elif roots[0] >= f[idx] and roots[0] <= f[next_idx]:
            r_limit = roots[0]
            l_limit = find_minima(p_spectrum, f, prev_idx, idx, idx)
        else:
            l_limit = find_minima(p_spectrum, f, prev_idx, idx, idx)
            r_limit = find_minima(p_spectrum, f, idx, next_idx, idx)
    elif len(roots) >= 2:
        #find left-closest root
        t = [(f[idx] - root, root) for root in roots if root < f[idx]]
        if len(t) == 0:
            l_limit = find_minima(p_spectrum, f, prev_idx, idx, idx)
        else:
            (d, l_limit) = min(t)
            if l_limit <= f[prev_idx]:
                l_limit = find_minima(p_spectrum, f, prev_idx, idx, idx)

        #find right-closest root
        t = [(root - f[idx], root) for root in roots if root > f[idx]]
        if len(t) == 0:
            r_limit = find_minima(p_spectrum, f, idx, next_idx, idx)
        else:
            d, r_limit = min(t)
            if r_limit >= f[next_idx]:
                r_limit = find_minima(p_spectrum, f, idx, next_idx, idx)
        '''diff = np.array([abs(root - f[idx]) for root in roots])
        sorted_indices = np.argsort(diff)
        i1,i2 = sorted_indices[0],sorted_indices[1]
        if f[i1] >= f[i2]:
            r_limit = roots[i1]
            l_limit = roots[i2]
        else:
            r_limit = roots[i2]
            l_limit = roots[i1]'''

    assert r_limit > l_limit
    if r_limit is None:
        print "r_limit is None"
        sys.exit()
    if l_limit is None:
        print "l_limit is None"
        sys.exit()

    num = int((r_limit - l_limit) *
              StepStrideFrequencyModuleConstants.sample_points /
              (Constants.sampling_frequency / 2))
    x = np.linspace(l_limit, r_limit, num=num)
    return np.trapz(p_ius(x), x)
Exemple #32
0
    U = get_vec(res_AF, 'U')
    
    m_AF = get_vec(res_AF, 'm_AF')
    chi_AF = get_vec(res_AF, 'chi')
    
    assert( np.array_equal(np.abs(m_AF) < 1e-6, chi_AF.real > 0.) ), \
        "Error: The AF susceptibility and order parameter do not agree."

    m_FM = get_vec(res_FM, 'm_FM')
    chi_FM = get_vec(res_FM, 'chi')
    
    assert( np.array_equal(np.abs(m_FM) < 1e-6, chi_FM.real > 0.) ), \
        "Error: The AF susceptibility and order parameter do not agree."

    spl_chi_AF = InterpolatedUnivariateSpline(U[::-1], 1./chi_AF[::-1])
    U_AF = spl_chi_AF.roots()[0]
    print 'U_AF =', U_AF

    spl_chi_FM = InterpolatedUnivariateSpline(U[::-1], 1./chi_FM[::-1])
    U_FM = spl_chi_FM.roots()[0]
    print 'U_FM =', U_FM

    # -- Compare divergencies of chi with the
    
    chi_m = get_vec(res_FM, 'chi_m')
    
    e_AF = chi_m[:, -1] # AF is triply degenerate [spin-SU(2)]
    e_FM = chi_m[:, -4] # FM is the 4th eigen mode

    spl_e_AF = InterpolatedUnivariateSpline(U[::-1], 1./e_AF[::-1])
    U_AF_ref = spl_e_AF.roots()[0]
    def generate_interpolators(self, tablefile):
        """Generates the interpolators from the full hdf5 file.
        """
        f = h5py.File(tablefile, 'r')
        self.ye_grid = f['ye'][:]
        self.rho_grid = f['logrho'][:] + np.log10(self.scaling['rho'])

        self.energy_shift = f['energy_shift'][0] * self.scaling['eps']

        rho_grid, ye_grid = np.meshgrid(self.rho_grid, self.ye_grid)
        pres_values = f['logpress'][:, 0, :] + np.log10(self.scaling['pres'])
        munu_values = f['munu'][:, 0, :]  # *          self.scaling['energy']
        energy_values = f['logenergy'][:, 0, :] + np.log10(self.scaling['eps'])
        f.close()

        self.ye_bounds = (np.min(self.ye_grid), np.max(self.ye_grid))
        self.rho_bounds = (np.min(self.rho_grid), np.max(self.rho_grid))
        self.pres_bounds = (np.min(pres_values), np.max(pres_values))

        self.energy_arr = np.zeros_like(self.rho_grid)
        self.pres_arr = np.zeros_like(self.rho_grid)
        self.ye_arr = np.zeros_like(self.rho_grid)

        prev_root = 0

        # for each rho, extract the values given ye such that munu = 0
        for i, rho in enumerate(self.rho_grid):
            munu_func = InterpolatedUnivariateSpline(self.ye_grid,
                                                     munu_values[:, i])
            pres_func = interp1d(self.ye_grid, pres_values[:, i])
            energy_func = interp1d(self.ye_grid, energy_values[:, i])

            ye_roots = munu_func.roots()

            if len(ye_roots) > 1:
                # in case several roots, we pick the closest one
                import warnings
                warnings.warn(
                    'Error, more than one root in munu! Using closest to previous'
                )
                ye_root = ye_roots[np.argmin(
                    np.abs(np.array(ye_roots) - prev_root))]
            elif len(ye_roots) == 0:
                # in case of no roots, we chose the previous value
                ye_root = prev_root
            else:
                ye_root = ye_roots[0]

            prev_root = ye_root

            self.ye_arr[i] = ye_root
            self.pres_arr[i] = pres_func(ye_root)
            self.energy_arr[i] = energy_func(ye_root)

        # generate interpolators
        self.rho_interp = interp1d(self.pres_arr,
                                   self.rho_grid,
                                   fill_value='extrapolate')
        self.eps_interp = interp1d(self.rho_grid,
                                   self.energy_arr,
                                   fill_value='extrapolate')
        self.pres_interp = interp1d(self.rho_grid,
                                    self.pres_arr,
                                    fill_value='extrapolate')
        self.ye_interp = interp1d(self.rho_grid,
                                  self.ye_arr,
                                  fill_value='extrapolate')