# -*- coding: utf-8 -*-
"""This module provides functionality for cell-wise assembly of forms in
Python, corresponding to the C++ LocalSolver functionality.

The C++ :py:class:`assemble <dolfin.cpp.assemble_local>` function
is wrapped with an additional preprocessing step where code is generated
using the FFC JIT compiler."""

# Copyright (C) 2015 Tormod Landet
#
# This file is part of DOLFIN.
#
# DOLFIN 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.
#
# DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.

# Import SWIG-generated extension module (DOLFIN C++)
import dolfin.cpp as cpp

# Local imports
from dolfin.fem.assembling import _create_dolfin_form

__all__ = ["assemble_local"]


# JIT assembler for local problems
def assemble_local(form, cell):
    """Assemble the given form on the given cell and return the
    corresponding local tensor.

    *Arguments*
        Depending on the input form, which may be a functional, linear
        form or bilinear form, a scalar value, a vector or a matrix is
        returned.

    The ``form`` can be either a UFL Form or a DOLFIN Form. The return
    value will be a Python float, or an appropriately sized numpy
    ndarray.

    To understand the connection between the returned local cell
    tensor and the global tensor the mapping can be found as normal
    from a function space as V.dofmap().cell_dofs(cell.index()).

    If you pass a UFL form it will be compiled with
    ``dolfin.Form(form)``. This operation is collective. If you do not
    run assemble_local on all MPI processes simultaneously you should
    pre-compile the form first on all ranks.

    """
    # Create dolfin Form object referencing all data needed by
    # assembler
    dolfin_form = _create_dolfin_form(form)

    assert dolfin_form.rank() in (0, 1, 2)
    tensor = cpp.fem.assemble_local(dolfin_form, cell)

    # Convert to float for scalars and matrix for bilinear forms
    if dolfin_form.rank() == 0:
        tensor = tensor[0]
    elif dolfin_form.rank() == 2:
        test_dofmap = dolfin_form.function_space(0).dofmap()
        test_dofs = test_dofmap.cell_dofs(cell.index())
        N = len(test_dofs)
        tensor = tensor.reshape((N, -1))

    # Return value
    return tensor
