Example #1
0
 def test_polyroots(self):
     assert_almost_equal(poly.polyroots([1]), [])
     assert_almost_equal(poly.polyroots([1, 2]), [-.5])
     for i in range(2, 5):
         tgt = np.linspace(-1, 1, i)
         res = poly.polyroots(poly.polyfromroots(tgt))
         assert_almost_equal(trim(res), trim(tgt))
Example #2
0
 def test_polyroots(self) :
     assert_almost_equal(poly.polyroots([1]), [])
     assert_almost_equal(poly.polyroots([1, 2]), [-.5])
     for i in range(2,5) :
         tgt = np.linspace(-1, 1, i)
         res = poly.polyroots(poly.polyfromroots(tgt))
         assert_almost_equal(trim(res), trim(tgt))
Example #3
0
def roots(b, a):

    b = np.array(b) / a[0]
    a = np.array(a) / a[0]
    b /= b[0]
    z = polyroots(b)
    p = polyroots(a)

    return z, p
def pronysMethod(y_model, y_coordinates, exponent):
  	"""Input  : real arrays y_model, y_coordinates of the same size (y_model(i), y_coordinates(i)
            : integer exponent - the number of modes in the exponential fit
    Output : arrays numerator and demoneator estimates such that y_coordinates(x_coordinate) ~ sum ai exp(bi*x_coordinates)"""
	N    = len(y_model)
	numerator_matrix = np.zeros((N-exponent, exponent))
	denomenator_matrix = y_coordinates[exponent:N]
	for jcol in range(exponent):
		numerator_matrix[:, jcol] = y_coordinates[exponent-jcol-1:N-1-jcol]
	sol = np.linalg.lstsq(numerator_matrix, denomenator_matrix)
	d = sol[0]
	c = np.zeros(exponent+1)
	c[exponent] = 1.
	for i in range(1,exponent+1):
		c[exponent-i] = -d[i-1]
	u = poly.polyroots(c)
	denominator_est = np.log(u)/(y_model[1] - y_model[0])
	numerator_matrix = np.zeros((N, exponent))
	denomenator_matrix = y_coordinates
	for irow in range(N):
		numerator_matrix[irow, :] = u**irow
	sol = np.linalg.lstsq(numerator_matrix, denomenator_matrix)
	numerator_est = sol[0]
	for prony_index, prony_value in prony_outliers:
		numerator_est[prony_index]/=prony_value
	return numerator_est, denominator_est
def checkRoots(a, b, Delta):
    if np.isnan(a) or np.isnan(b):
        return

    X = (a + b - 2) / 6.0
    Y = (a - b) / 4.0

    dU = lambda rho, a, b: rho**3 + (a + b - 2) * rho / 2.0 + (a - b) / 2.0
    rs = poly.polyroots([(a - b) / 2.0, (a + b - 2.0) / 2.0, 0, 1.0])
    print "a,b before: ", a, b
    A = -pow(Y - np.sqrt(Delta + 0J),
             1 / 3.0)  #-pow(Y**2 -Delta, 1/3.0)/pow(Y + np.sqrt(Delta), 1/3.0)
    B = pow(Y + np.sqrt(Delta + 0J), 1 / 3.0)
    w = -0.5 + np.sqrt(3) * 1J / 2.0
    w2 = -0.5 - np.sqrt(3) * 1J / 2.0
    r1 = A - B
    r2 = w2 * A - w * B
    r3 = w * A - w2 * B
    U = lambda rho, a, b: (1 + rho)**2 * (1 - rho)**2 + a * (
        1 + rho)**2 + b * (1 - rho)**2
    print "Heights: {:.2f}, {:.2f}, {:.2f}".format(
        U(r2, a, b) - U(r1, a, b),
        U(r3, a, b) - U(r1, a, b),
        U(r3, a, b) - U(r2, a, b))
    print "Roots theory: {:.2f}, {:.2f}, {:.2f}".format(r1, r2, r3)
    print "Values: {:.2f}, {:.2f}, {:.2f}".format(U(r1, a, b), U(r2, a, b),
                                                  U(r3, a, b))
def Bond_Yield(Price, Maturity, CouponRate, FaceValue):
    Coupon = 0.01 * CouponRate * FaceValue
    CF = np.hstack((-Price, np.tile(Coupon, int(Maturity) - 1), FaceValue + Coupon))
    Roots = pol.polyroots(CF)
    Real = np.real(Roots[np.isreal(Roots)])
    Positive = np.asscalar(Real[Real > 0.0])
    return (1.0 / Positive - 1.0) * 100
Example #7
0
def r_at_upd(dt, F, tl, mtg,
             parms):  # Motion of aster in response to the force
    u_r = np.zeros(D)  # Velocity of right aster
    u_l = np.zeros(D)  # Velocity of Left aster
    x_r = np.zeros(D)  # Position of Right aster
    x_l = np.zeros(D)  # Position of Left aster
    u_r[0:D] = F[0:D] / (tl[0] * parms[0].g
                         )  # Half spindle friction on each aster
    u_l[0:D] = F[D:2 * D] / (tl[1] * parms[0].g)
    x_r[0:D] = mtg[2 * nmt][0:D]
    x_l[0:D] = mtg[2 * nmt][D:2 * D]
    del_u = u_r - u_l
    del_x = x_r - x_l
    A = vdot(del_x, del_x, D)
    B = vdot(del_u, del_u, D)
    C = vdot(del_u, del_x, D)
    a = 4 * A[0]
    b = -4 * (A[0] + C[0] * dt)
    c = 2 * C[0] * dt + B[0] * (dt**2)
    coeff = np.array([c, b, a])
    roots = poly.polyroots(coeff)
    lm = np.min(roots)
    mtg[2 * nmt][0:D] = x_r + u_r * dt - lm * (x_r - x_l)
    mtg[2 * nmt][D:2 * D] = x_l + u_l * dt + lm * (x_r - x_l)
    mtg = aster_assigner(mtg)
    return mtg
Example #8
0
File: tf.py Project: pidpy/pidpy
    def tf_zero(self):

        if (self.__type == 'siso'):
            # reverse the order of numerator(s)' elements
            # to  be use in polyroots
            self.__zeros = poly.polyroots(self.__num[::-1])

        # calculates poles of mino systes
        else:
            for line in self.__num:
                for numij in line:
                    # reverse the order of numerator(s)' elements
                    # to  be use in polyroots
                    self.__zeros.append(poly.polyroots(numij[::-1]))

        return self.__zeros
Example #9
0
def drawCriticalLines2():

    eps3 = 1e-1

    derivative = npp.polyder(f_as_poly)
    criticalPoints = npp.polyroots(derivative)

    #phase = (lambda v: np.angle(npp.polyval(v[0]+1j*v[1],f_as_poly)))
    phase = np.angle(values)
    #hessian = nd.Hessian(phase)

    for z0 in criticalPoints:

        z1 = z0 + eps3
        z2 = z0 + eps3
        z3 = z0 - eps3
        z4 = z0 - eps3

        draw_contour_from(z1, eps3)
        draw_contour_from(z2, -eps3)
        draw_contour_from(z3, eps3)
        draw_contour_from(z4, -eps3)

        (x0, y0) = complex_to_pixel(z0)
        pg.draw.circle(window, (255, 0, 0), (x0, y0), circle_size, 0)
        pg.draw.circle(window, (0, 0, 0), (x0, y0), circle_size, 3)
def eigenvalues(A):
    n = len(A)
    I = np.identity(n)
    coef = []
    res = faddeevLeVerrier(n, A, n, I, coef)
    coef = list(reversed(coef))
    return poly.polyroots(coef)
Example #11
0
def process(seed, K):
    """
    K is model order / number of zeros
    """

    # create the dirac locations with many, many points
    rng = np.random.RandomState(seed)
    tk = np.sort(rng.rand(K)*period)

    # true zeros
    uk = np.exp(-1j*2*np.pi*tk/period)
    coef_poly = poly.polyfromroots(uk)   # more accurate than np.poly
    
    # estimate zeros
    uk_hat = np.roots(np.flipud(coef_poly))
    uk_hat_poly = poly.polyroots(coef_poly)
    uk_hat_mpmath = mpmath.polyroots(np.flipud(coef_poly), maxsteps=100, 
        cleanup=True, error=False, extraprec=50)

    # compute error
    min_dev_norm = distance(uk, uk_hat)[0]
    _err_roots = 20*np.log10(np.linalg.norm(uk)/min_dev_norm)

    min_dev_norm = distance(uk, uk_hat_poly)[0]
    _err_poly = 20*np.log10(np.linalg.norm(uk)/min_dev_norm)

    # for mpmath, need to compute error with its precision
    uk = np.sort(uk)
    uk_mpmath = [mpmath.mpc(z) for z in uk]
    uk_hat_mpmath = sorted(uk_hat_mpmath, key=cmp_to_key(compare_mpc))
    dev = [uk_mpmath[k] - uk_hat_mpmath[k] for k in range(len(uk_mpmath))]
    _err_mpmath = 20*mpmath.log(mpmath.norm(uk_mpmath) / mpmath.norm(dev), 
            b=10)

    return _err_roots, _err_poly, _err_mpmath
def IRR(CF):
    #      CF: キャッシュフロー
    #  Output: 内部収益率 (%)
    Roots = pol.polyroots(CF)
    Real = np.real(Roots[np.isreal(Roots)])
    Positive = np.asscalar(Real[Real > 0.0])
    return (1.0 / Positive - 1.0) * 100
Example #13
0
    def get_steady_states(self, positives_only = False):
        """
            return the list of steady states for the model
            INPUTS :
                positives_only -> if True, only returns positives steady_states
            OUTPUTS :
                [ss] -> a list of steady states where ss is a dict with keys :
                    'x' -> x position
                    'y' -> y position²
                    'eig_vals' -> a list of the jacobian eigen values
                    'eig_vects' -> a matrix such that eig_vects[:,k] is the kth eigen vector of the jacobian
                    'name' -> a letter unique to each steady state (ordered by y position)
        """

        letters = ['A', 'B', 'C', 'D', 'E']

        #compute the polynomial roots
        roots = poly.polyroots(self.polynomial_coeffs)
        roots = np.real(roots[(np.isreal(roots))])
        if positives_only:
            roots = roots[roots >= 0]

        # analyse the "y = 0" steady state
        steady_states = [self.__analyse_steady_state(self.nullcline_x(0), 0, letters[0])]

        # analyse each steady state
        i = 1
        for ss_y in roots:
            ss_x = self.nullcline_x(ss_y)
            if ss_x >=0 or (not positives_only):
                steady_states += [self.__analyse_steady_state(ss_x, ss_y, letters[i])]
            i += 1

        return steady_states
Example #14
0
def poly_solve(poly, tau, line, terminate):
    # Derivative
    if poly.size > 3 and np.abs(poly[-1]) < np.finfo(float).eps:
        poly[-1] = 0.0
    der = p.polyder(poly)
    # Stationary Points
    stat_x = p.polyroots(der)
    stat_f = p.polyval(stat_x, poly)
    stat_x_feasible = stat_x[terminate.feasible(line, stat_x, stat_f)]
    stat_f_feasible = stat_f[terminate.feasible(line, stat_x, stat_f)]
    # Bounds Extrema
    bound_x = tau
    bound_f = p.polyval(bound_x, poly)
    bound_x_feasible = bound_x[terminate.feasible(line, bound_x, bound_f)]
    bound_f_feasible = bound_f[terminate.feasible(line, bound_x, bound_f)]
    # Termination Extrema
    term_x = terminate.extrema(line, poly)
    if term_x.size > 0:
        term_f = p.polyval(term_x, poly)
    else:
        term_f = np.array([])
    # Combine
    comb_x = np.concatenate((stat_x_feasible, bound_x_feasible, term_x))
    comb_f = np.concatenate((stat_f_feasible, bound_f_feasible, term_f))
    # Bounds Filter
    comb_final_x = comb_x[np.logical_and(bound_x[0] <= comb_x, comb_x <= bound_x[1])]
    comb_final_f = comb_f[np.logical_and(bound_x[0] <= comb_x, comb_x <= bound_x[1])]
    # Return Result
    if comb_final_x.size == 0:
        return None
    else:
        return comb_final_x[np.argmin(comb_final_f)]
Example #15
0
File: tf.py Project: pidpy/pidpy
    def tf_pole(self):

        if (self.__type == 'siso'):
            # reverse the order of denominator(s)' elements
            # to  be use in polyroots
            self.__poles = poly.polyroots(self.__den[::-1])

        # calculates poles of mino systes
        else:
            for line in self.__den:
                for denij in line:
                    # reverse the order of denominator(s)' elements
                    # to  be use in polyroots
                    self.__poles.append(poly.polyroots(denij[::-1]))

        return self.__poles
Example #16
0
 def _solve_quartic_form(self, r_t):
     (a, b, c, r_0) = (self.a, self.b, self.c, self.r0_nominal_resistance)
     poly_coefficients = [
         r_0 - r_t, r_0 * a, r_0 * b, -100.0 * r_0 * c, r_0 * c
     ]
     roots = poly.polyroots(poly_coefficients)
     return RtdScaling._get_negative_real_root(roots)
Example #17
0
 def tmp(t):
     c[0] -= t
     roots = polyroots(c)
     for root in roots:
         if root > 0:
             return int(root.real)
     return 0
Example #18
0
def mixture_example3():
    p_max = 5
    T = 1000
    v = 0.25 * np.random.normal(size=T + p_max)
    y = np.array(v)

    mu = -0.7
    r = 1.2 / T

    b1 = 0.9
    b2 = -0.5
    b3 = 0.0
    b4 = 0.6
    b5 = -0.5

    true_roots = polyroots(np.append(-np.array([b1, b2, b3, b4, b5])[::-1], 1))
    print(np.abs(true_roots))

    for t in range(T):
        y[t] = (b1 * y[t - 1] + b2 * y[t - 2] + b3 * y[t - 3] + b4 * y[t - 4] +
                b5 * y[t - 5] + v[t])
    y = y + mu + r * np.arange(-p_max, T)
    y = y[p_max:].reshape(-1, 1)

    mu_th = np.ones(p_max + 1)  # / np.arange(1, p_max + 2)**(1./3)
    mu_th /= sum(mu_th)

    ar = BayesMixtureAR(normalize=False,
                        p_max=p_max,
                        n_chains=4,
                        warmup=3000,
                        mu_th=mu_th)
    ar.fit(y)

    ax = ar.plot_ppc(y, show=False)
    fig = ax.figure
    # fig.savefig(FIGURE_DIR + "mixture_time_series_ppc.png")
    # fig.savefig(FIGURE_DIR + "mixture_time_series_ppc.pdf")
    plt.show()

    fig, axes = plt.subplots(1, 2)
    axes = axes.ravel()
    ar.plot_posterior_params(show=False, ax=axes[0])
    ar.plot_poles(p=None, show=False, ax=axes[1])
    axes[1].scatter(true_roots.real,
                    true_roots.imag,
                    marker="o",
                    label="True Poles",
                    color="#117733")
    axes[1].legend(loc="upper right")
    # fig.savefig(FIGURE_DIR + "mixture_time_series_param_posterior.png")
    # fig.savefig(FIGURE_DIR + "mixture_time_series_param_posterior.pdf")
    plt.show()

    fig, ax = plt.subplots(1, 1)
    ar.plot_posterior_params(show=False, ax=ax)
    plt.show()

    return
Example #19
0
    def _power_model(self,
                     P_rider,
                     total_mass,
                     v_wind,
                     slope,
                     air_pressure,
                     air_temperature,
                     air_relative_humidity,
                     drivetrain_efficiency,
                     C_D,
                     C_rr,
                     specific_gas_constant_dry_air=287.058,
                     specific_gas_constant_water_vapor=461.495,
                     g_constant=9.8):
        """ Compute rider speed given power and other parameters

        :P_rider: power of the rider (Watts)

        :total_mass: total mass of the rider (kg)

        :v_wind: absolute speed of head wind (m/s)

        :slope: ckimbing slope (ratio of height and length)

        :air_pressure: air pressure (Pa)

        :air_temperature: air temperature (K)

        :air_relative_humidity: relative humidity (in interval [0,1])

        :drivetrain_efficiency: efficiency of the drivetrain

        :C_D: drag coefficient (default is questionable)

        :C_rr: rolling resistance coefficient

        :specific_gas_constant_dry_air: specific gas constant for dry air (J/(kg*K))

        :specific_gas_constant_water_vapor: specific gas constant for water vapor (J/(kg*K))

        :g_constant: free-body acceleration

        """
        # p_v = air_relative_humidity*610.78*10**(7.5*(air_temperature-273.15)/(air_temperature-35.85))
        # p_d = air_pressure - p_v
        # K_1 = (p_d/specific_gas_constant_dry_air + p_v/specific_gas_constant_water_vapor)*C_D/(2*air_temperature)

        K_1 = (air_pressure /
               specific_gas_constant_dry_air) * C_D / (2 * air_temperature)

        K_2 = total_mass * g_constant * (C_rr + math.sin(math.atan(slope)))

        v_bike = poly.polyroots([
            -P_rider * drivetrain_efficiency / K_1,
            v_wind * v_wind + K_2 / K_1, -2 * v_wind, 1
        ])

        # get a real root
        return float(np.real(v_bike[np.angle(v_bike) == 0])[0])
Example #20
0
 def meets_template(template, n):
     b = Bessel.get_poly(n)
     poles = poly.polyroots(c=b.coef)
     [gd, _] = group_delay(w=[template.wrg], p=poles, z=[])
     if gd[0] >= 1 - template.tol:
         return True
     else:
         return False
Example #21
0
def roots_A_B(z, u):
    a = get_a(z, u)
    A = get_A(z, a)
    B = get_B(z, a)
    r_A = poly.polyroots(A)
    r_B = poly.polyroots(B)
    plt.scatter(r_A.real,
                r_A.imag,
                s=80,
                facecolors='none',
                edgecolors='black')
    plt.scatter(r_B.real, r_B.imag, s=80, marker='*', color='r')
    plt.axhline(0, color='green')
    plt.axvline(0, color='green')
    plt.show()

    return r_A, r_B
Example #22
0
def filter_coeffs(p, norm=np.sqrt(2), linphase=False):
    ''' Calculate the filter coefficients for Daubechies Wavelets

    c.f. Strang, Nguyen - "Wavelets and Filters" ch. 5.5
    :param p: number of vanishing moments
    :param norm: specifies the euclidean norm of the final coefficients
    :param linphase: whether to use the "most linear phase" approximation or minimal phase
    '''
    if p < 1:
        raise ValueError("The order of the Wavelets must be at least 1")
    if p > 34:
        raise ValueError("Sorry, the method does currently not work for orders higher than 34")
    if norm <= 0:
        raise ValueError("The norm must be larger than 0")
    # find roots of the defining polynomial B(y)
    B_y = [comb(p + i - 1, i, exact=True) for i in range(p)]
    y = poly.polyroots(B_y)
    # calculate the roots of C(z) from the roots y via a quadratic formula
    roots = [poly.polyroots([1, 4*yi - 2, 1]) for yi in y]
    if not linphase:
        # take the ones inside the unit circle
        z = [root for pair in roots for root in pair if np.abs(root) < 1]
    else:
        # sort roots according to Kateb & Lemarie-Rieusset (1995)
        # note: This does not always yield the 'most linear' set
        #       but some 'more linear phase'. I might also have misread the paper
        imaglargerzero = list(filter(lambda root: np.imag(root[0]) >= 0, roots))
        imagsmallerzero = list(filter(lambda root: np.imag(root[0]) < 0, roots))
        imaglargerzero.sort(key=lambda x: np.absolute(x[0]))
        imagsmallerzero.sort(key=lambda x: np.absolute(x[0]), reverse=True)
        sortedroots = imaglargerzero + imagsmallerzero
        # take them in some alternating manner
        z = []
        for i, root in enumerate(sortedroots):
            takelarger = ( (i+1)%4 <= 1 )
            z.append(root[takelarger*1])
    z += [-1]*p
    # put together the polynomial C(z) and normalize the coefficients
    C_z = np.real(poly.polyfromroots(z)) # imaginary part may be non-zero because of rounding errors
    C_z *= norm / sum(C_z)
    return C_z[::-1]
Example #23
0
    def bimodal_test(popt):
        # Check if input is None?
        if popt is None:
            return None  # Unimodal

        # Require mu1 <= mu2
        if popt[0] <= popt[3]:
            mu1, a1, b1, mu2, a2, b2, c = popt
        else:
            mu2, a2, b2, mu1, a1, b1, c = popt

        # Define constants
        p1 = (a1 - c) * b1 * np.sqrt(2 * np.pi)
        p2 = (a2 - c) * b2 * np.sqrt(2 * np.pi)
        p = p1 / (p1 + p2)
        sigma1 = b1
        sigma2 = b2
        mu = (mu2 - mu1) / (sigma1)
        sigma = sigma2 / sigma1

        mu0 = np.sqrt(
            (2 * (sigma**4 - sigma**2 + 1)**1.5 -
             (2 * sigma**6 - 3 * sigma**4 - 3 * sigma**2 + 2)) / sigma**2)

        if mu <= mu0:
            return None  # Unimodal
        else:
            # Solve cubic equation
            coeff = [mu * sigma**2, -mu**2, -mu * (sigma**2 - 2), sigma**2 - 1]
            roots = np.array([])
            for r in poly.polyroots(coeff):
                # Check for (1) real roots, (2) less than mu, (3) greater
                # than zero.
                if (np.imag(r) == 0) and (mu > r) and (r > 0):
                    roots = np.append(roots, r)
            roots = np.sort(roots)

            def p_root(value):
                invp = 1 + (sigma**3 * value /
                            (mu - value)) * np.exp(-value**2 / 2 + (
                                (value - mu) / sigma)**2 / 2)
                return 1 / invp

            # Should only have two distinct real roots
            p1 = p_root(roots[0])
            if len(roots) > 1:
                p2 = p_root(roots[1])
                if (p1 < p) and (p < p2):
                    return 1  # Bimodal
                else:
                    return None  # Unimodal
            else:
                return None
Example #24
0
def Bond_Yield(Price, Maturity, CouponRate, FaceValue):
    #      Price: 債券価格
    #   Maturity: 残存期間
    # CouponRate: 表面利率 (%)
    #  FaceValue: 額面
    #     Output: 債券利回り (%)
    Coupon = 0.01 * CouponRate * FaceValue
    CF = np.r_[-Price, np.tile(Coupon, int(Maturity) - 1), FaceValue + Coupon]
    Roots = pol.polyroots(CF)
    Real = np.real(Roots[np.isreal(Roots)])
    Positive = np.asscalar(Real[Real > 0.0])
    return (1.0 / Positive - 1.0) * 100
def iqi(f, xs, tol = 0.1, nMax = 100):
	""" function, initial X values, tolerance, max iterations """
	start = time.time()
	n = 0
	while (abs(f(xs[0])) > tol) & (n < nMax):
		p = nppoly.polyfit(xs, map(f, xs), 3)
		guess = map(abs, nppoly.polyroots(p))[1]
		xs.pop()
		xs.insert(0, guess)
		n += 1
	# zero, iterct, runtime
	return xs[1], n, time.time()-start
Example #26
0
 def amplitude(self, energy):
     # we compute the 2 real roots closest to 0
     righthandside = np.zeros(self.deg+1)
     righthandside[0] = energy
     roots = Poly.polyroots(self.VPoly-righthandside)
     rplus = np.inf
     rminus = -np.inf
     for r in np.real(roots[np.isreal(roots)]):
         if r > 0 and r < rplus:
             rplus = r
         elif r < 0 and r > rminus:
             rminus = r
     return [rminus, rplus]
Example #27
0
def compute_point_and_mat_extrapo(deg):

    #computing the flux_point and the sol_point in the iso cell
    #computing the legendre polynomial of degree p
    P = legendre(deg)
    #computing the inverse of the roots of the legendre polynomial
    a = poly.polyroots(P)
    #storing the roots
    if deg % 2 == 0:
        flux_point = np.zeros(deg)
        for i in range(0, deg):
            flux_point.itemset(i, 1 / a[i])
    else:
        flux_point = np.zeros(deg)

        for i in range(0, math.floor(deg * 0.5)):
            flux_point.itemset(i, 1 / a[i])
        flux_point.itemset(math.floor(deg * 0.5), 0)
        for i in range(math.floor(deg * 0.5) + 1, deg):
            flux_point.itemset(i, 1 / a[i - 1])

    #we add the extrem flux points
    flux_point = np.append(-1, flux_point)
    flux_point = np.append(flux_point, 1)

    #computing the solution points
    sol_point = np.zeros(deg + 1)
    Tche = np.polynomial.chebyshev.Chebyshev.basis(deg + 1)
    #computing the roots of the chebyshev polynomial
    sol_point = np.polynomial.chebyshev.Chebyshev.roots(Tche)

    #building the extrapolation matrix sol point toward flux point
    mat_sol_point = np.zeros((deg + 2, deg + 1))
    Id = np.identity(deg + 1)
    for j in range(0, deg + 1):
        Lag = sp.interpolate.lagrange(sol_point, Id[j])
        for i in range(0, deg + 2):
            mat_sol_point[i, j] = Lag(flux_point[i])

    #building the derivative matrix to compute the derivative of the flux at
    #sol point

    mat_d_flux_at_sol_point = np.zeros((deg + 1, deg + 2))
    Id = np.identity(deg + 2)
    for j in range(0, deg + 2):
        Lag = sp.interpolate.lagrange(flux_point, Id[j])
        Lag = np.polyder(Lag, 1)
        for i in range(0, deg + 1):
            mat_d_flux_at_sol_point[i, j] = Lag(sol_point[i])

    return (sol_point, flux_point, mat_sol_point, mat_d_flux_at_sol_point)
    def _roots0(self):
        """
        Complex roots of pseudo-poly using `np.polynomial.polyroots` method,
        which finds the eigenvalues of the companion matrix of the root-finding
        poly.

        First finds common roots between `p` and `q` polynomials, then divides
        these roots from the `root_finding_poly`.

        Returns
        -------
        roots : list (of floats)
            (Complex) roots of the `root_finding_poly`
        p : tuple of floats
            Coefficients of the root finding polynomial
        dp : tuple of floats
            Coefficients of the derivative of the root finding polynomial
        """
        p  = self.root_finding_poly()
        dp = remove_zeros(pol.polyder(p))

        roots_p = pol.polyroots(self.p)
        roots_q = pol.polyroots(self.q)

        roots = []
        for root in roots_p:
            if any([ abs(rq - root) < 1E-5 for rq in roots_q ]):
                roots.append(root)

        pr    = remove_zeros(pol.polyfromroots(roots))
        p2, _ = pol.polydiv(p, pol.polymul(pr, pr))
        p2    = remove_zeros(p2)

        new_roots = list(pol.polyroots(p2))

        roots.extend(new_roots)

        return roots, p, dp
def exponential_decomposition(X, F, m):
    """Use Prony's method to approximate the sampled real function F=f(X) as a sum of m
    exponential functions x → Σ a_i exp(lamda_i x).

    Parameters
    ----------
    X: 1D array
        sampling points.
    F: 1D array (same size as X)
        values of the function to approximate at the points of x.
    m: integer
        number of exponential functions

    Return
    ------
    a: 1D array (size m)
        coefficients of the exponentials
    lamda: 1D array (size m)
        growth rate of the exponentials
    """
    assert X.shape == F.shape

    # Compute the coefficients of the polynomials of Prony's method
    A = toeplitz(c=F[m - 1:-1], r=F[:m][::-1])
    P, *_ = np.linalg.lstsq(A, F[m:], rcond=None)

    # Build and solve polynomial function
    coeffs = np.ones(m + 1)
    # coeffs[:m] = -P[::-1]
    for i in range(m):
        coeffs[m - i - 1] = -P[i]
    roots = polynomial.polyroots(coeffs)

    # Discard values where log is undefined
    roots = roots[np.logical_or(np.imag(roots) != 0.0, np.real(roots) >= 0.0)]

    # Deduce lamda and keep only interesting values
    lamda = np.real(np.log(roots) / (X[1] - X[0]))
    lamda = np.unique(lamda)
    lamda = lamda[np.logical_and(-20.0 < lamda, lamda < 0.0)]

    # Fit the values of 'a' on the curve
    def f(x, *ar):
        ar = np.asarray(ar)[:, np.newaxis]
        la = lamda[:, np.newaxis]
        return np.sum(ar * np.exp(la * x), axis=0)

    a, *_ = curve_fit(f, X, F, p0=np.zeros(lamda.shape))

    return a, lamda
def test_pathological_roots(r, nroots, delta, rseed=42, tol=1E-5):
    rand = np.random.RandomState(rseed)
    roots = [root for root in rand.rand(max([int(nroots / 2), 1]))]
    for i in range(nroots - len(roots)):
        rt = roots[i] + np.sign(0.5 - rand.rand()) * delta
        if abs(rt) < 1:
            roots.append(rt)

    roots = np.sort(roots)
    p = pol.polyfromroots(roots)
    q = pol.polyfromroots(roots)

    pp = PseudoPolynomial(p=p, q=q, r=r)

    pproots = np.sort(pp.real_roots())

    print(roots, pproots)

    proots = pol.polyroots(p)
    qroots = pol.polyroots(q)

    for root in proots:
        dr = min(np.absolute(np.array(roots) - root))
        assert (dr < tol)

    for root in qroots:
        dr = min(np.absolute(np.array(roots) - root))
        assert (dr < tol)

    for root in pproots:
        assert (abs(pp(root)) < tol)

    for root in roots:
        dr = min(
            np.absolute(np.array(pproots) - root) /
            max([tol, np.absolute(root)]))
        assert (abs(pp(root)) < tol and dr < tol)
Example #31
0
def compute_convergence_matrix(c, boundaries, shape):
    x_min, x_max = boundaries[0]
    y_min, y_max = boundaries[1]
    height, width = shape
    conv_mat = np.zeros(shape=(height, width))
    roots = poly.polyroots(c)
    dc = poly.polyder(c)
    for row in range(height):
        y = row * (y_max - y_min) / height + y_min
        for col in range(width):
            x = col * (x_max - x_min) / width + x_min
            z_n = complex(x, y)
            conv_val = find_convergence(c, dc, z_n, roots)
            conv_mat[row, col] = conv_val
    return conv_mat
Example #32
0
def shollMetrics(
    crossCounts: np.ndarray, radii: np.ndarray, polyDegree: int=_DEFAULT_POLY_DEGREE
) -> Tuple[np.ndarray, float, float]:
    bounds: List[float] = [np.min(radii), np.max(radii)]

    # Fit to polynomial...
    pCoeff = npPoly.polyfit(radii, crossCounts, polyDegree)

    # ...then find max value, happens at a critical point:
    roots = npPoly.polyroots(npPoly.polyder(pCoeff))
    critX: List[float] = bounds + [r.real for r in roots if bounds[0] <= r.real <= bounds[1]]
    critY = npPoly.polyval(critX, pCoeff)
    maxYIdx = int(np.argmax(critY))
    maxX = critX[maxYIdx]
    maxY = critY[maxYIdx]
    return pCoeff, maxX, maxY
Example #33
0
def mixture_example1():
    p_max = 5
    T = 50
    v = 0.25 * np.random.normal(size=T + p_max)
    y = np.array(v)
    b1 = 1.6
    b2 = -0.8

    mu = -0.7
    r = 1.2 / T

    true_roots = polyroots(np.append(-np.array([b1, b2])[::-1], 1))

    for t in range(T):
        y[t] = b1 * y[t - 1] + b2 * y[t - 2] + v[t]
    y = y + mu + r * np.arange(-p_max, T)

    nu_th = 3  # Priors for model order
    mu_th = 1. / np.arange(1, p_max + 2)**(1. / 3)
    mu_th /= sum(mu_th)

    ar = BayesMixtureAR(normalize=False,
                        p_max=p_max,
                        n_chains=4,
                        warmup=3000,
                        nu_th=nu_th,
                        mu_th=mu_th)
    ar.fit(y)

    ax = ar.plot_ppc(y, show=False)
    fig = ax.figure
    fig.savefig(FIGURE_DIR + "mixture_time_series_ppc.png")
    fig.savefig(FIGURE_DIR + "mixture_time_series_ppc.pdf")
    plt.show()

    axes = ar.plot_posterior_params(show=False)
    axes[1].scatter(true_roots.real,
                    true_roots.imag,
                    marker="o",
                    label="True Poles",
                    color="#117733")
    axes[1].legend(loc="upper right")
    fig.savefig(FIGURE_DIR + "mixture_time_series_param_posterior.png")
    fig.savefig(FIGURE_DIR + "mixture_time_series_param_posterior.pdf")
    plt.show()

    return
Example #34
0
def roots_in_unit_interval(coeffs):
    r"""Compute roots of a polynomial in the unit interval.

    Args:
        coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in
            monomial / power basis.

    Returns:
        numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`.
    """
    all_roots = polynomial.polyroots(coeffs)
    # Only keep roots inside or very near to the unit interval.
    all_roots = all_roots[(_UNIT_INTERVAL_WIGGLE_START < all_roots.real)
                          & (all_roots.real < _UNIT_INTERVAL_WIGGLE_END)]
    # Only keep roots with very small imaginary part. (Really only
    # keep the real parts.)
    real_inds = np.abs(all_roots.imag) < _IMAGINARY_WIGGLE
    return all_roots[real_inds].real
def nroots(a, b):
    r = poly.polyroots([-b, a + b + 1, -3, 2])

    diff_r = []

    for i in range(r.size):
        b = False
        # if np.abs(np.imag(r[i])) < 0.01:
        #     print r[i]

        for j in range(len(diff_r)):
            if np.abs(np.real(r[i]) - np.real(diff_r[j])) < 0.1:
                b = True

        if not b:  #and np.abs(np.imag(r[i])) < 0.01:
            diff_r.append(r[i])

    return len(diff_r)
Example #36
0
	def findPulseEnergyParameters2(self,pulse_energy):
		if 0.1<=pulse_energy<0.6:
			cv = 0
			coeffs=[1.94459015e-12,-1.81483740e-09,5.17304397e-07,-4.00311154e-05,8.31747187e-04,-1.65116819e-03-pulse_energy]
			roots=poly.polyroots(list(reversed(coeffs)))
			out_amp=max([i.real for i in roots if 0<=i<=255])
		elif 0.6<=pulse_energy<6:
			cv = 150
			coeffs=[1.41450562e-11,-1.56935466e-08,4.84624652e-06,-4.02332700e-04,1.05627054e-02,-4.51490621e-02-pulse_energy]
			roots=poly.polyroots(list(reversed(coeffs)))
			out_amp=max([i.real for i in roots if 0<=i<=255])
		elif 6<=pulse_energy<50:
			cv = 200
			coeffs=[1.04214979e-10,-1.37340226e-07,4.41423797e-05,-3.46540682e-03,8.62171737e-02,-3.39443464e-01-pulse_energy]
			roots=poly.polyroots(list(reversed(coeffs)))
			out_amp=max([i.real for i in roots if 0<=i<=255])
		elif 50<=pulse_energy<300:
			cv = 300
			coeffs=[2.61473188e-09,-2.04138516e-06,5.04291260e-04,-3.57951343e-02,8.25651766e-01,-2.91489951e+00-pulse_energy]
			roots=poly.polyroots(list(reversed(coeffs)))
			out_amp=max([i.real for i in roots if 0<=i<=255])
		elif 300<=pulse_energy<800:
			cv = 400
			coeffs=[6.45286337e-09,-4.74508305e-06,1.09800111e-03,-6.98114957e-02,1.43770885e+00,-4.39976880e+00-pulse_energy]
			roots=poly.polyroots(list(reversed(coeffs)))
			out_amp=max([i.real for i in roots if 0<=i<=255])
		elif 800<=pulse_energy<1500:
			cv = 600
			coeffs=[1.72181502e-08,-1.13030471e-05,2.27310235e-03,-1.06494515e-01,1.33015298e+00,-1.59100539e-01-pulse_energy]
			roots=poly.polyroots(list(reversed(coeffs)))
			out_amp=max([i.real for i in roots if 0<=i<=255])
		elif 1500<=pulse_energy<=2500:
			cv = 800
			coeffs=[1.23034922e-08,-7.88456449e-06,1.35484993e-03,1.53123638e-02,-2.60172649e+00,1.78468265e+01-pulse_energy]
			roots=poly.polyroots(list(reversed(coeffs)))
			out_amp=max([i.real for i in roots if 0<=i<=255])
		else:
			print  'Error: Pulse Energy cannot be read.'
			return None
		return cv,out_amp
Example #37
0
def vector_field(params, F=1.0):
    """
    Display the vector field of an oscillator.

    For a given set of intrinsic parameters, show the vector field for an
    oscillator as the one defined by :func:`.zdot`.

    Args:
        params (:class:`.Zparam`): oscillator intrinsic parameters
        F (``scalar`` or ``iterable``): Forcing values to plot
    """
    colormap = plt.cm.gist_heat

    try:
        len(F)
    except:
        F = [F]

    # FIXME: customizable?
    colors = [colormap(i) for i in np.linspace(0, 0.7, len(F))]

    # \dot{r} = f(r, F)
    r = np.arange(0, 1/np.sqrt(params.epsilon), 0.01)
    rdot = np.add.outer(params.alpha * r +
                        params.beta1 * r**3 +
                        ((params.epsilon* params.beta2 * r**5) /
                            (1 - params.epsilon * r**2)),
                        F)

    # plot it
    plt.figure()
    ax = plt.gca()
    ax.set_color_cycle(colors)
    plt.plot(r, rdot, zorder=0, linewidth=2)
    plt.title(r'$\alpha={:.3g},'
              r'\beta_1={:.3g},'
              r'\beta_2={:.3g}$'.format(params.alpha,
                                        params.beta1,
                                        params.beta2))

    ## assymptote
    # plt.vlines(x=1/np.sqrt(epsilon), ymin=-1, ymax=2, color='r', linestyle=':')
    # plt.ylim(-5,5)
    ax.axhline(y=0,xmin=min(r),xmax=max(r),c="k",zorder=5, alpha=0.5)

    plt.xlabel(r'$r$')
    plt.ylabel(r'$\dot{r}$', labelpad=-10)

    # find roots (r^*)
    roots = [None] * len(F)
    for i in xrange(len(F)):
        r = polyroots([F[i],  # ^0
                       params.alpha,  # ^1
                       -params.epsilon*F[i],  # ^2
                       params.beta1-params.epsilon*params.alpha,  # ^3
                       0,  # ^4
                       params.epsilon*(params.beta2-params.beta1)])  # ^5
        r = np.real(r[np.abs(np.imag(r)) < 1e-20])
        r = r[(r>=0) & (r < 1/params.sqe)]
        roots[i] = r
    # print roots

    # plot the roots
    plt.gca().set_color_cycle(colors)
    for r in roots:
        plt.plot(r, np.zeros_like(r), 'o', markersize=4, zorder=10)
Example #38
0
    def test_siso_system_creation(self):

        num = [1,2,3,4]
        den = [1,0,0]
        # expected numerator
        num_exp = np.array([1, 2, 3, 4])
        # expected denumerator
        den_exp = np.array([0, 1, 0, 0])
        # expectted zeros
        zero_exp = []
        zero_exp = (poly.polyroots(num_exp[::-1]))
        # expected poles
        pole_exp = []
        pole_exp = (poly.polyroots(den_exp[::-1]))
        #creates a siso system
        siso_sys = TF(num,den)
        assert siso_sys.type == 'siso'
        # checks the number of outputs
        assert siso_sys.ounbr == 1
        # checks the number of inputs
        assert siso_sys.innbr == 1
        # checks the outputs' names
        npt.assert_array_equal(siso_sys.inname,['in1'])
        # checks the inputs' names
        npt.assert_array_equal(siso_sys.ouname,['out1'])
        npt.assert_array_equal(siso_sys.num,num_exp)
        npt.assert_array_equal(siso_sys.den,den_exp)
        # checks the poles
        npt.assert_equal(siso_sys.poles,pole_exp)
        # checks the zeros
        npt.assert_equal(siso_sys.zeros,zero_exp)

        num = [1]
        den = [1, 2, 4, 5, 6, 0, 1]
        # expected numerator
        num_exp = np.array([0, 0, 0, 0, 0, 0, 1])
        # expected denumerator
        den_exp = np.array([1, 2, 4, 5, 6, 0, 1])
        # expectted zeros
        zero_exp = []
        zero_exp = (poly.polyroots(num_exp[::-1]))
        # expected poles
        pole_exp = []
        pole_exp = (poly.polyroots(den_exp[::-1]))
        # creates a siso system
        siso_sys = TF(num,den)
        # checks the number of outputs
        assert siso_sys.ounbr == 1
        # checks the number of inputs
        assert siso_sys.innbr == 1
        # checks the outputs' names
        npt.assert_array_equal(siso_sys.inname,['in1'])
        # checks the inputs' names
        npt.assert_array_equal(siso_sys.ouname,['out1'])
        assert siso_sys.type == 'siso'
        npt.assert_array_equal(siso_sys.num,num_exp)
        npt.assert_array_equal(siso_sys.den,den_exp)
        # checks the poles
        npt.assert_equal(siso_sys.poles,pole_exp)
        # checks the zeros
        npt.assert_equal(siso_sys.zeros,zero_exp)

        num = [0]
        den = [1]
        # expected numerator
        num_exp = np.array([0])
        # expected denumerator
        den_exp = np.array([1])
        # expectted zeros
        zero_exp = []
        zero_exp = (poly.polyroots(num_exp[::-1]))
        # expected poles
        pole_exp = []
        pole_exp = (poly.polyroots(den_exp[::-1]))
        #creates a siso system
        siso_sys = TF(num,den)
        # checks the number of outputs
        assert siso_sys.ounbr == 1
        # checks the number of inputs
        assert siso_sys.innbr == 1
        # checks the outputs' names
        npt.assert_array_equal(siso_sys.inname,['in1'])
        # checks the inputs' names
        npt.assert_array_equal(siso_sys.ouname,['out1'])
        assert siso_sys.type == 'siso'
        npt.assert_array_equal(siso_sys.num,num_exp)
        npt.assert_array_equal(siso_sys.den,den_exp)
        # checks the poles
        npt.assert_equal(siso_sys.poles,pole_exp)
        # checks the zeros
        npt.assert_equal(siso_sys.zeros,zero_exp)

        # empty siso system 
        num = []
        den = [1]
        # expected numerator
        num_exp = np.array([0])
        # expected denumerator
        den_exp = np.array([1])
        # expectted zeros
        zero_exp = []
        zero_exp = (poly.polyroots(num_exp[::-1]))
        # expected poles
        pole_exp = []
        pole_exp = (poly.polyroots(den_exp[::-1]))
        #creates a siso system
        siso_sys = TF(num,den)
        # checks the number of outputs
        assert siso_sys.ounbr == 1
        # checks the number of inputs
        assert siso_sys.innbr == 1
        # checks the outputs' names
        npt.assert_array_equal(siso_sys.inname,['in1'])
        # checks the inputs' names
        npt.assert_array_equal(siso_sys.ouname,['out1'])
        assert siso_sys.type == 'siso'
        npt.assert_array_equal(siso_sys.num,num_exp)
        npt.assert_array_equal(siso_sys.den,den_exp)
        # checks the poles
        npt.assert_equal(siso_sys.poles,pole_exp)
        # checks the zeros
        npt.assert_equal(siso_sys.zeros,zero_exp)
Example #39
0
    def test_mimo_system_creation(self):
        
        # mimo 2x2
        num = [[[1], [1]], [[1, 0], [8, 2]]]
        den = [[[1], [1]], [[1, 2, 3], [1, 4, 3]]]
        # expected numerator
        num_exp = np.zeros(shape = (2,2,3))
        num_exp = [[[0, 0, 1], [0, 0, 1]], [[0, 1, 0], [0, 8, 2]]]
        # expected denumerator
        den_exp = np.zeros(shape = (2,2,3))
        den_exp = [[[0,0,1],[0,0,1]],[[1, 2, 3],[1, 4, 3]]]
        # expectted zeros
        zero_exp = []
        for line in num_exp:
            for numij in line:
                zero_exp.append(poly.polyroots(numij[::-1]))
        # expected poles
        pole_exp = []
        for line in den_exp:
            for denij in line:
                pole_exp.append(poly.polyroots(denij[::-1]))
        # creates a siso system
        mimo_sys = TF(num,den)
        # checks the system type
        assert mimo_sys.type == 'mimo'
        # checks the number of outputs
        assert mimo_sys.ounbr == 2
        # checks the number of inputs
        assert mimo_sys.innbr == 2
        # checks the outputs' names
        npt.assert_array_equal(mimo_sys.inname, ['IN_0(s)','IN_1(s)'])
        # checks the inputs' names
        npt.assert_array_equal(mimo_sys.ouname, ['OU_0(s)','OU_1(s)'])
        # checks the numerator(s)
        npt.assert_array_equal(mimo_sys.num.tolist(), num_exp)
        # checks the denumerator(s)
        npt.assert_array_equal(mimo_sys.den.tolist(), den_exp)
        # checks the poles
        npt.assert_equal(mimo_sys.poles,pole_exp)
        # checks the zeros
        npt.assert_equal(mimo_sys.zeros,zero_exp)

        # mimo 1x2
        num = [[[1,2], [0,4]]]
        den = [[[2,3], [1,4,1]]]
        # expected numerator
        num_exp = np.zeros(shape = (1,2,2))
        num_exp = [[[0, 1, 2], [0, 0, 4]]]
        # expected denumerator
        den_exp = np.zeros(shape = (1,2,2))
        den_exp = [[[0, 2, 3],[1, 4, 1]]]
        # expectted zeros
        zero_exp = []
        for line in num_exp:
            for numij in line:
                zero_exp.append(poly.polyroots(numij[::-1]))
        # expected poles
        pole_exp = []
        for line in den_exp:
            for denij in line:
                pole_exp.append(poly.polyroots(denij[::-1]))
        # creates a siso system
        mimo_sys = TF(num,den)
        # checks the system type
        assert mimo_sys.type == 'mimo'
        # checks the number of outputs
        assert mimo_sys.ounbr == 1
        # checks the number of inputs
        assert mimo_sys.innbr == 2
        # checks the outputs' names
        npt.assert_array_equal(mimo_sys.inname,['IN_0(s)','IN_1(s)'])
        # checks the inputs' names
        npt.assert_array_equal(mimo_sys.ouname,['OU_0(s)'])
        # checks the numerator(s)
        npt.assert_array_equal(mimo_sys.num.tolist(),num_exp)
        # checks the denumerator(s)
        npt.assert_array_equal(mimo_sys.den.tolist(),den_exp)
        # checks the  poles
        npt.assert_equal(mimo_sys.poles,pole_exp)
        # checks the zeros
        npt.assert_equal(mimo_sys.zeros,zero_exp)

        # empty 1x2 mimo system 
        num = [[[],[]]]
        den = [[[1],[1]]]
        # expected numerator
        num_exp = np.zeros(shape = (1,2,1))
        num_exp = [[[0],[0]]]
        # expected denumerator
        den_exp = np.zeros(shape = (1,2,1))
        den_exp = [[[1],[1]]]
        # expectted zeros
        zero_exp = []
        for line in num_exp:
            for numij in line:
                zero_exp.append(poly.polyroots(numij[::-1]))
        # expected poles
        pole_exp = []
        for line in den_exp:
            for denij in line:
                pole_exp.append(poly.polyroots(denij[::-1]))
        # creates a siso system
        mimo_sys = TF(num,den)
        # checks the system type
        assert mimo_sys.type == 'mimo'
        # checks the number of outputs
        assert mimo_sys.ounbr == 1
        # checks the number of inputs
        assert mimo_sys.innbr == 2
        # checks the outputs' names
        npt.assert_array_equal(mimo_sys.inname,['IN_0(s)','IN_1(s)'])
        # checks the inputs' names
        npt.assert_array_equal(mimo_sys.ouname,['OU_0(s)'])
        # checks the numerator(s)
        npt.assert_array_equal(mimo_sys.num.tolist(),num_exp)
        # checks the denumerator(s)
        npt.assert_array_equal(mimo_sys.den.tolist(),den_exp)
        # checks the  poles
        npt.assert_equal(mimo_sys.poles,pole_exp)
        # checks the zeros
        npt.assert_equal(mimo_sys.zeros,zero_exp)
import numpy as np
from numpy.polynomial import polynomial as P
import matplotlib.pyplot as plt

x = np.linspace(0, 8 * np.pi, 50)
y1 = np.cos(x)
y2 = np.sin(x - np.pi)

# Fitting data
coeff, stats = P.polyfit(x, y1, 20, full=True)
roots = np.real(P.polyroots(coeff))
fit = P.Polynomial(coeff)
yf1 = fit(x)

# Differentiating fitted polynomial
new_coeff = P.polyder(coeff)
dfit = P.Polynomial(new_coeff)
yf2 = dfit(x)

# Plotting results for illustration
fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.set_title('Data and fitting')
ax2.set_title('Differentiation')

ax1.set_xlim(0, x.max())
ax2.set_xlim(0, x.max())
ax1.set_ylim(-1.25, 1.25)
ax2.set_ylim(-1.25, 1.25)
Example #41
0
 def extrema(self, line, poly):
     """ Calculates upper extrema. """
     return np.concatenate((polyroots(polysub(np.array([line.start.cost, np.inner(self.inexact["c_u"]*line.start.grad, line.dire)]), poly)),
                            polyroots(polysub(np.array([line.start.cost, np.inner(self.inexact["c_l"]*line.start.grad, line.dire)]), poly))))
Example #42
0
    def test_polyvalfromroots(self):
        # check exception for broadcasting x values over root array with
        # too few dimensions
        assert_raises(ValueError, poly.polyvalfromroots,
                      [1], [1], tensor=False)

        # check empty input
        assert_equal(poly.polyvalfromroots([], [1]).size, 0)
        assert_(poly.polyvalfromroots([], [1]).shape == (0,))

        # check empty input + multidimensional roots
        assert_equal(poly.polyvalfromroots([], [[1] * 5]).size, 0)
        assert_(poly.polyvalfromroots([], [[1] * 5]).shape == (5, 0))

        # check scalar input
        assert_equal(poly.polyvalfromroots(1, 1), 0)
        assert_(poly.polyvalfromroots(1, np.ones((3, 3))).shape == (3,))

        # check normal input)
        x = np.linspace(-1, 1)
        y = [x**i for i in range(5)]
        for i in range(1, 5):
            tgt = y[i]
            res = poly.polyvalfromroots(x, [0]*i)
            assert_almost_equal(res, tgt)
        tgt = x*(x - 1)*(x + 1)
        res = poly.polyvalfromroots(x, [-1, 0, 1])
        assert_almost_equal(res, tgt)

        # check that shape is preserved
        for i in range(3):
            dims = [2]*i
            x = np.zeros(dims)
            assert_equal(poly.polyvalfromroots(x, [1]).shape, dims)
            assert_equal(poly.polyvalfromroots(x, [1, 0]).shape, dims)
            assert_equal(poly.polyvalfromroots(x, [1, 0, 0]).shape, dims)

        # check compatibility with factorization
        ptest = [15, 2, -16, -2, 1]
        r = poly.polyroots(ptest)
        x = np.linspace(-1, 1)
        assert_almost_equal(poly.polyval(x, ptest),
                            poly.polyvalfromroots(x, r))

        # check multidimensional arrays of roots and values
        # check tensor=False
        rshape = (3, 5)
        x = np.arange(-3, 2)
        r = np.random.randint(-5, 5, size=rshape)
        res = poly.polyvalfromroots(x, r, tensor=False)
        tgt = np.empty(r.shape[1:])
        for ii in range(tgt.size):
            tgt[ii] = poly.polyvalfromroots(x[ii], r[:, ii])
        assert_equal(res, tgt)

        # check tensor=True
        x = np.vstack([x, 2*x])
        res = poly.polyvalfromroots(x, r, tensor=True)
        tgt = np.empty(r.shape[1:] + x.shape)
        for ii in range(r.shape[1]):
            for jj in range(x.shape[0]):
                tgt[ii, jj, :] = poly.polyvalfromroots(x[jj], r[:, ii])
        assert_equal(res, tgt)
Example #43
0
def polyroots(cs):
    from numpy.polynomial.polynomial import polyroots
    return polyroots(cs)
Example #44
0
 def extrema(self, line, poly):
     """ Calculates upper extrema. """
     return polyroots(polysub(np.array([line.start.cost]), poly))