Exemple #1
0
def jit(ufl_object, parameters=None, indirect=False):
    """Just-in-time compile the given form or element

    Parameters:

      ufl_object : The UFL object to be compiled
      parameters : A set of parameters
    """
    # Check parameters
    parameters = validate_jit_parameters(parameters)

    # FIXME: Setting the log level here becomes a permanent side effect...
    # Set log level
    set_level(parameters["log_level"])
    set_prefix(parameters["log_prefix"])

    # Make unique module name for generated code
    kind, module_name = compute_jit_prefix(ufl_object, parameters)

    # Inspect cache and generate+build if necessary
    module = jit_build(ufl_object, module_name, parameters)

    # Raise exception on failure to build or import module
    if module is None:
        # TODO: To communicate directory name here, need dijitso params to call
        #fail_dir = dijitso.cache.create_fail_dir_path(signature, dijitso_cache_params)
        raise FFCJitError("A directory with files to reproduce the jit build failure has been created.")

    # Construct instance of object from compiled code unless indirect
    if indirect:
        return module_name
    else:
        # FIXME: Streamline number of return arguments here across kinds
        if kind == "form":
            if parameters.get("representation") == "quadrature" or \
                    any(itg.metadata().get("representation") == "quadrature" for itg in ufl_object.integrals()):
                from ffc.quadrature.deprecation import issue_deprecation_warning
                issue_deprecation_warning()

            compiled_form = _instantiate_form(module, module_name)
            return (compiled_form, module, module_name)
            # TODO: module, module_name are never used in dolfin, drop?
            #return _instantiate_form(module, module_name)
        elif kind == "element":
            fe, dm = _instantiate_element_and_dofmap(module, module_name)
            return fe, dm
        elif kind == "coordinate_mapping":
            cm = _instantiate_coordinate_mapping(module, module_name)
            return cm
        else:
            error("Unknown kind %s" % (kind,))
Exemple #2
0
from ufl import Form
from ufl.algorithms import as_form
from ffc import default_parameters, compile_form as ffc_compile_form
from ffc import constants
from ffc.log import set_level, ERROR

from caching import DiskCached, KernelCached
from op2 import Kernel
from mpi import MPI

from ir.ast_base import PreprocessNode, Root

_form_cache = {}

# Silence FFC
set_level(ERROR)

ffc_parameters = default_parameters()
ffc_parameters['write_file'] = False
ffc_parameters['format'] = 'pyop2'
ffc_parameters['pyop2-ir'] = True

# Include an md5 hash of pyop2_geometry.h in the cache key
with open(os.path.join(os.path.dirname(__file__), 'pyop2_geometry.h')) as f:
    _pyop2_geometry_md5 = md5(f.read()).hexdigest()


def _check_version():
    from version import __compatible_ffc_version_info__ as compatible_version, \
        __compatible_ffc_version__ as version
    try:
Exemple #3
0
from ffc.quadrature.quadraturetransformerbase import EmptyIntegrandError

from pyop2.caching import DiskCached
from pyop2.op2 import Kernel
from pyop2.mpi import MPI
from pyop2.coffee.ast_base import PreprocessNode, Root

import fiat_utils
import functionspace
from parameters import parameters as default_parameters

_form_cache = {}

# Only spew ffc message on rank zero
if MPI.comm.rank != 0:
    log.set_level(log.ERROR)
del log


def _check_version():
    from version import __compatible_ffc_version_info__ as compatible_version, \
        __compatible_ffc_version__ as version
    try:
        if constants.PYOP2_VERSION_INFO[:2] == compatible_version[:2]:
            return
    except AttributeError:
        pass
    raise RuntimeError("Incompatible PyOP2 version %s and FFC PyOP2 version %s."
                       % (version, getattr(constants, 'PYOP2_VERSION', 'unknown')))

                        solve(a3 == L3, u1, bcs=bcu, solver_parameters=vparams)
                end()

                if save:
                    # Save to file
                    ufile << u1
                    pfile << p1

                if compute_norms:
                    nu1, np1 = norm(u1), norm(p1)
                    if MPI.rank(mpi_comm_world()) == 0:
                        print t, 'u1:', nu1, 'p1:', np1

                # Move to next time step
                u0.assign(u1)
                t += dt
        t = timings(True)
        for task in ['Assemble system', 'Build sparsity', 'PETSc Krylov solver']:
            self.register_timing(task, float(t.get(task, 'Total time')))

if __name__ == '__main__':
    set_log_active(False)
    from ffc.log import set_level
    set_level('ERROR')

    # Benchmark
    DolfinNavierStokes().main()

    # Output VTU files
    # DolfinNavierStokes().navier_stokes(save=True)
Exemple #5
0
            # Compute solution
            u = Function(V)
        if preassemble:
            with self.timed_region('matrix assembly'):
                A = assemble(a)
                bc.apply(A)
                self.meta['dofs'] = A.size(0)
            with self.timed_region('rhs assembly'):
                b = assemble(L)
                bc.apply(b)
            with self.timed_region('solve'):
                solve(A, u.vector(), b, 'cg', pc)
        else:
            with self.timed_region('solve'):
                solve(a == L, u, bcs=bc, solver_parameters=params)
        a = Expression(analytical[dim])
        l2 = sqrt(assemble(dot(u - a, u - a) * dx))
        if print_norm and MPI.rank(mpi_comm_world()) == 0:
            print 'L2 error norm:', l2
        t = timings(True)
        for task in ['Apply (PETScMatrix)', 'Apply (PETScVector)', 'Assemble cells',
                     'Build sparsity', 'DirichletBC apply', 'PETSc Krylov solver']:
            self.register_timing(task, float(t.get(task, 'Total time')))

if __name__ == '__main__':
    set_log_active(False)
    from ffc.log import set_level
    set_level('ERROR')

    DolfinPoisson().main()
import sys
import os
import math
import xml.etree.cElementTree as ET
from firedrake import * 
op2.init(log_level="ERROR")
from ffc import log as ffc_log
ffc_log.set_level(ffc_log.ERROR)
from ufl import log as ufl_log
ufl_log.set_level(ufl_log.ERROR)
import gravitywaves
from mixedoperators import *
import pressuresolver.solvers
from pressuresolver.operators import *
from pressuresolver.preconditioners import *
from pressuresolver.smoothers import *
from pressuresolver.mu_tilde import *
from pressuresolver.lumpedmass import *
from pressuresolver.hierarchy import *
from orography import *
from auxilliary.logger import *
from auxilliary.ksp_monitor import *
from auxilliary.gaussian_expression import *
import profile_wrapper
from parameters import Parameters
from mpi4py import MPI
from pyop2 import profiling
from pyop2.profiling import timed_region
from pyop2 import performance_summary
from pyop2.base import ParLoop
from firedrake.petsc import PETSc
Exemple #7
0
from pyop2.caching import DiskCached
from pyop2.op2 import Kernel
from pyop2.mpi import MPI

from coffee.base import PreprocessNode, Root, Invert

import firedrake.fiat_utils as fiat_utils
import firedrake.functionspace as functionspace
from firedrake.parameters import parameters as default_parameters

_form_cache = {}

# Only spew ffc message on rank zero
if MPI.comm.rank != 0:
    log.set_level(log.ERROR)
del log


def _check_version():
    from firedrake.version import __compatible_ffc_version_info__ as compatible_version, \
        __compatible_ffc_version__ as version
    try:
        if constants.FIREDRAKE_VERSION_INFO[:2] == compatible_version[:2]:
            return
    except AttributeError:
        pass
    raise RuntimeError(
        "Incompatible Firedrake version %s and FFC version %s." %
        (version, getattr(constants, 'FIREDRAKE_VERSION', 'unknown')))
Exemple #8
0
def jit_form(form, parameters=None):
    "Just-in-time compile the given form."
    from ffc.backends.ufc import build_ufc_module

    # Check that we get a Form
    if not isinstance(form, Form):
        error("Unable to convert object to a UFL form: %s" % repr(form))

    # Check parameters
    parameters = _check_parameters(form, parameters)

    # Set log level
    set_level(parameters["log_level"])
    set_prefix(parameters["log_prefix"])

    # Wrap input
    jit_object = JITObject(form, parameters)

    # Set prefix for generated code
    module_name = "ffc_form_" + jit_object.signature()

    # Use Instant cache if possible
    cache_dir = parameters["cache_dir"] or None
    module = instant.import_module(module_name, cache_dir=cache_dir)
    if module:
        debug("Reusing form from cache.")
    else:
        # Take lock to serialise file removal.
        # Need to add "_0" to lock as instant.import_module acquire
        # lock with name: module_name
        with instant.file_lock(instant.get_default_cache_dir(),
                               module_name + "_0") as lock:

            # Retry Instant cache. The module may have been created while we waited
            # for the lock, even if it didn't exist before.
            module = instant.import_module(module_name, cache_dir=cache_dir)
            if module:
                debug("Reusing form from cache.")
            else:
                # Write a message
                log(INFO + 5,
                    "Calling FFC just-in-time (JIT) compiler, this may take some time.")

                # Generate code
                compile_form(form,
                             prefix=module_name,
                             parameters=parameters)

                # Build module using Instant (through UFC)
                debug("Compiling and linking Python extension module, this may take some time.")
                hfile   = module_name + ".h"
                cppfile = module_name + ".cpp"

                if parameters["cpp_optimize"]:
                    cppargs = parameters["cpp_optimize_flags"].split()
                else:
                    cppargs = ["-O0"]

                module = build_ufc_module(
                    hfile,
                    source_directory = os.curdir,
                    signature = module_name,
                    sources = [cppfile] if parameters["split"] else [],
                    cppargs = cppargs,
                    cache_dir = cache_dir)

                # Remove code
                if os.path.isfile(hfile):
                    os.unlink(hfile)
                if parameters["split"] :
                    if os.path.isfile(cppfile):
                        os.unlink(cppfile)

    # Construct instance of compiled form
    check_swig_version(module)
    prefix = module_name
    compiled_form = _instantiate_form(module, prefix)
    return compiled_form, module, prefix