# Copyright (C) 2014 Anders Logg
#
# This file is part of FFC.
#
# FFC is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FFC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with FFC. If not, see <http://www.gnu.org/licenses/>.
#
# First added:  2014-06-10
# Last changed: 2014-06-17
#
# This demo illustrates the use of custom integrals with mixed elements.
#
# Compile this form with FFC: ffc CustomMixedIntegral.ufl

# Define element
P2 = VectorElement("Lagrange", triangle, 2)
P1 = FiniteElement("Lagrange", triangle, 1)
TH = P2 * P1

# Define trial and test functions and right-hand side
(u, p) = TrialFunctions(TH)
(v, q) = TestFunctions(TH)
f = Coefficient(P2)

# Define facet normal and mesh size
n = FacetNormal(triangle)
h = 2.0*Circumradius(triangle)
h = (h('+') + h('-')) / 2

# Define custom measures (FIXME: prettify this)
dc0 = dc(0, metadata={"num_cells": 1})
dc1 = dc(1, metadata={"num_cells": 2})
dc2 = dc(2, metadata={"num_cells": 2})

# Define measures for integration
dx = dx + dc0 # domain integral
di = dc1      # interface integral
do = dc2      # overlap integral

# Parameters
alpha = 4.0

def tensor_jump(v, n):
    return outer(v('+'), n('+')) + outer(v('-'), n('-'))

def a_h(v, w):
    return inner(grad(v), grad(w))*dx \
         - inner(avg(grad(v)), tensor_jump(w, n))*di \
         - inner(avg(grad(w)), tensor_jump(v, n))*di

def b_h(v, q):
    return -div(v)*q*dx + jump(v, n)*avg(q)*di

def s_h(v, w):
    return inner(jump(grad(v)), jump(grad(w)))*do

# Bilinear form
a = a_h(u, v) + b_h(v, p) + b_h(u, q) + s_h(u, v)

# Linear form
L = dot(f, v)*dx
