Пример #1
0
def rmnGreen_Taylor_Mmn_vec(n, k, R, rmnRgM, rnImM, rmnvecM):
    """
    act on wave with radial representation Cpol(kr) by spherical Green's function
    this is for Arnoldi process with the regular M waves
    the leading asymptotice for vecM is r^n
    so rmnv_vecM stores Taylor series representation of (kr)^(-n) * vecM
    rmnRgM stores (kr)^(-n) * RgM, rnImM stores (kr)^(n+1) * ImM
    """

    kR = mp.mpf(k * R)
    Mfact_prefactpow, Mfact = rmnMpol_dot(2 * n, rmnRgM, rmnvecM)
    Mfact = po.Polynomial(Mfact)

    RgMfact_intgd = rnImM * rmnvecM
    RgMfact_intgd = [0] + RgMfact_intgd.coef.tolist()
    RgMfact = po.polyint(RgMfact_intgd, lbnd=kR)
    RgMfact = po.Polynomial(RgMfact)

    ###first add on Asym(G) part
    MfactkR = kR**Mfact_prefactpow * po.polyval(kR, Mfact.coef)
    newrmnvecM = 1j * MfactkR * rmnRgM
    #newimag_rmnv_vecM = MfactkR * rmnRgM
    ###then deal with (kr)^(n+2*vecnum+2) part###
    newrmnvecM = newrmnvecM - rnImM * Mfact * po.Polynomial(
        [0, 0, 1]) + rmnRgM * RgMfact
    #return newreal_rmnv_vecM, newimag_rmnv_vecM #return the real and imaginary part separately
    return newrmnvecM
Пример #2
0
def test_pseudopoly_eval(r, rseed=42):
    rand = np.random.RandomState(rseed)
    x = rand.rand(10)
    p = rand.randint(-5, 5, 3)
    q = rand.randint(-5, 5, 2)
    rfac_p = (1 - x**2)**r
    rfac_q = (1 - x**2)**(r + 0.5)

    poly_p = pol.Polynomial(p)
    poly_q = pol.Polynomial(q)

    # empty
    poly = PseudoPolynomial(r=r)
    assert_allclose(poly(x), 0)

    # p only
    poly = PseudoPolynomial(p=p, r=r)
    assert_allclose(poly(x), rfac_p * poly_p(x))

    # q only
    poly = PseudoPolynomial(q=q, r=r)
    assert_allclose(poly(x), rfac_q * poly_q(x))

    # p and q
    poly = PseudoPolynomial(p=p, q=q, r=r)
    assert_allclose(poly(x), rfac_p * poly_p(x) + rfac_q * poly_q(x))
Пример #3
0
def B_1(N_1, z_k):
    r_k = z_k
    ret_value = poly.Polynomial([1])
    for k in range(1, N_1 + 1):
        ret_value *= (poly.Polynomial([-r_k[k - 1], 1])) / np.sqrt(
            np.abs(r_k[k - 1]))
    return ret_value
Пример #4
0
def B_3(N_3, z_k):
    ret_value = poly.Polynomial([1])
    for k in range(1, N_3 + 1):
        ret_value *= (
            poly.Polynomial([np.abs(z_k[k - 1])**2, -2 * z_k[k - 1].real, 1]) /
            np.abs(z_k[k - 1]))
    return ret_value
Пример #5
0
def plot_spine_debug(pod, name):
    xs = [s.position.x for s in pod.slices]
    ys = [s.position.y for s in pod.slices]
    zs = [s.position.z for s in pod.slices]

    x_ffit = poly.Polynomial(pod.spine[0])
    y_ffit = poly.Polynomial(pod.spine[1])
    x_new = np.linspace(zs[0], zs[-1])

    fig = plt.figure(figsize=[1, 4.8])
    ax = fig.add_subplot(111, projection="3d")
    ax.plot(x_ffit(x_new), y_ffit(x_new), x_new)
    ax.plot(xs, ys, zs, linewidth=0.5)
    ax.plot(
        [s.position.x for s in pod.seeds],
        [s.position.y for s in pod.seeds],
        [s.position.z for s in pod.seeds],
        ms=3,
        linestyle="",
        markerfacecolor="None",
        markeredgecolor="green",
        alpha=0.6,
        marker="o",
    )

    ax.view_init(10, 0)
    phi = np.linspace(0, 2 * np.pi, num=200)

    def update(phi):
        ax.view_init(10, phi * 180.0 / np.pi)

    ani = matplotlib.animation.FuncAnimation(fig, update, frames=phi)
    ani.save("plot_{}.gif".format(name), fps=18, dpi=196, writer="imagemagick")
Пример #6
0
def linFromPZ(poles=[], zeros=[], gain=1.0, wgain=0, ingain=None):
    """
    @linFromPZ
    linFromPZ(poles,zeros,gain,ingain)
    Creates a system from the list of poles and zeros

    Parameters:
      poles : List of poles
      zeros : List of zeros 

    Gain can be defined as:
      gain : Gain defined as the quotient of first num/den coef.
     wgain : Frequency where gain is defined 
     igain : Gain defined at infinite freq. in high pass 

    Returns a linblk object 
    """
    # Create new block
    s = linblk()
    s.den = P.Polynomial(P.polyfromroots(poles))
    s.num = P.Polynomial(P.polyfromroots(zeros))
    # Add gain
    if ingain == None:
        #curr = s.gain()
        curr = np.abs(s.eval(1j * wgain))
        s.num = s.num * gain / curr
    else:
        curr = s.num.coef[-1] / s.den.coef[-1]
        s.num = s.num * gain / curr
    return s
Пример #7
0
 def fit(self, xs, ys, ts=None):
     assert len(xs) == len(ys)
     if ts is None:
         ts = np.arange(len(xs))
     coefs_x = poly.polyfit(ts, xs, self.degree)
     coefs_y = poly.polyfit(ts, ys, self.degree)
     self.poly_x = poly.Polynomial(coefs_x)
     self.poly_y = poly.Polynomial(coefs_y)
Пример #8
0
 def set_coeff(self, new_coeff, index=None):
     # assume new coeff is just a new set of coefficients
     if index is None:
         self.coeffs = new_coeff
         self.degree = len(self.coeffs) - 1
         self.polynomial = polynomial.Polynomial(new_coeff)
     else:
         self.coeffs[index] = new_coeff
         self.polynomial = polynomial.Polynomial(self.coeffs)
Пример #9
0
 def __init__(self, num=[1.0], den=[1.0]):
     """
     linblk Class constructor
     A new object can be created with:
     >> l1 = linblk()               # H(s) = 1 block
     >> l2 = linblk([1],[1,1/p1])   # H(s) = 1 / ( 1 + s/p1 )
     """
     self.num = P.Polynomial(num)
     self.den = P.Polynomial(den)
Пример #10
0
    def fit(self):
        xs = [s.position.x for s in self.slices]
        ys = [s.position.y for s in self.slices]
        zs = [s.position.z for s in self.slices]

        x_params = poly.polyfit(zs, xs, 3)
        y_params = poly.polyfit(zs, ys, 3)

        self.spine = (poly.Polynomial(x_params), poly.Polynomial(y_params))
Пример #11
0
 def test_divmod(self):
     tquo = poly.Polynomial([1])
     trem = poly.Polynomial([2])
     quo, rem = divmod(self.p5, self.p1)
     assert_(quo == tquo and rem == trem)
     quo, rem = divmod(self.p5, [1, 2, 3])
     assert_(quo == tquo and rem == trem)
     quo, rem = divmod([3, 2, 3], self.p1)
     assert_(quo == tquo and rem == trem)
Пример #12
0
    def resample(self, trajs, poly_degree):
        """

        :param trajs: list of demos
        :param poly_degree: degree of polynomal to smooth
        :return:
        """

        t = []
        alpha = 1.0
        demos = []

        # DWT distance function
        manhattan_distance = lambda x, y: np.abs(x - y)

        idx = np.argmax([l.shape[0] for l in trajs])
        # get the decay term
        t.append(1.0)  #
        for i in range(1, len(trajs[idx])):
            t.append(t[i - 1] - alpha * t[i - 1] *
                     0.01)  # Update of decay term (ds/dt=-alpha s) )
        t = np.array(t)

        # Smooth the data
        coefs = poly.polyfit(t, trajs[idx], 20)
        ffit = poly.Polynomial(coefs)  # instead of np.poly1d
        x_fit = ffit(t)
        data = []

        # scale all the data using DTW
        for ii, y in enumerate(trajs):
            dtw_data = {}
            d, cost_matrix, acc_cost_matrix, path = dtw(
                trajs[idx], y, dist=manhattan_distance)
            # d, cost_matrix, acc_cost_matrix, path = dtw(x_fit, y, dist=manhattan_distance)
            dtw_data["cost"] = d
            dtw_data["cost_matrix"] = cost_matrix
            dtw_data["acc_cost_matrix"] = acc_cost_matrix
            dtw_data["path"] = path
            data.append(dtw_data)
            #data_warp = [y[path[1]][:x_fit.shape[0]]]
            data_warp = [y[path[1]]]
            data_warp_rsp = signal.resample(
                data_warp[0],
                x_fit.shape[0])  # resample dtw output 188 points to 118 points
            #data_warp = [y[:][:x_fit.shape[0]]]
            #coefs = poly.polyfit(t, data_warp[0], 20)
            coefs = poly.polyfit(t, data_warp_rsp, 20)
            ffit = poly.Polynomial(coefs)  # instead of np.poly1d
            y_fit = ffit(t)
            # y_fit = data_warp[0]
            y_fit = data_warp_rsp
            temp = [[np.array(ele)] for ele in y_fit.tolist()]
            temp = np.array(temp)
            demos.append(temp)
        return demos, data
    def eval(self, x):
        """Evaluate the polynomial at the given value"""
        p, q = pol.Polynomial(self.p), pol.Polynomial(self.q)

        lmx2 = 1 - np.power(x, 2)

        num = p(x) + np.sqrt(lmx2) * q(x)
        denom = lmx2 ** self.r

        return num * denom
Пример #14
0
    def __init__(self, xs=None, ys=None, ts=None, degree=None):
        if degree is None:
            self.degree = 1
        else:
            self.degree = degree

        if xs is None and ys is None:
            self.poly_x = poly.Polynomial(np.zeros((self.degree + 1)))
            self.poly_y = poly.Polynomial(np.zeros((self.degree + 1)))
        else:
            self.fit(xs, ys, ts)
Пример #15
0
def rmnGreen_Taylor_Nmn_vec(n, k, R, rmnRgN_Bpol, rmnRgN_Ppol, rnImN_Bpol,
                            rnImN_Ppol, rmnvecBpol, rmnvecPpol):
    """
    act on the wave with radial representation Bpol(kr), Ppol(kr) by the spherical Green's fcn
    central subroutine for Arnoldi iteration starting from RgN
    rmnRgN_Bpol, rmnRgN_Ppol stores Taylor series representation of (kr)^{-(n-1)}*RgN(kr) with np polynomials
    rnImN_Bpol, rnImN_Ppol stores Taylor series representation of (kr)^{n+2} * Im{N(kr)}
    the real part of N(kr) is just RgN(kr)
    rmnvecBpol, rmnvecPpol store Taylor series representations of (kr)^{-(n-1)}*vec(kr), where vec is the current Arnoldi iterate
    the prefactors are there to efficiently use the numpy polynomial package,
    avoiding carrying a long list of zeros leading to large polynomials and slow running time
    N has radial dependence with negative powers so the prefactor lets use np polynomials
    just need to divide results after multiplication of N by (kr)^{n+2} 
    """
    kR = mp.mpf(k * R)
    ti = time.time()
    Nfact_prefactpow, Nfact = rmnNpol_dot(2 * n - 2, rmnRgN_Bpol, rmnRgN_Ppol,
                                          rmnvecBpol, rmnvecPpol)
    #Nfact_prefactpow should be 2*n+1
    Nfact = po.Polynomial(Nfact)
    #Nfact = po.Polynomial(1j*Npol_dot(RgN_Bpol,RgN_Ppol, vecBpol,vecPpol))

    RgNfact_intgd = rnImN_Bpol * rmnvecBpol + rnImN_Ppol * rmnvecPpol
    RgNfact_intgd = [0, 0] + RgNfact_intgd.coef.tolist()
    #print('1/r term size',RgNfact_intgd[2]) #check that the 1/r term of integrand is indeed 0 up to floating point error
    #print('r term size',RgNfact_intgd[4])
    RgNfact_intgd = po.Polynomial(
        RgNfact_intgd[3:])  #n+2-(n-1) divide by (kr)^{3} to get true intgd

    #print(time.time()-ti,'in GTNv, 1')
    #    print(len(RgNfact_intgd))
    RgNfact = po.Polynomial(po.polyint(RgNfact_intgd.coef, lbnd=kR))

    #print(time.time()-ti,'in GTNv, 2')

    ######first add on the Asym(G) part
    NfactkR = kR**Nfact_prefactpow * po.polyval(kR, Nfact.coef)
    newrmnBpol = 1j * NfactkR * rmnRgN_Bpol
    newrmnPpol = 1j * NfactkR * rmnRgN_Ppol

    #print(time.time()-ti,'in GTNv, 3')
    ######then add on the Sym(G) part
    newrmnBpol = newrmnBpol - Nfact * rnImN_Bpol
    newrmnPpol = newrmnPpol - Nfact * rnImN_Ppol
    newrmnBpol = newrmnBpol + RgNfact * rmnRgN_Bpol
    newrmnPpol = newrmnPpol + RgNfact * rmnRgN_Ppol - rmnvecPpol  #the subtraction at end is delta fcn contribution
    #print(time.time()-ti,'in GTNv, 4')
    #print(len(newrmnBpol),len(newrmnPpol),len(RgNfact),len(Nfact),len(rmnRgN_Bpol),len(rmnRgN_Ppol),len(rnImN_Bpol), len(rnImN_Ppol))
    return newrmnBpol, newrmnPpol
Пример #16
0
def GetHorizontalSmoothRecords(trackRecs, windowSize):
    """ This method uses the 11 points (for window size = 11) smoothing algorithm """
    midSize = windowSize // 2
    index = 0
    numPoints = len(trackRecs)
    SmoothRecs = [rec for rec in trackRecs]

    while index <= numPoints - windowSize:
        xArray = []
        yArray = []
        for i in range(index, index + windowSize):
            xArray.append(trackRecs[i].x)
            yArray.append(trackRecs[i].y)
        coefs = poly.polyfit(xArray, yArray, 2)
        ffit = poly.Polynomial(coefs)
        SmoothRecs[index + midSize].y = ffit(xArray[midSize])
        if index == 0:
            for j in range(1, midSize):
                SmoothRecs[j].y = ffit(xArray[j])
        if index == numPoints - windowSize:
            for k in range(midSize + 1, len(xArray) - 1):
                SmoothRecs[index + k].y = ffit(xArray[k])
        index +=1
   
    return SmoothRecs
Пример #17
0
def GetVerticalSmoothRecords(trackRecs, windowSize):
    """ This method uses the 11 points (for window size = 11) smoothing algorithm """
    midSize = windowSize // 2
    index = 0
    numPoints = len(trackRecs)
    SmoothedRecs = deepcopy(trackRecs)

    while index <= numPoints - windowSize:
        kpArray = []
        zArray = []
        for i in range(index, index + windowSize):
            kpArray.append(trackRecs[i].kp)
            zArray.append(trackRecs[i].z)
        coefs = poly.polyfit(kpArray, zArray, 2)
        ffit = poly.Polynomial(coefs)
        SmoothedRecs[index + midSize].z = ffit(kpArray[midSize])
        if index == 0:
            for j in range(1, midSize):
                SmoothedRecs[j].z = ffit(kpArray[j])
        if index == numPoints - windowSize:
            for k in range(midSize + 1, len(kpArray) - 1):
                SmoothedRecs[index + k].z = ffit(kpArray[k])
        index +=1
   
    return SmoothedRecs
Пример #18
0
def polycntm(x, y, deg, rtol=1e-3, fullout=False, maxiter=50):
    '''
    Fits a polynomial continuum of degree deg to the data 
    '''
    #Initializing Variables
    p = npp.Polynomial([0] * (deg + 1))
    keepgoing = True
    counter = 0
    datalist, linelist, reslist, gpmslist = [y], [], [], []
    #Iterations
    while keepgoing and counter < maxiter:
        pold, p = p, npp.Polynomial.fit(x, y, deg)
        test_result, test_bool = ct.midpnttest(pold.coef, p.coef, rtol)
        if np.all(test_bool):
            break
        linelist.append(p)
        y, res, params = yupdate(x, y, p)
        datalist.append(y)
        reslist.append(res)
        gpmslist.append(params)
        counter += 1

    #legacy code used to create plots of each iteration of yupdate
    #if counter >= maxiter:
    #   print("Exceeded maximum amount of itinerations")
    #    print(test_result)
    #if fullout:
    #    datalist.__delitem__(len(datalist)-1)
    #    return p, datalist, linelist, reslist, gpmslist
    return p
Пример #19
0
    def poly_lagrange(i, alldata: pd.DataFrame):
        if i < 3 or i > len(alldata):
            logging.warning('"outside fit interval"')
        data = alldata.iloc[i - 3:i + 5, :]
        mid = data.iloc[3, :]
        scale = data.iloc[7, :] - data.iloc[0, :]
        scaled_data = (data - mid) / scale

        polys_svid = {}
        vel_svid = {}
        time_col = scaled_data.iloc[:, 0]
        for dfcol in scaled_data.columns:
            if dfcol != 'UTC Time':
                coefs = (P.Polynomial(
                    lagrange(np.array(time_col),
                             np.array(scaled_data[dfcol]))).coef)[::-1]
                polys_svid[dfcol] = coefs
                vel_svid[dfcol] = P.polyder(coefs)

        return {
            i: {
                'mid': mid,
                'scale': scale,
                'polys_svid': polys_svid,
                'vel_svid': vel_svid
            }
        }
Пример #20
0
def calculate_imitation_metric(file_name):
    angles = get_data()
    demos = [angles["Lhip"], angles["Lknee"], angles["Lankle"]]
    runner = TPGMMRunner.TPGMMRunner(file_name)
    path = runner.run()
    print(path[:,0])


    alpha = 1.0
    manhattan_distance = lambda x, y: abs(x - y)

    costs = []
    for i in range(3):
        imitation = path[:, i]
        T = len(imitation)
        M = len(demos[i])
        metric = 0.0
        t = []
        t.append(1.0)
        for k in range(1, T):
            t.append(t[k - 1] - alpha * t[k - 1] * 0.01)  # Update of decay term (ds/dt=-alpha s) )
        t = np.array(t)

        for m in range(M):
            d, cost_matrix, acc_cost_matrix, path_im = dtw(imitation, demos[i][m], dist=manhattan_distance)
            data_warp = [demos[i][m][path_im[1]][:imitation.shape[0]]]
            coefs = poly.polyfit(t, data_warp[0], 20)
            ffit = poly.Polynomial(coefs)
            y_fit = ffit(t)
            metric += np.sum(abs(y_fit - imitation.flatten()))

        costs.append(metric / (M * T))
        print("cost ")
        print(costs)
    return costs
Пример #21
0
def fitFunc(name, order, func, domain, fixed, inputName):
    (mn, mx) = domain
    x = mn + (mx - mn) * (np.arange(FIT_SAMPLES * 1.0) / (FIT_SAMPLES - 1))
    y = func(x)

    # fit polynomial (with fixed points)
    coefs = polyfitWithFixedPoints(order, x, y, fixed, func(np.array(fixed)))
    fitted = poly.Polynomial(coefs)

    # compute max error
    ex = mn + (mx - mn) * (np.arange(ERR_SAMPLES * 1.0) / (ERR_SAMPLES - 1))
    ey = func(ex)
    err = ey - fitted(ex)
    errmax = np.max(err)

    # print polynomial error and code
    print(f'  order {order}: {-np.log2(errmax):0.4} bits')

    for ndx in range(len(coefs)):
        coef = coefs[ndx]
        if np.abs(coef) < 1e-12:
            coef = 0
        print(f"    const int C{ndx} = {int(coef * (1 << 30))}; // {coef}")

    print(f"    int y = {genQmul(inputName, 1, order)} + C0;")
    print()

    return fitted
Пример #22
0
    def getPixelToWavelength(self, npixels, pxs):
        """
        Return the lookup table pixel number of the CCD -> wavelength observed.
        npixels (1 <= int): number of pixels on the CCD (horizontally), after
          binning.
        pxs (0 < float): pixel size in m (after binning)
        return (list of floats): pixel number -> wavelength in m
        """
        pl = list(self._wlp)
        pl[0] = self.position.value["wavelength"]

        # This polynomial is from m (distance from centre) to m (wavelength),
        # but we need from px (pixel number on spectrum) to m (wavelength). So
        # we need to convert by using the density and quantity of pixels
        # wl = pn(x)
        # x = a + bx' = pn1(x')
        # wl = pn(pn1(x')) = pnc(x')
        # => composition of polynomials
        # with "a" the distance of the centre of the left-most pixel to the
        # centre of the image, and b the density in meters per pixel.
        # distance from the pixel 0 to the centre (in m)
        distance0 = -(npixels - 1) / 2 * pxs
        pnc = self.polycomp(pl, [distance0, pxs])

        npn = polynomial.Polynomial(
            pnc,  # pylint: disable=E1101
            domain=[0, npixels - 1],
            window=[0, npixels - 1])
        return npn.linspace(npixels)[1]
def calculate_imitation_metric_1(demos, imitation):
    M = len(demos)
    T = len(imitation)
    imitation = np.array(imitation)
    metric = 0.0
    paths = []
    t = []
    t.append(1.0)
    alpha = 1.0
    manhattan_distance = lambda x, y: np.abs(x - y)
    for i in range(1, T):
        t.append(
            t[i - 1] -
            alpha * t[i - 1] * 0.01)  # Update of decay term (ds/dt=-alpha s) )
    t = np.array(t)

    for m in range(M):
        d, cost_matrix, acc_cost_matrix, path = dtw(imitation,
                                                    demos[m],
                                                    dist=manhattan_distance)
        data_warp = [demos[m][path[1]][:imitation.shape[0]]]
        coefs = poly.polyfit(t, data_warp[0], 20)
        ffit = poly.Polynomial(coefs)
        y_fit = ffit(t)
        paths.append(y_fit)
        metric += np.sum(np.sqrt(np.power(y_fit - imitation.flatten(), 2)))

    return paths, metric / (M * T)
Пример #24
0
def embed_polynomials_l2(p1, p2, l=1.0, calc_score=False):
    """Find lambda for inclusion p1->p2, i.e., such that p1(t) ~ p2(t/lambda), |t|<l.
    
    Params:
        p1, p2  -- instances of polynomial.Polynomial class
        l       -- defines embedding segment [-l,l]
    """

    # we minimize S(mu) = int_{-l}^l |p1(t)-p2(mu t)|^2 dt
    # S(mu) is a polynomial in mu: sum_{i,j} (a_i - b_i*mu^i)(a_j - b_j*mu^j)int_{l}^l t^{i+j}
    a, b, d = p1.coef, p2.coef, p1.degree()
    assert p2.degree() == d
    s_coef = np.zeros(2 * d + 1)
    for i in range(d + 1):
        for j in range(d + 1):
            # (a_i - b_i*mu^i)(a_j - b_j*mu^j)int_{l}^l t^{i+j}
            # int t^k = t^{k+1)|_{-l}^l = 0 if k+1 is even else 2*l^{k+1}/(k+1)
            if (i + j + 1) % 2 == 0:
                continue
            int_t = 2 * l**(i + j + 1) / (i + j + 1)
            s_coef[0] += int_t * a[i] * a[j]
            s_coef[i] -= int_t * b[i] * a[j]
            s_coef[j] -= int_t * a[i] * b[j]
            s_coef[i + j] += int_t * b[i] * b[j]

    s_poly = polynomial.Polynomial(s_coef)
    min_value, min_mu = minimize_polynomial(s_poly, -1, 1)
    if not calc_score:
        return 1 / min_mu
    if min_value == 0:
        score = 10000
    else:
        score = s_poly(0) / min_value
    return {'lambda': 1 / min_mu, 'score': score}
Пример #25
0
    def __init__(self, information_length: int, polynomial: int):
        log.debug("Create cyclical _coder")

        self.lengthInformation = information_length
        self.lengthAdditional = int(math.log2(polynomial))
        self.lengthTotal = self.lengthInformation + self.lengthAdditional
        self._polynomial = plm.Polynomial(int_to_bit_list(polynomial,
                                                          rev=True))
Пример #26
0
    def clean(self, ratio=1000.0):
        """
        Eliminates poles and zeros that cancel each other
        A pole and a zero are considered equal if their distance
        is lower than 1/ratio its magnitude
           ratio : Ratio to cancel PZ (default = 1000)
        Return a new object   
        """
        gain = self.gain()
        poles = self.poles()
        zeros = self.zeros()

        # Return if there are no poles or zeros
        if len(poles) == 0: return
        if len(zeros) == 0: return

        outPoles = []  # Empty pole list
        for pole in poles:
            outZeros = []  # Empty zero list
            found = False
            for zero in zeros:
                if not found:
                    distance = np.absolute(pole - zero)
                    threshold = (np.absolute(pole) +
                                 np.absolute(zero)) / (2.0 * ratio)
                    if distance > threshold:
                        outZeros.append(zero)
                    else:
                        found = True
                else:
                    outZeros.append(zero)
            if not found:
                outPoles.append(pole)
            zeros = outZeros
        poles = outPoles

        s = linblk()
        s.den = P.Polynomial(P.polyfromroots(poles))
        s.num = P.Polynomial(P.polyfromroots(zeros))

        # Add gain
        # curr = s.num.coef[0]/s.den.coef[0]
        curr = s.gain()
        s.num = s.num * gain / curr

        return s
Пример #27
0
def get_wavelength_per_pixel(da):
    """
    Computes the wavelength for each pixel along the C dimension

    :param da: (model.DataArray of shape C...): the DataArray with metadata
        either MD_WL_POLYNOMIAL or MD_WL_LIST
    :return: (list of float of length C): the wavelength (in m) for each pixel
        in C
    :raises:
        AttributeError: if no metadata is present
        KeyError: if no metadata is available
        ValueError: if the metadata doesn't provide enough information
    """

    if not hasattr(da, 'metadata'):
        raise AttributeError("No metadata found in data array")

    # check dimension of data
    dims = da.metadata.get(model.MD_DIMS, "CTZYX"[-da.ndim:])
    if len(dims) == 3 and dims == "YXC" and da.shape[2] in (3, 4):  # RGB?
        # This is a hack to handle RGB projections of CX (ie, line spectrum)
        # and CT (temporal spectrum) data. In theory the MD_DIMS should be
        # XCR and TCR (where the R is about the RGB channels). However,
        # this is confusing, and the GUI would not know how to display it.
        ci = 1
    else:
        try:
            ci = dims.index("C")  # get index of dimension C
        except ValueError:
            raise ValueError(
                "Dimension 'C' not in dimensions, so skip computing wavelength list."
            )

    # MD_WL_LIST has priority
    if model.MD_WL_LIST in da.metadata:
        wl = da.metadata[model.MD_WL_LIST]

        if len(wl) != da.shape[ci]:
            raise ValueError(
                "Length of wavelength list does not match length of wavelength data."
            )
        return wl
    elif model.MD_WL_POLYNOMIAL in da.metadata:
        pn = da.metadata[model.MD_WL_POLYNOMIAL]
        pn = polynomial.polytrim(pn)
        if len(pn) >= 2:
            npn = polynomial.Polynomial(
                pn,  #pylint: disable=E1101
                domain=[0, da.shape[ci] - 1],
                window=[0, da.shape[ci] - 1])
            ret = npn.linspace(da.shape[ci])[1]
            return ret.tolist()
        else:
            # a polynomial of 0 or 1 value is useless
            raise ValueError("Wavelength polynomial has only %d degree" %
                             len(pn))

    raise KeyError("No MD_WL_* metadata available")
Пример #28
0
def plot_GNmn_image(n, k, R, rmnvecBpol, rmnvecPpol, klim=30, Taylor_tol=1e-4):
    kR = mp.mpf(k * R)
    pow_jndiv, coe_jndiv, pow_djn, coe_djn, pow_yndiv, coe_yndiv, pow_dyn, coe_dyn = get_Taylor_jndiv_djn_yndiv_dyn(
        n, kR, klim, tol=Taylor_tol)
    print(len(pow_jndiv))
    nfac = mp.sqrt(n * (n + 1))
    pow_jndiv = np.array(pow_jndiv)
    coe_jndiv = np.array(coe_jndiv)
    pow_djn = np.array(pow_djn)
    coe_djn = np.array(coe_djn)
    rmnRgN_Bpol = mp.one * np.zeros(pow_jndiv[-1] + 1 - (n - 1))
    rmnRgN_Ppol = mp.one * np.zeros(pow_jndiv[-1] + 1 - (n - 1))
    rmnRgN_Bpol[pow_jndiv - (n - 1)] += coe_jndiv
    rmnRgN_Bpol[pow_djn - (n - 1)] += coe_djn
    rmnRgN_Ppol[pow_jndiv - (n - 1)] += coe_jndiv
    rmnRgN_Ppol *= nfac

    rmnRgN_Bpol = po.Polynomial(rmnRgN_Bpol)
    rmnRgN_Ppol = po.Polynomial(rmnRgN_Ppol)

    rnImN_Bpol = mp.one * np.zeros(pow_yndiv[-1] + 1 + (n + 2),
                                   dtype=np.complex)
    rnImN_Ppol = mp.one * np.zeros(pow_yndiv[-1] + 1 + (n + 2),
                                   dtype=np.complex)
    pow_yndiv = np.array(pow_yndiv)
    pow_dyn = np.array(pow_dyn)
    rnImN_Bpol[(n + 2) + pow_yndiv] += coe_yndiv
    rnImN_Bpol[(n + 2) + pow_dyn] += coe_dyn
    rnImN_Ppol[(n + 2) + pow_yndiv] += coe_yndiv
    rnImN_Ppol *= nfac

    rnImN_Bpol = po.Polynomial(rnImN_Bpol)
    rnImN_Ppol = po.Polynomial(rnImN_Ppol)

    rmnBimage, rmnPimage = rmnGreen_Taylor_Nmn_vec(n, k, R, rmnRgN_Bpol,
                                                   rmnRgN_Ppol, rnImN_Bpol,
                                                   rnImN_Ppol, rmnvecBpol,
                                                   rmnvecPpol)
    print('real part')
    plot_rmnNpol(n, mp_re(rmnBimage.coef), mp_re(rmnPimage.coef), kR * 0.01,
                 kR)

    print('imag part')
    plot_rmnNpol(n, mp_im(rmnBimage.coef), mp_im(rmnPimage.coef), kR * 0.01,
                 kR)
Пример #29
0
def main():
    print("Лабораторная работа №6",
          "Приближенное вычисление интегралов при помощи КФ НАСТ",
          "-----------------------------------------------------",
          sep='\n',
          end='\n\n')

    print(f.__doc__)
    print(w.__doc__)
    print("[a, b] = [{0}, {1}]".format(a, b))

    N = input_value("Введите N: ", value_type=int, check=lambda N: N > 0)
    m = input_value("Введите число шагов m составной КФ: ",
                    value_type=int,
                    check=lambda m: m > 0)
    print()

    J_gauss_ref = gauss_mult(lambda x: f(x) * w(x), a, b, N, m)
    print("J =", J_gauss_ref, end='\n\n')

    mu = [simpson(lambda x: w(x) * (x**k), a, b, 100000) for k in range(2 * N)]
    print("Моменты весовой функции:", mu)

    aval = np.linalg.solve([mu[i:i + N] for i in range(N)],
                           [-x for x in mu[-N:]])
    P = polynomial.Polynomial(aval) + polynomial.Polynomial(
        polynomial.polyx)**N
    print("Ортогональный w_n(x) =", print_polynomial(P))

    xs = P.roots()
    print("Узлы КФ типа Гаусса:", xs)

    W = polynomial.Polynomial([1])
    for x_i in xs:
        W *= polynomial.Polynomial([-x_i, 1])
    W_prime = W.deriv()
    As = [
        gauss_mult(lambda x: w(x) * W(x) / ((x - x_i) * W_prime(x_i)), a, b, N,
                   m) for x_i in xs
    ]

    print("Коэффициенты КФ:", As)

    J_gauss = sum(A * f(x) for x, A in zip(xs, As))
    print("J =", J_gauss)
Пример #30
0
def get_labeled_point(line):
    items = line.strip().split()
    y = items[0]
    x = items[1:]
    # return LabeledPoint(y, x)
    ## this explicitly maps each example to a higher dimensional space
    ## namely the space of a degree 2 polynomial kernel
    poly = npp.Polynomial([float(_) for _ in x])
    return LabeledPoint(y, (poly * poly).coef)