"""Functions on the cube [-1, 1]^n that are sums of products of polynomials in one variable, with exact derivatives and integrals (standard library only). A polynomial in one variable is a tuple of fractions, lowest degree first. A function is a list of terms, and a term is a tuple of n polynomials, one for each coordinate. """ from fractions import Fraction def poly(*coefficients): return tuple(Fraction(c) for c in coefficients) def poly_mul(f, g): out = [Fraction(0)] * (len(f) + len(g) - 1) for i, a in enumerate(f): for j, b in enumerate(g): out[i + j] += a * b return tuple(out) def poly_derivative(f): return tuple(k * f[k] for k in range(1, len(f))) def poly_integral(f): """The integral over [-1, 1].""" return sum((2 * c / (k + 1) for k, c in enumerate(f) if k % 2 == 0), Fraction(0)) class ProductSum: """A sum of products f_1(x_1) ... f_n(x_n).""" def __init__(self, dimension, terms=()): self.dimension = dimension self.terms = [tuple(term) for term in terms if all(any(factor) for factor in term)] def __add__(self, other): return ProductSum(self.dimension, self.terms + other.terms) def scaled(self, number): number = Fraction(number) return ProductSum(self.dimension, [(tuple(number * c for c in term[0]),) + term[1:] for term in self.terms]) def times(self, coordinate, factor): """The product with a polynomial in one coordinate.""" return ProductSum(self.dimension, [ term[:coordinate] + (poly_mul(term[coordinate], factor),) + term[coordinate + 1:] for term in self.terms]) def derivative(self, coordinate): return ProductSum(self.dimension, [ term[:coordinate] + (poly_derivative(term[coordinate]),) + term[coordinate + 1:] for term in self.terms]) def laplacian(self): out = ProductSum(self.dimension) for coordinate in range(self.dimension): out = out + self.derivative(coordinate).derivative(coordinate) return out def integral_with(self, other): """The integral over the cube of the product of the two functions.""" total = Fraction(0) for term1 in self.terms: for term2 in other.terms: value = Fraction(1) for f, g in zip(term1, term2): value *= poly_integral(poly_mul(f, g)) if not value: break total += value return total def total(functions): functions = list(functions) out = ProductSum(functions[0].dimension) for f in functions: out = out + f return out CLAMPED = poly(1, 0, -2, 0, 1) HINGED = poly(1, 0, -1) def example(dimension, bump=CLAMPED): """A function on the cube without symmetry: a sum of two products of the polynomials bump(t) (a + b t). With bump = CLAMPED = (1 - t^2)^2 every factor vanishes to second order at t = -1 and t = 1, so the function is in H^2_0 of the open cube. With bump = HINGED = 1 - t^2 the function vanishes on the boundary and its normal derivative does not.""" terms = [] for k in range(2): terms.append(tuple( poly_mul(bump, poly(1 + (k + 2 * i) % 3, (3 * k + i) % 4 - 1)) for i in range(dimension))) return ProductSum(dimension, terms)