Exemple #1
0
    def get_input_current_smooth_soc_as_x(self, charging_c_rates, mesh_points):
        """
        Helper function to generate a waveform with smoothly varying charging current. Should return a vector
        of current values and vector of corresponding state of charge (soc) values.

        Args:
            charging_c_rates (list): c-rates for each of the charging steps. Each step is assumed to be an equal
                SOC portion of the charge, and the length of the list just needs to be at least 1
            mesh_points (list): soc values for beginning and end of each of the charging windows

        returns
        np.array: array with the current as a function of soc
        np.array: array with the corresponding soc values
        """
        mesh_points_mid = np.copy(mesh_points)

        for indx in range(len(mesh_points) - 1):
            mesh_points_mid[indx] = (mesh_points[indx] +
                                     mesh_points[indx + 1]) / 2

        soc_vector = np.linspace(self.soc_i, self.soc_f, self.soc_points)

        mesh_points_mid = list([self.soc_i]) + list(mesh_points_mid) + list(
            [self.soc_f * 1.01])
        mesh_points_mid = np.array(mesh_points_mid)

        charging_c_rate_start = charging_c_rates[0]
        rates = np.clip([charging_c_rate_start] + charging_c_rates +
                        [charging_c_rates[-1]], self.min_c_rate,
                        self.max_c_rate)

        interpolator = interpolate.PchipInterpolator(mesh_points_mid,
                                                     rates,
                                                     axis=0,
                                                     extrapolate=0)

        charging_c_rate_soc1_end = interpolator.__call__(mesh_points[1])

        charging_c_rate_start = np.max([
            charging_c_rates[0] -
            (charging_c_rate_soc1_end - charging_c_rates[0]),
            charging_c_rates[0]
        ])
        charging_c_rate_start = np.min(
            [self.max_c_rate, charging_c_rate_start])

        rates = np.clip([charging_c_rate_start] + charging_c_rates +
                        [charging_c_rates[-1]], self.min_c_rate,
                        self.max_c_rate)

        interpolator = interpolate.PchipInterpolator(mesh_points_mid,
                                                     rates,
                                                     axis=0,
                                                     extrapolate=0)

        input_current = interpolator.__call__(soc_vector)
        input_current = np.nan_to_num(input_current, copy=False, nan=0)
        input_curent_smooth_soc_as_x = input_current

        return input_curent_smooth_soc_as_x, soc_vector
Exemple #2
0
    def load(self, fpath, **kwargs):
        '''
        Loads and interpolates missing data

        source - data source. Currently only 'etdata' is supported
        interp - whether to interpolate data
        '''

        if not (kwargs.has_key('source')):
            print 'ERROR LOADING'
            return ()

        if kwargs['source'] == 'etdata':
            self.data = np.load(fpath)

        self.maskInterp = np.zeros(len(self.data), dtype=np.bool)
        if kwargs.has_key('interp') & kwargs['interp'] == True:
            r = np.arange(len(self.data))
            mask = np.isnan(self.data['x']) | np.isnan(self.data['y'])
            fx = interp.PchipInterpolator(r[~mask],
                                          self.data[~mask]['x'],
                                          extrapolate=True)
            fy = interp.PchipInterpolator(r[~mask],
                                          self.data[~mask]['y'],
                                          extrapolate=True)
            self.data['x'][mask] = fx(r[mask])
            self.data['y'][mask] = fy(r[mask])
            self.maskInterp = mask
Exemple #3
0
def bdbr(ref, test, yuv_sel):
    ref = np.asarray(ref)
    test = np.asarray(test)

    ref = ref[ref[:, 0].argsort()]
    test = test[test[:, 0].argsort()]

    xa, ya = np.log10(ref[:, 0]), ref[:, yuv_sel]
    xb, yb = np.log10(test[:, 0]), test[:, yuv_sel]

    max_i = len(ya)
    i = 1
    while (i < max_i):
        if ya[i] < ya[i - 1] or yb[i] < yb[i - 1]:
            ya = np.delete(ya, i)
            yb = np.delete(yb, i)
            xa = np.delete(xa, i)
            xb = np.delete(xb, i)
            max_i = len(ya)
        else:
            i += 1

    x_interp = [max(min(xa), min(xb)), min(max(xa), max(xb))]
    y_interp = [max(min(ya), min(yb)), min(max(ya), max(yb))]

    interp_br_a = interpolate.PchipInterpolator(ya, xa)
    interp_br_b = interpolate.PchipInterpolator(yb, xb)

    bdbr_a = integrate.quad(interp_br_a, y_interp[0], y_interp[1])[0]
    bdbr_b = integrate.quad(interp_br_b, y_interp[0], y_interp[1])[0]

    bdbr = (bdbr_b - bdbr_a) / (y_interp[1] - y_interp[0])
    bdbr = (math.pow(10., bdbr) - 1) * 100

    return bdbr
Exemple #4
0
def get_cdf(x, smoothiter=3, window=None, order=1, **kwargs):
    """
    Take a set of points x and find the CDF.
    Use get_cdf_raw, fit and return an interpolating function.
    
    By default we use scipy.interpolate.Akima1DInterpolator
    kwargs are passed to the interpolating function.
    (We do not fit a perfectly interpolating spline right now, because if two points have identical x's,
    you get infinity for the derivative.)
    Note: scipy v1 has a bug in all splines right now that rejects any distribution of points with exactly equal x's.
    
    You can obtain the PDF by taking the first derivative.
    """
    xcdf, ycdf = get_cdf_raw(x)
    # Smooth the CDF
    if window is None:
        window = int(len(xcdf)/100.)
    else:
        window = int(window)
    if window % 2 == 0: window += 1
    F = interpolate.PchipInterpolator(xcdf,ycdf,extrapolate=False)#**kwargs)
    for i in range(smoothiter):
        ycdf = signal.savgol_filter(F(xcdf), window, order)
        F = interpolate.PchipInterpolator(xcdf,ycdf,extrapolate=False)#**kwargs)
    
    #if "ext" not in kwargs:
    #    kwargs["ext"] = 3 #return the boundary value rather than extrapolating
    #F = interpolate.UnivariateSpline(xcdf, ycdf, **kwargs)
    #F = interpolate.Akima1DInterpolator(xcdf,ycdf,**kwargs)
    return F
def get_equidistant_curve(z2, add=0, rate=0.5, high_dens=True):
    def func2(x, rate):
        a = 3.0 / (2 + rate)
        b = a * rate
        return np.where(
            x < 1 / 6, a * x,
            np.where(
                x < 2 / 6,
                b * (x - 1 / 6) + a / 6,
                np.where(
                    x < 4 / 6,
                    a * (x - 2 / 6) + (a + b) / 6,
                    np.where(x < 5 / 6,
                             b * (x - 4 / 6) + (3 * a + b) / 6,
                             a * (x - 5 / 6) + (3 * a + 2 * b) / 6))))

    t, total_len = get_length_rate(z2, output_total_length=True)
    fx = interpolate.PchipInterpolator(np.hstack((t, np.array([1.0]))),
                                       np.real(np.hstack((z2, z2[0]))))
    fy = interpolate.PchipInterpolator(np.hstack((t, np.array([1.0]))),
                                       np.imag(np.hstack((z2, z2[0]))))
    if high_dens:
        equidistant_t = func2(
            np.linspace(0, 1, z2.shape[0] + add + 1)[:z2.shape[0] + add], rate)
    else:
        equidistant_t = np.linspace(0, 1,
                                    z2.shape[0] + add + 1)[:z2.shape[0] + add]
    return fx(equidistant_t) + 1j * fy(equidistant_t)
Exemple #6
0
def bdbr(HEVC, VVC, yuv_sel):
    HEVC = np.asarray(HEVC)
    VVC = np.asarray(VVC)

    HEVC = HEVC[HEVC[:, 0].argsort()]
    VVC = VVC[VVC[:, 0].argsort()]

    xa, ya = np.log10(HEVC[:, 0]), HEVC[:, yuv_sel]
    xb, yb = np.log10(VVC[:, 0]), VVC[:, yuv_sel]

    max_i = len(ya)
    i = 1
    while (i < max_i):
        if ya[i] < ya[i - 1] or yb[i] < yb[i - 1]:
            ya = np.delete(ya, i)
            yb = np.delete(yb, i)
            xa = np.delete(xa, i)
            xb = np.delete(xb, i)
            max_i = len(ya)
        else:
            i += 1

    x_interp = [max(min(xa), min(xb)), min(max(xa), max(xb))]
    y_interp = [max(min(ya), min(yb)), min(max(ya), max(yb))]

    interp_br_a = interpolate.PchipInterpolator(ya, xa)
    interp_br_b = interpolate.PchipInterpolator(yb, xb)

    bdbr_a = integrate.quad(interp_br_a, y_interp[0], y_interp[1])[0]
    bdbr_b = integrate.quad(interp_br_b, y_interp[0], y_interp[1])[0]

    bdbr = (bdbr_b - bdbr_a) / (y_interp[1] - y_interp[0])
    bdbr = (math.pow(10., bdbr) - 1) * 100

    return bdbr
Exemple #7
0
    def map2fd(self, newGeometry=True):

        if newGeometry == True:
            for i in range(self.Nlayers - 1):
                spl = interpolate.PchipInterpolator([p.y for p in self.H[i]],
                                                    [p.z for p in self.H[i]])
                self.Hfd[i + 1, :] = spl(self.Hfd[0])
            for i in range(self.nex):
                for j in range(self.ney):
                    l = 0
                    z = self.Hfd[1, j]
                    for k in range(self.nez):
                        while (k + 0.5) * self.h > z and l < self.Nlayers - 1:
                            l += 1
                            z += self.Hfd[l + 1, j]
                        self.layerID[k, j, i] = l

        # mantle serpentinization
        spl = interpolate.PchipInterpolator([p.y for p in self.H[-1]],
                                            self.serpw)
        serpFDtop = spl(self.Hfd[0])
        z0 = -self.Hfd[1:self.Nlayers, :].sum(axis=0)

        for i in range(self.nex):
            for j in range(self.ney):
                self.serpwFD[:,j,i] = serpFDtop[j] * \
                    np.exp(-abs(self.Zh - z0[j])/self.serpDepth)
Exemple #8
0
def parallel_IG(p,T,W,frog,SpecFund,keep_fundspec=False,max_population=12,NStep=25,parallel=True,
                Type='SHG-FROG'):
    """uses the idea from Opt. Express 27, 2112-2124 (2019)
    starts from a number of initial guesses (IG) and returns the best one
    uses the multi-grid approach
    p is a Pool object"""
    
    TBP=TBP_frog(T,W,frog)
    if TBP*4 < max_population:
        population=int(TBP*4)
    else:
        population=max_population
    
    
    #first step with Nbin/4 multigrid
    (T1,W1,frog1)=multigrig_resize(T,W,frog,4) #resize the FROG
    F1=interpolate.PchipInterpolator(W/2,SpecFund)
    Sf1=F1(W1/2)
    if parallel:
        Out1=np.array(p.starmap(PCGPA_reconstruct_IG,
                            [[T1,W1,frog1,NStep,Sf1,keep_fundspec,Type,[]] for i in range(population)]))
    else:
        Out1=np.array(list(map(PCGPA_reconstruct_IG,
                            [T1]*population,[W1]*population,[frog1]*population,
                            [NStep]*population,[Sf1]*population,
                            [keep_fundspec]*population,[Type]*population,[[]]*population)))
    ind=Out1[:,0].argsort()
    Out1=Out1[ind]
    
    #second step with Nbin/2 multigrid
    In2=Out1[:int(len(Out1)/2)] #take best results from the first step
    for i in range(len(In2)):
        (In2[i][1],In2[i][2])=shift2zerodelay(In2[i][1],In2[i][2])
    (T2,W2,frog2)=multigrig_resize(T,W,frog,2) #resize the FROG
    F2=interpolate.PchipInterpolator(W/2,SpecFund)
    Sf2=F2(W2/2)
    F_pulse=[interpolate.PchipInterpolator(T1,In2[i][1]) for i in range(len(In2))]
    Pulse=np.array([f(T2) for f in F_pulse])
    ind0=np.logical_or(T2<T1[0],T2>T1[-1])
    Pulse[:,ind0]=0
    if parallel:
        Out2=np.array(p.starmap(PCGPA_reconstruct_IG,
                            [[T2,W2,frog2,NStep,Sf2,keep_fundspec,Type,Pulse[i]] 
                            for i in range(len(Pulse))]))
    else:
        Out2=np.array(list(map(PCGPA_reconstruct_IG,
                            [T2]*len(Pulse),[W2]*len(Pulse),[frog2]*len(Pulse),[NStep]*len(Pulse),
                            [Sf2]*len(Pulse),[keep_fundspec]*len(Pulse),[Type]*len(Pulse),
                            Pulse)))
    ind=Out2[:,0].argsort()
    Out2=Out2[ind]
    #fit to the full original time window
    pulse_out=Out2[0][1]
    Fp=interpolate.PchipInterpolator(T2,pulse_out)
    pulse=Fp(T)
    ind0=np.logical_or(T<T2[0],T>T2[-1])
    pulse[ind0]=0
    return pulse
Exemple #9
0
    def get_repaneled_airfoil(self, n_points_per_side=100):
        # Returns a repaneled version of the airfoil with cosine-spaced coordinates on the upper and lower surfaces.
        # Inputs:
        #   # n_points_per_side is the number of points PER SIDE (upper and lower) of the airfoil. 100 is a good number.
        # Notes: The number of points defining the final airfoil will be n_points_per_side*2-1,
        # since one point (the leading edge point) is shared by both the upper and lower surfaces.

        upper_original_coors = self.upper_coordinates(
        )  # Note: includes leading edge point, be careful about duplicates
        lower_original_coors = self.lower_coordinates(
        )  # Note: includes leading edge point, be careful about duplicates

        # Find distances between coordinates, assuming linear interpolation
        upper_distances_between_points = np.sqrt(
            np.power(
                upper_original_coors[:-1, 0] -
                upper_original_coors[1:, 0], 2) +
            np.power(
                upper_original_coors[:-1, 1] - upper_original_coors[1:, 1], 2))
        lower_distances_between_points = np.sqrt(
            np.power(
                lower_original_coors[:-1, 0] -
                lower_original_coors[1:, 0], 2) +
            np.power(
                lower_original_coors[:-1, 1] - lower_original_coors[1:, 1], 2))
        upper_distances_from_TE = np.hstack(
            (0, np.cumsum(upper_distances_between_points)))
        lower_distances_from_LE = np.hstack(
            (0, np.cumsum(lower_distances_between_points)))
        upper_distances_from_TE_normalized = upper_distances_from_TE / upper_distances_from_TE[
            -1]
        lower_distances_from_LE_normalized = lower_distances_from_LE / lower_distances_from_LE[
            -1]

        # Generate a cosine-spaced list of points from 0 to 1
        s = cosspace(n_points=n_points_per_side)

        x_upper_func = sp_interp.PchipInterpolator(
            x=upper_distances_from_TE_normalized, y=upper_original_coors[:, 0])
        y_upper_func = sp_interp.PchipInterpolator(
            x=upper_distances_from_TE_normalized, y=upper_original_coors[:, 1])
        x_lower_func = sp_interp.PchipInterpolator(
            x=lower_distances_from_LE_normalized, y=lower_original_coors[:, 0])
        y_lower_func = sp_interp.PchipInterpolator(
            x=lower_distances_from_LE_normalized, y=lower_original_coors[:, 1])

        x_coors = np.hstack((x_upper_func(s), x_lower_func(s)[1:]))
        y_coors = np.hstack((y_upper_func(s), y_lower_func(s)[1:]))

        coordinates = np.column_stack((x_coors, y_coors))

        # Make a new airfoil with the coordinates
        name = self.name + ", repaneled to " + str(n_points_per_side) + " pts"
        new_airfoil = Airfoil(name=name,
                              coordinates=coordinates,
                              repanel=False)

        return new_airfoil
Exemple #10
0
def interpolation(x_axis,
                  y_axis,
                  x_value,
                  model='chip',
                  method=None,
                  is_function=False):
    methods = [
        'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
        'previous', 'next'
    ]
    # print(type(x_value),type(min(x_axis)))
    models = [
        'akima', 'chip', 'interp1d', 'cubicspline', 'krogh', 'barycentric'
    ]
    # print('x_axis => ',x_axis)

    result = None
    f = None
    if model is None or model == 'interp1d':
        if method in methods:
            f = interpolate.interp1d(x_axis, y_axis, kind=method)
        else:
            f = interpolate.interp1d(x_axis, y_axis, kind='cubic')

    elif model in models:
        if model == 'akima':
            f = interpolate.Akima1DInterpolator(x_axis, y_axis)

        elif model == 'chip':
            f = interpolate.PchipInterpolator(x_axis, y_axis)

        elif model == 'cubicspline':
            f = interpolate.CubicSpline(x_axis, y_axis)

        elif model == 'krogh':
            f = interpolate.KroghInterpolator(x_axis, y_axis)

        elif model == 'barycentric':
            f = interpolate.BarycentricInterpolator(x_axis, y_axis)
    else:
        f = interpolate.PchipInterpolator(x_axis, y_axis)

    if is_function == True:
        return f
    else:
        if not isinstance(x_value, list):
            # if x_value <min(x_axis) or x_value >max(x_axis):
            #    raise Exception('interpolation error: value requested is outside of range')
            #    return result
            try:
                result = float(f(x_value))
            except:
                return result

        else:
            result = list(map(lambda x: float(f(x)), x_value))

        return result
Exemple #11
0
    def spectrum2time(self,
                      set_T=False,
                      timewindow=[],
                      tstep=0,
                      correct2power2=True,
                      slow_custom=False):
        """calculating temporal profile from the given spectrum"""

        if slow_custom:
            """slow but simple and reliable version when just temporal structure
            is wanted (not for iterative algoritms)"""
            T = np.linspace(timewindow[0], timewindow[1],
                            round((timewindow[1] - timewindow[0]) / tstep) -
                            1)  #time vector
            self.T = T
            self.Field_T = fourier_fixedT(self.Field_W, T, self.W)

        else:
            if set_T:
                self.settimewindow(timewindow, tstep, correct2power2)
                dw = 2 * Pi / (self.T[-1] - self.T[0])
                Nw = len(self.T)
                W = np.linspace(-Nw / 2, Nw / 2 - 1, Nw) * dw + self.W0
                Ew = interpolate.PchipInterpolator(self.W, self.Field_W)
                Field_W = np.zeros(Nw) * 1j
                indS = np.logical_and(
                    np.ones(Nw) * W[0] <= W, W <= np.ones(Nw) * W[-1])
                #calculate the new interpolated E in frequency domain; with 0 values outside the interpolation range
                Field_W[indS] = Ew(W[indS])

            else:
                Nw0 = len(self.W)
                if np.log2(Nw0) % 1:
                    Nw = int(
                        2**(np.floor(np.log2(Nw0)) + 1)
                    )  #increase the number of points to the nearest 2**? value
                else:
                    Nw = Nw0
                #interpolate spectrum to even ferquency spacing
                Ew = interpolate.PchipInterpolator(self.W, self.Field_W)
                W = np.linspace(self.W[0], self.W[-1], Nw)
                Field_W = np.zeros(Nw) * 1j
                indS = np.logical_and(
                    np.ones(Nw) * W[0] <= W, W <= np.ones(Nw) * W[-1])
                #calculate the new interpolated E in frequency domain; with 0 values outside the interpolation range
                Field_W[indS] = Ew(W[indS])
                #define corresponding time vector
                Nt = Nw
                dt = 2 * Pi / (W[-1] - W[0])
                T = np.linspace(-Nt / 2, Nt / 2 - 1, Nt) * dt
                self.T = T
                self.T0 = 0

    #        W0=self.W0
    #        T0=self.T0
            self.Field_T = ifftshift(ifft(Field_W)) * np.exp(
                -1j * W[0] * self.T)
Exemple #12
0
def simp_(p, val, m=1):
    nthres = len(val)
    if nthres == 2:
        out = (val[1] - val[0]) * p**m + val[0]
    else:
        p_interp = np.linspace(0, 1, nthres)
        tsimp_re = interpolate.PchipInterpolator(p_interp, val.real)
        tsimp_im = interpolate.PchipInterpolator(p_interp, val.imag)
        out = tsimp_re(p**m) + 1j * tsimp_im(p**m)
    return out
Exemple #13
0
def INTER(t, point):
    #pointは[x,y]のリスト
    x = np.array(point)[:, 0]
    y = np.array(point)[:, 1]
    if len(x) > 2:
        ts = np.linspace(0, 1, len(x))
        in1 = interpolate.PchipInterpolator(ts, x)
        in2 = interpolate.PchipInterpolator(ts, y)
        return ([in1(t), in2(t)])
    else:  #制御点が二つだけの時の例外処理
        return ([x[0] + t * (x[1] - x[0]), y[0] + t * (y[1] - y[0])])
Exemple #14
0
def siftStepPchp(xArray, sigArray):
    """ EMD sifting function  : 
            - Input     -> [ xArray, sigArray ] signal time-history
            - Output    -> [ candidate mode, inf envelope, sup envelope ]
        calculates a candidate Empirical Mode as a point-to-point average of
        sup and inf envelopes - using PCHIP interpolation.
    """
    #
    # signal length
    sigLen = len(sigArray)
    # point-to-point differential
    sigDiff = 0.0 * sigArray
    sigDiff[1:sigLen] = sigArray[1:sigLen] - sigArray[0:sigLen - 1]
    #
    # gradient signature - positive and negative
    grdPls = sigDiff > 0.0
    grdMns = ~grdPls
    #
    # calculate indexes to local sup and inf elements
    #
    # negative and positive gradients
    negGrdId = 1 * grdMns
    posGrdId = 1 * grdPls
    # markers of sup and inf elements
    supMrkFlg = 0 * grdPls
    infMrkFlg = 0 * grdMns
    supMrkFlg[0:sigLen - 1] = posGrdId[0:sigLen - 1] + negGrdId[1:sigLen]
    infMrkFlg[0:sigLen - 1] = negGrdId[0:sigLen - 1] + posGrdId[1:sigLen]
    #
    # inf and sup indexes
    supIdx = supMrkFlg == 2
    infIdx = infMrkFlg == 2
    #
    # extend supIdx and infIdx to extremes
    supIdx[0] = True
    supIdx[sigLen - 1] = True
    infIdx[0] = True
    infIdx[sigLen - 1] = True
    #
    # calculate sup and inf envelopes by cubic spline
    #
    infIntpFcn = intp.PchipInterpolator(xArray[infIdx], sigArray[infIdx])
    supIntpFcn = intp.PchipInterpolator(xArray[supIdx], sigArray[supIdx])
    #
    infEnv = infIntpFcn(xArray)
    supEnv = supIntpFcn(xArray)
    #
    # calculate candidate mode
    cndMode = sigArray - 0.5 * (infEnv + supEnv)
    #
    return [cndMode, infEnv, supEnv]
Exemple #15
0
def Compare_RungeKutta_Hermite(s=set1, n=4, n_step=20):
    # Hermite interpolation
    """
    Here we view our
        x = u
        y = epsilon, eta
        
    in our formulas

    We generate new x_substitutes with "step" increments as our
    interpolation points.
    """
    # Create Runge-Kutta Values to interpolate from
    H, alpha_ett, epsilon_ett, eta_ett, \
           delta_alpha, delta_epsilon, delta_eta, \
           kvot_alpha, kvot_epsilon, kvot_eta, \
           u_print, alpha_print, epsilon_print, eta_print = RungeKutta(set_value = s, N = n)

    # Create interpolation points
    step = n_step
    x = np.arange(step + 1) * (2 * np.pi) / step

    # Interpolation functions
    f_alpha = spint.PchipInterpolator(u_print, alpha_print)
    f_epsilon = spint.PchipInterpolator(u_print, epsilon_print)
    f_eta = spint.PchipInterpolator(u_print, eta_print)

    # Mid point
    R_s, a_s, b_s = s
    xp, yp = klippArket(R_s, a_s, b_s)

    # Plotting
    plt.subplot(221)
    plt.plot(epsilon_print, eta_print, f_epsilon(x), f_eta(x), '--', xp, yp,
             'x')
    plt.title('$\epsilon$ - $\eta$')

    plt.subplot(222)
    plt.plot(u_print, alpha_print, x, f_alpha(x), '--')
    plt.title(r'$\alpha$')

    plt.subplot(223)
    plt.plot(u_print, epsilon_print, x, f_epsilon(x), '--')
    plt.title('$\epsilon$')

    plt.subplot(224)
    plt.plot(u_print, eta_print, x, f_eta(x), '--')
    plt.title('$\eta$')

    plt.suptitle('Compare Runga-Kutta and Hermite')
    plt.show()
Exemple #16
0
    def repanel_current_airfoil(self, n_points_per_side=100):
        """This method returns a repaneled version of the airfoil with cosine-spaced
        coordinates on the upper and lower
        surfaces.

        The number of points defining the final airfoil will be (n_points_per_side *
        2 - 1), since the leading edge
        point is shared by both the upper and lower surfaces.

        :param n_points_per_side: int, optional
            This is the number of points on the upper and lower surfaces. The default
            value is 100.
        :return: None
        """

        # Get the upper and lower surface coordinates. These both contain the leading
        # edge point.
        upper_original_coordinates = self.upper_coordinates()
        lower_original_coordinates = self.lower_coordinates()

        # Generate a cosine-spaced list of points from 0 to 1.
        cosine_spaced_x_values = functions.cosspace(
            n_points=n_points_per_side,
            endpoint=True,
        )

        # Create interpolated functions for the x and y values of the upper and lower
        # surfaces as a function of the
        # chord fractions
        upper_func = sp_interp.PchipInterpolator(
            x=np.flip(upper_original_coordinates[:, 0]),
            y=np.flip(upper_original_coordinates[:, 1]),
        )
        lower_func = sp_interp.PchipInterpolator(
            x=lower_original_coordinates[:, 0],
            y=lower_original_coordinates[:, 1])

        # Find the x and y coordinates of the upper and lower surfaces at each of the
        # cosine-spaced x values.
        x_coordinates = np.hstack(
            (np.flip(cosine_spaced_x_values), cosine_spaced_x_values[1:]))
        y_coordinates = np.hstack((
            upper_func(np.flip(cosine_spaced_x_values)),
            lower_func(cosine_spaced_x_values[1:]),
        ))

        # Stack the coordinates together and return them.
        coordinates = np.column_stack((x_coordinates, y_coordinates))
        self.coordinates = coordinates
def interpolate_from_key_frame(max_loc, traj, obj_time_line):
    #create a time list for key_frame
    ori_time_list = []
    key_frame = []
    key_frame_time = []

    if len(max_loc) != 0:
        if max_loc[0][0] != 0:
            ori_time_list.append(obj_time_line[0])
            key_frame.append(traj[0])
            key_frame_time.append(obj_time_line[0])
    else:
        ori_time_list.append(obj_time_line[0])
        key_frame.append(traj[0])
        key_frame_time.append(obj_time_line[0])
    for item in max_loc:
        ori_time_list.append(obj_time_line[int(item[0])])
        key_frame.append(traj[int(item[0])])
        key_frame_time.append(obj_time_line[int(item[0])])

    ori_time_list.append(obj_time_line[-1])
    key_frame_time.append(obj_time_line[-1])
    key_frame.append(traj[-1])
    #	f = interpolate.interp1d(ori_time_list, key_frame, kind='cubic')
    #	recreated_signal = f(obj_time_line)
    f = interpolate.PchipInterpolator(key_frame_time, key_frame)
    recreated_signal = f(obj_time_line)
    return recreated_signal
Exemple #18
0
 def loadspectralphase(self, FP, xcal='nm', axis=(0, 1)):
     Sp = imp_phase(FP, xcal=xcal, axis=axis)
     if len(self.Field_W) == 0:
         self.Field_W = np.ones(len(Sp)) * 1j
     IntPh = interpolate.PchipInterpolator(Sp[:, 0], Sp[:, 1])
     Ph = IntPh(self.W)
     self.Field_W = self.Field_W * np.exp(1j * Ph)
Exemple #19
0
    def pulseduration(self, method='FWHM', transform_limited=False):
        if transform_limited:
            #for the transform limited option
            Nw0 = len(self.W)
            if np.log2(Nw0) % 1:
                Nw = int(2**(
                    np.floor(np.log2(Nw0)) + 1
                ))  #increase the number of points to the nearest 2**? value
            else:
                Nw = Nw0
            #interpolate spectrum to even ferquency spacing
            Ew = interpolate.PchipInterpolator(self.W, np.abs(
                self.Field_W))  #spectral phase is removed by np.abs
            W = np.linspace(self.W[0], self.W[-1], Nw)
            Field_W = np.zeros(Nw) * 1j
            indS = np.logical_and(
                np.ones(Nw) * W[0] <= W, W <= np.ones(Nw) * W[-1])
            #calculate the new interpolated E in frequency domain; with 0 values outside the interpolation range
            Field_W[indS] = Ew(W[indS])
            #define corresponding time vector
            Nt = Nw
            dt = 2 * Pi / (W[-1] - W[0])
            T = np.linspace(-Nt / 2, Nt / 2 - 1, Nt) * dt
            Field_T = ifftshift(ifft(Field_W) * np.exp(1j * W[0] * T))
            It = np.abs(Field_T)**2
        else:
            It = np.abs(self.Field_T)**2
            T = self.T

        return width(T, It, method)
Exemple #20
0
def plot():
    #x=np.array([1,2,3,4,5,6])
    #y=[0,0.29,0.11,0.27,-0.97,-0.09]
    #x=np.array([1,2,3,4])
    #y=[0,-0.88,-0.46,-0.88]
    x = np.array([1, 2, 3])
    y = [0, 0.14, -0.25]
    global count
    count = len(y)
    #x=np.linspace(0,count,num=count)
    x_new = np.linspace(x.min(), x.max(), num=count * 100)
    #plt.plot(x,y,'o',color='#01545a')
    for i, j in zip(x, y):
        plt.text(i,
                 j - 0.03,
                 '{0:.2f}'.format(j),
                 ha='center',
                 va='bottom',
                 fontsize=16)
    f = interpolate.PchipInterpolator(x, y)  #通过最高点拟合
    y_new = f(x_new)
    plt.plot(x_new, y_new)
    #plt.plot([[0.85,1.85,2.85,3.85,4.85,5.85],[1.15,2.15,3.15,4.15,5.15,6.15]],[[0,0.29,0.11,0.27,-0.97,-0.09],[0,0.29,0.11,0.27,-0.97,-0.09]],color='#01545a',linewidth=4)
    #plt.plot([[0.85,1.85,2.85,3.85],[1.15,2.15,3.15,4.15]],[[0,-0.88,-0.46,-0.88],[0,-0.88,-0.46,-0.88]],color='#01545a',linewidth=4)
    plt.plot([[0.85, 1.85, 2.85], [1.15, 2.15, 3.15]],
             [[0, 0.14, -0.25], [0, 0.14, -0.25]],
             color='#01545a',
             linewidth=4)
Exemple #21
0
def histogram_voodoo(image, num_control_points=3):
    '''
    This function kindly provided by Daniel Eaton from the Paulsson lab.
    It performs an elastic deformation on the image histogram to simulate
    changes in illumination

    Parameters
    ----------
    image : 2D numpy array
        Input image.
    num_control_points : int, optional
        Number of inflection points to use on the histogram conversion curve. 
        The default is 3.

    Returns
    -------
    2D numpy array
        Modified image.

    '''
    control_points = np.linspace(0, 1, num=num_control_points + 2)
    sorted_points = copy.copy(control_points)
    random_points = np.random.uniform(low=0.1,
                                      high=0.9,
                                      size=num_control_points)
    sorted_points[1:-1] = np.sort(random_points)
    mapping = interpolate.PchipInterpolator(control_points, sorted_points)

    return mapping(image)
Exemple #22
0
def _gufunc_pchip_roots_old(x, y, target, out):
    xy = preprocess_nan_func(x, y, out)
    if xy is None:
        out[:] = np.nan
        return
    x, y = xy

    # reshape to [target, ...]
    target = np.reshape(
        target,
        [len(target)] + [
            1,
        ] * y.ndim,
    )
    y = y[np.newaxis, ...]

    interpolator = interpolate.PchipInterpolator(
        x,
        y - target,
        extrapolate=False,
        axis=-1,
    )
    roots = interpolator.roots()
    flattened = roots.ravel()
    for idx, f in enumerate(flattened):
        if f.size > 1:
            warnings.warn(
                "Found multiple roots. Picking the first one. This will depend on the ordering of `dim`",
                UserWarning,
            )
            flattened[idx] = f[0]
    good = flattened.nonzero()[0]
    out[:] = np.where(np.isin(np.arange(flattened.size), good), flattened,
                      np.nan).reshape(roots.shape)
Exemple #23
0
    def __init__(self, fN_mtype, zmnx=(0.,0.), pivots=[0.],
                 param=None, zpivot=2.4, gamma=1.5):
        self.fN_mtype = fN_mtype  # Should probably check the choice

        if fN_mtype == 'Gamma':  # I14 values
            zmnx = (0., 10.)
            param = [ [12., 23., 21., 28.], # Common
                      [1.75828e8, 9.62288e-4],             # Bi values
                      [500, 1.7, 1.2, 4.7, 0.2, 2.7, 4.5], # LAF
                      [1.1, 0.9, 2.0, 1.0, 2.0] ] # DLA
        self.zmnx = zmnx  

        # Pivots
        if pivots == None: self.pivots = np.zeros(2)
        else: self.pivots = pivots
        self.npivot = len(pivots)

        # Param
        if param is None:
            self.param = np.zeros(self.npivot)
        else:
            self.param = param
            #if np.amax(self.pivots) < 99.:
            #    self.pivots.append(99.)
            #    self.param = np.append(self.param,-30.)
            # Init
            if fN_mtype == 'Hspline':
                self.model = scii.PchipInterpolator(self.pivots, self.param)

        # Redshift (needs updating)
        self.zpivot = zpivot
        self.gamma = gamma
Exemple #24
0
    def __init__(self):
        """Initialize a cosmological model and arrays to interpolate
        redshift to comoving distance. Note that H0 = 100 h km/s/Mpc is
        used. For now the cosmological parameters measured by Planck
        (P.A.R. Ade et al., Paper XIII, A&A 594:A13, 2016) are used.
        """
        h = 0.677
        pl15 = cosmology.LambdaCDM(name='pl15',
                                   H0=100 * u.km / (u.Mpc * u.s),
                                   Om0=0.307,
                                   Ob0=0.0486,
                                   Ode0=0.693,
                                   Tcmb0=2.725 * u.K,
                                   Neff=3.05,
                                   m_nu=np.asarray([0., 0., 0.06]) * u.eV)

        z0 = 0.
        z1 = 3.
        nz = int((z1 - z0) / 0.001) + 1
        self.z = np.linspace(z0, z1, nz)
        self.r = np.zeros(nz, dtype=float)
        self.r[1:] = pl15.comoving_distance(self.z[1:])

        # Define an interpolation. Use the 1D cubic monotonic interpolator
        # from scipy.
        self.r_vs_z = interpolate.PchipInterpolator(self.z, self.r)
Exemple #25
0
    def update_parameters(self, parm):
        """ Update parameters (mainly used in the MCMC)

        Updates other things as needed

        Parameters
        ----------
        parm : ndarray
          Parameters for the f(N) model to update to
        """
        if self.mtype == 'Hspline':
            self.param['sply'] = np.array(parm)
            # Need to update the model too
            self.model = scii.PchipInterpolator(self.pivots,
                                                self.param['sply'])
        elif self.mtype == 'Gamma':
            if len(parm) == 4:  # A,beta for LAF and A,beta for DLA
                self.param['LAF']['Aval'] = parm[0]
                self.param['LAF']['beta'] = parm[1]
                self.param['DLA']['Aval'] = parm[2]
                self.param['DLA']['beta'] = parm[3]
            else:
                raise ValueError(
                    'fN/model: Not ready for {:d} parameters'.format(
                        len(parm)))
Exemple #26
0
def matchGrids(data, oldGrid, newGrid, interp_method='pchip'):
    """
    General function for interpolating one grid of hydographic data onto a
    desired grid

    Parameters
    ----------
    data : the data to be gridded onto a new grid
    griddata : the datagrid to interpolate onto

    Returns
    -------
    gridded_data : the data gridded onto chosen grid

    """

    newGrid = np.squeeze(newGrid)
    oldGrid = np.squeeze(oldGrid)

    # find which axis to interpolate along (and which counts the stations)
    data_dims = np.array(data.shape)
    axis_choose = int(np.where(data_dims != len(oldGrid))[0])

    gridded_data = np.empty((len(newGrid), data.shape[axis_choose]))
    # Interpolate vertically through each cast
    for i in range(data.shape[axis_choose]):
        f = interp.PchipInterpolator(oldGrid, data[:, i])
        gridded_data[:, i] = f(newGrid)

    return gridded_data
Exemple #27
0
    def make_graph(self, data, icon):
        x = [0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7]
        y = [data[0]] + data + [data[len(data) - 1]]

        f = interpolate.PchipInterpolator(x, y)
        x_new = np.arange(0, len(y) - 2, 0.01)
        y_new = f(x_new)

        fig = plt.figure(frameon=False)
        fig.set_size_inches(12, 4)
        ax = plt.subplot(111)
        ax.fill_between(x_new, y_new, min(y) - 1)
        ax.set_axis_off()

        buf = BytesIO()
        plt.savefig(buf, format='png', transparent=True)
        buf.seek(0)

        plot = Image.open(buf)
        plot.load()
        buf.close()
        plot = self.png_crop(plot)

        grad = Image.open(f'{self.path}/resources/{icon}_grad.png').convert(
            'RGBA')
        back = Image.new('RGBA', grad.size, (255, 255, 255, 0))

        plot = plot.resize(grad.size, resample=Image.ANTIALIAS)

        back.paste(grad, plot)
        return back
Exemple #28
0
def interpolate_raw_dataset(dataset, orig_raw_dataset):
    """
    Interpolate the downsampled dataset to the original sampling rate

    :param mne.io.RawArray dataset: object holding the downsampled dataset
    :param mne.io.RawArray orig_raw_dataset: object holding the raw dataset with the original sampling rate

    :return: mne.io.RawArray object holding the interpolated dataset
    """

    # obtain the time stamps, data and the info object from the dataset
    ts = dataset.times
    data = dataset.get_data()

    # obtain the original time stamps
    orig_ts = orig_raw_dataset.times

    # perform interpolation
    interpolator = interpolate.PchipInterpolator(ts,
                                                 data,
                                                 axis=1,
                                                 extrapolate=True)
    interpolated_data = interpolator(orig_ts, extrapolate=True)
    info = orig_raw_dataset.info

    # substitute the ECG data with original ECG data
    interpolated_dataset = mne.io.RawArray(interpolated_data,
                                           info,
                                           verbose=False)

    return interpolated_dataset
def gen_interp_branch_points(points, div):
    result = []
    x, y, dist, w = [], [], [], []

    for point in points:
        x.append(point.x)
        y.append(point.y)
        dist.append(math.sqrt(point.x * point.x + point.y * point.y))
        w.append(point.w)

    fx = interpolate.interp1d(dist, x, kind="cubic")
    fy = interpolate.interp1d(dist, y, kind="cubic")
    fw = interpolate.PchipInterpolator(dist, w)

    dist_min = min(dist)
    dist_max = max(dist)
    new_dist = []
    for i in range(0, div + 1):
        dist_i = dist_min + (dist_max - dist_min) * i / float(div)
        if (dist_i > dist_max):
            dist_i = dist_max
        new_dist.append(dist_i)
    new_x = fx(new_dist)
    new_y = fy(new_dist)
    new_w = fw(new_dist)

    for (xi, yi, wi) in zip(new_x, new_y, new_w):
        result.append(BranchPoint(xi, yi, wi, float('nan')))
    return result
Exemple #30
0
 def __init__(self,
              data,
              child,
              name=None,
              interpolator="cubic spline",
              extrapolate=True):
     if data.ndim != 2 or data.shape[1] != 2:
         raise ValueError("""
             data should have exactly two columns (x and y) but has shape {}
             """.format(data.shape))
     elif interpolator == "pchip":
         interpolating_function = interpolate.PchipInterpolator(
             data[:, 0], data[:, 1], extrapolate=extrapolate)
     elif interpolator == "cubic spline":
         interpolating_function = interpolate.CubicSpline(
             data[:, 0], data[:, 1], extrapolate=extrapolate)
     else:
         raise ValueError(
             "interpolator '{}' not recognised".format(interpolator))
     # Set name
     if name is not None:
         name = "interpolating function ({})".format(name)
     else:
         name = "interpolating function"
     super().__init__(interpolating_function,
                      child,
                      name=name,
                      derivative="derivative")
     # Store information as attributes
     self.interpolator = interpolator
     self.extrapolate = extrapolate