Example #1
0
    def __init__(self, part: Particle, net: Network):

        self._pid = part.pid
        self._sid = part.sid
        self._m0 = part.mass[part.first_idx]
        self._v0 = part.volume[part.first_idx]

        self._c0 = np.zeros(net.solution_size)

        for sp, idx in net.species_map.items():
            try:
                self._c0[idx] = part.composition[sp]
            except KeyError:
                print(f"WARNING: can't find {sp} in particle data")
                self._c0[idx] = 0.0

        self.premake("C", "O", "CO", net)
        self.premake("Si", "O", "SiO", net)

        # self._fT = InterpolatedUnivariateSpline(part.times, part.temperatures, k=1)
        # self._fD = InterpolatedUnivariateSpline(part.times, part.densities, k=1)
        # self._fx = InterpolatedUnivariateSpline(part.times, part.position[:,0], k=1)
        # self._fy = InterpolatedUnivariateSpline(part.times, part.position[:,1], k=1)

        self._fT = Akima1DInterpolator(part.times, part.temperatures)
        self._fD = Akima1DInterpolator(part.times, part.densities)
        self._fx = Akima1DInterpolator(part.times, part.position)
Example #2
0
    def __init__(self, d_lam=0.1, detector_altitude_km=3.880):
        self.Earth_radius = 6371.  # km
        self.detector_altitude_km = detector_altitude_km
        self.d_lam = d_lam
        # Initialize US standard atmosphere
        self.h_km = [
            -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40, 50, 60,
            70, 80, 81., 1.e20
        ]
        self.dens_kg_m3 = 0.1 * np.array([
            13.47, 12.25, 11.12, 10.07, 9.093, 8.194, 7.364, 6.601, 5.900,
            5.258, 4.671, 4.135, 1.948, 0.8891, 0.4008, 0.1841, 0.03996,
            0.01027, 0.003097, 0.0008283, 0.0001846, 0., 0.
        ])
        # self.get_density = interp1d(self.h_km, self.dens_kg_m3)
        self.get_density = Akima1DInterpolator(self.h_km, self.dens_kg_m3)

        self.lam_array = np.arange(0., 80., self.d_lam)[::-1]

        self.proton_log10_energy = np.array(
            [14., 15., 16., 17., 18., 19., 20., 21.])
        self.proton_Xmax = np.array(
            [5000., 5800., 6400., 6900., 7600., 8000., 8450.,
             8800.])  # in kg/m^2
        self.get_proton_Xmax = Akima1DInterpolator(self.proton_log10_energy,
                                                   self.proton_Xmax)
Example #3
0
def test_photoz_shift_fill_nan():
    z = np.linspace(0, 2, 500)
    nz = np.exp(-0.5 * (z - 0.5)**2 / 0.25 / 0.25)
    spline = Akima1DInterpolator(z, nz)

    src = DummySource()
    src.z = z
    src.nz = nz
    src.z_ = z.copy()
    src.nz_ = nz.copy()
    src.nz_interp = spline

    delta_z = 0.5
    params = {'delta_z': delta_z}

    sys = PhotoZShiftBias(delta_z='delta_z')
    sys.apply(None, params, src)

    z = np.linspace(0, 2, 500)
    nz = np.exp(-0.5 * (z - 0.5)**2 / 0.25 / 0.25)
    spline = Akima1DInterpolator(z, nz)

    msk = z - 0.5 <= 0
    assert np.all(src.nz_[msk] == 0)
    assert np.all(src.nz_[~msk] != 0)
Example #4
0
    def __init__(self):
        #print 'IMPORTING DETECTOR'
        self.kB = 1.3806488e-17  #Watt / MHz / Kelvin
        self.c = 299.792458  # in m MHz
        self.Z0 = 120. * np.pi  # Ohms
        f = np.load('filter_function_20190115.npz')
        self.filter = f[
            'filter_array']  # made for self.fr_fine = np.arange(30., 80.1, 0.1)
        #self.filter = 1.
        #self.filter[250] = 1.
        #self.filter *= 1.e-8
        #self.filter[250] = 1.
        #self.filter[250]
        '''Antenna zenithal gain pattern'''
        zen = np.array([0., 15., 30., 45., 60., 75., 80., 85., 90.])
        zen_gain = np.array(
            [8.6, 8.03, 7.28, 5.84, 4.00, 0., -2.9, -8.3, -40.])
        self.zen_gain_interp = Akima1DInterpolator(
            zen, zen_gain -
            3.)  # -3 is the conversion from dBic to dBi in linear polarization
        '''Antenna impeance'''
        fr = [24., 34., 44., 54., 64., 74., 84., 94.]
        Z_re = [1.8, 10., 40., 128., 317., 271., 158., 129.]
        Z_im = [-68.5, 12.6, 91.5, 169., 88.2, -80.3, -89.4, -58]

        self.Z_re_interp = Akima1DInterpolator(fr, Z_re)
        self.Z_im_interp = Akima1DInterpolator(fr, Z_im)
        self.Z_in = 100.  # Ohms, the impedance seen by the terminals of the antenna.
        '''Noise'''
        df = 0.1
        self.fr_fine = np.arange(30., 80.1, df)
        '''P_div is the power from the voltage divider'''
        P_div = np.abs(
            self.Z_in)**2 / np.abs(self.Z_in + self.Z_re_interp(self.fr_fine) +
                                   1j * self.Z_im_interp(self.fr_fine))**2
        self.Noise = (4. * (self.kB * 1.e-6) * self.galactic_noise_temp(
            self.fr_fine)) * self.Z_re_interp(self.fr_fine)
        self.Noise *= P_div
        self.Noise *= self.filter
        self.Noise += self.kB * 1.e-6 * 250. * np.real(
            self.Z_in)  # 250. Kelvin internal noise

        self.f_c = 55.  # MHz
        lam_c = self.c / self.f_c

        self.h_eff = 4. * self.Z_re_interp(
            self.fr_fine) / self.Z0 * lam_c**2 / 4. / np.pi
        self.h_eff *= np.abs(self.Z_in)**2 / np.abs(
            self.Z_re_interp(self.fr_fine) +
            1j * self.Z_im_interp(self.fr_fine) + self.Z_in)**2
        self.h_eff *= self.filter
        self.h_eff = np.sqrt(self.h_eff)

        self.h_0 = np.mean(self.h_eff)  # assume flat spectrum for CR pulse
        #self.A_0 = 4. * self.Z_re_interp(self.f_c) / self.Z0 * lam_c**2 / 4. / np.pi
        #self.A_0 *= np.abs(self.Z_in)**2 / np.abs(self.Z_re_interp(self.f_c)+1j*self.Z_im_interp(self.f_c)+self.Z_in)**2

        self.V_rms = np.sqrt(np.sum(self.Noise * df * 1.e6))
Example #5
0
def sdhRvB(data, R, ws1, Bthreshold, range, minmax):
    # Takes data in and does a moving mean with window size ws1
    # -1xBthreshold and B threshold

    B = data.B
    # B, R = rollm(B, R)
    Rmm = movmean(R, ws1)

    x1 = np.where(((B[ws1 - 1:]) > range[0]) & ((B[ws1 - 1:]) < range[1]))
    x2 = np.where((B[ws1 - 1:] < -range[0]) & (B[ws1 - 1:] > -range[1]))
    if minmax.lower() == 'min':
        y1 = np.argmin(Rmm[x1])
        y2 = np.argmin(Rmm[x2])
    elif minmax.lower() == 'max':
        y1 = np.argmax(Rmm[x1])
        y2 = np.argmax(Rmm[x2])
    else:
        print('Need to input min or max!')
        sys.exit(1)
    print(B[ws1 - 1 + y1 + x1[0][0]])
    print(B[ws1 - 1 + y2 + x2[0][0]])
    Boffset = (B[ws1 - 1 + y1 + x1[0][0]] + B[ws1 - 1 + y2 + x2[0][0]]) / 2

    B2 = B[ws1 - 1:] - Boffset

    power = math.ceil(math.log(len(Rmm), 2))
    B_smooth1 = np.linspace(0, Bthreshold, 2**(power + 1))
    B_smooth2 = np.linspace(0, -Bthreshold, 2**(power + 1))
    Bidx = np.where(abs(B2) < Bthreshold)
    B2 = B2[Bidx]
    Rmm = Rmm[Bidx]

    print(B2[-1], B2[-2], B2[0], B2[1])
    # Akima Spline requires values to be finite, real and ascending
    if (B2[-1] > B2[0]):
        Bdiff = np.diff(B2)
        diffidx = np.where(Bdiff < 0)
        #Bdiff = np.append(Bdiff, 0)
        B2 = np.delete(B2, diffidx[0] + 1)
        Rmm = np.delete(Rmm, diffidx[0] + 1)
        b1 = Akima1DInterpolator(B2, Rmm)
    else:

        Bdiff = np.diff(B2)
        diffidx = np.where(Bdiff > 0)
        #Bdiff = np.append(Bdiff, 0)
        B2 = np.delete(B2, diffidx[0] + 1)
        Rmm = np.delete(Rmm, diffidx[0] + 1)
        b1 = Akima1DInterpolator(-B2, Rmm)
    R_smooth1 = b1(B_smooth1)
    R_smooth2 = b1(B_smooth2)
    R_out = (R_smooth1 + R_smooth2) / 2
    return B_smooth1, R_out, B2, Rmm, Boffset
Example #6
0
    def __init__(self, log10_Energy_array):
        #print 'Initializing Xmax_modeler'
        self.log10_Energy_array = log10_Energy_array
        # initiate modeling parameters derived from Conex
        # model names
        self.model = ["qgsjetII04" ,"eposlhc"] 
        # The nuclear masses used to obtain Conex parameters
        self.A_Conex = [1,4,14,28,40,56] # p, He, N, Si, Ca, Fe
        self.A_array = range(1,57)

        # Define 2x6 arrays. The first index is for the model, and the second is for A_Conex.
        self.Offset_A_Conex = np.array([[ 652.6, 660.2, 652.8, 650.7, 646.0, 642.5],
                                        [ 674.3, 687.8, 685.1, 678.2, 673.7, 669.1]])
        self.Offset_B_Conex = np.array([[ 63.1,  60.8,  59.6,  59.3,  59.3,  59.6 ],
                                        [ 63.7,  64.1,  62.8,  63.1,  63.1,  63.3 ]])
        self.Tau_A_Conex    = np.array([[ 27.5,  19.4,  14.7,  12.1,  11.2,  10.3 ],
                                        [ 26.1,  17.2,  11.5,   9.5,   8.6,   7.8 ]])
        self.Tau_B_Conex    = np.array([[ -1.7,  -1.2,  -0.8,  -0.6,  -0.5,  -0.5 ],
                                        [ -1.4,  -1.3,  -0.8,  -0.7,  -0.6,  -0.5 ]])

        foa = Akima1DInterpolator((self.A_Conex), self.Offset_A_Conex, axis=1)
        self.Offset_A = foa((self.A_array))
        fob = Akima1DInterpolator((self.A_Conex), self.Offset_B_Conex, axis=1)
        self.Offset_B = fob((self.A_array))
        fta = Akima1DInterpolator((self.A_Conex), self.Tau_A_Conex, axis=1)
        self.Tau_A = fta((self.A_array))
        ftb = Akima1DInterpolator((self.A_Conex), self.Tau_B_Conex, axis=1)
        self.Tau_B = ftb((self.A_array))
        #print 'self.Offset_A.shape', self.Offset_A.shape
        #print 'self.Offset_A.shape', self.Offset_A.shape
        #print 'self.Offset_B.shape', self.Offset_B.shape
        #print 'self.Tau_A.shape',    self.Tau_A.shape
        #print 'self.Tau_B.shape',    self.Tau_B.shape
        # Create Energy Dependet Parameters
        
        self.Offset_A = np.einsum('ij,k->ijk', self.Offset_A,  np.ones(len(self.log10_Energy_array)))
        self.Offset_B = np.einsum('ij,k->ijk', self.Offset_B,  (self.log10_Energy_array-19.))
        self.Offset = self.Offset_A + self.Offset_B
        
        self.Tau_A = np.einsum('ij,k->ijk', self.Tau_A,  np.ones(len(self.log10_Energy_array)))
        self.Tau_B = np.einsum('ij,k->ijk', self.Tau_B,  (self.log10_Energy_array-19.))
        self.Tau = self.Tau_A + self.Tau_B
        # Extend Grid to all nuclear masses from 1 to 56 by interpolating the Conex results
        
        #print 'self.Offset.shape', self.Offset.shape
        #print 'self.Tau.shape',    self.Tau.shape
        #print len(self.A_array), self.A_array
        
        self.Mean_Matrix = self.Offset + 5.*self.Tau
        self.MeanSquare_Matrix  = 30.*self.Tau**2 + self.Offset**2 + 10.*self.Tau*self.Offset
Example #7
0
 def LoadRadialDistFuncs(self,
                         filename_current,
                         filename_target,
                         spacing=0.005):
     #read in the data
     r, gr = self.GetRadialDistData(filename_current)
     r_tgt, gr_tgt = self.GetRadialDistData(filename_target)
     #sample according to an akima spline fit
     r_lower, r_upper = (max(r[0], r_tgt[0]), min(r[-1], r_tgt[-1]))
     self.r = arange(r_lower, r_upper, spacing)
     akima = Akima(r, gr)
     self.gr = akima.__call__(self.r, nu=0, extrapolate=None)
     akima = Akima(r_tgt, gr_tgt)
     self.gr_tgt = akima.__call__(self.r, nu=0, extrapolate=None)
     return None
Example #8
0
def regenerateCablePhase(f, phase, dF=5. / 512., length=513):
    """
    A cable has a very flat group delay (Tg(w)), so we should, instead of trying to resample it,
    just regenerate the phase entirely of a cable using the measured phase
    
    Also, since I'm doing this for the transfer function most likely, I'm going to set the defaults
    that everything else has:
    time domain: 10GS/S and n=1024
    freq domain: dF = 5/512 and length=513
    """

    #only use the first half for determining the mean, since it gets noisier at the ends
    #    groupDelayMean = np.mean(groupDelay[:len(groupDelay)/2])

    #or do a fit!
    phaseNew = minimizeGroupDelayFromPhase(f, phase)

    #now do a spline on that I guess
    phaseOutInterp = Akima1DInterpolator(f, phaseNew)

    outF = np.arange(length) * dF
    phaseOut = phaseOutInterp(outF)

    #out of range it should be zero I guess
    phaseOut = np.nan_to_num(phaseOut)

    return outF, phaseOut
Example #9
0
def adiabaticramp(J, Bx, dB, Bz_max, dt_steps, dt_steps_bool, g):
    XY = XYMatrix(J)
    B_x = BxMatrix(Bx)

    intervals = int(Bz_max / dB)
    Bz = np.zeros(intervals + 1)
    Bz[0] = Bz_max
    time = np.zeros(intervals + 1)
    time[0] = 0
    thisTime = 0

    for i in range(0, intervals):
        thisBz = Bz_max - dB * (i + 1)
        Bz[i + 1] = thisBz
        dt = g * dB / delta(XY, B_x, thisBz)**2
        thisTime += dt
        time[i + 1] = thisTime

    print('Adiabatic Ramp Time: ', str(time[-1]))
    if dt_steps_bool == 'dt':
        max_t = time[-1] - time[-1] % dt_steps
        time_steps_dt = max_t / dt_steps
        print(time_steps_dt)
        time_grid = np.linspace(0, max_t, int(time_steps_dt))
        dt = dt_steps
    else:
        time_grid = np.linspace(0, time[-1], dt_steps + 1)
        time_steps_dt = time_grid[1] - time_grid[0]
        dt = time_steps_dt

    f = Akima1DInterpolator(time, Bz)
    Bz_grid = f(time_grid)

    return time_grid, Bz_grid, time_steps_dt, dt
Example #10
0
def solint(a, b):
    """
    integral of solar constant from wavelengths a to b in micometers

    This uses scipy functions which will produce different results
    from the IPW equvialents of 'akcoef' and 'splint'
    """

    # Solar data
    data = solar_data()

    wave = data[:, 0]
    val = data[:, 1]

    # calculate splines
    c = Akima1DInterpolator(wave, val)

    with warnings.catch_warnings(record=True) as messages:
        warnings.simplefilter('always', category=IntegrationWarning)
        # Take the integral between the two wavelengths
        intgrl, ierror = quad(c,
                              a,
                              b,
                              epsabs=1.49e-05,
                              epsrel=1.49e-05,
                              limit=200)

        log = logging.getLogger(__name__)
        for warning in messages:
            log.warning(warning.message)

    return intgrl * SOLAR_CONSTANT
Example #11
0
def convertFile(referenceFile, databaseFile, save_file_path):
    #Open reference file and calculate spline function for RT conversion
    if (referenceFile.endswith('.csv') and databaseFile.endswith('.csv')):
        ## Calculate Spline Function
        data = pd.read_csv(referenceFile)

        index = data.iloc[:, 0].values
        ref_retention_time = data.iloc[:, 1].values

        #Start interpolator function
        cs = Akima1DInterpolator(ref_retention_time, index)

        #Open mzML conversion file
        rawFile = pd.read_csv('Compounds.csv')

        ##convert the retention times or retention indices and save output
        newFile = pd.DataFrame({
            'Compounds': rawFile.iloc[:, 0],
            'Converted': cs(rawFile.iloc[:, 1].values)
        })

        print('test')
        newFile.to_csv(save_file_path, index=False)

    else:
        sg.PopupError(
            'Wrong data format. Please select a .csv file for the reference file and a .csv file for the data file.'
        )
Example #12
0
def interpolate(meanVector, type, factor):
    y = meanVector
    y_len = len(y)
    x = np.arange(0, y_len)

    if type == 'akima':
        interpolate = Akima1DInterpolator(x, y)
    elif type == 'cubic':
        interpolate = interp1d(x, y, kind='cubic')
    elif type == 'linear':
        interpolate = interp1d(x, y, kind='linear')
    else:
        interpolate = Akima1DInterpolator(x, y)

    myArray = ''
    mid_factor = factor / 2

    for i in range(factor):
        my_x = np.arange(i, y_len, factor)
        try:
            myArray += interpolate(my_x)
        except:
            myArray = interpolate(my_x)
        np.append(myArray, interpolate(my_x), axis=0)

    my_x = np.arange(mid_factor, y_len, factor)

    if type == 'akima':
        extrapolate = Akima1DInterpolator(my_x, myArray / factor)
    elif type == 'cubic':
        extrapolate = interp1d(my_x, myArray / factor, kind='cubic')
    elif type == 'linear':
        extrapolate = interp1d(my_x, myArray / factor, kind='linear')
    else:
        extrapolate = Akima1DInterpolator(my_x, myArray / factor)

    new_x = np.arange(mid_factor, y_len - mid_factor)
    interpolated = extrapolate(np.arange(mid_factor, y_len - mid_factor))

    # pad front and back with mean vector

    xprime = np.append(np.arange(0, mid_factor), new_x)
    xprime = np.append(xprime, np.arange(max(xprime) + 1, y_len))
    yprime = np.append(y[:mid_factor], interpolated)
    yprime = np.append(yprime, y[-mid_factor:])

    return xprime, yprime
Example #13
0
def integrate_eccentric_curve_appx_one(binary, phases, reduced_orbit_arr,
                                       counterpart_postion_arr, potentials,
                                       crv_labels, curve_fn, **kwargs):
    """
    Function calculates curves for eccentric orbits for selected filters using approximation
    where curve points on the one side of the apsidal line are calculated exactly and the second
    half of the curve points are calculated by mirroring the surface geometries of the first
    half of the points to the other side of the apsidal line. Since those mirrored
    points are not alligned with desired phases, the fluxes for each phase is interpolated.

    :param binary: elisa.binary_system.system.BinarySystem;
    :param phases: numpy.array;
    :param reduced_orbit_arr: numpy.array; base orbital positions
    :param counterpart_postion_arr: numpy.array; orbital positions symmetric to the `base_orbit_arr`
    :param potentials: dict; corrected potentials
    :param crv_labels: list; curve_labels
    :param curve_fn: curve integrator function
    :param kwargs: Dict;
    :**kwargs options**:
        * ** passband ** - Dict[str, elisa.observer.PassbandContainer]
        * ** left_bandwidth ** - float
        * ** right_bandwidth ** - float
        * ** atlas ** - str
    :return: Dict[str, numpy.array];
    """
    orbital_supplements = OrbitalSupplements(body=reduced_orbit_arr,
                                             mirror=counterpart_postion_arr)
    orbital_supplements.sort(by='distance')

    orbital_positions = np.stack(
        (orbital_supplements.body, orbital_supplements.mirror), axis=1)
    fn_args = (binary, potentials, crv_labels, curve_fn)

    stacked_band_curves = manage_observations(
        fn=c_managed.integrate_eccentric_curve_w_orbital_symmetry,
        fn_args=fn_args,
        position=orbital_positions,
        **kwargs)

    # interpolation of the points in the second half of the light curves using splines
    x = np.concatenate(
        (orbital_supplements.body[:, 4], orbital_supplements.mirror[:, 4] % 1))
    sort_idx = np.argsort(x)
    x = x[sort_idx]
    x = np.concatenate((x[-5:] - 1, x, x[:5] + 1))

    band_curves = dict()
    for curve in crv_labels:
        y = np.concatenate(
            (stacked_band_curves[curve][:, 0], stacked_band_curves[curve][:,
                                                                          1]))
        y = y[sort_idx]
        y = np.concatenate((y[-5:], y, y[:5]))

        i = Akima1DInterpolator(x, y)
        f = i(phases)
        band_curves[curve] = f

    return band_curves
Example #14
0
 def log_frequency_spectrum(self):
     """
     ่ฟ”ๅ›žๅฏน ๆ•ฐ้ข‘็Ž‡็ฉบ้—ด๏ผˆlogarithmic frequency space๏ผ‰็š„ๆŒฏๅน…่ฐฑ๏ผˆamplitude spectrum๏ผ‰ใ€‚
     """
     self.fft.input_array[:] = np.multiply(self.audio_mono, self.window)
     amplitudes = np.absolute(self.fft())
     interp = Akima1DInterpolator(self.fft_freqs_in_hertz, amplitudes)
     return np.multiply(interp(self.notespace), self.weights)
Example #15
0
def water_fresh_density(temperature_c: float) -> float:
    r"""Fresh water density.

    cf. https://www.engineeringtoolbox.com/water-density-specific-weight-d_595.html

    """
    t = np.array([0.1,     1.,     4.,    10.,    15.,    20.,    25.,    30.,    35.,    40.])
    d = np.array([999.85, 999.90, 999.97, 999.70, 999.10, 998.21, 997.05, 995.65, 994.03, 992.22])
    return Akima1DInterpolator(t, d)(temperature_c)
Example #16
0
def func_potential():
    """
    Return the potential curve
    :return: Function of intensity: f(t) (0<=t<=1)
    """
    # End of Tree  <--------------------------> Root of Tree
    ys = np.array([1.50, 1.20, 1.00, 0.80, 0.50])  # Potential Factor
    xs = np.linspace(0.0, 1.0, num=len(ys), endpoint=True)
    return Akima1DInterpolator(xs, ys)
Example #17
0
def water_sea_density(temperature_c: float) -> float:
    r"""For a salinity [g/lwl] of 35 g/lwl.

    https://www.engineeringtoolbox.com/sea-water-properties-d_840.html

    """
    t = np.array([0.,   10.,   15.,   20.,   23.,   26.,    30.])
    d = np.array([1028., 1027., 1026., 1025., 1024., 1023.,  1022.])
    return Akima1DInterpolator(t, d)(temperature_c)
Example #18
0
def smoother(data, col1, col2, num1=100, num2=20):
    data = monoData(data, col1)
    target = data[:, col2]
    f1 = interp1d(target, data, axis=0)
    newX1 = np.linspace(target.min(), target.max(), num2)
    data1 = f1(newX1)
    f2 = Akima1DInterpolator(newX1, data1, axis=0)
    newX2 = np.linspace(target.min(), target.max(), num1)
    return f2(newX2)
Example #19
0
def interp(x, y, e, xi, kind, model, **kwargs):
    """
    Interpolates data the wavelength axis X, if X is a numpy array,
    or X.x if X is Spectrum type. This returns a new spectrum rather than
    updating a spectrum in place, however this can be acheived by

    >>> S1 = S1.interp(X)

    Wavelengths outside the range of the original spectrum are filled with
    zeroes.
    """
    if kind == "Akima":
        yi = Akima1DInterpolator(x, y)(xi)
        ei = Akima1DInterpolator(x, e)(xi)
        nan = np.isnan(yi) | np.isnan(ei)
        yi[nan] = 0.
        if not model:
            ei[nan] = 0.
    elif kind == "sinc":
        yi = lanczos(x, y, xi)
        extrap = (xi < x.min()) | (xi > x.max())
        yi[extrap] = 0.
        if not model:
            ei = lanczos(x, np.log(e + 1E-300), xi)
            ei[extrap] = np.inf
    else:
        yi = interp1d(x, y, kind=kind, \
            bounds_error=False, fill_value=0., **kwargs)(xi)
        if not model:
            #If any errors were inf (zero weight) we need to make
            #sure the interpolated range stays inf
            inf = np.isinf(e)
            if np.any(inf):
                ei = interp1d(x[~inf], e[~inf], kind=kind, \
                    bounds_error=False, fill_value=np.inf, **kwargs)(xi)
                inf2 = interp1d(x, inf, kind='nearest', \
                    bounds_error=False, fill_value=0, **kwargs)(xi).astype(bool)
                ei[inf2] = np.inf
            else:
                ei = interp1d(x, e, kind=kind, \
                    bounds_error=False, fill_value=np.inf, **kwargs)(xi)

    ei = 0 if model else np.where(ei < 0, 0, ei)
    return yi, ei
Example #20
0
def pp_fit_1d(x, y, thin=True, rtol=0, atol=1E-06, poly='akima'):
    if thin:
        x, y = thin_series_data(x, y, rtol, atol)

    if poly == 'akima':
        return Akima1DInterpolator(x, y)
    # TODO: implement additional poly fit methods
    else:
        raise ValueError('invalid poly fit method: "%s"' % poly)
    pass
Example #21
0
    def __init__(self, name):
        if name is None:
            raise ValueError("Material type not specified")

        # initialize the class library if it has not already been done
        if Material._library is None:
            path = 'materialLibrary.yml'
            filepath = pkg_resources.resource_filename(__name__, path)
            stream = open(filepath, 'r')
            Material._library = yaml.load(stream, Loader=yaml.FullLoader)
            stream.close()

        # check to see if the name is in the library
        name = name.lower()
        if name not in Material._library.keys():
            raise ValueError("Material not found in the Material Library")

        # initialize the object
        self._name = name
        properties = Material._library.get(self._name)
        self.density = properties.get("density")
        self._atten_energy_bins = np.array(
            properties.get("mass-atten-coff-energy"))
        self._mass_atten_coff = np.array(properties.get("mass-atten-coff"))
        self._en_abs_energy_bins = np.array(
            properties.get("mass-en-abs-coff-energy"))
        self._mass_en_abs_coff = np.array(properties.get("mass-en-abs-coff"))
        self._gp_energy_bins = np.array(properties.get("gp-coff-energy"))
        gp_array = np.array(properties.get("gp-coeff"))
        self._gp_b = gp_array[:, 0]
        self._gp_c = gp_array[:, 1]
        self._gp_a = gp_array[:, 2]
        self._gp_X = gp_array[:, 3]
        self._gp_d = gp_array[:, 4]
        # here we are building interpolators based on the Akima method.
        # For more information on the use of Akima method on G-P coefficients,
        # see https://www.nrc.gov/docs/ML1905/ML19059A414.pdf
        # "QAD-CGGP2 and G33-GP2: Revised Version of QAD-CGGP and G33-GP"
        self._bi = Akima1DInterpolator(self._gp_energy_bins, self._gp_b)
        self._ci = Akima1DInterpolator(self._gp_energy_bins, self._gp_c)
        self._ai = Akima1DInterpolator(self._gp_energy_bins, self._gp_a)
        self._Xi = Akima1DInterpolator(self._gp_energy_bins, self._gp_X)
        self._di = Akima1DInterpolator(self._gp_energy_bins, self._gp_d)
Example #22
0
def water_sea_dynamic_viscosity(temperature_c: float) -> float:
    r"""Dynamic viscosity of sea water (ยต [Ns/m2]).

    https://www.engineeringtoolbox.com/sea-water-properties-d_840.html
    salinity = 35g/lwl

    """
    t = np.array([0.,      5.,     10.,     15.,     20.,     25.,     30.])
    d = np.array([0.00188, 0.00162, 0.00141, 0.00123, 0.00108, 0.00096, 0.00086])
    return Akima1DInterpolator(t, d)(temperature_c)
Example #23
0
def do_interpolate_pad(x0, y0, interpolation_times, extend_data_number):
    #### Padding - add zeros at the end.
    dx = x0[1] - x0[0]
    for i in range(extend_data_number):
        x0 = np.append(x0, x0[-1] + dx )
        y0 = np.append(y0, 0.0)
    #### Interpolation
    x1 = np.linspace(x0[0],x0[-1],interpolation_times*len(x0))    # interpolation_times* means twice the number of points.
    # y1 = interp1d(x0,y0,kind = 'cubic')
    y1 = Akima1DInterpolator(x0,y0 )
    return x1, y1(x1)
Example #24
0
def identify_bad_point(pot, thresh=0.05):
    """ Identifies a single bad point in a torsional potential based on a
        comparison of Akima and cubic spline fits
    """

    vals_conv = pot.keys()
    step_enes = pot.values()

    # Get the sorted angles
    shifted_angles = []
    for idx, angle in enumerate(vals_conv):
        if len(angle) == 1:  # if a tuple, just take the first value
            angle = angle[0]
        if idx == 0:
            start_angle = angle
        angle = angle - start_angle
        if angle > 180:
            angle = angle - 360
        shifted_angles.append(angle)
    shifted_angles = numpy.array(shifted_angles)

    # For methyl rotors, double the threshold
    if len(shifted_angles) == 4:
        thresh *= 2

    # Get the potentials and then sort them according to increasing angle
    step_enes = numpy.array(list(step_enes))
    sorted_idxs = numpy.argsort(shifted_angles)
    sorted_angles = shifted_angles[sorted_idxs]
    sorted_potentials = step_enes[sorted_idxs]

    # Fit cubic and Akima splines
    cub_spline = CubicSpline(sorted_angles, sorted_potentials)
    akima_spline = Akima1DInterpolator(sorted_angles, sorted_potentials)

    # Evaluate the splines on a fine grid to check for ringing
    fine_grid = numpy.arange(min(sorted_angles), max(sorted_angles), 1)
    diff = cub_spline(fine_grid) - akima_spline(fine_grid)
    max_fine_angle = fine_grid[numpy.argmax(diff)]
    max_norm_diff = max(diff) / max(step_enes)  # normalized by max potential

    # Remove the bad point
    bad_angle = None
    print('max norm diff of splines ', max_norm_diff, thresh)
    if max_norm_diff > thresh:
        max_idxs = numpy.argsort(abs(shifted_angles - max_fine_angle))[:2]
        suspect_enes = [step_enes[idx] for idx in max_idxs]
        bad_angle = shifted_angles[max_idxs[numpy.argmax(suspect_enes)]]
        if bad_angle < 0:
            bad_angle += 360  # convert back to original angle
        bad_angle += start_angle

    return bad_angle
Example #25
0
def subtract_sun(spectrum, sun):
    nm = []
    br = []
    interp = Akima1DInterpolator(spectrum["nm"], spectrum["br"])
    for sun_nm, sun_br in zip(sun["nm"], sun["br"]):
        corrected = interp(sun_nm) / sun_br
        if not np.isnan(corrected):
            br.append(corrected)
            nm.append(sun_nm)
    spectrum.update({"nm": nm, "br": br, "sun": False})

    return spectrum
def FindCalDelays():
    times, depths = LoadSpice()
    f_depths = interpolate.interp1d(times, depths)
    event_times = np.load("cAL_event_times.npy")
    event_depths = []
    event_delays = []
    max_cors = []
    #cutoffs = {0:260.0,1:175.0,8:310.0,9:210,16:475.0,17:375.0,24:450.0,25:350.0}
    for i in range(2500, len(t0[:, 0])):  #d.N()):
        print(i)

        if (volt0[i, -1] == 0.0 or volt1[i, -1] == 0.0):
            continue
        t_cal_even = np.arange(t0[i, 0], t0[i, -1] - 1.0, 0.3125)
        f = Akima1DInterpolator(t0[i, :], volt0[i, :])
        this_v0 = f(t_cal_even)

        f = Akima1DInterpolator(t1[i, :], volt1[i, :])
        this_v1 = f(t_cal_even)

        this_v0 = signal.resample(this_v0, len(this_v0) * 10)
        this_v1, t_cal_even = signal.resample(this_v1,
                                              len(this_v1) * 10,
                                              t=t_cal_even)
        #if(np.max(this_v0)<150):
        #    continue
        dt = t_cal_even[1] - t_cal_even[0]

        this_v0[int(cutoffs[ch0] / dt):] = 0.0
        this_v1[int(cutoffs[ch1] / dt):] = 0.0

        cor = signal.correlate(this_v0 / np.std(this_v0),
                               this_v1 / np.std(this_v1)) / len(this_v0)
        max_cors.append(np.max(cor))
        #if(np.max(cor)>0.65):
        this_delay = (np.argmax(cor) - np.size(cor) / 2.) * dt
        event_delays.append(this_delay)
        event_depths.append(f_depths(event_times[i]))

    return (event_delays, event_depths)
def interpolate(meanVector, kind, factor):
    y = meanVector
    y_len = len(y)
    x = np.arange(0,y_len)

    interpolator = {
        'akima': Akima1DInterpolator(x, y),
        'cubic': interp1d(x, y, kind='cubic'),
        'linear': interp1d(x, y, kind='linear')
    }

    interpolate = interpolator[kind]

    mid_factor = factor/2

    interp = [interpolate(np.arange(i,y_len, factor)) for i in range(factor)]
    myArray = reduce(lambda x,y:x+y,interp)

    my_x = np.arange(mid_factor,y_len, factor)

    extrapolator = {
        'akima': Akima1DInterpolator(my_x, myArray/factor),
        'cubic': interp1d(my_x, myArray/factor, kind='cubic'),
        'linear': interp1d(my_x, myArray/factor, kind='linear')
    }

    extrapolate = extrapolator[kind]

    new_x = np.arange(mid_factor,y_len-mid_factor)
    interpolated = extrapolate( np.arange(mid_factor,y_len-mid_factor))

    #wut??
    #pad front and back with mean vector
    xprime = np.append(np.arange(0,mid_factor), new_x)
    xprime = np.append(xprime, np.arange(max(xprime)+1,y_len))
    yprime = np.append(y[:mid_factor], interpolated)
    yprime = np.append(yprime, y[-mid_factor:])

    return yprime
Example #28
0
def redistribute_blade_planform(pfIn, x):

    pfOut = BladePlanformVT()
    pfOut.s = x.copy()

    for name in pfIn.list_vars():
        var = getattr(pfIn, name)
        if not isinstance(var, np.ndarray): continue
        tck = Akima1DInterpolator(pfIn.s, var)
        newvar = tck(x)
        setattr(pfOut, name, newvar)

    return pfOut
Example #29
0
def main():
    '''
	print("Tracking in:")
	print("5")
	time.sleep(1)
	print("4")
	time.sleep(1)
	print("3")
	time.sleep(1)
	print("2")
	'''
    time.sleep(1)
    print("1")
    time.sleep(1)
    print("Start!")

    path = track(5)
    Ax_data = []
    Ay_data = []
    rep = 0
    for entry in path:
        if rep > 0:
            Ax_data.append(abs(float(entry[0])))
            Ay_data.append(abs(float(entry[1])))
            rep += 1
        if rep == 0:
            rep = 1

    x_data = np.array(Ax_data)
    y_data = np.array(Ay_data)

    x_data_smooth = np.linspace(min(x_data), max(x_data), 1000)

    fig, ax = plt.subplots(1, 1)

    spl = UnivariateSpline(x_data, y_data, s=0, k=2)
    y_data_smooth = spl(x_data_smooth)
    ax.plot(x_data_smooth, y_data_smooth, 'b')

    bi = Akima1DInterpolator(x_data, y_data)
    y_data_smooth = bi(x_data_smooth)
    ax.plot(x_data_smooth, y_data_smooth, 'g')

    bi = PchipInterpolator(x_data, y_data)
    y_data_smooth = bi(x_data_smooth)
    ax.plot(x_data_smooth, y_data_smooth, 'k')

    ax.plot(x_data_smooth, y_data_smooth)
    ax.scatter(x_data, y_data)

    plt.show()
Example #30
0
def sdhfft(B, R, ws2, mininvB, maxinvB):

    nanidx = np.isnan(R)
    B = B[~nanidx]
    R = R[~nanidx]
    # print(B)
    # print(R)
    invB = (np.divide(1, B))

    # Sorts 1/B and R together by 1/B
    invB_sorted, R_sorted = zip(*sorted(zip(invB, R)))

    x = np.array(invB_sorted)
    y = np.array(R_sorted)

    dx = np.diff(x)
    dy = np.diff(y)

    dydx = dy / dx

    x_data = x[ws2:]
    y_data = movmean(dydx[:], ws2)

    power = math.ceil(math.log(len(x_data), 2))
    x_data_smooth = np.linspace(mininvB, maxinvB, 2**(power + 1))

    bi = Akima1DInterpolator(x_data, y_data)

    y_data_smooth = bi(x_data_smooth)
    # x_data_smooth = np.pad(x_data_smooth[~np.isnan(y_data_smooth)],
    # [0, 2**(power + 1)], 'constant')
    # y_data_smooth = np.pad(y_data_smooth[~np.isnan(y_data_smooth)],
    # [0, 2**(power + 1)], 'constant')
    # Zero Pad for higher resolution in FFT

    # FFT with different windows
    Rfft1 = sp.fft(y_data_smooth[:])
    Rfft2 = sp.fft(y_data_smooth[:] * blackman(len(y_data_smooth)))
    Rfft3 = sp.fft(y_data_smooth[:] * hamming(len(y_data_smooth)))
    Rfft4 = sp.fft(y_data_smooth[:] * hanning(len(y_data_smooth)))
    fB = (2**(power + 1)) / (maxinvB - mininvB)
    # fB is the 'sampling frequency' in B
    # print(Rfft.shape)
    xfft = np.linspace(x_data_smooth[0], len(x_data_smooth),
                       len(x_data_smooth)) * fB / len(x_data_smooth)
    # print(xfft.shape)
    # xfft2 =np.linspace(0,len(x_data_smooth),
    #                    len(x_data_smooth))*fB/len(x_data_smooth)

    return x_data, y_data, x_data_smooth, y_data_smooth,\
        xfft, Rfft1, Rfft2, Rfft3, Rfft4