Esempio n. 1
0
def legendrePolynomial(order, x):
    coef = []
    if type(x) is float:

        if x <= 0 or x > 1:
            return 0
        else:
            for n in range(0, order + 1):
                if(n == order):
                    coef.append(1)
                else:
                    coef.append(0)
            return (2.*order + 1.)**.5 \
                * leg.Legendre(coef, domain=[-1, 1])(2.0*x - 1)
    else:
        y = np.zeros(x.size)

        for i in range(x.size):

            if x[i] <= 0 or x[i] > 1:
                y[i] = 0
            else:
                for n in range(0, order+1):
                    if(n == order):
                        coef.append(1)
                    else:
                        coef.append(0)

                y[i] = (2.*order + 1.)**.5 \
                    * leg.Legendre(coef, domain=[-1, 1])(2.0*x[i] - 1)
                coef.clear()
    return y
Esempio n. 2
0
 def test_divmod(self):
     tquo = leg.Legendre([1])
     trem = leg.Legendre([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)
Esempio n. 3
0
def draw_electrostatic(E):
    #points of the polynomials.
    xaxis = np.arange(-1, 1, 0.01)

    #vector which F(X) = 0
    X = nr.Newton_Raphson(energy_electrostatic, jacobian_electrostatic, E,
                          iteration_number, epsilon)

    #elements of the vector X
    charges = plt.scatter(X, np.full(len(X), 0))
    colors = "red", "blue", "green", "cyan", "purple", "orange", "magenta"

    #drawing the 8 first polynomials.
    for n in range(3, 8, 1):
        #array of 0.
        T = np.zeros(n)
        #put the coefficient relate to the polynomial wanted to 1
        T[n - 1] = 1
        #give the polynomial
        L = npl.Legendre(T)
        #the derivative of the polynomial
        D = npl.Legendre.deriv(L)
        yaxis = D(xaxis)
        plt.plot(xaxis, yaxis, color=colors[n - 1])

    plt.show()
Esempio n. 4
0
 def normlegAl(self, coefs):
     d = 0.0
     for i in range(len(coefs)):
         d += (coefs[i]**2) / (2 * i + 1)
     d = np.sqrt(d)
     coefs = np.divide(coefs, d)
     #print coefs
     return L.Legendre(coefs)
Esempio n. 5
0
def hamiltonian(coefs, func=BASIS_FUNC, V=V, C=C):
    '''hamiltonian operator acting on wavefunction'''
    if func == 'legendre':
        ham = -C * L.legder(L.legder(coefs)) + V * L.Legendre(coefs)
        return ham
    elif func == 'fourier':
        ham = [V] + [(i**2) * C * coefs[i] for i in range(1, len(coefs))]
        return ham
Esempio n. 6
0
 def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None):
     if x is None:
         x = self.mesh(False, False)
     x = np.atleast_1d(x)
     basis = np.zeros(self.shape(True))
     basis[i] = 1
     basis = leg.Legendre(basis)
     if k > 0:
         basis = basis.deriv(k)
     return basis(x)
Esempio n. 7
0
def plot(U0, epsilon, N, a_min=0.001):
    fig=plt.figure()
    coeff=np.zeros(len(U0)+2)
    coeff[len(U0)+1]=1
    plt.plot(resolve(U0, epsilon, N, a_min),np.zeros((len(U0))),'+',color='b',label='Electrostatic equilibrium positions')
    plt.plot(leg.Legendre(coeff).deriv().roots(),np.zeros((len(U0))),'x',color='r',label='Legendre polynomial\'s derivative roots')
    plt.legend()
    plt.title("Roots of Legendre polynomial derivative of order {}\n and the electrostatic equilibrium's positions of the system".format(len(U0)))
    plt.savefig("img/roots_{}".format(len(U0)), dpi=fig.dpi)
    print("creating img/roots_{}\n".format(len(U0)))
Esempio n. 8
0
 def test_collocation_points_legendre_gauss_lobatto(self):
     for num_coll_points in range(2, 13):
         coefs = np.zeros(num_coll_points)
         coefs[-1] = 1.
         coll_points_numpy = np.concatenate(
             ([-1.], legendre.Legendre(coefs).deriv().roots(), [1.]))
         mesh = Mesh1D(num_coll_points, Basis.Legendre,
                       Quadrature.GaussLobatto)
         coll_points_spectre = collocation_points(mesh)
         np.testing.assert_allclose(coll_points_numpy, coll_points_spectre,
                                    1e-12, 1e-12)
Esempio n. 9
0
def weights(order):

    x = roots(order)
    w = np.empty(order)
    coef = []
    for n in range(0, order+1):
        if(n == order):
            coef.append(1)
        else:
            coef.append(0)

    derivative_coefficients = leg.legder(coef)
    del coef[-1]
    del coef[-1]
    coef.append(1)
    for i in range(0, order):
        tmp = leg.Legendre(derivative_coefficients, domain=[-1, 1])(2*x[i] - 1)
        tmp2 = leg.Legendre(coef, domain=[-1, 1])(2.0*x[i] - 1)
        w[i] = 1/(order*tmp*tmp2)
        # Possibly some bug here, get a factor 2 different using mathematica
    return w
Esempio n. 10
0
 def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None):
     if x is None:
         x = self.mesh(False, False)
     if output_array is None:
         output_array = np.zeros(x.shape)
     x = np.atleast_1d(x)
     basis = np.zeros(self.shape(True))
     basis[np.array([i, i + 2])] = (1, -i * (i + 1.) / (i + 2.) / (i + 3.))
     basis = leg.Legendre(basis)
     if k > 0:
         basis = basis.deriv(k)
     output_array[:] = basis(x)
     return output_array
def get_orthpoly(n_deg,
                 f_weighting,
                 n_extra_point=10,
                 return_coef=True,
                 representation='chebyshev',
                 integral_method='legendre'):
    """
    Get orthogonal polynomials with respect to the weighting (f_weighting).
    The polynomials are represented by coefficients of Chebyshev polynomials.
    Evaluate it as: np.dot(cheb.chebvander(set_of_x, n_deg), repr_coef)
    See weighted_orthpoly1.py for validation of this algorithm.
    """
    n_sampling = n_deg + 1 + n_extra_point
    # Do the intergration by discrete sampling at good points.
    if integral_method == 'chebyshev':
        # Here we use (first kind) Chebyshev points.
        x_sampling = chebyshev_roots(n_sampling)
        # Put together the weighting and the weighting of the Gauss-Chebyshev quadrature.
        diag_weight = np.array(
            [f_weighting(x) / cheb.chebweight(x)
             for x in x_sampling]) * (pi / n_sampling)
    elif integral_method == 'legendre':
        # Use Gauss-Legendre quadrature.
        x_sampling, int_weight = lege.leggauss(n_sampling)
        diag_weight = np.array(
            [f_weighting(x) * w for x, w in zip(x_sampling, int_weight)])

    if representation == 'chebyshev':
        V = cheb.chebvander(x_sampling, n_deg)
    else:
        V = lege.legvander(x_sampling, n_deg)

    # Get basis from chol of the Gramian matrix.


#    inner_prod_matrix = dot(V.T, diag_weight[:, np.newaxis] * V)
#    repr_coef = inv(cholesky(inner_prod_matrix).T)
# QR decomposition should give more accurate result.
    repr_coef = inv(qr(sqrt(diag_weight[:, np.newaxis]) * V, mode='r'))
    repr_coef = repr_coef * sign(sum(repr_coef, axis=0))

    if return_coef:
        return repr_coef
    else:
        if representation == 'chebyshev':
            polys = [cheb.Chebyshev(repr_coef[:, i]) for i in range(n_deg + 1)]
        else:
            polys = [lege.Legendre(repr_coef[:, i]) for i in range(n_deg + 1)]
        return polys
def legendre_roots(n, n_iter=3):
    """
    Get roots of legendre polynomial of degree n, by Newton's iteration.
    n_iter is the number of iteration.
    Accurate to machine epsilon, although le(ar) may significantly \
      deviate from zero (e.g. 1e-11).
    Effectively ar = lege.legroots(1*(arange(n+1)==n)), but faster for large n.
    """
    # Approximation of roots
    # https://math.stackexchange.com/questions/12160/roots-of-legendre-polynomial/12270
    ar = (1 - 1 / (8 * n * n) + 1 /
          (8 * n * n * n)) * cos(pi * (4 * arange(1, n + 1) - 1) /
                                 (4 * n + 2) - pi)
    # Newton's iteration
    le = lege.Legendre(1 * (arange(n + 1) == n))
    dle = le.deriv()
    for i in range(n_iter):
        ar = ar - le(ar) / dle(ar)
    return ar
Esempio n. 13
0
 def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None):
     if x is None:
         x = self.mesh(False, False)
     if output_array is None:
         output_array = np.zeros(x.shape)
     x = np.atleast_1d(x)
     if i < self.N - 4:
         basis = np.zeros(self.shape(True))
         basis[np.array([i, i + 2,
                         i + 4])] = (1, -2 * (2 * i + 5.) / (2 * i + 7.),
                                     ((2 * i + 3.) / (2 * i + 7.)))
         basis = leg.Legendre(basis)
         if k > 0:
             basis = basis.deriv(k)
         output_array[:] = basis(x)
     else:
         output_array[:] = sympy.lambdify(
             sympy.symbols('x'),
             self.sympy_basis(i).diff(sympy.symbols('x'), k))(x)
     return output_array
Esempio n. 14
0
    def _get_single_element(self):
        """Calculate local grid nodes, corresponding weights and differentiation matrix
        using numpy.polynomial.legendre module


        Sets
        ----
        x_, w_, dmat_

        """
        # Interested in Legendre polynomial #(Np-1):
        coefs = np.append(np.zeros(self.Np - 1), 1)

        # Calculate grid points:
        self.x_ = np.append(
            np.append(-1,
                      legendre.Legendre(coefs).deriv().roots()), 1)

        # Need legendre polynomial at grid points:
        Ln = legendre.legval(self.x_, coefs)

        # Calculate weights:
        self.w_ = 2 / ((self.Np - 1) * self.Np * Ln**2)

        # Calculate differentiation matrix:
        self.dmat_ = np.zeros((len(Ln), len(Ln)))
        for i in range(self.Np):
            for j in range(self.Np):
                if i != j:
                    self.dmat_[i][j] = Ln[i] / \
                        (Ln[j] * (self.x_[i] - self.x_[j]))
                else:
                    self.dmat_[i][i] = 0
        self.dmat_[0, 0] = -(self.Np - 1) * (self.Np) / 4
        self.dmat_[-1, -1] = (self.Np - 1) * (self.Np) / 4

        # Scale locals:
        self.x_ *= self.ele_scale_
        self.w_ *= self.ele_scale_
        self.dmat_ /= self.ele_scale_
Esempio n. 15
0
    def __init__(self, fitparams):
        # handed a list or tuple of firparams (which includes flags
        # for type of fit) sets up the irafcurve instance.

        # should be an int but it i'nt sometimes
        typecode = int(fitparams[0] + 0.001)

        if typecode == 1: self.curvetype = 'chebyshev'
        elif typecode == 2: self.curvetype = 'legendre'
        elif typecode == 3: self.curvetype = 'spline3'
        else:
            print("Unknown fit type: ", fitparams[0])

        # the 'iraforder' is not the conventional order; it's
        # the number of coefficients for a polynomial, so a
        # a straight line has iraforder = 2.  For a spline3 it is
        # the number of spline segments.

        self.iraforder = int(fitparams[1] + 0.001)

        self.xrange = (fitparams[2], fitparams[3])
        self.span = self.xrange[1] - self.xrange[0]
        self.sumrange = self.xrange[0] + self.xrange[1]

        self.fitcoeffs = np.array(fitparams[4:])

        # Numpy provides built-in legendre and chebyshev apparatuses that make
        # this trivial.  The numpy spline3 is apparently oriented toward interpolation,
        # and wasn't as easy to adapt, though I'm probably missing something.  My own
        # spline3 stuff works correctly though it's more awkward.

        if self.curvetype == 'legendre':
            self.lpoly = leg.Legendre(self.fitcoeffs, domain = [self.xrange[0], self.xrange[1]])

        if self.curvetype == 'chebyshev':
            self.chpoly = cheb.Chebyshev(self.fitcoeffs, domain = [self.xrange[0], self.xrange[1]])
Esempio n. 16
0
def leg_gauss_quad(field_data, rings=3, arms=6, obs=0.0, symm=False):
    """Calculate normalised pupil coordinates for Legendre-Gauss quadrature
       rayset selection.

    Parameters
    ----------
    field_data : list of fieldData named tuples
        The field coordinates to use for generation of the coordinates. Must
        be a list as returned from Zemax by zGetFieldTuple().  
    rings : int
        The number of rings of rays for which to compute radial pupil coordinates.
        Minimum of 3, which is the default.
    arms : int
        The number of radial arms along which to calculate the pupil coordinates.
        Default is 6. Minimum is 6. Must be even.
    obs : float
        The fractional radius of the pupil which is obscured. Defaults to 0.0
    symm : boolean
        Will reduce the number of returned points if the provided field points
        are found to lie only along the x axis or only along the y axis.
        Default is False, symmetry not to be assumed.

    Returns
    -------
    hx : array of float
        Relative field x coordinates of the ray list.
    hy : array of float
        Relative field y coordinates of the ray list.
    px : array of float
        Relative pupil x coordinates of the ray list.
    py : array of float
        Relative pupil y coodinates of the ray list.
    weights : array of float
        Legendre-Gauss weighting factors for each ray.

    Reference:
    Brian J. Bauman and Hong Xiao,
    Gaussian quadrature for optical design with non-circular pupils and fields, 
    and broad wavelength ranges, https://doi.org/10.1117/12.872773

    Notes
    ----- 
    This function only handles circular pupils with centered circular obscurations.

    """
    # Check that arms is even
    if arms < 6 or (arms // 2 != arms / 2.0):
        raise ValueError('Input parameter arms must be even and 6 or more.')
    if rings < 3:
        raise ValueError('Input parameter rings must be 3 or more.')
    hx = np.array([])
    hy = np.array([])
    px = np.array([])
    py = np.array([])
    weights = np.array([])  # LGQ weights
    order_tuple = tuple([0] * rings + [1])
    order_tuple1 = tuple([0] * (rings + 1) + [1])
    # Get the Legendre polynomial of order equal to the number of rings
    leg_poly = leg.Legendre(order_tuple)
    # And the one after that for calculating the weights below
    leg_poly1 = leg.Legendre(order_tuple1)
    # Get the roots of the polynomial
    leg_roots = leg_poly.roots()
    # The relative radii of the rings are computed as follows (see Bauman Eq. 6)
    ring_radii = np.sqrt(obs**2.0 + (1.0 + leg_roots) * (1.0 - obs**2.0) / 2.0)
    # Get the weights, see e.g. https://mathworld.wolfram.com/Legendre-GaussQuadrature.html
    leg_weights = 2.0 * (1.0 - leg_roots**2.0) / ((rings + 1.0)**2.0 *
                                                  (leg_poly1(leg_roots)**2.0))
    if obs > 0.0:
        pupil_weights = (1.0 - obs) * leg_weights / 2.0
    else:
        pupil_weights = leg_weights / 2.0
    # Run through the field points
    theta_inc = 360.0 / arms  # degrees. Angular increment between arms
    for field_point in field_data:
        # Get the coordinates and weighting factor for this field point
        xf, yf, wgt = field_point.xf, field_point.yf, field_point.wgt
        # Generate the relative pupil coordinates for this field position
        # Takes symmetry flag into account
        if xf == 0.0:
            if symm:  # Generate polar angles that are symmetric only across the y-axis
                if yf == 0.0:  # On axis
                    theta = 0.0  # A single arm is enough if the system is symmetric
                else:
                    theta = np.linspace(-90.0 + theta_inc / 2.0,
                                        90.0 - theta_inc / 2.0, arms // 2)
            else:
                theta = np.linspace(0.0, 360.0 - theta_inc, arms)
        elif yf == 0.0:
            if symm:  # Generate polar angles that are symmetric only cross the x-axis
                theta = np.linspace(theta_inc / 2.0, 180.0 - theta_inc / 2.0,
                                    arms // 2)
            else:
                theta = np.linspace(-180.0 + theta_inc / 2.0,
                                    180.0 - theta_inc / 2.0, arms)
        theta_rad = np.deg2rad(theta)
        # Meshgrid the radii and the angles, variables fp_ are for this field point
        fp_ring_radii, fp_theta_rad = np.meshgrid(ring_radii, theta_rad)
        # pup_weights are meshgridded to make an array corresponding to the radius
        fp_pupil_weights, fp_theta_rad = np.meshgrid(pupil_weights, theta_rad)
        fp_px, fp_py = fp_ring_radii * np.cos(
            fp_theta_rad), fp_ring_radii * np.sin(fp_theta_rad)
        # Flatten arrays, should now all be the same length
        fp_px, fp_py, fp_pupil_weights = fp_px.flatten(), fp_py.flatten(
        ), fp_pupil_weights.flatten()
        fp_len = np.ones(fp_px.size)
        # Replicate up the field points and field weights to the correct length
        fp_hx, fp_hy, fp_wgt = xf * fp_len, yf * fp_len, wgt * fp_pupil_weights
        # The field weigts
        hx, hy, weights = np.hstack((hx, fp_hx)), np.hstack(
            (hy, fp_hy)), np.hstack((weights, fp_wgt))
        px, py = np.hstack((px, fp_px)), np.hstack((py, fp_py))
    # Get the maximum field radial position to perform field normalisation
    max_field_radius = np.sqrt(hx**2.0 + hy**2.0).max()
    hx /= max_field_radius
    hy /= max_field_radius
    return hx, hy, px, py, weights
Esempio n. 17
0
 def test_mul(self):
     tgt = leg.Legendre([4.13333333, 8.8, 11.23809524, 7.2, 4.62857143])
     assert_poly_almost_equal(self.p1 * self.p1, tgt)
     assert_poly_almost_equal(self.p1 * [1, 2, 3], tgt)
     assert_poly_almost_equal([1, 2, 3] * self.p1, tgt)
Esempio n. 18
0
 def normlegExpect(self, coefs):
     lOrig = L.Legendre(coefs)
     d = (stats.uniform.expect(lOrig**2, loc=-1, scale=2))**0.5
     return lOrig / d
Esempio n. 19
0
 def normlegInteg(self, coefs):
     lOrig = L.Legendre(coefs)
     l2integ = (lOrig**2).integ()
     d = ((l2integ(1) - l2integ(-1)) / 2)**0.5
     return lOrig / d
Esempio n. 20
0
 def test_add(self):
     tgt = leg.Legendre([2, 4, 6])
     assert_(self.p1 + self.p1 == tgt)
     assert_(self.p1 + [1, 2, 3] == tgt)
     assert_([1, 2, 3] + self.p1 == tgt)
Esempio n. 21
0
class TestLegendreClass(TestCase):

    p1 = leg.Legendre([1, 2, 3])
    p2 = leg.Legendre([1, 2, 3], [0, 1])
    p3 = leg.Legendre([1, 2])
    p4 = leg.Legendre([2, 2, 3])
    p5 = leg.Legendre([3, 2, 3])

    def test_equal(self):
        assert_(self.p1 == self.p1)
        assert_(self.p2 == self.p2)
        assert_(not self.p1 == self.p2)
        assert_(not self.p1 == self.p3)
        assert_(not self.p1 == [1, 2, 3])

    def test_not_equal(self):
        assert_(not self.p1 != self.p1)
        assert_(not self.p2 != self.p2)
        assert_(self.p1 != self.p2)
        assert_(self.p1 != self.p3)
        assert_(self.p1 != [1, 2, 3])

    def test_add(self):
        tgt = leg.Legendre([2, 4, 6])
        assert_(self.p1 + self.p1 == tgt)
        assert_(self.p1 + [1, 2, 3] == tgt)
        assert_([1, 2, 3] + self.p1 == tgt)

    def test_sub(self):
        tgt = leg.Legendre([1])
        assert_(self.p4 - self.p1 == tgt)
        assert_(self.p4 - [1, 2, 3] == tgt)
        assert_([2, 2, 3] - self.p1 == tgt)

    def test_mul(self):
        tgt = leg.Legendre([4.13333333, 8.8, 11.23809524, 7.2, 4.62857143])
        assert_poly_almost_equal(self.p1 * self.p1, tgt)
        assert_poly_almost_equal(self.p1 * [1, 2, 3], tgt)
        assert_poly_almost_equal([1, 2, 3] * self.p1, tgt)

    def test_floordiv(self):
        tgt = leg.Legendre([1])
        assert_(self.p4 // self.p1 == tgt)
        assert_(self.p4 // [1, 2, 3] == tgt)
        assert_([2, 2, 3] // self.p1 == tgt)

    def test_mod(self):
        tgt = leg.Legendre([1])
        assert_((self.p4 % self.p1) == tgt)
        assert_((self.p4 % [1, 2, 3]) == tgt)
        assert_(([2, 2, 3] % self.p1) == tgt)

    def test_divmod(self):
        tquo = leg.Legendre([1])
        trem = leg.Legendre([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)

    def test_pow(self):
        tgt = leg.Legendre([1])
        for i in range(5):
            res = self.p1**i
            assert_(res == tgt)
            tgt = tgt * self.p1

    def test_call(self):
        # domain = [-1, 1]
        x = np.linspace(-1, 1)
        tgt = 3 * (1.5 * x**2 - .5) + 2 * x + 1
        assert_almost_equal(self.p1(x), tgt)

        # domain = [0, 1]
        x = np.linspace(0, 1)
        xx = 2 * x - 1
        assert_almost_equal(self.p2(x), self.p1(xx))

    def test_degree(self):
        assert_equal(self.p1.degree(), 2)

    def test_trimdeg(self):
        assert_raises(ValueError, self.p1.cutdeg, .5)
        assert_raises(ValueError, self.p1.cutdeg, -1)
        assert_equal(len(self.p1.cutdeg(3)), 3)
        assert_equal(len(self.p1.cutdeg(2)), 3)
        assert_equal(len(self.p1.cutdeg(1)), 2)
        assert_equal(len(self.p1.cutdeg(0)), 1)

    def test_convert(self):
        x = np.linspace(-1, 1)
        p = self.p1.convert(domain=[0, 1])
        assert_almost_equal(p(x), self.p1(x))

    def test_mapparms(self):
        parms = self.p2.mapparms()
        assert_almost_equal(parms, [-1, 2])

    def test_trim(self):
        coef = [1, 1e-6, 1e-12, 0]
        p = leg.Legendre(coef)
        assert_equal(p.trim().coef, coef[:3])
        assert_equal(p.trim(1e-10).coef, coef[:2])
        assert_equal(p.trim(1e-5).coef, coef[:1])

    def test_truncate(self):
        assert_raises(ValueError, self.p1.truncate, .5)
        assert_raises(ValueError, self.p1.truncate, 0)
        assert_equal(len(self.p1.truncate(4)), 3)
        assert_equal(len(self.p1.truncate(3)), 3)
        assert_equal(len(self.p1.truncate(2)), 2)
        assert_equal(len(self.p1.truncate(1)), 1)

    def test_copy(self):
        p = self.p1.copy()
        assert_(self.p1 == p)

    def test_integ(self):
        p = self.p2.integ()
        assert_almost_equal(p.coef, leg.legint([1, 2, 3], 1, 0, scl=.5))
        p = self.p2.integ(lbnd=0)
        assert_almost_equal(p(0), 0)
        p = self.p2.integ(1, 1)
        assert_almost_equal(p.coef, leg.legint([1, 2, 3], 1, 1, scl=.5))
        p = self.p2.integ(2, [1, 2])
        assert_almost_equal(p.coef, leg.legint([1, 2, 3], 2, [1, 2], scl=.5))

    def test_deriv(self):
        p = self.p2.integ(2, [1, 2])
        assert_almost_equal(p.deriv(1).coef, self.p2.integ(1, [1]).coef)
        assert_almost_equal(p.deriv(2).coef, self.p2.coef)

    def test_roots(self):
        p = leg.Legendre(leg.poly2leg([0, -1, 0, 1]), [0, 1])
        res = p.roots()
        tgt = [0, .5, 1]
        assert_almost_equal(res, tgt)

    def test_linspace(self):
        xdes = np.linspace(0, 1, 20)
        ydes = self.p2(xdes)
        xres, yres = self.p2.linspace(20)
        assert_almost_equal(xres, xdes)
        assert_almost_equal(yres, ydes)

    def test_fromroots(self):
        roots = [0, .5, 1]
        p = leg.Legendre.fromroots(roots, domain=[0, 1])
        res = p.coef
        tgt = leg.poly2leg([0, -1, 0, 1])
        assert_almost_equal(res, tgt)

    def test_fit(self):
        def f(x):
            return x * (x - 1) * (x - 2)

        x = np.linspace(0, 3)
        y = f(x)

        # test default value of domain
        p = leg.Legendre.fit(x, y, 3)
        assert_almost_equal(p.domain, [0, 3])

        # test that fit works in given domains
        p = leg.Legendre.fit(x, y, 3, None)
        assert_almost_equal(p(x), y)
        assert_almost_equal(p.domain, [0, 3])
        p = leg.Legendre.fit(x, y, 3, [])
        assert_almost_equal(p(x), y)
        assert_almost_equal(p.domain, [-1, 1])
        # test that fit accepts weights.
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        p = leg.Legendre.fit(x, yw, 3, w=w)
        assert_almost_equal(p(x), y)

    def test_identity(self):
        x = np.linspace(0, 3)
        p = leg.Legendre.identity()
        assert_almost_equal(p(x), x)
        p = leg.Legendre.identity([1, 3])
        assert_almost_equal(p(x), x)
Esempio n. 22
0
 def test_roots(self):
     p = leg.Legendre(leg.poly2leg([0, -1, 0, 1]), [0, 1])
     res = p.roots()
     tgt = [0, .5, 1]
     assert_almost_equal(res, tgt)
Esempio n. 23
0
def legendreToNewton(legCoeffs):
    return leg.Legendre(legCoeffs).convert(kind=np.polynomial.polynomial.Polynomial)
Esempio n. 24
0
 def test_trim(self):
     coef = [1, 1e-6, 1e-12, 0]
     p = leg.Legendre(coef)
     assert_equal(p.trim().coef, coef[:3])
     assert_equal(p.trim(1e-10).coef, coef[:2])
     assert_equal(p.trim(1e-5).coef, coef[:1])
Esempio n. 25
0
 def test_pow(self):
     tgt = leg.Legendre([1])
     for i in range(5):
         res = self.p1**i
         assert_(res == tgt)
         tgt = tgt * self.p1
Esempio n. 26
0
 def test_sub(self):
     tgt = leg.Legendre([1])
     assert_(self.p4 - self.p1 == tgt)
     assert_(self.p4 - [1, 2, 3] == tgt)
     assert_([2, 2, 3] - self.p1 == tgt)
Esempio n. 27
0
 def test_mod(self):
     tgt = leg.Legendre([1])
     assert_((self.p4 % self.p1) == tgt)
     assert_((self.p4 % [1, 2, 3]) == tgt)
     assert_(([2, 2, 3] % self.p1) == tgt)
Esempio n. 28
0
def test_hamiltonian():
    '''checks if hamiltonian is calculated correctly'''
    haml = schrod.hamiltonian((1,1), 'legendre', 1, 0)
    assert haml == L.Legendre((1,1))
    hamf = schrod.hamiltonian((1,2,3), 'fourier', 1, 0)
Esempio n. 29
0
def legfit(xs, ys, deg):
    coeffs = leg.legfit(xs, ys, deg)
    p = leg.Legendre(coeffs)
    return mkseries(xs, ys, p)
Esempio n. 30
0
 def test_floordiv(self):
     tgt = leg.Legendre([1])
     assert_(self.p4 // self.p1 == tgt)
     assert_(self.p4 // [1, 2, 3] == tgt)
     assert_([2, 2, 3] // self.p1 == tgt)