예제 #1
0
    def _refine_pass(self, ascending_date, descending_date) -> BasicPassInfo:
        tca_dt = self._find_tca(ascending_date, descending_date)
        elevation = self._elevation_at(tca_dt)
        if elevation > self.max_elevation_gt:
            aos_dt = self._find_aos(tca_dt)
            los_dt = self._find_los(tca_dt)
        else:
            aos_dt = los_dt = None
            return BasicPassInfo(aos_dt, tca_dt, los_dt, elevation)
        # Find visual pass details
        # First, get endpoints of when location is not sunlit
        # Use cubic splines to find sun elevation
        jd0 = sum(julian_date_from_datetime(aos_dt))
        jdf = sum(julian_date_from_datetime(los_dt))
        jd = np.linspace(jd0, jdf, 5)  # use 5 points for spline
        sun_el_fn = lambda j: self.location.sun_elevation_jd(j) + 6
        el = np.array([sun_el_fn(j) for j in jd])
        if np.min(el) > 0:
            # entire pass in sunlit
            return BasicPassInfo(aos_dt, tca_dt, los_dt, elevation, type_=PassType.daylight)

        tol = 1/86400  # one second
        # part of the pass is in darkness. Find new jd0, jdf
        sun_el = CubicSpline(jd, el, bc_type='natural')
        for root in sun_el.roots(extrapolate=False):
            tmp1 = sun_el(root - tol)
            tmp2 = sun_el(root + tol)
            if tmp1 < tmp2:
                # sun elevation is decreasing
                jd0 = root
            else:
                jdf = root
        # Now use jd0 and jdf to find when satellite is illuminated by sun
        jd = np.linspace(jd0, jdf, 5)  # use 10 points for spline
        illum_fn = lambda j: self.satellite.illumination_distance_jd(j) - R_EARTH
        illum_pts = np.array([illum_fn(j) for j in jd])
        if np.max(illum_pts) < 0:
            # entire pass is in shadow
            return BasicPassInfo(aos_dt, tca_dt, los_dt, elevation, type_=PassType.unlit)

        # part of the pass is visible
        illum = CubicSpline(jd, illum_pts, bc_type='natural')
        for root in illum.roots(extrapolate=False):
            tmp1 = illum(root - tol)
            tmp2 = illum(root + tol)
            if tmp1 < tmp2:
                # satellite is going into shadow
                jdf = root
            else:
                # satellite is coming out of shadow
                jd0 = root
        # Set visible start and end points for Pass
        vis_begin_dt = jday2datetime(jd0)
        vis_end_dt = jday2datetime(jdf)
        return BasicPassInfo(
            aos_dt, tca_dt, los_dt, elevation, type_=PassType.visible,
            vis_begin_dt=vis_begin_dt, vis_end_dt=vis_end_dt,
        )
예제 #2
0
파일: lines.py 프로젝트: benstahl92/respext
def FWHM(wavelength, flux, eflux, lambda_m, flux_m, cont):
    '''compute FWHM from normalized feature'''

    fc_m, _, _, e_fc_m = cont(lambda_m) # continuum flux and uncertainty at minimum
    fc, _, _, e_fc = cont(wavelength) # continuum flux and uncertainty

    # half maximum normalized flux occurs is mean of extreme (normalized) flux and continuum flux (normalize = 1)
    hm = np.mean([flux_m / fc_m, 1])

    # solve for intersection points with cubic spline
    results = []
    for factor in [0, eflux, -1*eflux]:
        cs = CubicSpline(wavelength, ((flux + factor) / fc) - hm, extrapolate = False)
        roots = cs.roots()
        if len(roots[roots - lambda_m < 0]) == 0:
            low = np.nan
        else:
            low = roots[roots - lambda_m < 0].max()
        if len(roots[roots - lambda_m > 0]) == 0:
            high = np.nan
        else:
            high = roots[roots - lambda_m > 0].min()
        results.append(high - low)

    fwhm = results[0]
    e_fwhm = np.mean(np.abs([results[1] - fwhm, results[1] - fwhm]))
    if np.isnan(fwhm) or np.isnan(e_fwhm):
        fwhm, e_fwhm = np.nan, np.nan
    return fwhm, e_fwhm
예제 #3
0
def points(x, y, energy_diff, xlim=None, ylim=None):
    eqy = []
    #plt.scatter(x.reshape(-1),y.reshape(-1),c=energy_diff.reshape(-1))
    #plt.colorbar()
    #plt.show()
    test = np.linspace(0, 20, 500)
    if xlim is None:
        xlim = np.array([x.min(), x.max()] * x.shape[0]).reshape(2, -1)
        ylim = np.array([y.min(), y.max()] * y.shape[1]).reshape(2, -1)
    print(xlim.shape)
    print(x.shape[0])
    print(ylim.shape)
    print(y.shape[1])
    for idx, row in enumerate(energy_diff.T):
        #plt.plot(y[:,idx], row)
        #plt.show()
        c = CubicSpline(y[:, idx], row)
        roots = c.roots()
        for root in roots:
            if root > ylim[0][idx] and root <= ylim[1][idx]:
                #plt.plot(test, c(test))
                #plt.title('{}{}'.format(x[0,idx],roots))
                #plt.show()
                eqy.append([x[0, idx], root])
    eqx = []
    test = np.linspace(-3, 0, 100)
    for idx, column in enumerate(energy_diff):
        #plt.plot(x[idx,:], column)
        #plt.show()
        c = CubicSpline(x[idx, :], column)
        roots = c.roots()
        for root in roots:
            if root > xlim[0][idx] and root <= xlim[1][idx]:
                eqx.append([root, y[idx, 0]])
                #plt.plot(test, c(test))
                #plt.title('{}{}'.format(y[idx,0], roots))
                #plt.show()
    return np.array(eqx), np.array(eqy), energy_diff > 0, energy_diff <= 0
예제 #4
0
def get_zperiod(s):
    xz = s[int(s.shape[0] / 2), int(s.shape[1] / 2), :, 0, 0]
    sp_qm = CubicSpline(range(len(xz)), xz)
    roots= np.array(sorted(sp_qm.roots().tolist()))
    roots=roots[np.logical_and(roots>=0,roots<= len(xz))]
    if len(roots)>1:
        dr=np.diff(roots)
        dr=dr[dr>2]
        print(f'{dr = }')
        if len(dr)>0:
            print(f'{100/np.mean(dr) = }')
            return np.mean(dr)
        else:
            return s.shape[2]
    else:
        return s.shape[2]
예제 #5
0
def funkcja(x, y):
    spline = CubicSpline(x, y)

    y_x = np.arange(1.0, 3, 0.01)

    x_root = spline.roots()[1:-1]
    y_root = np.zeros(len(x_root))

    print('y\'(2.1) = ', spline(2.1, 1))
    print('Miejsca zerowe:', x_root)

    plt.plot(y_x, spline(y_x))
    plt.plot(x, y, 'oy')
    plt.plot(x_root, y_root, 'xk')
    plt.grid()
    plt.legend(['dane', 'spline_func_3'], loc='best')
    plt.show()
예제 #6
0
def get_density_profiles(mainpath, desired_list):
    #determine the location of the period
    datalist = []

    path_maindensity = os.path.join(mainpath, 'density.dat')
    data = np.loadtxt(path_maindensity)
    fAmin = np.min(data[:, 1])
    cs = CubicSpline(data[:, 0], data[:, 1] - fAmin)
    x = np.linspace(np.min(data[:, 0]), np.max(data[:, 0]), 1000)
    roots = cs.roots()
    loc = np.where((roots > np.min(data[:, 0]))
                   & (roots < np.max(data[:, 0])))[0]
    domain_min = np.min(roots[loc[1]])
    domain_max = np.max(roots[loc[3]])
    loc = np.where((data[:, 0] > domain_min) & (data[:, 0] < domain_max))[0]
    data_domain = data[loc, :]
    data_domain[:, 0] = data_domain[:, 0] - np.min(data_domain[:, 0])
    cs = CubicSpline(data_domain[:, 0] / np.max(data_domain[:, 0]),
                     data_domain[:, 1])
    integral = 1  #cs.integrate(0,1)
    x = np.linspace(0, 1, 10000)
    y = cs(x) / integral
    datalist.append(np.vstack((x, y)).transpose())
    path_data = os.path.join(mainpath, 'density_chain0.dat')

    all_data = np.loadtxt(path_data)

    loc = np.where((all_data[:, 0] > domain_min)
                   & (all_data[:, 0] < domain_max))[0]
    data = all_data[loc, :]
    data[:, 0] = data[:, 0] - np.min(data[:, 0])
    shape = np.shape(data)
    for i in range(1, shape[1]):

        if i in desired_list:

            cs = CubicSpline(data[:, 0] / np.max(data[:, 0]), data[:, i])
            integral = cs.integrate(0, 1)
            x = np.linspace(0, 1, 10000)
            y = cs(x) / integral
            datalist.append(np.vstack((x, y)).transpose())
    return datalist
예제 #7
0
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import CubicSpline
from scipy.misc import derivative

x = np.array([1, 1.25, 1.5, 1.75, 2., 2.25, 2.5, 2.75, 3.])
y = np.array([
    -0.5403, -0.0104, 0.9423, 0.17445, 1.3073, -0.7718, -2.4986, -0.7903,
    2.7334
])

cubspli = CubicSpline(x, y)  #interpoluje

pierwiastki = cubspli.roots(-2, 5)
for a in pierwiastki:
    print("%12.8f %12.8e" % (a, cubspli(a)))

print('\n', " dla x=2.1 f'(x)= ", (derivative(cubspli, 2.1)))
plt.plot(x, y, 'x')
plt.plot(np.arange(0.8, 3.1, 0.05), cubspli(np.arange(0.8, 3.1, 0.05)), '-')
plt.show()
예제 #8
0
def calc_A(G,
           K,
           m,
           als=np.logspace(9, 1, 1 + 20 * (9 - 1)),
           plot=False,
           useBT=False):
    """
    solve G = K*A for A, where A is normalized to A.sum() ~ 1

    G: binned data with shape (nbin, ntau)
    K: kernel with shape (ntau, nw)
    m: default model function. shape is (nw,)
    als: list of alphas
    plot: loglog plot of chi2 vs. alpha
    """
    # miscellaneous settings
    W_ratio_max = 1e8
    svd_threshold = 1e-12  # drop singular vals if < max singular val * this

    # estimate parameters of multivariate Gaussian distribution from G
    nbin = G.shape[0]
    Gavg = G.mean(0)
    # calculate unitary matrix for diagonalizing covariance matrix
    # sigma2, Uc = np.linalg.eigh(np.cov(G.T) / nbin)
    # Uc = Uc.T
    # W = 1.0/sigma2
    # equivalent to above, using svd
    sigma, Uc = np.linalg.svd(G - Gavg, False)[1:]
    W = (nbin * (nbin - 1)) / (sigma * sigma)
    # cap W in case covariance matrix is nearly singular
    W_cap = W_ratio_max * W.min()
    n_large = np.sum(W.max() > W_cap)
    if W.max() > W_cap:
        print(f"clipping {n_large} W values to W.min()*{W_ratio_max}")
        W[W > W_cap] = W_cap

    # rotate K and Gavg
    Kp = np.dot(Uc, K)
    Gavgp = np.dot(Uc, Gavg)

    # svd of kernel: K = V Sigma U.T
    V, Sigma, U = np.linalg.svd(Kp, False)
    # drop singular values less than threshold
    mask = (Sigma / Sigma.max() >= svd_threshold)
    # pre-calculate some stuff
    U = U.T[:, mask]
    SigmaVT = (V[:, mask] * Sigma[mask]).T
    M = np.dot(SigmaVT * W, SigmaVT.T)
    precalc = (U, SigmaVT, M)

    # if specified alpha
    if np.isscalar(als):
        return calc_A_al(Gavgp, W, Kp, m, als, precalc)[0]

    us = np.zeros((als.shape[0], M.shape[0]))
    chi2s = np.zeros_like(als)
    lnPs = np.zeros_like(als)
    dlnPs = np.zeros_like(als)

    for i, al in enumerate(als):
        us[i], chi2s[i], lnPs[i], dlnPs[i] = calc_A_al(Gavgp, W, Kp, m, al,
                                                       precalc, us[i - 1])[1:]

    order = als.argsort()
    #BT
    fit = CubicSpline(np.log(als[order]), np.log(chi2s[order]))
    k = fit(np.log(als), 2) / (1 + fit(np.log(als), 1)**2)**1.5
    i = k.argmax()
    # A = m * np.exp(np.dot(U, us[i, :]))

    #classic
    fit = CubicSpline(np.log(als[order]), dlnPs[order])
    roots = fit.roots(extrapolate=False)
    if useBT or len(roots) == 0:
        if not useBT:
            print("maximum of P(alpha) outside range. defaulting to BT.")
        al = als[i]
        chi2 = chi2s[i]
        A = m * np.exp(np.dot(U, us[i, :]))
    else:
        al = np.exp(fit.roots(extrapolate=False)[0])
        A, _unused, chi2 = calc_A_al(Gavgp, W, Kp, m, al, precalc)[:3]

    dof = len(W) - n_large
    print(f"alpha={al:.3f}\tchi2/dof={chi2/dof:.3f}\tA.sum()={A.sum():6f}")

    if plot:
        c2lo, c2hi = scipy.stats.chi2.interval(0.95, dof)
        f, ax1 = plt.subplots()
        ax1.plot([als[i], als[i]], [chi2s.min(), chi2s.max()], 'b', lw=1)
        ax1.plot([als.min(), als.max()], [dof, dof], 'k', lw=1)
        ax1.plot([als.min(), als.max()], [c2lo, c2lo], 'k--', lw=1)
        ax1.plot([als.min(), als.max()], [c2hi, c2hi], 'k--', lw=1)
        ax1.plot(als, chi2s, 'b.', ms=3)
        ax1.set_xscale("log")
        ax1.set_yscale("log")
        ax1.set_xlabel(r"$\alpha$")
        ax1.set_ylabel(r"$\chi^2$")
        ax2 = ax1.twinx()
        ax2.plot(als, np.exp(lnPs), 'g.', ms=3)
        ax2.plot([al, al], [0, np.exp(lnPs.max())], 'g', lw=1)
        ax2.set_ylabel(r"$P(\alpha)$")
        plt.show()

    return A
예제 #9
0
from os.path import join
from scipy.interpolate import CubicSpline
import matplotlib.pyplot as plt

#-------------------------------------------------------------------------------
#INPUT

dirbatch = 'results'

fnout = 'thaw_times.csv'

#-------------------------------------------------------------------------------
#MAIN

#read the trials csv
trials = read_csv(join(dirbatch, fntrials), index_col=0)

#find thaw times
trials['t'] = nan
for idx in trials.index:
    t = fromfile(join(dirbatch, str(idx) + '_t'))
    minT = fromfile(join(dirbatch, str(idx) + '_minT'))
    s = CubicSpline(t, minT - 273)
    try:
        trials.at[idx, 't'] = s.roots()[0]
    except IndexError:
        print(idx)

#write to file
trials.to_csv(fnout)
예제 #10
0
def splinesolver(spline, xmin, xmax, y):
    xspace = np.linspace(xmin, xmax, 100)
    yspace = spline(xspace) - y
    cs = CubicSpline(xspace, yspace)
    return cs.roots()[0]