__author__ = "Anders Logg (logg@simula.no)"
__date__ = "2005-03-14 -- 2005-07-05"
__copyright__ = "Copyright (C) 2005 Anders Logg"
__license__  = "GNU GPL Version 2"

"""This is a simple test program to verify the precision of quadrature
rules generated by FIAT."""

# FIAT modules
from FIAT.shapes import *
from FIAT.quadrature import *

class Polynomial:
    "A polynomial of degree q."

    def __init__(self, q):
        self.q = q

    def __call__(self, x):
        d = len(x)

        if d == 2:
            sum = 0.0
            sgn = 1
            for i in range(self.q + 1):
                for j in range(self.q + 1 - i):
                    sum += sgn*pow(x[0], i) * pow(x[1], j)
                    sgn = -sgn
            return sum
        elif d == 3:
            sum = 0.0
            sgn = 1
            for i in range(self.q + 1):
                for j in range(self.q + 1 - i):
                    for k in range(self.q + 1 - i - j):
                        sum += sgn*pow(x[0], i) * pow(x[1], j) * pow(x[2], k)
                        sgn = -sgn
            return sum
        else:
            raise RuntimeError, "Dimension must be 2 or 3."

def integral(basis, shape, m):
    """Compute integral of function with given number of points m in
    each dimension."""

    rule = make_quadrature(shape, m)
    x = rule.get_points()
    w = rule.get_weights()

    #print "Total number of quadrature points: " + str(len(x))

    sum = 0.0
    for i in range(len(x)):
        sum += w[i] * v(x[i])

    if shape == TRIANGLE:
        sum *= 0.5
    else:
        sum *= 0.75

    print "    m = %d: I = %.14e (total number of points: %d)" % (m, sum, len(x))


if __name__ == "__main__":
    
    print "  FIAT quadrature on triangles:"
    print "  -----------------------------"

    for q in range(0, 10):
        print "  q = %d:" % q
        v = Polynomial(q)
        for m in range(1, q + 3):
            integral(v, TRIANGLE, m)

    print ""
    print "  FIAT quadrature on tetrahedrons:"
    print "  --------------------------------"

    for q in range(0, 10):
        print "  q = %d:" % q
        v = Polynomial(q)
        for m in range(1, q + 3):
            I = integral(v, TETRAHEDRON, m)
