Exemplo n.º 1
0
def newton_weights(x, newtonCotesOrder):
    """
    Constructs the weights for a composite Newton-Cotes rule for integration.
    These weights should be multipled by the step-size, equally spaced steps
    are assumed. The argument x should be a numpy array of the x samples points.
    
    If the order Newton-Cotes order specified does not produce a rule that fits
    into len(x), the order is decremented and that is used to fill gaps that do no fit.
    """
    # ensure we have a 1xN array
    x = np.array(x).squeeze()

    if newtonCotesOrder == 0:
        return np.ones(x.shape)

    W = newton_cotes(newtonCotesOrder, 1)[0]

    wx = np.zeros(x.shape, dtype=np.float64)

    N = len(W)

    i = 0

    while i < len(x) - 1:
        try:
            wx[i:(i + len(W))] += W

            i += len(W) - 1
        except ValueError as ex:

            if len(wx[i:(i + len(W))]) < len(W):
                newtonCotesOrder -= 1
                W = newton_cotes(newtonCotesOrder, 1)[0]

    return wx
Exemplo n.º 2
0
def newtonCotes(inf, sup, h, func):
    """
        nc's algorithms's tests 
    """
    nc1 = nc.trapeze(inf, sup, h, func)
    nc2 = nc.simpson_1_3(inf, sup, h, func)
    nc3 = nc.simpson_3_8(inf, sup, h, func)
    nc4 = nc.villarceau(inf, sup, h, func)
    print("trapeze :", nc1, "simpson 1/3 :", nc2)
    print("simpson 3/8 :", nc3, "villarceau :", nc4)

    # Use of integrate
    somme = [0, 0, 0, 0]
    x = inf
    N = int(abs(sup - inf) / h)
    for i in range(0, N):
        for n in range(1, 5):
            y = np.linspace(x, x + h, n + 1)
            an, B = integrate.newton_cotes(n, 1)
            dy = h / n
            quad = dy * np.sum(an * func(y))
            somme[n - 1] += quad
        x += h

    for result in somme:
        print('{:10.9f}'.format(result))
Exemplo n.º 3
0
 def mynewton_cotes(x, f) :
     if x.shape[0] < 2 :
         return 0
     rn = (x.shape[0] - 1) * (x - x[0]) / (x[-1] - x[0])
     #weights = scipy.integrate.newton_cotes(rn)[0]
     weights = newton_cotes(rn)[0]
     return (x[-1] - x[0]) / (x.shape[0] - 1) * np.dot(weights, f)
Exemplo n.º 4
0
    def test_newton_cotes2(self):
        """Test newton_cotes with points that are not evenly spaced."""

        x = np.array([0.0, 1.5, 2.0])
        y = x**2
        wts, errcoff = newton_cotes(x)
        exact_integral = 8.0/3
        numeric_integral = np.dot(wts, y)
        assert_almost_equal(numeric_integral, exact_integral)

        x = np.array([0.0, 1.4, 2.1, 3.0])
        y = x**2
        wts, errcoff = newton_cotes(x)
        exact_integral = 9.0
        numeric_integral = np.dot(wts, y)
        assert_almost_equal(numeric_integral, exact_integral)
Exemplo n.º 5
0
def _newton_cotes(order, lower, upper, segments=1, growth=False):
    """Backend for Newton-Cotes quadrature rule."""
    if order == 0:
        return numpy.array([0.5 * (lower + upper)]), numpy.ones(1)
    order = 2**order if growth else order

    if segments != 1 and order > 2:
        segments = segments if segments else int(numpy.sqrt(order))
        assert segments < order, "fewer samples to distribute than intervals"
        abscissas = []
        weights = []

        nodes = numpy.linspace(0, 1, segments + 1)
        for lower, upper in zip(nodes[:-1], nodes[1:]):

            abscissa, weight = _newton_cotes(order // segments, lower, upper)
            weight = weight * (upper - lower)
            if abscissas:
                weights[-1] += weight[0]
                abscissa = abscissa[1:]
                weight = weight[1:]
            abscissas.extend(abscissa)
            weights.extend(weight)

        assert len(abscissas) == order + 1
        assert len(weights) == order + 1
        return numpy.array(abscissas), numpy.array(weights)

    return (
        numpy.linspace(lower, upper, order + 1),
        newton_cotes(order)[0] / (upper - lower) / order,
    )
Exemplo n.º 6
0
    def test_newton_cotes2(self):
        """Test newton_cotes with points that are not evenly spaced."""

        x = np.array([0.0, 1.5, 2.0])
        y = x**2
        wts, errcoff = newton_cotes(x)
        exact_integral = 8.0/3
        numeric_integral = np.dot(wts, y)
        assert_almost_equal(numeric_integral, exact_integral)

        x = np.array([0.0, 1.4, 2.1, 3.0])
        y = x**2
        wts, errcoff = newton_cotes(x)
        exact_integral = 9.0
        numeric_integral = np.dot(wts, y)
        assert_almost_equal(numeric_integral, exact_integral)
Exemplo n.º 7
0
def _newton_cotes(order, lower, upper, growth):
    """Backend for Newton-Cotes quadrature rule."""
    if order == 0:
        return numpy.array([0.5*(lower+upper)]), numpy.ones(1)
    order = 2**order if growth else order
    return (
        numpy.linspace(lower, upper, order+1),
        newton_cotes(order)[0]/(upper-lower),
    )
Exemplo n.º 8
0
 def newton_cotes(x, f):
     if x.shape[0] < 2:
         return 0
     rn = (x.shape[0]-1)*(x-x[0])/(x[-1]-x[0])
     # Just making sure ...
     rn[0]= 0
     rn[-1]= len(rn)-1
     weights= integrate.newton_cotes(rn)[0]
     return (x[-1]-x[0])/(x.shape[0]-1)*numpy.dot(weights,f)
Exemplo n.º 9
0
 def newton_cotes(x, f):
     if x.shape[0] < 2:
         return 0
     rn = (x.shape[0] - 1) * (x - x[0]) / (x[-1] - x[0])
     # Just making sure ...
     rn[0] = 0
     rn[-1] = len(rn) - 1
     weights = integrate.newton_cotes(rn)[0]
     return (x[-1] - x[0]) / (x.shape[0] - 1) * numpy.dot(weights, f)
Exemplo n.º 10
0
def integrate_newton_cotes(func, a, b):
    N = 9
    X = numpy.linspace(a, b, N)
    A, B = integrate.newton_cotes(N - 1)
    result = 0

    for i in range(N):
        result += A[i] * func(X[i])

    result *= (b - a) / (N - 1)
    return result
Exemplo n.º 11
0
    def test_newton_cotes(self):
        """Test the first few degrees, for evenly spaced points."""
        n = 1
        wts, errcoff = newton_cotes(n, 1)
        assert_equal(wts, n*np.array([0.5, 0.5]))
        assert_almost_equal(errcoff, -n**3/12.0)

        n = 2
        wts, errcoff = newton_cotes(n, 1)
        assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0)
        assert_almost_equal(errcoff, -n**5/2880.0)

        n = 3
        wts, errcoff = newton_cotes(n, 1)
        assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0)
        assert_almost_equal(errcoff, -n**5/6480.0)

        n = 4
        wts, errcoff = newton_cotes(n, 1)
        assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0)
        assert_almost_equal(errcoff, -n**7/1935360.0)
Exemplo n.º 12
0
    def test_newton_cotes(self):
        """Test the first few degrees, for evenly spaced points."""
        n = 1
        wts, errcoff = newton_cotes(n, 1)
        assert_equal(wts, n*np.array([0.5, 0.5]))
        assert_almost_equal(errcoff, -n**3/12.0)

        n = 2
        wts, errcoff = newton_cotes(n, 1)
        assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0)
        assert_almost_equal(errcoff, -n**5/2880.0)

        n = 3
        wts, errcoff = newton_cotes(n, 1)
        assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0)
        assert_almost_equal(errcoff, -n**5/6480.0)

        n = 4
        wts, errcoff = newton_cotes(n, 1)
        assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0)
        assert_almost_equal(errcoff, -n**7/1935360.0)
 def newton_cotes(x, f):
     if x.shape[0] < 2:
         return 0
     rn = (x.shape[0] - 1) * (x - x[0]) / (x[-1] - x[0])
     weights = integrate.newton_cotes(rn)[0]
     """
     # I added this part for the last remaining non 5 points, it will only use the available points
     lw, lf = len(weights), len(f)
     if lw != lf:
         last_weights = []
         for i, fi in enumerate(f):
             last_weights.append(weights[i])
         weights = np.array(last_weights)
     """
     dot_wf = np.dot(weights, f)
     return (x[-1] - x[0]) / (x.shape[0] - 1) * dot_wf
Exemplo n.º 14
0
def integrate_newton_cotes(func, a, b):
    '''
    Calculates an integral of `func`
    for t = a..b via newton-cotes of order 9.
    '''
    # Количество точек используемых в формуле Ньютона-Котеса
    N = 9

    # the 9 sample points
    X = numpy.linspace(a, b, N)

    # get newton-cotes coefficients
    # for the order N
    A, B = integrate.newton_cotes(N - 1)
    result = 0

    for it in range(N):
        result += A[it] * func(X[it])

    # multiply by the average step
    result *= (b - a) / (N - 1)
    return result
Exemplo n.º 15
0
def _newton_cotes(order):
    """Backend for Newton-Cotes quadrature rule."""
    if order == 0:
        return numpy.full((1, 1), 0.5), numpy.ones(1)
    return numpy.linspace(0, 1,
                          order + 1), integrate.newton_cotes(order)[0] / order
Exemplo n.º 16
0
 def newton_cotes(x, f) :
     if x.shape[0] < 2 :
         return 0
     rn = (x.shape[0] - 1) * (x - x[0]) / (x[-1] - x[0])
     weights = integrate.newton_cotes(rn)[0]
     return (x[-1] - x[0]) / (x.shape[0] - 1) * np.dot(weights, f)
Exemplo n.º 17
0
def riemann_HG_knm(x,
                   y,
                   mode_in,
                   mode_out,
                   q1,
                   q2,
                   q1y=None,
                   q2y=None,
                   Axy=None,
                   cache=None,
                   delta=(0, 0),
                   params={},
                   newtonCotesOrder=0):

    if Axy is None:
        Axy == np.ones((len(x), len(y)))

    if q1y is None:
        q1y = q1

    if q2y is None:
        q2y = q2

    if len(mode_in) != 2 or len(mode_out) != 2:
        raise BasePyKatException(
            "Both mode in and out should be a container with modes [n m]")

    dx = abs(x[1] - x[0])
    dy = abs(y[1] - y[0])

    if cache is None:
        Hg_in = HG_mode(qx=q1, qy=q1y, n=mode_in[0], m=mode_in[1])
        Hg_out = HG_mode(qx=q2, qy=q2y, n=mode_out[0], m=mode_out[1])

        U1 = Hg_in.Unm(x + delta[0], y + delta[1])
        U2 = Hg_out.Unm(x, y).conjugate()

        if newtonCotesOrder > 0:

            W = newton_cotes(newtonCotesOrder, 1)[0]

            if newtonCotesOrder > 1:
                if (len(x) - len(W)) % newtonCotesOrder != 0:
                    raise ValueError(
                        "To use Newton-Cotes order {0} the number of data points in x must ensure: (N_x - ({0}+1)) mod {0} == 0"
                        .format(newtonCotesOrder))

                if (len(y) - len(W)) % newtonCotesOrder != 0:
                    raise ValueError(
                        "To use Newton-Cotes order {0} the number of data points in y must ensure: (N_y - ({0}+1)) mod {0} == 0"
                        .format(newtonCotesOrder))

            wx = np.zeros(x.shape, dtype=np.float64)
            wy = np.zeros(y.shape, dtype=np.float64)

            N = len(W)

            for i in range(0, (len(wx) - 1) / newtonCotesOrder):
                wx[(i * (N - 1)):(i * (N - 1) + N)] += W
            for i in range(0, (len(wy) - 1) / newtonCotesOrder):
                wy[(i * (N - 1)):(i * (N - 1) + N)] += W

            Wxy = np.outer(wx, wy)

        if newtonCotesOrder == 0:
            return dx * dy * np.einsum('ij,ij', Axy, U1 * U2)
        else:
            return dx * dy * np.einsum('ij,ij', Axy, U1 * U2 * Wxy)
    else:

        strx = "u1[%i,%i]" % (mode_in[0], mode_out[0])
        stry = "u2[%i,%i]" % (mode_in[1], mode_out[1])

        return dx * dy * np.einsum('ij,ij', Axy,
                                   np.outer(cache[strx], cache[stry]))