firedrake package

Submodules

firedrake.assemble module

firedrake.assemble.assemble(f, tensor=None, bcs=None, form_compiler_parameters=None, inverse=False, mat_type=None, sub_mat_type=None, appctx={}, **kwargs)[source]

Evaluate f.

Parameters:
  • f – a Form, Expr or a TensorBase expression.
  • tensor – an existing tensor object to place the result in (optional).
  • bcs – a list of boundary conditions to apply (optional).
  • form_compiler_parameters – (optional) dict of parameters to pass to the form compiler. Ignored if not assembling a Form. Any parameters provided here will be overridden by parameters set on the Measure in the form. For example, if a quadrature_degree of 4 is specified in this argument, but a degree of 3 is requested in the measure, the latter will be used.
  • inverse – (optional) if f is a 2-form, then assemble the inverse of the local matrices.
  • mat_type – (optional) string indicating how a 2-form (matrix) should be assembled – either as a monolithic matrix (‘aij’ or ‘baij’), a block matrix (‘nest’), or left as a ImplicitMatrix giving matrix-free actions (‘matfree’). If not supplied, the default value in parameters["default_matrix_type"] is used. BAIJ differs from AIJ in that only the block sparsity rather than the dof sparsity is constructed. This can result in some memory savings, but does not work with all PETSc preconditioners. BAIJ matrices only make sense for non-mixed matrices.
  • sub_mat_type – (optional) string indicating the matrix type to use inside a nested block matrix. Only makes sense if mat_type is nest. May be one of ‘aij’ or ‘baij’. If not supplied, defaults to parameters["default_sub_matrix_type"].
  • appctx – Additional information to hang on the assembled matrix if an implicit matrix is requested (mat_type “matfree”).

If f is a Form then this evaluates the corresponding integral(s) and returns a float for 0-forms, a Function for 1-forms and a Matrix or ImplicitMatrix for 2-forms.

If f is an expression other than a form, it will be evaluated pointwise on the Functions in the expression. This will only succeed if all the Functions are on the same FunctionSpace.

If f is a Slate tensor expression, then it will be compiled using Slate’s linear algebra compiler.

If tensor is supplied, the assembled result will be placed there, otherwise a new object of the appropriate type will be returned.

If bcs is supplied and f is a 2-form, the rows and columns of the resulting Matrix corresponding to boundary nodes will be set to 0 and the diagonal entries to 1. If f is a 1-form, the vector entries at boundary nodes are set to the boundary condition values.

firedrake.assemble_expressions module

class firedrake.assemble_expressions.Assign(lhs, rhs)[source]

Bases: firedrake.assemble_expressions.AssignmentBase

A UFL assignment operator.

ufl_free_indices = ()
ufl_index_dimensions = ()
ufl_shape
class firedrake.assemble_expressions.AssignmentBase(lhs, rhs)[source]

Bases: ufl.core.operator.Operator

Base class for UFL augmented assignments.

ast
ufl_shape
class firedrake.assemble_expressions.AugmentedAssignment(lhs, rhs)[source]

Bases: firedrake.assemble_expressions.AssignmentBase

Base for the augmented assignment operators +=, -=, *=, /=

class firedrake.assemble_expressions.ComponentTensor(expression, indices)[source]

Bases: ufl.tensors.ComponentTensor

Subclass of ufl.tensors.ComponentTensor which only prints the first operand.

ast
class firedrake.assemble_expressions.DummyFunction(function, argnum, intent=Access('READ'))[source]

Bases: ufl.coefficient.Coefficient

A dummy object to take the place of a Function in the expression. This has the sole role of producing the right strings when the expression is unparsed and when the arguments are formatted.

arg
ast
class firedrake.assemble_expressions.ExpressionSplitter(variable_cache=None)[source]

Bases: ufl.algorithms.transformer.ReuseTransformer

Split an expression tree into a subtree for each component of the appropriate FunctionSpace.

component_tensor(o, *operands)[source]

Only return the first operand.

indexed(o, *operands)[source]

Reconstruct the ufl.indexed.Indexed only if the coefficient is defined on a FunctionSpace with rank 1.

operator(o, *operands)[source]

Reconstruct an operator on each of the component spaces.

product(o, *operands)[source]

Reconstruct a product on each of the component spaces.

split(expr)[source]

Split the given expression.

terminal(o)[source]
class firedrake.assemble_expressions.ExpressionWalker[source]

Bases: ufl.algorithms.transformer.ReuseTransformer

algebra_operator(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched

as a default rule.

coefficient(o)[source]
component_tensor(o, *operands)[source]

Override string representation to only print first operand.

condition(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched

as a default rule.

conditional(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched

as a default rule.

indexed(o, *operands)[source]

Override string representation to only print first operand.

ln(o, *operands)[source]
math_function(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched

as a default rule.

operator(o)[source]
power(o, *operands)[source]
walk(expr)[source]

Walk the given expression and return a tuple of the transformed expression, the list of coefficients sorted by their count and the function space the expression is defined on.

class firedrake.assemble_expressions.IAdd(lhs, rhs)[source]

Bases: firedrake.assemble_expressions.AugmentedAssignment

A UFL += operator.

ufl_free_indices = ()
ufl_index_dimensions = ()
class firedrake.assemble_expressions.IDiv(lhs, rhs)[source]

Bases: firedrake.assemble_expressions.AugmentedAssignment

A UFL /= operator.

ufl_free_indices = ()
ufl_index_dimensions = ()
class firedrake.assemble_expressions.IMul(lhs, rhs)[source]

Bases: firedrake.assemble_expressions.AugmentedAssignment

A UFL *= operator.

ufl_free_indices = ()
ufl_index_dimensions = ()
class firedrake.assemble_expressions.ISub(lhs, rhs)[source]

Bases: firedrake.assemble_expressions.AugmentedAssignment

A UFL -= operator.

ufl_free_indices = ()
ufl_index_dimensions = ()
class firedrake.assemble_expressions.Indexed(expression, multiindex)[source]

Bases: ufl.indexed.Indexed

Subclass of ufl.indexed.Indexed which only prints the first operand.

ast
class firedrake.assemble_expressions.Ln(argument)[source]

Bases: ufl.mathfunctions.Ln

Subclass of ufl.mathfunctions.Ln which prints log(x) instead of ln(x).

ast
class firedrake.assemble_expressions.Power(a, b)[source]

Bases: ufl.algebra.Power

Subclass of ufl.algebra.Power which prints pow(x,y) instead of x**y.

ast
firedrake.assemble_expressions.assemble_expression(expr, subset=None)[source]

Evaluates UFL expressions on Functions pointwise and assigns into a new Function.

firedrake.assemble_expressions.evaluate_expression(expr, subset=None)[source]

Evaluates UFL expressions on Functions.

firedrake.assemble_expressions.evaluate_preprocessed_expression(kernel, args, subset=None)[source]
firedrake.assemble_expressions.expression_kernel(expr, args)[source]

Produce a pyop2.Kernel from the processed UFL expression expr and the corresponding args.

firedrake.assemble_expressions.ufl_type(*args, **kwargs)[source]

Decorator mimicing ufl.core.ufl_type.ufl_type().

Additionally adds the class decorated to the appropriate set of ufl classes.

firedrake.bcs module

class firedrake.bcs.DirichletBC(V, g, sub_domain, method='topological')[source]

Bases: object

Implementation of a strong Dirichlet boundary condition.

Parameters:
  • V – the FunctionSpace on which the boundary condition should be applied.
  • g – the boundary condition values. This can be a Function on V, a Constant, an Expression, an iterable of literal constants (converted to an Expression), or a literal constant which can be pointwise evaluated at the nodes of V. Expressions are projected onto V if it does not support pointwise evaluation.
  • sub_domain – the integer id(s) of the boundary region over which the boundary condition should be applied. The string “on_boundary” may be used to indicate all of the boundaries of the domain. In the case of extrusion the top and bottom strings are used to flag the bcs application on the top and bottom boundaries of the extruded mesh respectively.
  • method – the method for determining boundary nodes. The default is “topological”, indicating that nodes topologically associated with a boundary facet will be included. The alternative value is “geometric”, which indicates that nodes associated with basis functions which do not vanish on the boundary will be included. This can be used to impose strong boundary conditions on DG spaces, or no-slip conditions on HDiv spaces.
apply(r, u=None)[source]

Apply this boundary condition to r.

Parameters:
  • r – a Function or Matrix to which the boundary condition should be applied.
  • u – an optional current state. If u is supplied then r is taken to be a residual and the boundary condition nodes are set to the value u-bc. Supplying u has no effect if r is a Matrix rather than a Function. If u is absent, then the boundary condition nodes of r are set to the boundary condition values.

If r is a Matrix, it will be assembled with a 1 on diagonals where the boundary condition applies and 0 in the corresponding rows and columns.

domain_args[source]

The sub_domain the BC applies to.

function_arg

The value of this boundary condition.

function_space()[source]

The FunctionSpace on which this boundary condition should be applied.

homogenize()[source]

Convert this boundary condition into a homogeneous one.

Set the value to zero.

node_set[source]

The subset corresponding to the nodes at which this boundary condition applies.

nodes[source]

The list of nodes at which this boundary condition applies.

restore()[source]

Restore the original value of this boundary condition.

This uses the value passed on instantiation of the object.

set(r, val)[source]

Set the boundary nodes to a prescribed (external) value. :arg r: the Function to which the value should be applied. :arg val: the prescribed value.

set_value(val)[source]

Set the value of this boundary condition.

Parameters:val – The boundary condition values. See DirichletBC for valid values.
zero(r)[source]

Zero the boundary condition nodes on r.

Parameters:r – a Function to which the boundary condition should be applied.
firedrake.bcs.homogenize(bc)[source]

Create a homogeneous version of a DirichletBC object and return it. If bc is an iterable containing one or more DirichletBC objects, then return a list of the homogeneous versions of those DirichletBCs.

Parameters:bc – a DirichletBC, or iterable object comprising DirichletBC(s).

firedrake.checkpointing module

class firedrake.checkpointing.DumbCheckpoint(basename, single_file=True, mode=2, comm=None)[source]

Bases: object

A very dumb checkpoint object.

This checkpoint object is capable of writing Functions to disk in parallel (using HDF5) and reloading them on the same number of processes and a Mesh() constructed identically.

Parameters:
  • basename – the base name of the checkpoint file.
  • single_file – Should the checkpoint object use only a single on-disk file (irrespective of the number of stored timesteps)? See new_file() for more details.
  • mode – the access mode (one of FILE_READ, FILE_CREATE, or FILE_UPDATE)
  • comm – (optional) communicator the writes should be collective over.

This object can be used in a context manager (in which case it closes the file when the scope is exited).

Note

This object contains both a PETSc Viewer, used for storing and loading Function data, and an File opened on the same file handle. DO NOT call File.close() on the latter, this will cause breakages.

close()[source]

Close the checkpoint file (flushing any pending writes)

get_timesteps()[source]

Return all the time steps (and time indices) in the current checkpoint file.

This is useful when reloading from a checkpoint file that contains multiple timesteps and one wishes to determine the final available timestep in the file.

h5file

An h5py File object pointing at the open file handle.

has_attribute(obj, name)[source]

Check for existance of an HDF5 attribute on a specified data object.

Parameters:
  • obj – The path to the data object.
  • name – The name of the attribute.
load(function, name=None)[source]

Store a function from the checkpoint file.

Parameters:
  • function – The function to load values into.
  • name – an (optional) name used to find the function values. If not provided, uses function.name().

This function is timestep-aware and reads from the appropriate place if set_timestep() has been called.

new_file(name=None)[source]

Open a new on-disk file for writing checkpoint data.

Parameters:name – An optional name to use for the file, an extension of .h5 is automatically appended.

If name is not provided, a filename is generated from the basename used when creating the DumbCheckpoint object. If single_file is True, then we write to BASENAME.h5 otherwise, each time new_file() is called, we create a new file with an increasing index. In this case the files created are:

BASENAME_0.h5
BASENAME_1.h5
...
BASENAME_n.h5

with the index incremented on each invocation of new_file() (whenever the custom name is not provided).

read_attribute(obj, name, default=None)[source]

Read an HDF5 attribute on a specified data object.

Parameters:
  • obj – The path to the data object.
  • name – The name of the attribute.
  • default – Optional default value to return. If not provided an AttributeError is raised if the attribute does not exist.
set_timestep(t, idx=None)[source]

Set the timestep for output.

Parameters:
  • t – The timestep value.
  • idx – An optional timestep index to use, otherwise an internal index is used, incremented by 1 every time set_timestep() is called.
store(function, name=None)[source]

Store a function in the checkpoint file.

Parameters:
  • function – The function to store.
  • name – an (optional) name to store the function under. If not provided, uses function.name().

This function is timestep-aware and stores to the appropriate place if set_timestep() has been called.

vwr

The PETSc Viewer used to store and load function data.

write_attribute(obj, name, val)[source]

Set an HDF5 attribute on a specified data object.

Parameters:
  • obj – The path to the data object.
  • name – The name of the attribute.
  • val – The attribute value.

Raises AttributeError if writing the attribute fails.

class firedrake.checkpointing.HDF5File(filename, file_mode, comm=None)[source]

Bases: object

An object to facilitate checkpointing.

This checkpoint object is capable of writing Functions to disk in parallel (using HDF5) and reloading them on the same number of processes and a Mesh() constructed identically.

Parameters:
  • filename – filename (including suffix .h5) of checkpoint file.
  • file_mode – the access mode, passed directly to h5py, see File for details on the meaning.
  • comm – communicator the writes should be collective over.

This object can be used in a context manager (in which case it closes the file when the scope is exited).

attributes(obj)[source]
Parameters:obj – The path to the group.
close()[source]

Close the checkpoint file (flushing any pending writes)

flush()[source]

Flush any pending writes.

get_timestamps()[source]

Get the timestamps this HDF5File knows about.

read(function, path, timestamp=None)[source]

Store a function from the checkpoint file.

Parameters:
  • function – The function to load values into.
  • path – the path under which the function is stored.
write(function, path, timestamp=None)[source]

Store a function in the checkpoint file.

Parameters:
  • function – The function to store.
  • path – the path to store the function under.
  • timestamp – timestamp associated with function, or None for stationary data
firedrake.checkpointing.FILE_READ = 0

Open a checkpoint file for reading. Raises an error if file does not exist.

firedrake.checkpointing.FILE_CREATE = 1

Create a checkpoint file. Truncates the file if it exists.

firedrake.checkpointing.FILE_UPDATE = 2

Open a checkpoint file for updating. Creates the file if it does not exist, providing both read and write access.

firedrake.citations module

class firedrake.citations.Citations[source]

Bases: dict

Entry point to citations management.

This singleton object may be used to record Bibtex citation information and then register that a particular citation is relevant for a particular computation. It hooks up with PETSc’s citation registration mechanism, so that running with -citations does the right thing.

Example usage:

Citations().add("key", "bibtex-entry-for-my-funky-method")

...

if using_funky_method:
    Citations().register("key")
add(key, entry)[source]

Add a paper to the database of possible citations.

Parameters:
  • key – The key to use.
  • entry – The bibtex entry.
classmethod print_at_exit()[source]

Print citations when exiting.

register(key)[source]

Register a paper to be cited so that PETSc knows about it.

Parameters:key – The key of the relevant citation.
Raises:KeyError if no such citation is found in the database.

Papers to be cited can be added using add().

Note

The intended use is that register() should be called only when the referenced functionality is actually being used.

firedrake.constant module

class firedrake.constant.Constant(value, domain=None)[source]

Bases: ufl.coefficient.Coefficient

A “constant” coefficient

A Constant takes one value over the whole Mesh(). The advantage of using a Constant in a form rather than a literal value is that the constant will be passed as an argument to the generated kernel which avoids the need to recompile the kernel if the form is assembled for a different value of the constant.

Parameters:
  • value – the value of the constant. May either be a scalar, an iterable of values (for a vector-valued constant), or an iterable of iterables (or numpy array with 2-dimensional shape) for a tensor-valued constant.
  • domain – an optional Mesh() on which the constant is defined.

Note

If you intend to use this Constant in a Form on its own you need to pass a Mesh() as the domain argument.

assign(value)[source]

Set the value of this constant.

Parameters:value – A value of the appropriate shape
cell_node_map(bcs=None)[source]

Return a null cell to node map.

evaluate(x, mapping, component, index_values)[source]

Return the evaluation of this Constant.

Parameters:
  • x – The coordinate to evaluate at (ignored).
  • mapping – A mapping (ignored).
  • component – The requested component of the constant (may be None or () to obtain all components).
  • index_values – ignored.
exterior_facet_node_map(bcs=None)[source]

Return a null exterior facet to node map.

function_space()[source]

Return a null function space.

interior_facet_node_map(bcs=None)[source]

Return a null interior facet to node map.

split()[source]
values()[source]

Return a (flat) view of the value of the Constant.

firedrake.dmhooks module

Firedrake uses PETSc for its linear and nonlinear solvers. The interaction is carried out through DM objects. These carry around any user-defined application context and can be used to inform the solvers how to create field decompositions (for fieldsplit preconditioning) as well as creating sub-DMs (which only contain some fields), along with multilevel information (for geometric multigrid)

The way Firedrake interacts with these DMs is, broadly, as follows:

A DM is tied to a FunctionSpace and remembers what function space that is. To avoid reference cycles defeating the garbage collector, the DM holds a weakref to the FunctionSpace (which holds a strong reference to the DM). Use get_function_space() to get the function space attached to the DM, and set_function_space() to attach it.

Similarly, when a DM is used in a solver, an application context is attached to it, such that when PETSc calls back into Firedrake, we can grab the relevant information (how to make the Jacobian, etc…). This functions in a similar way using set_appctx() and get_appctx() on the DM. You can set whatever you like in here, but most of the rest of Firedrake expects to find either None or else a firedrake.solving_utils._SNESContext object.

A crucial part of this, for composition with multi-level solvers (-pc_type mg and -snes_type fas) is decomposing the DMs. When a field decomposition is created, the callback create_field_decomposition() checks to see if an application context exists. If so, it splits it apart (one for each of fields) and attaches these split contexts to the subdms returned to PETSc. This facilitates runtime composition with multilevel solvers. When coarsening a DM, the application context is coarsened and transferred to the coarse DM. The combination of these two symbolic transfer operations allow us to nest geometric multigrid preconditioning inside fieldsplit preconditioning, without having to set everything up in advance.

firedrake.dmhooks.attach_hooks(dm, level=None, sf=None, section=None)[source]

Attach callback hooks to a DM.

Parameters:
  • DM – The DM to attach callbacks to.
  • level – Optional refinement level.
  • sf – Optional PETSc SF object describing the DM’s points.
  • section – Optional PETSc Section object describing the DM’s data layout.
firedrake.dmhooks.coarsen(dm, comm)[source]

Callback to coarsen a DM.

Parameters:
  • DM – The DM to coarsen.
  • comm – The communicator for the new DM (ignored)

This transfers a coarse application context over to the coarsened DM (if found on the input DM).

firedrake.dmhooks.create_field_decomposition(dm, *args, **kwargs)[source]

Callback to decompose a DM.

Parameters:DM – The DM.

This grabs the function space in the DM, splits it apart (only makes sense for mixed function spaces) and returns the DMs on each of the subspaces. If an application context is present on the input DM, it is split into individual field contexts and set on the appropriate subdms as well.

firedrake.dmhooks.create_matrix(dm)[source]

Callback to create a matrix from this DM.

Parameters:DM – The DM.

Note

This only works if an application context is set, in which case it returns the stored Jacobian. This does not make a new matrix.

firedrake.dmhooks.create_subdm(dm, fields, *args, **kwargs)[source]

Callback to create a sub-DM describing the specified fields.

Parameters:
  • DM – The DM.
  • fields – The fields in the new sub-DM.

Note

This should, but currently does not, transfer appropriately split application contexts onto the sub-DMs.

firedrake.dmhooks.get_appctx(dm)[source]

Get an application context from a DM.

Parameters:DM – The DM.
Returns:Either the stored application context, or None if none was found.
firedrake.dmhooks.get_function_space(dm)[source]

Get the FunctionSpace attached to this DM.

Parameters:dm – The DM to get the function space from.
Raises:RuntimeError – if no function space was found.
firedrake.dmhooks.refine(dm, comm)[source]

Callback to refine a DM.

Parameters:
  • DM – The DM to refine.
  • comm – The communicator for the new DM (ignored)
firedrake.dmhooks.set_appctx(dm, ctx)[source]

Set an application context on a DM.

Parameters:
  • DM – The DM.
  • ctx – The context.

Note

This stores a weakref to the context in the DM, so you should hold a strong reference somewhere else.

firedrake.dmhooks.set_function_space(dm, V)[source]

Set the FunctionSpace on this DM.

Parameters:
  • dm – The DM
  • V – The function space.

Note

This stores a weakref to the function space in the DM, so you should hold a strong reference somewhere else.

firedrake.dmplex module

firedrake.dmplex.boundary_nodes()

Extract boundary nodes from a function space..

Parameters:
  • V – the function space
  • sub_domain – a mesh marker selecting the part of the boundary (may be “on_boundary” indicating the entire boundary).
  • method – how to identify boundary dofs on the reference cell.
Returns:

a numpy array of unique nodes on the boundary of the requested subdomain.

firedrake.dmplex.cell_facet_labeling()

Computes a labeling for the facet numbers on a particular cell (interior and exterior facet labels). The i-th local facet is represented as:

cell_facets[c, i]

If this result is 0, then the local facet ci is an exterior facet, otherwise if the result is 1 it is interior.

Parameters:
  • plex – The DMPlex object representing the mesh topology.
  • cell_numbering – PETSc.Section describing the global cell numbering
  • cell_closures – 2D array of ordered cell closures.
firedrake.dmplex.clear_adjacency_callback()

Clear the callback for DMPlexGetAdjacency.

Parameters:dm – The DMPlex object
firedrake.dmplex.closure_ordering()

Apply Fenics local numbering to a cell closure.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • vertex_numbering – Section describing the universal vertex numbering
  • cell_numbering – Section describing the global cell numbering
  • entity_per_cell – List of the number of entity points in each dimension
Vertices := Ordered according to global/universal
vertex numbering
Edges/faces := Ordered according to lexicographical
ordering of non-incident vertices
firedrake.dmplex.create_section()

Create the section describing a global numbering.

Parameters:
  • mesh – The mesh.
  • nodes_per_entity – Number of nodes on each type of topological entity of the mesh. Or, if the mesh is extruded, the number of nodes on, and on top of, each topological entity in the base mesh.
Returns:

A PETSc Section providing the number of dofs, and offset of each dof, on each mesh point.

firedrake.dmplex.exchange_cell_orientations()

Halo exchange of cell orientations.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • section – Section describing the cell numbering
  • orientations – Cell orientations to exchange, values in the halo will be overwritten.
firedrake.dmplex.facet_numbering()

Compute the parent cell(s) and the local facet number within each parent cell for each given facet.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • kind – String indicating the facet kind (interior or exterior)
  • facets – Array of input facets
  • cell_numbering – Section describing the global cell numbering
  • cell_closures – 2D array of ordered cell closures
firedrake.dmplex.get_cell_markers()

Get the cells marked by a given subdomain_id.

Parameters:
  • plex – The DM for the mesh topology
  • cell_numbering – Section mapping plex cell points to firedrake cell indices.
  • subdomain_id – The subdomain_id to look for.
Raises:

ValueError – if the subdomain_id is not valid.

Returns:

A numpy array (possibly empty) of the cell ids.

firedrake.dmplex.get_cell_nodes()

Builds the DoF mapping.

Parameters:
  • mesh – The mesh
  • global_numbering – Section describing the global DoF numbering
  • entity_dofs – FInAT element entity dofs for the cell
  • offset – offsets for each entity dof walking up a column.

Preconditions: This function assumes that cell_closures contains mesh entities ordered by dimension, i.e. vertices first, then edges, faces, and finally the cell. For quadrilateral meshes, edges corresponding to dimension (0, 1) in the FInAT element must precede edges corresponding to dimension (1, 0) in the FInAT element.

firedrake.dmplex.get_cell_remote_ranks()

Returns an array assigning the rank of the owner to each locally visible cell. Locally owned cells have -1 assigned to them.

Parameters:plex – The DMPlex object encapsulating the mesh topology
firedrake.dmplex.get_entity_classes()

Builds PyOP2 entity class offsets for all entity levels.

Parameters:plex – The DMPlex object encapsulating the mesh topology
firedrake.dmplex.get_facet_markers()

Get an array of facet labels in the mesh.

Parameters:
  • dm – The DM that contains labels.
  • facets – The array of facet points.
Returns:

a numpy array of facet ids (or None if all facets had the default marker).

firedrake.dmplex.get_facet_nodes()

Build to DoF mapping from facets.

Parameters:
  • mesh – The mesh.
  • cell_nodes – numpy array mapping from cells to function space nodes.
  • label – which set of facets to ask for (interior_facets or exterior_facets).
  • offset – optional offset (extruded only).
Returns:

numpy array mapping from facets to nodes in the closure of the support of that facet.

firedrake.dmplex.get_facet_ordering()

Builds a list of all facets ordered according to the given numbering.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • facet_numbering – A Section describing the global facet numbering
firedrake.dmplex.get_facets_by_class()

Builds a list of all facets ordered according to PyOP2 entity classes and computes the respective class offsets.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • ordering – An array giving the global traversal order of facets
  • label – Label string that marks the facets to order
firedrake.dmplex.halo_begin()

Begin a halo exchange.

Parameters:
  • sf – the PETSc SF to use for exchanges
  • dat – the pyop2.Dat to perform the exchange on
  • dtype – an MPI datatype describing the unit of data
  • reverse – should a reverse (local-to-global) exchange be performed.

Forward exchanges are implemented using PetscSFBcastBegin, reverse exchanges with PetscSFReduceBegin.

firedrake.dmplex.halo_end()

End a halo exchange.

Parameters:
  • sf – the PETSc SF to use for exchanges
  • dat – the pyop2.Dat to perform the exchange on
  • dtype – an MPI datatype describing the unit of data
  • reverse – should a reverse (local-to-global) exchange be performed.

Forward exchanges are implemented using PetscSFBcastEnd, reverse exchanges with PetscSFReduceEnd.

firedrake.dmplex.label_facets()

Add labels to facets in the the plex

Facets on the boundary are marked with “exterior_facets” while all others are marked with “interior_facets”.

Parameters:label_boundary – if False, don’t label the boundary faces (they must have already been labelled).
firedrake.dmplex.make_global_numbering()

Build an array of global numbers for local dofs

Parameters:
  • lsec – Section describing local dof layout and numbers.
  • gsec – Section describing global dof layout and numbers.
firedrake.dmplex.mark_entity_classes()

Mark all points in a given Plex according to the PyOP2 entity classes:

core : owned and not in send halo owned : owned and in send halo ghost : in halo

Parameters:plex – The DMPlex object encapsulating the mesh topology
firedrake.dmplex.orientations_facet2cell()

Converts local quadrilateral facet orientations into global quadrilateral cell orientations.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • vertex_numbering – Section describing the universal vertex numbering
  • facet_orientations – Facet orientations (edge directions) relative to the local DMPlex ordering.
  • cell_numbering – Section describing the cell numbering
firedrake.dmplex.plex_renumbering()

Build a global node renumbering as a permutation of Plex points.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • entity_classes – Array of entity class offsets for each dimension.
  • reordering – A reordering from reordered to original plex points used to provide the traversal order of the cells (i.e. the inverse of the ordering obtained from DMPlexGetOrdering). Optional, if not provided (or None), no reordering is applied and the plex is traversed in original order.

The node permutation is derived from a depth-first traversal of the Plex graph over each entity class in turn. The returned IS is the Plex -> PyOP2 permutation.

firedrake.dmplex.prune_sf()

Prune an SF of roots referencing the local rank

Parameters:sf – The PETSc SF to prune.
firedrake.dmplex.quadrilateral_closure_ordering()

Cellwise orders mesh entities according to the given cell orientations.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • vertex_numbering – Section describing the universal vertex numbering
  • cell_numbering – Section describing the cell numbering
  • cell_orientations – Specifies the starting vertex for each cell, and the order of traversal (CCW or CW).
firedrake.dmplex.quadrilateral_facet_orientations()

Returns globally synchronised facet orientations (edge directions) incident to locally owned quadrilateral cells.

Parameters:
  • plex – The DMPlex object encapsulating the mesh topology
  • vertex_numbering – Section describing the universal vertex numbering
  • cell_ranks – MPI rank of the owner of each (visible) non-owned cell, or -1 for (locally) owned cell.
firedrake.dmplex.reordered_coords()

Return coordinates for the plex, reordered according to the global numbering permutation for the coordinate function space.

Shape is a tuple of (plex.numVertices(), geometric_dim).

firedrake.dmplex.set_adjacency_callback()

Set the callback for DMPlexGetAdjacency.

Parameters:dm – The DMPlex object.

This is used during DMPlexDistributeOverlap to determine where to grow the halos.

firedrake.dmplex.validate_mesh()

Perform some validation of the input mesh.

Parameters:plex – The DMPlex object encapsulating the mesh topology.

firedrake.exceptions module

exception firedrake.exceptions.ConvergenceError[source]

Bases: Exception

Error raised when a solver fails to converge

firedrake.expression module

class firedrake.expression.Expression(code=None, element=None, cell=None, degree=None, **kwargs)[source]

Bases: ufl.coefficient.Coefficient

A code snippet or Python function that may be evaluated on a FunctionSpace. This provides a mechanism for setting Function values to user-determined values.

To use an Expression, we can either interpolate() it onto a Function, or project() it into a FunctionSpace. Note that not all FunctionSpaces support interpolation, but all do support projection.

Expressions may be provided as snippets of C code, which results in fast execution but offers limited functionality to the user, or as a Python function, which is more flexible but slower, since a Python function is called for every cell in the mesh.

The C interface

The code in an Expression has access to the coordinates in the variable x, with x[0] corresponding to the x component, x[1] to the y component and so forth. You can use mathematical functions from the C library, along with the variable pi for \(\pi\).

For example, to build an expression corresponding to

\[\sin(\pi x)\sin(\pi y)\sin(\pi z)\]

we use:

expr = Expression('sin(pi*x[0])*sin(pi*x[1])*sin(pi*x[2])')

If the FunctionSpace the expression will be applied to is vector valued, a list of code snippets of length matching the number of components in the function space must be provided.

The Python interface

The Python interface is accessed by creating a subclass of Expression with a user-specified eval` method. For example, the following expression sets the output Function to the square of the magnitude of the coordinate:

class MyExpression(Expression):
    def eval(self, value, X):
        value[:] = numpy.dot(X, X)

Observe that the (single) entry of the value parameter is written to, not the parameter itself.

This Expression could be interpolated onto the Function f by executing:

f.interpolate(MyExpression())

Note the brackets required to instantiate the MyExpression object.

If a Python Expression is to set the value of a vector-valued Function then it is necessary to explicitly override the value_shape() method of that Expression. For example:

class MyExpression(Expression):
    def eval(self, value, X):
        value[:] = X

    def value_shape(self):
        return (2,)
Parameters:
  • code – a string C statement, or list of statements.
  • element – a FiniteElement, optional (currently ignored)
  • cell – a Cell, optional (currently ignored)
  • degree – the degree of quadrature to use for evaluation (currently ignored)
  • kwargs

    user-defined values that are accessible in the Expression code. These values maybe updated by accessing the property of the same name. This can be used, for example, to pass in the current timestep to an Expression without necessitating recompilation. For example:

    f = Function(V)
    e = Expression('sin(x[0]*t)', t=t)
    while t < T:
        f.interpolate(e)
        ...
        t += dt
        e.t = t
    

The currently ignored parameters are retained for API compatibility with Dolfin.

rank()[source]

Return the rank of this Expression

ufl_shape
value_shape()[source]

Return the shape of this Expression.

This is the number of values the code snippet in the expression contains.

firedrake.extrusion_numbering module

Computation dof numberings for extruded meshes

On meshes with a constant number of cell layers (i.e. each column contains the same number of cells), it is possible to compute all the correct numberings by just lying to DMPlex about how many degrees of freedom there are on the base topological entities.

This ceases to be true as soon as we permit variable numbers of cells in each column, since now, although the number of degrees of freedom on a cell does not change from column to column, the number that are stacked up on each topological entity does change.

This module implements the necessary chicanery to deal with it.

Computation of topological layer extents

First, a picture.

Consider a one-dimensional mesh:

x---0---x---1---x---2---x

Extruded to form the following two-dimensional mesh:

                      x--------x
                      |        |
                      |        |
2                     |        |
                      |        |
    x--------x--------x--------x
    |        |        |
    |        |        |
1   |        |        |
    |        |        |
    x--------x--------x
    |        |
    |        |
0   |        |
    |        |
    x--------x

This is constructed by providing the number of cells in each column as well as the starting cell layer:

[[0, 2],
 [1, 1],
 [2, 1]]

We need to promote this cell layering to layering for all topological entities. Our solution to “interior” facets that only have one side is to require that they are geometrically zero sized, and then guarantee that we never iterate over them. We therefore need to keep track of two bits of information, the layer extent for allocation purposes and also the layer extent for iteration purposes.

We compute both by iterating over the cells and transferring cell layers to points in the closure of each cell. Allocation bounds use min-max on the cell bounds, iteration bounds use max-min.

To simplify some things, we require that the resulting mesh is not topologically disconnected anywhere. Offset cells must, at least, share a vertex with some other cell.

Computation of function space allocation size

With the layer extents computed, we need to compute the dof allocation. For this, we need the number of degrees of freedom on the base topological entity, and above it in each cell:

x-------x
|   o   |
o   o   o
o   o   o
|   o   |
o---o---o

This element has one degree of freedom on each base vertex and cell, two degrees of freedom “above” each vertex, and four above each cell. To compute the number of degrees of freedom on the column of topological entities we sum the number on the entity, multiplied by the number of layers with the number above, multiplied by the number of layers minus one (due to the fencepost error difference). This number of layers naturally changes from entity to entity, and so we can’t compute this up front, but must do it point by point, constructing the PETSc Section as we go.

Computation of function space maps

Now we need the maps from topological entities (cells and facets) to the function space nodes they can see. The allocation offsets that the numbering section gives us are wrong, because when we have a step in the column height, the offset will be wrong if we’re looking from the higher cell. Consider a vertex discretisation on the previous mesh, with a numbering:

                  8--------10
                  |        |
                  |        |
                  |        |
                  |        |
2--------5--------7--------9
|        |        |
|        |        |
|        |        |
|        |        |
1--------4--------6
|        |
|        |
|        |
|        |
0--------3

The cell node map we get by just looking at allocation offsets is:

[[0, 1, 3, 4],
 [3, 4, 6, 7],
 [6, 7, 9, 10]]

note how the second and third cells have the wrong value for their “left” vertices. Instead, we need to shift the numbering we obtain from the allocation offset by the number of entities we’re skipping over, to result in:

[[0, 1, 3, 4],
 [4, 5, 6, 7],
 [7, 8, 9, 10]]

Now, when we iterate over cells, we ensure that we access the correct dofs. The same trick needs to be applied to facet maps too.

Computation of boundary nodes

For the top and bottom boundary nodes, we walk over the cells at, respectively, the top and bottom of the column and pull out those nodes whose entity height matches the appropriate cell height. As an example:

                  8--------10
                  |        |
                  |        |
                  |        |
                  |        |
2--------5--------7--------9
|        |        |
|        |        |
|        |        |
|        |        |
1--------4--------6
|        |
|        |
|        |
|        |
0--------3

The bottom boundary nodes are:

[0, 3, 4, 6, 7, 9]

whereas the top are:

[2, 5, 7, 8, 10]

For these strange “interior” facets, we first walk over the cells, picking up the dofs in the closure of the base (ceiling) of the cell, then we walk over facets, picking up all the dofs in the closure of facets that are exposed (there may be more than one of these in the cell column). We don’t have to worry about any lower-dimensional entities, because if a co-dim 2 or greater entity is exposed in a column, then the co-dim 1 entity in its star is also exposed.

For the side boundary nodes, we can make a simplification: we know that the facet heights are always the same as the cell column heights (because there is only one cell in the support of the facet). Hence we just walk over the boundary facets of the base mesh, extract out the nodes on that facet on the bottom cell and walk up the column. This is guaranteed to pick up all the nodes in the closure of the facet column.

Applying boundary conditions in matrix assembly

When assembling a matrix with a “top” or “bottom” boundary condition, we must communicate which boundary dofs are being killed to the compiled code. Unlike in the constant layer case, it no longer suffices to check if we are on the top (respectively bottom) cell in the column, since some “interior” cells may have some exposed entities. To communicate this data we record, for each cell (or pair of cells for interior vertical facets), which entities are exposed. This is done using a bitmask (since we only need one bit of information per entity). The generated code can then discard the appropriate entries from the local tensor when assembling the global matrix.

firedrake.extrusion_numbering.cell_entity_masks()

Compute a masking integer for each cell in the extruded mesh.

This integer indicates for each cell, which topological entities in the cell are on the boundary of the domain. If the ith bit in the integer is on, that indicates that the ith entity is on the boundary, meaning that the appropriate boundary mask should be used to discard element tensor contributions when assembling bilinear forms.

Parameters:mesh – the extruded mesh.
Returns:a tuple of section, bottom, and top masks. The section records the number of entities in each column and the offset in the masking arrays for the start of each column.
firedrake.extrusion_numbering.entity_layers()

Compute the layers for a given entity type.

Parameters:
  • mesh – the extruded mesh to compute layers for.
  • height – the height of the entity to consider (in the DMPlex sense). e.g. 0 -> cells, 1 -> facets, etc…
  • label – optional label to select some subset of the points of the given height (may be None meaning select all points).
Returns:

a numpy array of shape (num_entities, 2) providing the layer extents for iteration on the requested entities.

firedrake.extrusion_numbering.facet_entity_masks()

Compute a masking integer for each facet in the extruded mesh.

This integer indicates for each facet, which topological entities in the closure of the support of the facet are on the boundary of the domain. If the ith bit in the integer is on, that indicates that the ith entity is on the boundary, meaning that the appropriate boundary mask should be used to discard element tensor contributions when assembling bilinear forms.

Parameters:
  • mesh – the extruded mesh.
  • layers – The start and end layers for iteration for the facet column
  • label – A label selecting the type of facet.
Returns:

a tuple of section, bottom, and top masks. The section records the number of entities in each column and the offset in the masking arrays for the start of each column.

firedrake.extrusion_numbering.layer_extents()

Compute the extents (start and stop layers) for an extruded mesh.

Parameters:
  • dm – The DMPlex.
  • cell_numbering – The cell numbering (plex points to Firedrake points).
  • cell_extents – The cell layers.
Returns:

a numpy array of shape (npoints, 4) where npoints is the number of mesh points in the base mesh. npoints[p, 0:2] gives the start and stop layers for allocation for mesh point p (in plex ordering), while npoints[p, 2:4] gives the start and stop layers for iteration over mesh point p (in plex ordering).

Warning

The indexing of this array uses DMPlex point ordering, not Firedrake ordering. So you always need to iterate over plex points and translate to Firedrake numbers if necessary.

firedrake.extrusion_numbering.node_classes()

Compute the node classes for a given extruded mesh.

Parameters:
  • mesh – the extruded mesh.
  • nodes_per_entity – Number of nodes on, and on top of, each type of topological entity on the base mesh for a single cell layer. Multiplying up by the number of layers happens in this function.
Returns:

A numpy array of shape (3, ) giving the set entity sizes for the given nodes per entity.

firedrake.extrusion_numbering.top_bottom_boundary_nodes()

Extract top or bottom boundary nodes from an extruded function space.

Parameters:
  • mesh – The extruded mesh.
  • cell_node_list – The map from cells to nodes.
  • masks – masks for dofs in the closure of the facets of the cell. First the vertical facets, then the horizontal facets (bottom then top).
  • offsets – Offsets to apply walking up the column.
  • kind – Whether we should select the bottom, or the top, nodes.
Returns:

a numpy array of unique indices of nodes on the bottom or top of the mesh.

firedrake.extrusion_utils module

firedrake.extrusion_utils.entity_closures(cell)[source]

Map entities in a cell to points in the topological closure of the entity.

Parameters:cell – a FIAT cell.
firedrake.extrusion_utils.entity_indices(cell)[source]

Return a dict mapping topological entities on a cell to their integer index.

This provides an iteration ordering for entities on extruded meshes.

Parameters:cell – a FIAT cell.
firedrake.extrusion_utils.entity_reordering(cell)[source]

Return an array reordering extruded cell entities.

If we iterate over the base cell, it is natural to then go over all the entities induced by the product with an interval. This iteration order is not the same as the natural iteration order, so we need a reordering.

Parameters:cell – a FIAT tensor product cell.
firedrake.extrusion_utils.flat_entity_dofs(entity_dofs)[source]
firedrake.extrusion_utils.make_extruded_coords(extruded_topology, base_coords, ext_coords, layer_height, extrusion_type='uniform', kernel=None)[source]

Given either a kernel or a (fixed) layer_height, compute an extruded coordinate field for an extruded mesh.

Parameters:
  • extruded_topology – an ExtrudedMeshTopology to extrude a coordinate field for.
  • base_coords – a Function to read the base coordinates from.
  • ext_coords – a Function to write the extruded coordinates into.
  • layer_height – an equi-spaced height for each layer.
  • extrusion_type – the type of extrusion to use. Predefined options are either “uniform” (creating equi-spaced layers by extruding in the (n+1)dth direction), “radial” (creating equi-spaced layers by extruding in the outward direction from the origin) or “radial_hedgehog” (creating equi-spaced layers by extruding coordinates in the outward cell-normal direction, needs a P1dgxP1 coordinate field).
  • kernel – an optional kernel to carry out coordinate extrusion.

The kernel signature (if provided) is:

void kernel(double **base_coords, double **ext_coords,
            double *layer_height, int layer)

The kernel iterates over the cells of the mesh and receives as arguments the coordinates of the base cell (to read), the coordinates on the extruded cell (to write to), the fixed layer height, and the current cell layer.

firedrake.formmanipulation module

class firedrake.formmanipulation.ExtractSubBlock[source]

Bases: ufl.corealg.multifunction.MultiFunction

Extract a sub-block from a form.

argument(o)[source]
expr(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched

as a default rule.

multi_index(o)[source]
split(form, argument_indices)[source]

Split a form.

Parameters:
  • form – the form to split.
  • argument_indices – indices of test and trial spaces to extract. This should be 0-, 1-, or 2-tuple (whose length is the same as the number of arguments as the form) whose entries are either an integer index, or else an iterable of indices.

Returns a new ufl.classes.Form on the selected subspace.

class firedrake.formmanipulation.SplitForm(indices, form)

Bases: tuple

Create new instance of SplitForm(indices, form)

form

Alias for field number 1

indices

Alias for field number 0

firedrake.formmanipulation.split_form(form)[source]

Split a form into a tuple of sub-forms defined on the component spaces.

Each entry is a SplitForm tuple of the indices into the component arguments and the form defined on that block.

For example, consider the following code:

V = FunctionSpace(m, 'CG', 1)
W = V*V*V
u, v, w = TrialFunctions(W)
p, q, r = TestFunctions(W)
a = q*u*dx + p*w*dx

Then splitting the form returns a tuple of two forms.

((0, 2), w*p*dx),
 (1, 0), q*u*dx))

Due to the limited amount of simplification that UFL does, some of the returned forms may eventually evaluate to zero. The form compiler will remove these in its more complex simplification stages.

firedrake.function module

class firedrake.function.Function(function_space, val=None, name=None, dtype=dtype('float64'))[source]

Bases: ufl.coefficient.Coefficient

A Function represents a discretised field over the domain defined by the underlying Mesh(). Functions are represented as sums of basis functions:

\[f = \sum_i f_i \phi_i(x)\]

The Function class provides storage for the coefficients \(f_i\) and associates them with a FunctionSpace object which provides the basis functions \(\phi_i(x)\).

Note that the coefficients are always scalars: if the Function is vector-valued then this is specified in the FunctionSpace.

Parameters:function_space – the FunctionSpace, or MixedFunctionSpace on which to build this Function. Alternatively, another Function may be passed here and its function space will be used to build this Function. In this

case, the function values are copied. :param val: NumPy array-like (or pyop2.Dat) providing initial values (optional).

If val is an existing Function, then the data will be shared.
Parameters:
  • name – user-defined name for this Function (optional).
  • dtype – optional data type for this Function (defaults to ScalarType).
assign(expr, subset=None)[source]

Set the Function value to the pointwise value of expr. expr may only contain Functions on the same FunctionSpace as the Function being assigned to.

Similar functionality is available for the augmented assignment operators +=, -=, *= and /=. For example, if f and g are both Functions on the same FunctionSpace then:

f += 2 * g

will add twice g to f.

If present, subset must be an pyop2.Subset of this Function’s node_set. The expression will then only be assigned to the nodes on that subset.

at(arg, *args, **kwargs)[source]

Evaluate function at points.

Parameters:
  • arg – The point to locate.
  • args – Additional points.
  • dont_raise – Do not raise an error if a point is not found.
  • tolerance – Tolerance to use when checking for points in cell.
copy(deepcopy=False)[source]

Return a copy of this Function.

Parameters:deepcopy – If True, the new Function will allocate new space and copy values. If False, the default, then the new Function will share the dof values.
evaluate(coord, mapping, component, index_values)[source]
function_space()[source]

Return the FunctionSpace, or MixedFunctionSpace on which this Function is defined.

interpolate(expression, subset=None)[source]

Interpolate an expression onto this Function.

Parameters:expressionExpression or a UFL expression to interpolate
Returns:this Function object
project(b, *args, **kwargs)[source]

Project b onto self. b must be a Function or an Expression.

This is equivalent to project(b, self). Any of the additional arguments to project() may also be passed, and they will have their usual effect.

split()[source]

Extract any sub Functions defined on the component spaces of this this Function’s FunctionSpace.

sub(i)[source]

Extract the ith sub Function of this Function.

Parameters:i – the index to extract

See also split().

If the Function is defined on a VectorFunctionSpace, this returns a proxy object indexing the ith component of the space, suitable for use in boundary condition application.

topological

The underlying coordinateless function.

vector()[source]

Return a Vector wrapping the data in this Function

exception firedrake.function.PointNotInDomainError(domain, point)[source]

Bases: Exception

Raised when attempting to evaluate a function outside its domain, and no fill value was given.

Attributes: domain, point

firedrake.functionspace module

This module implements the user-visible API for constructing FunctionSpace and MixedFunctionSpace objects. The API is functional, rather than object-based, to allow for simple backwards-compatibility, argument checking, and dispatch.

firedrake.functionspace.MixedFunctionSpace(spaces, name=None, mesh=None)[source]

Create a MixedFunctionSpace.

Parameters:
  • spaces – An iterable of constituent spaces, or a MixedElement.
  • name – An optional name for the mixed function space.
  • mesh – An optional mesh. Must be provided if spaces is a MixedElement, ignored otherwise.
firedrake.functionspace.FunctionSpace(mesh, family, degree=None, name=None, vfamily=None, vdegree=None)[source]

Create a FunctionSpace.

Parameters:
  • mesh – The mesh to determine the cell from.
  • family – The finite element family.
  • degree – The degree of the finite element.
  • name – An optional name for the function space.
  • vfamily – The finite element in the vertical dimension (extruded meshes only).
  • vdegree – The degree of the element in the vertical dimension (extruded meshes only).

The family argument may be an existing ufl.FiniteElementBase, in which case all other arguments are ignored and the appropriate FunctionSpace is returned.

firedrake.functionspace.VectorFunctionSpace(mesh, family, degree=None, dim=None, name=None, vfamily=None, vdegree=None)[source]

Create a rank-1 FunctionSpace.

Parameters:
  • mesh – The mesh to determine the cell from.
  • family – The finite element family.
  • degree – The degree of the finite element.
  • dim – An optional number of degrees of freedom per function space node (defaults to the geometric dimension of the mesh).
  • name – An optional name for the function space.
  • vfamily – The finite element in the vertical dimension (extruded meshes only).
  • vdegree – The degree of the element in the vertical dimension (extruded meshes only).

The family argument may be an existing ufl.FiniteElementBase, in which case all other arguments are ignored and the appropriate FunctionSpace is returned. In this case, the provided element must have an empty ufl.FiniteElementBase.value_shape().

Note

The element that you provide need be a scalar element (with empty value_shape), however, it should not be an existing VectorElement. If you already have an existing VectorElement, you should pass it to FunctionSpace() directly instead.

firedrake.functionspace.TensorFunctionSpace(mesh, family, degree=None, shape=None, symmetry=None, name=None, vfamily=None, vdegree=None)[source]

Create a rank-2 FunctionSpace.

Parameters:
  • mesh – The mesh to determine the cell from.
  • family – The finite element family.
  • degree – The degree of the finite element.
  • shape – An optional shape for the tensor-valued degrees of freedom at each function space node (defaults to a square tensor using the geometric dimension of the mesh).
  • symmetry – Optional symmetries in the tensor value.
  • name – An optional name for the function space.
  • vfamily – The finite element in the vertical dimension (extruded meshes only).
  • vdegree – The degree of the element in the vertical dimension (extruded meshes only).

The family argument may be an existing FiniteElementBase, in which case all other arguments are ignored and the appropriate FunctionSpace is returned. In this case, the provided element must have an empty value_shape().

Note

The element that you provide must be a scalar element (with empty value_shape). If you already have an existing TensorElement, you should pass it to FunctionSpace() directly instead.

firedrake.functionspacedata module

This module provides an object that encapsulates data that can be shared between different FunctionSpace objects.

The sharing is based on the idea of compatibility of function space node layout. The shared data is stored on the Mesh() the function space is created on, since the created objects are mesh-specific. The sharing is done on an individual key basis. So, for example, Sets can be shared between all function spaces with the same number of nodes per topological entity. However, maps are specific to the node ordering.

This means, for example, that function spaces with the same node ordering, but different numbers of dofs per node (e.g. FiniteElement vs VectorElement) can share the PyOP2 Set and Map data.

firedrake.functionspacedata.get_shared_data(mesh, finat_element)[source]

Return the FunctionSpaceData for the given element.

Parameters:
  • mesh – The mesh to build the function space data on.
  • finat_element – A FInAT element.
Raises:

ValueError – if mesh or finat_element are invalid.

Returns:

a FunctionSpaceData object with the shared data.

firedrake.functionspaceimpl module

This module provides the implementations of FunctionSpace and MixedFunctionSpace objects, along with some utility classes for attaching extra information to instances of these.

firedrake.functionspaceimpl.ComponentFunctionSpace(parent, component)[source]

Build a new FunctionSpace that remembers it represents a particular component. Used for applying boundary conditions to components of a VectorFunctionSpace().

Parameters:
  • parent – The parent space (a FunctionSpace with a VectorElement).
  • component – The component to represent.
Returns:

A new ProxyFunctionSpace with the component set.

class firedrake.functionspaceimpl.FunctionSpace(mesh, element, name=None)[source]

Bases: object

A representation of a function space.

A FunctionSpace associates degrees of freedom with topological mesh entities. The degree of freedom mapping is determined from the provided element.

Parameters:
  • mesh – The Mesh() to build the function space on.
  • element – The FiniteElementBase describing the degrees of freedom.
  • name – An optional name for this FunctionSpace, useful for later identification.

The element can be a essentially any FiniteElementBase, except for a MixedElement, for which one should use the MixedFunctionSpace constructor.

To determine whether the space is scalar-, vector- or tensor-valued, one should inspect the rank of the resulting object. Note that function spaces created on intrinsically vector-valued finite elements (such as the Raviart-Thomas space) have rank 0.

Warning

Users should not build a FunctionSpace directly, instead they should use the utility FunctionSpace() function, which provides extra error checking and argument sanitising.

boundary_nodes(sub_domain, method)[source]

Return the boundary nodes for this FunctionSpace.

Parameters:
  • sub_domain – the mesh marker selecting which subset of facets to consider.
  • method – the method for determining boundary nodes.
Returns:

A numpy array of the unique function space nodes on the selected portion of the boundary.

See also DirichletBC for details of the arguments.

cell_node_list[source]

A numpy array mapping mesh cells to function space nodes.

cell_node_map(bcs=None)[source]

Return the pyop2.Map from interior facets to function space nodes. If present, bcs must be a tuple of DirichletBCs. In this case, the facet_node_map will return negative node indices where boundary conditions should be applied. Where a PETSc matrix is employed, this will cause the corresponding values to be discarded during matrix assembly.

component = None

The component of this space in its parent VectorElement space, or None.

dim()[source]

The global number of degrees of freedom for this function space.

See also dof_count and node_count.

dm[source]

A PETSc DM describing the data layout for this FunctionSpace.

dof_count[source]

The number of degrees of freedom (includes halo dofs) of this function space on this process. Cf. node_count.

dof_dset = None

A pyop2.DataSet representing the function space degrees of freedom.

exterior_facet_node_map(bcs=None)[source]

Return the pyop2.Map from exterior facets to function space nodes. If present, bcs must be a tuple of DirichletBCs. In this case, the facet_node_map will return negative node indices where boundary conditions should be applied. Where a PETSc matrix is employed, this will cause the corresponding values to be discarded during matrix assembly.

index = None

The position of this space in its parent MixedFunctionSpace, or None.

interior_facet_node_map(bcs=None)[source]

Return the pyop2.Map from interior facets to function space nodes. If present, bcs must be a tuple of DirichletBCs. In this case, the facet_node_map will return negative node indices where boundary conditions should be applied. Where a PETSc matrix is employed, this will cause the corresponding values to be discarded during matrix assembly.

make_dat(val=None, valuetype=None, name=None, uid=None)[source]

Return a newly allocated pyop2.Dat defined on the dof_dset of this Function.

mesh()[source]
name = None

The (optional) descriptive name for this space.

node_count[source]

The number of nodes (includes halo nodes) of this function space on this process. If the FunctionSpace has rank 0, this is equal to the dof_count, otherwise the dof_count is dim times the node_count.

node_set = None

A pyop2.Set representing the function space nodes.

parent = None

The parent space if this space was extracted from one, or None.

rank = None

The rank of this FunctionSpace. Spaces where the element is scalar-valued (or intrinsically vector-valued) have rank zero. Spaces built on VectorElement or TensorElement instances have rank equivalent to the number of components of their value_shape().

split()[source]

Split into a tuple of constituent spaces.

sub(i)[source]

Return a view into the ith component.

topological

Function space on a mesh topology.

ufl_element()[source]
value_size = None

The total number of degrees of freedom at each function space node.

firedrake.functionspaceimpl.IndexedFunctionSpace(index, space, parent)[source]

Build a new FunctionSpace that remembers it is a particular subspace of a MixedFunctionSpace.

Parameters:
  • index – The index into the parent space.
  • space – The subspace to represent
  • parent – The parent mixed space.
Returns:

A new ProxyFunctionSpace with index and parent set.

class firedrake.functionspaceimpl.MixedFunctionSpace(spaces, name=None)[source]

Bases: object

A function space on a mixed finite element.

This is essentially just a bag of individual FunctionSpace objects.

Parameters:
  • spaces – The constituent spaces.
  • name – An optional name for the mixed space.

Warning

Users should not build a MixedFunctionSpace directly, but should instead use the functional interface provided by MixedFunctionSpace().

cell_node_map(bcs=None)[source]

A pyop2.MixedMap from the Mesh.cell_set of the underlying mesh to the node_set of this MixedFunctionSpace. This is composed of the FunctionSpace.cell_node_maps of the underlying FunctionSpaces of which this MixedFunctionSpace is composed.

component = None
dim()[source]

The global number of degrees of freedom for this function space.

See also dof_count and node_count.

dm[source]

A PETSc DM describing the data layout for fieldsplit solvers.

dof_count[source]

Return a tuple of FunctionSpace.dof_counts of the FunctionSpaces of which this MixedFunctionSpace is composed.

dof_dset[source]

A pyop2.MixedDataSet containing the degrees of freedom of this MixedFunctionSpace. This is composed of the FunctionSpace.dof_dsets of the underlying FunctionSpaces of which this MixedFunctionSpace is composed.

exterior_facet_node_map(bcs=None)[source]

Return the pyop2.Map from exterior facets to function space nodes. If present, bcs must be a tuple of DirichletBCs. In this case, the facet_node_map will return negative node indices where boundary conditions should be applied. Where a PETSc matrix is employed, this will cause the corresponding values to be discarded during matrix assembly.

index = None
interior_facet_node_map(bcs=None)[source]

Return the pyop2.MixedMap from interior facets to function space nodes. If present, bcs must be a tuple of DirichletBCs. In this case, the facet_node_map will return negative node indices where boundary conditions should be applied. Where a PETSc matrix is employed, this will cause the corresponding values to be discarded during matrix assembly.

make_dat(val=None, valuetype=None, name=None, uid=None)[source]

Return a newly allocated pyop2.MixedDat defined on the dof_dset of this MixedFunctionSpace.

mesh()[source]
node_count[source]

Return a tuple of FunctionSpace.node_counts of the FunctionSpaces of which this MixedFunctionSpace is composed.

node_set[source]

A pyop2.MixedSet containing the nodes of this MixedFunctionSpace. This is composed of the FunctionSpace.node_sets of the underlying FunctionSpaces this MixedFunctionSpace is composed of one or (for VectorFunctionSpaces) more degrees of freedom are stored at each node.

num_sub_spaces()[source]

Return the number of FunctionSpaces of which this MixedFunctionSpace is composed.

parent = None
rank = 1
split()[source]

The list of FunctionSpaces of which this MixedFunctionSpace is composed.

sub(i)[source]

Return the i`th :class:`FunctionSpace in this MixedFunctionSpace.

topological

Function space on a mesh topology.

ufl_element()[source]

The Mixedelement this space represents.

value_size[source]

Return the sum of the FunctionSpace.value_sizes of the FunctionSpaces this MixedFunctionSpace is composed of.

class firedrake.functionspaceimpl.ProxyFunctionSpace(mesh, element, name=None)[source]

Bases: firedrake.functionspaceimpl.FunctionSpace

A FunctionSpace that one can attach extra properties to.

Parameters:
  • mesh – The mesh to use.
  • element – The UFL element.
  • name – The name of the function space.

Warning

Users should not build a ProxyFunctionSpace directly, it is mostly used as an internal implementation detail.

identifier = None

An optional identifier, for debugging purposes.

make_dat(*args, **kwargs)[source]

Create a pyop2.Dat.

Raises:ValueError – if no_dats is True.
no_dats = False

Can this proxy make pyop2.Dat objects

class firedrake.functionspaceimpl.RealFunctionSpace(mesh, element, name)[source]

Bases: firedrake.functionspaceimpl.FunctionSpace

FunctionSpace based on elements of family “Real”. A :class`RealFunctionSpace` only has a single global value for the whole mesh.

This class should not be directly instantiated by users. Instead, FunctionSpace objects will transform themselves into RealFunctionSpace objects as appropriate.

bottom_nodes()[source]

RealFunctionSpace objects have no bottom nodes.

cell_node_map(bcs=None)[source]

RealFunctionSpace objects have no cell node map.

dim = 1
exterior_facet_node_map(bcs=None)[source]

RealFunctionSpace objects have no exterior facet node map.

finat_element = None
interior_facet_node_map(bcs=None)[source]

RealFunctionSpace objects have no interior facet node map.

make_dat(val=None, valuetype=None, name=None, uid=None)[source]

Return a newly allocated pyop2.Global representing the data for a Function on this space.

node_set = None
rank = 0
shape = ()
top_nodes()[source]

RealFunctionSpace objects have no bottom nodes.

value_size = 1
class firedrake.functionspaceimpl.WithGeometry(function_space, mesh)[source]

Bases: ufl.functionspace.FunctionSpace

Attach geometric information to a FunctionSpace.

Function spaces on meshes with different geometry but the same topology can share data, except for their UFL cell. This class facilitates that.

Users should not instantiate a WithGeometry object explicitly except in a small number of cases.

Parameters:
  • function_space – The topological function space to attach geometry to.
  • mesh – The mesh with geometric information to use.
dm[source]
get_work_function(zero=True)[source]

Get a temporary work Function on this FunctionSpace.

Parameters:zero – Should the Function be guaranteed zero? If zero is False the returned function may or may not be zeroed, and the user is responsible for appropriate zeroing.
Raises:ValueError – if max_work_functions are already checked out.

Note

This method is intended to be used for short-lived work functions, if you actually need a function for general usage use the Function constructor.

When you are finished with the work function, you should restore it to the pool of available functions with restore_work_function().

max_work_functions

The maximum number of work functions this FunctionSpace supports.

See get_work_function() for obtaining work functions.

mesh()

Return ufl domain.

num_work_functions

The number of checked out work functions.

restore_work_function(function)[source]

Restore a work function obtained with get_work_function().

Parameters:function – The work function to restore
Raises:ValueError – if the provided function was not obtained with get_work_function() or it has already been restored.

Warning

This does not invalidate the name in the calling scope, it is the user’s responsibility not to use a work function after restoring it.

split()[source]

Split into a tuple of constituent spaces.

sub(i)[source]
ufl_cell()[source]

The Cell this FunctionSpace is defined on.

ufl_function_space()[source]

The FunctionSpace this object represents.

firedrake.halo module

class firedrake.halo.Halo(dm, section)[source]

Bases: pyop2.base.Halo

Build a Halo for a function space.

Parameters:
  • dm – The DMPlex describing the topology.
  • section – The data layout.

The halo is implemented using a PETSc SF (star forest) object and is usable as a PyOP2 pyop2.Halo.

comm[source]
global_to_local_begin(dat, insert_mode)[source]
global_to_local_end(dat, insert_mode)[source]
local_to_global_begin(dat, insert_mode)[source]
local_to_global_end(dat, insert_mode)[source]
local_to_global_numbering[source]
sf[source]

firedrake.hdf5interface module

firedrake.hdf5interface.get_h5py_file()

Attempt to convert PETSc viewer file handle to h5py File.

Parameters:vwr – The PETSc Viewer (must have type HDF5).

Warning

For this to work, h5py and PETSc must both have been compiled against the same HDF5 library (otherwise the file handles are not interchangeable). This is the likeliest reason for failure when attempting the conversion.

firedrake.interpolation module

firedrake.interpolation.interpolate(expr, V, subset=None)[source]

Interpolate an expression onto a new function in V.

Parameters:

Returns a new Function in the space V (or V if it was a Function).

Note

If you find interpolating the same expression again and again (for example in a time loop) you may find you get better performance by using a Interpolator instead.

class firedrake.interpolation.Interpolator(expr, V, subset=None)[source]

Bases: object

A reusable interpolation object.

Parameters:

This object can be used to carry out the same interpolation multiple times (for example in a timestepping loop).

Note

The Interpolator holds a reference to the provided arguments (such that they won’t be collected until the Interpolator is also collected).

interpolate()[source]

Compute the interpolation.

Returns:The resulting interpolated Function.

firedrake.linear_solver module

class firedrake.linear_solver.LinearSolver(A, P=None, solver_parameters=None, nullspace=None, transpose_nullspace=None, near_nullspace=None, options_prefix=None)[source]

Bases: firedrake.solving_utils.ParametersMixin

A linear solver for assembled systems (Ax = b).

Parameters:
  • A – a MatrixBase (the operator).
  • P – an optional MatrixBase to construct any preconditioner from; if none is supplied A is used to construct the preconditioner.
  • parameters – (optional) dict of solver parameters.
  • nullspace – an optional VectorSpaceBasis (or MixedVectorSpaceBasis spanning the null space of the operator.
  • transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
  • near_nullspace – as for the nullspace, but used to set the near nullpace.
  • options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the solver_parameters dict.

Note

Any boundary conditions for this solve must have been applied when assembling the operator.

solve(x, b)[source]

firedrake.logging module

firedrake.logging.set_level(level)

Set the log level for Firedrake components.

Parameters:level – The level to use.

This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.

firedrake.logging.set_log_level(level)[source]

Set the log level for Firedrake components.

Parameters:level – The level to use.

This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.

firedrake.logging.set_log_handlers(handlers=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Set handlers for the log messages of the different Firedrake components.

Parameters:
  • handlers – Optional dict of handlers keyed by the name of the logger. If not provided, a separate logging.StreamHandler will be created for each logger.
  • comm – The communicator the handler should be collective over. If provided, only rank-0 on that communicator will write to the handler, other ranks will use a logging.NullHandler. If set to None, all ranks will use the provided handler. This could be used, for example, if you want to log to one file per rank.
firedrake.logging.info_red(message, *args, **kwargs)[source]

Write info message in red.

Parameters:message – the message to be printed.
firedrake.logging.info_green(message, *args, **kwargs)[source]

Write info message in green.

Parameters:message – the message to be printed.
firedrake.logging.info_blue(message, *args, **kwargs)[source]

Write info message in blue.

Parameters:message – the message to be printed.

firedrake.matrix module

class firedrake.matrix.ImplicitMatrix(a, bcs, *args, **kwargs)[source]

Bases: firedrake.matrix.MatrixBase

A representation of the action of bilinear form operating without explicitly assembling the associated matrix. This class wraps the relevant information for Python PETSc matrix.

Parameters:
  • a – the bilinear form this Matrix represents.
  • bcs – an iterable of boundary conditions to apply to this Matrix. May be None if there are no boundary conditions to apply.

Note

This object acts to the right on an assembled Function and to the left on an assembled cofunction (currently represented by a Function).

assemble()[source]
assembled
force_evaluation()
class firedrake.matrix.Matrix(a, bcs, *args, **kwargs)[source]

Bases: firedrake.matrix.MatrixBase

A representation of an assembled bilinear form.

Parameters:
  • a – the bilinear form this Matrix represents.
  • bcs – an iterable of boundary conditions to apply to this Matrix. May be None if there are no boundary conditions to apply.

A pyop2.Mat will be built from the remaining arguments, for valid values, see pyop2.Mat.

Note

This object acts to the right on an assembled Function and to the left on an assembled cofunction (currently represented by a Function).

M

The pyop2.Mat representing the assembled form

Note

This property forces an actual assembly of the form, if you just need a handle on the pyop2.Mat object it’s wrapping, use _M instead.

assemble()[source]

Actually assemble this Matrix.

This calls the stashed assembly callback or does nothing if the matrix is already assembled.

Note

If the boundary conditions stashed on the Matrix have changed since the last time it was assembled, this will necessitate reassembly. So for example:

A = assemble(a, bcs=[bc1])
solve(A, x, b)
bc2.apply(A)
solve(A, x, b)

will apply boundary conditions from bc1 in the first solve, but both bc1 and bc2 in the second solve.

assembled

Return True if this Matrix has been assembled.

force_evaluation()[source]

Ensures that the matrix is fully assembled.

class firedrake.matrix.MatrixBase(a, bcs)[source]

Bases: object

A representation of the linear operator associated with a bilinear form and bcs. Explicitly assembled matrices and matrix-free matrix classes will derive from this

Parameters:
  • a – the bilinear form this MatrixBase represents.
  • bcs – an iterable of boundary conditions to apply to this MatrixBase. May be None if there are no boundary conditions to apply.
a

The bilinear form this MatrixBase was assembled from

add_bc(bc)[source]

Add a boundary condition to this MatrixBase.

Parameters:bc – the DirichletBC to add.

If the subdomain this boundary condition is applied over is the same as the subdomain of an existing boundary condition on the MatrixBase, the existing boundary condition is replaced with this new one. Otherwise, this boundary condition is added to the set of boundary conditions on the MatrixBase.

assemble()[source]

Actually assemble this matrix.

Ensures any pending calculations needed to populate this matrix are queued up.

Note that this does not guarantee that those calculations are executed. If you want the latter, see force_evaluation().

assembled()[source]

Is this matrix currently assembled?

See also assemble().

bcs

The set of boundary conditions attached to this MatrixBase (may be empty).

force_evaluation()[source]

Force any pending writes to this matrix.

Ensures that the matrix is assembled and populated with values, ready for sending to PETSc.

has_bcs

Return True if this MatrixBase has any boundary conditions attached to it.

firedrake.mesh module

firedrake.mesh.Mesh(meshfile, **kwargs)[source]

Construct a mesh object.

Meshes may either be created by reading from a mesh file, or by providing a PETSc DMPlex object defining the mesh topology.

Parameters:
  • meshfile – Mesh file name (or DMPlex object) defining mesh topology. See below for details on supported mesh formats.
  • dim – optional specification of the geometric dimension of the mesh (ignored if not reading from mesh file). If not supplied the geometric dimension is deduced from the topological dimension of entities in the mesh.
  • reorder – optional flag indicating whether to reorder meshes for better cache locality. If not supplied the default value in parameters["reorder_meshes"] is used.
  • distribute – should the mesh be distributed. May be None (use the default choice), False (do not) True (do), or a 2-tuple that specifies a partitioning of the cells (only really useful for debugging).
  • comm – the communicator to use when creating the mesh. If not supplied, then the mesh will be created on COMM_WORLD. Ignored if meshfile is a DMPlex object (in which case the communicator will be taken from there).

When the mesh is read from a file the following mesh formats are supported (determined, case insensitively, from the filename extension):

  • GMSH: with extension .msh
  • Exodus: with extension .e, .exo
  • CGNS: with extension .cgns
  • Triangle: with extension .node

Note

When the mesh is created directly from a DMPlex object, the dim parameter is ignored (the DMPlex already knows its geometric and topological dimensions).

firedrake.mesh.ExtrudedMesh(mesh, layers, layer_height=None, extrusion_type='uniform', kernel=None, gdim=None)[source]

Build an extruded mesh from an input mesh

Parameters:
  • mesh – the unstructured base mesh
  • layers – number of extruded cell layers in the “vertical” direction. One may also pass an array of shape (cells, 2) to specify a variable number of layers. In this case, each entry is a pair [a, b] where a indicates the starting cell layer of the column and b the number of cell layers in that column.
  • layer_height – the layer height, assuming all layers are evenly spaced. If this is omitted, the value defaults to 1/layers (i.e. the extruded mesh has total height 1.0) unless a custom kernel is used. Must be provided if using a variable number of layers.
  • extrusion_type – the algorithm to employ to calculate the extruded coordinates. One of “uniform”, “radial”, “radial_hedgehog” or “custom”. See below.
  • kernel – a pyop2.Kernel to produce coordinates for the extruded mesh. See make_extruded_coords() for more details.
  • gdim – number of spatial dimensions of the resulting mesh (this is only used if a custom kernel is provided)

The various values of extrusion_type have the following meanings:

"uniform"
the extruded mesh has an extra spatial dimension compared to the base mesh. The layers exist in this dimension only.
"radial"
the extruded mesh has the same number of spatial dimensions as the base mesh; the cells are radially extruded outwards from the origin. This requires the base mesh to have topological dimension strictly smaller than geometric dimension.
"radial_hedgehog"
similar to radial, but the cells are extruded in the direction of the outward-pointing cell normal (this produces a P1dgxP1 coordinate field). In this case, a radially extruded coordinate field (generated with extrusion_type="radial") is available in the radial_coordinates attribute.
"custom"
use a custom kernel to generate the extruded coordinates

For more details see the manual section on extruded meshes.

firedrake.mesh.SubDomainData(geometric_expr)[source]

Creates a subdomain data object from a boolean-valued UFL expression.

The result can be attached as the subdomain_data field of a ufl.Measure. For example:

x = mesh.coordinates sd = SubDomainData(x[0] < 0.5) assemble(f*dx(subdomain_data=sd))
firedrake.mesh.unmarked = -1

A mesh marker that selects all entities that are not explicitly marked.

firedrake.norms module

firedrake.norms.errornorm(u, uh, norm_type='L2', degree_rise=None, mesh=None)[source]

Compute the error \(e = u - u_h\) in the specified norm.

Parameters:
  • u – a Function or UFL expression containing an “exact” solution
  • uh – a Function containing the approximate solution
  • norm_type – the type of norm to compute, see norm() for details of supported norm types.
  • degree_rise – ignored.
  • mesh – an optional mesh on which to compute the error norm (currently ignored).
firedrake.norms.norm(v, norm_type='L2', mesh=None)[source]

Compute the norm of v.

Parameters:
  • v – a ufl expression (Expr) to compute the norm of
  • norm_type – the type of norm to compute, see below for options.
  • mesh – an optional mesh on which to compute the norm (currently ignored).

Available norm types are:

  • L2

    \[||v||_{L^2}^2 = \int (v, v) \mathrm{d}x\]
  • H1

    \[||v||_{H^1}^2 = \int (v, v) + (\nabla v, \nabla v) \mathrm{d}x\]
  • Hdiv

    \[||v||_{H_\mathrm{div}}^2 = \int (v, v) + (\nabla\cdot v, \nabla \cdot v) \mathrm{d}x\]
  • Hcurl

    \[||v||_{H_\mathrm{curl}}^2 = \int (v, v) + (\nabla \wedge v, \nabla \wedge v) \mathrm{d}x\]

firedrake.nullspace module

class firedrake.nullspace.VectorSpaceBasis(vecs=None, constant=False)[source]

Bases: object

Build a basis for a vector space.

You can use this basis to express the null space of a singular operator.

Parameters:
  • vecs – a list of Vectors or Functions spanning the space.
  • constant – does the null space include the constant vector? If you pass constant=True you should not also include the constant vector in the list of vecs you supply.

Note

Before using this object in a solver, you must ensure that the basis is orthonormal. You can do this by calling orthonormalize(), this modifies the provided vectors in place.

Warning

The vectors you pass in to this object are not copied. You should therefore not modify them after instantiation since the basis will then be incorrect.

check_orthogonality(orthonormal=True)[source]

Check if the basis is orthogonal.

Parameters:orthonormal – If True check that the basis is also orthonormal.
Raises:ValueError – If the basis is not orthogonal/orthonormal.
is_orthogonal()[source]

Is this vector space basis orthogonal?

is_orthonormal()[source]

Is this vector space basis orthonormal?

nullspace(comm=None)[source]

The PETSc NullSpace object for this VectorSpaceBasis.

Parameters:comm – Communicator to create the nullspace on.
orthogonalize(b)[source]

Orthogonalize b with respect to this VectorSpaceBasis.

Parameters:b – a Function

Note

Modifies b in place.

orthonormalize()[source]

Orthonormalize the basis.

Warning

This modifies the basis in place.

class firedrake.nullspace.MixedVectorSpaceBasis(function_space, bases)[source]

Bases: object

A basis for a mixed vector space

Parameters:
  • function_space – the MixedFunctionSpace this vector space is a basis for.
  • bases – an iterable of bases for the null spaces of the subspaces in the mixed space.

You can use this to express the null space of a singular operator on a mixed space. The bases you supply will be used to set null spaces for each of the diagonal blocks in the operator. If you only care about the null space on one of the blocks, you can pass an indexed function space as a placeholder in the positions you don’t care about.

For example, consider a mixed poisson discretisation with pure Neumann boundary conditions:

V = FunctionSpace(mesh, "BDM", 1)
Q = FunctionSpace(mesh, "DG", 0)

W = V*Q

sigma, u = TrialFunctions(W)
tau, v = TestFunctions(W)

a = (inner(sigma, tau) + div(sigma)*v + div(tau)*u)*dx

The null space of this operator is a constant function in Q. If we solve the problem with a Schur complement, we only care about projecting the null space out of the QxQ block. We can do this like so

nullspace = MixedVectorSpaceBasis(W, [W[0], VectorSpaceBasis(constant=True)])
solve(a == ..., nullspace=nullspace)

firedrake.optimizer module

firedrake.optimizer.slope(mesh, debug=False)[source]

Initialize the SLOPE library by providing information about the mesh, including:

  • Mesh coordinates
  • All available maps binding sets of mesh components

firedrake.output module

class firedrake.output.File(filename, project_output=False, comm=None, restart=0)[source]

Bases: object

Create an object for outputting data for visualisation.

This produces output in VTU format, suitable for visualisation with Paraview or other VTK-capable visualisation packages.

Parameters:
  • filename – The name of the output file (must end in .pvd).
  • project_output – Should the output be projected to linears? Default is to use interpolation.
  • comm – The MPI communicator to use.
  • restart – Restart at count.

Note

Visualisation is only possible for linear fields (either continuous or discontinuous). All other fields are first either projected or interpolated to linear before storing for visualisation purposes.

write(*functions, **kwargs)[source]

Write functions to this File.

Parameters:
  • functions – list of functions to write.
  • time – optional timestep value.

You may save more than one function to the same file. However, all calls to write() must use the same set of functions.

firedrake.parameters module

The parameters dictionary contains global parameter settings.

class firedrake.parameters.Parameters(name=None, **kwargs)[source]

Bases: dict

add(key, value=None)[source]
name()[source]
rename(name)[source]
set_update_function(callable)[source]

Set a function to be called whenever a dictionary entry is changed.

Parameters:callable – the function.

The function receives two arguments, the key-value pair of updated entries.

firedrake.parameters.parameters = {'default_matrix_type': 'nest', 'coffee': {'optlevel': 'Ov'}, 'form_compiler': {'quadrature_degree': 'auto', 'quadrature_rule': 'auto', 'mode': 'spectral', 'unroll_indexsum': 3, 'precision': 15}, 'reorder_meshes': True, 'pyop2_options': {'check_src_hashes': True, 'compiler': 'gnu', 'matnest': True, 'opt_level': 'Ov', 'no_fork_available': False, 'simd_isa': 'sse', 'lazy_evaluation': True, 'print_summary': False, 'dump_gencode_path': '/tmp/pyop2-gencode', 'block_sparsity': True, 'blas': '', 'cflags': '', 'type_check': True, 'ldflags': '', 'lazy_max_trace_length': 100, 'debug': False, 'print_cache_size': False, 'dump_gencode': False, 'log_level': 'WARNING', 'loop_fusion': False, 'cache_dir': '/data/dham/src/firedrake/.cache/pyop2'}, 'type_check_safe_par_loops': False, 'default_sub_matrix_type': 'baij'}

A nested dictionary of parameters used by Firedrake

firedrake.parameters.disable_performance_optimisations()[source]

Switches off performance optimisations in Firedrake.

This is mostly useful for debugging purposes.

This switches off all of COFFEE’s kernel compilation optimisations and enables PyOP2’s runtime checking of par_loop arguments in all cases (even those where they are claimed safe). Additionally, it switches to compiling generated code in debug mode.

Returns a function that can be called with no arguments, to restore the state of the parameters dict.

firedrake.parloops module

This module implements parallel loops reading and writing Functions. This provides a mechanism for implementing non-finite element operations such as slope limiters.

firedrake.parloops.par_loop(kernel, measure, args, **kwargs)[source]

A par_loop() is a user-defined operation which reads and writes Functions by looping over the mesh cells or facets and accessing the degrees of freedom on adjacent entities.

Parameters:
  • kernel – is a string containing the C code to be executed.
  • measure – is a UFL Measure which determines the manner in which the iteration over the mesh is to occur. Alternatively, you can pass direct to designate a direct loop.
  • args – is a dictionary mapping variable names in the kernel to Functions or components of mixed Functions and indicates how these Functions are to be accessed.
  • kwargs – additional keyword arguments are passed to the Kernel constructor

Example

Assume that A is a Function in CG1 and B is a Function in DG0. Then the following code sets each DoF in A to the maximum value that B attains in the cells adjacent to that DoF:

A.assign(numpy.finfo(0.).min)
par_loop('for (int i=0; i<A.dofs; i++) A[i][0] = fmax(A[i][0], B[0][0]);', dx,
    {'A' : (A, RW), 'B': (B, READ)})

Argument definitions

Each item in the args dictionary maps a string to a tuple containing a Function or Constant and an argument intent. The string is the c language variable name by which this function will be accessed in the kernel. The argument intent indicates how the kernel will access this variable:

READ
The variable will be read but not written to.
WRITE
The variable will be written to but not read. If multiple kernel invocations write to the same DoF, then the order of these writes is undefined.
RW
The variable will be both read and written to. If multiple kernel invocations access the same DoF, then the order of these accesses is undefined, but it is guaranteed that no race will occur.
INC
The variable will be added into using +=. As before, the order in which the kernel invocations increment the variable is undefined, but there is a guarantee that no races will occur.

Note

Only READ intents are valid for Constant coefficients, and an error will be raised in other cases.

The measure

The measure determines the mesh entities over which the iteration will occur, and the size of the kernel stencil. The iteration will occur over the same mesh entities as if the measure had been used to define an integral, and the stencil will likewise be the same as the integral case. That is to say, if the measure is a volume measure, the kernel will be called once per cell and the DoFs accessible to the kernel will be those associated with the cell, its facets, edges and vertices. If the measure is a facet measure then the iteration will occur over the corresponding class of facets and the accessible DoFs will be those on the cell(s) adjacent to the facet, and on the facets, edges and vertices adjacent to those facets.

For volume measures the DoFs are guaranteed to be in the FInAT local DoFs order. For facet measures, the DoFs will be in sorted first by the cell to which they are adjacent. Within each cell, they will be in FInAT order. Note that if a continuous Function is accessed via an internal facet measure, the DoFs on the interface between the two facets will be accessible twice: once via each cell. The orientation of the cell(s) relative to the current facet is currently arbitrary.

A direct loop over nodes without any indirections can be specified by passing direct as the measure. In this case, all of the arguments must be Functions in the same FunctionSpace.

The kernel code

The kernel code is plain C in which the variables specified in the args dictionary are available to be read or written in according to the argument intent specified. Most basic C operations are permitted. However there are some restrictions:

  • Only functions from math.h may be called.
  • Pointer operations other than dereferencing arrays are prohibited.

Indirect free variables referencing Functions are all of type double** in which the first index is the local node number, while the second index is the vector (or tensor) component. The latter only applies to Functions over a FunctionSpace with FunctionSpace.rank greater than zero (spaces with a VectorElement or TensorElement). In the case of scalar FunctionSpaces, the second index is always 0.

In a direct par_loop(), the variables will all be of type double* with the single index being the vector component.

Constants are always of type double*, both for indirect and direct par_loop() calls.

firedrake.parloops.direct = direct

A singleton object which can be used in a par_loop() in place of the measure in order to indicate that the loop is a direct loop over degrees of freedom.

firedrake.petsc module

firedrake.plot module

firedrake.plot.plot(function_or_mesh, num_sample_points=10, axes=None, plot3d=False, **kwargs)[source]

Plot a Firedrake object.

Parameters:
  • function_or_mesh – The Function or Mesh() to plot. An iterable of Functions may also be provided, in which case an animated plot will be available.
  • num_sample_points – Number of Sample points per element, ignored if degree < 4 where an exact Bezier curve will be used instead of sampling at points. For 2D plots, the number of sampling points per element will not exactly this value. Instead, it is used as a guide to the number of subdivisions to use when triangulating the surface.
  • axes – Axes to be plotted on
  • plot3d – For 2D plotting, use matplotlib 3D functionality? (slow)
  • contour – For 2D plotting, True for a contour plot
  • bezier – For 1D plotting, interpolate using bezier curve instead of piece-wise linear
  • auto_resample – For 1D plotting for functions with degree >= 4, resample automatically when zoomed
  • interactive – For 1D plotting for multiple functions, use an interactive inferface in Jupyter Notebook
  • kwargs – Additional keyword arguments passed to matplotlib.plot.

firedrake.pointeval_utils module

firedrake.pointeval_utils.compile_element(expression, coordinates, parameters=None)[source]

Generates C code for point evaluations.

Parameters:
  • expression – UFL expression
  • coordinates – coordinate field
  • parameters – form compiler parameters
Returns:

C code as string

firedrake.pointquery_utils module

firedrake.pointquery_utils.compile_coordinate_element(ufl_coordinate_element, contains_eps, parameters=None)[source]

Generates C code for changing to reference coordinates.

Parameters:ufl_coordinate_element – UFL element of the coordinates
Returns:C code as string
firedrake.pointquery_utils.make_args(function)[source]
firedrake.pointquery_utils.make_wrapper(function, **kwargs)[source]
firedrake.pointquery_utils.src_locate_cell(mesh, tolerance=None)[source]

firedrake.projection module

firedrake.projection.project(v, V, bcs=None, mesh=None, solver_parameters=None, form_compiler_parameters=None, name=None)[source]

Project an Expression or Function into a FunctionSpace

Parameters:
  • v – the Expression, ufl.Expr or Function to project
  • V – the FunctionSpace or Function to project into
  • bcs – boundary conditions to apply in the projection
  • mesh – the mesh to project into
  • solver_parameters – parameters to pass to the solver used when projecting.
  • form_compiler_parameters – parameters to the form compiler
  • name – name of the resulting Function

If V is a Function then v is projected into V and V is returned. If V is a FunctionSpace then v is projected into a new Function and that Function is returned.

The mesh and form_compiler_parameters are currently ignored.

class firedrake.projection.Projector(v, v_out, bcs=None, solver_parameters=None, constant_jacobian=True)[source]

Bases: object

A projector projects a UFL expression into a function space and places the result in a function from that function space, allowing the solver to be reused. Projection reverts to an assign operation if v is a Function and belongs to the same function space as v_out.

Parameters:
  • v – the ufl.Expr or Function to project
  • v_outFunction to put the result in
  • bcs – an optional set of DirichletBC objects to apply on the target function space.
  • solver_parameters – parameters to pass to the solver used when projecting.
project()[source]

Apply the projection.

firedrake.solving module

firedrake.solving.solve(*args, **kwargs)[source]

Solve linear system Ax = b or variational problem a == L or F == 0.

The Firedrake solve() function can be used to solve either linear systems or variational problems. The following list explains the various ways in which the solve() function can be used.

1. Solving linear systems

A linear system Ax = b may be solved by calling

solve(A, x, b, bcs=bcs, solver_parameters={...})

where A is a Matrix and x and b are Functions. If present, bcs should be a list of DirichletBCs specifying the strong boundary conditions to apply. For the format of solver_parameters see below.

2. Solving linear variational problems

A linear variational problem a(u, v) = L(v) for all v may be solved by calling solve(a == L, u, …), where a is a bilinear form, L is a linear form, u is a Function (the solution). Optional arguments may be supplied to specify boundary conditions or solver parameters. Some examples are given below:

solve(a == L, u)
solve(a == L, u, bcs=bc)
solve(a == L, u, bcs=[bc1, bc2])

solve(a == L, u, bcs=bcs,
      solver_parameters={"ksp_type": "gmres"})

The linear solver uses PETSc under the hood and accepts all PETSc options as solver parameters. For example, to solve the system using direct factorisation use:

solve(a == L, u, bcs=bcs,
      solver_parameters={"ksp_type": "preonly", "pc_type": "lu"})

3. Solving nonlinear variational problems

A nonlinear variational problem F(u; v) = 0 for all v may be solved by calling solve(F == 0, u, …), where the residual F is a linear form (linear in the test function v but possibly nonlinear in the unknown u) and u is a Function (the solution). Optional arguments may be supplied to specify boundary conditions, the Jacobian form or solver parameters. If the Jacobian is not supplied, it will be computed by automatic differentiation of the residual form. Some examples are given below:

The nonlinear solver uses a PETSc SNES object under the hood. To pass options to it, use the same options names as you would for pure PETSc code. See NonlinearVariationalSolver for more details.

solve(F == 0, u)
solve(F == 0, u, bcs=bc)
solve(F == 0, u, bcs=[bc1, bc2])

solve(F == 0, u, bcs, J=J,
      # Use Newton-Krylov iterations to solve the nonlinear
      # system, using direct factorisation to solve the linear system.
      solver_parameters={"snes_type": "newtonls",
                         "ksp_type" : "preonly",
                         "pc_type" : "lu"})

In all three cases, if the operator is singular you can pass a VectorSpaceBasis (or MixedVectorSpaceBasis) spanning the null space of the operator to the solve call using the nullspace keyword argument.

If you need to project the transpose nullspace out of the right hand side, you can do so by using the transpose_nullspace keyword argument.

In the same fashion you can add the near nullspace using the near_nullspace keyword argument.

firedrake.solving_utils module

class firedrake.solving_utils.ParametersMixin(parameters, options_prefix)[source]

Bases: object

commandline_options = frozenset({'b', 'd'})
count = count(0)

Mixin class that helps with managing setting petsc options on solvers.

Parameters:
  • parameters – The dictionary of parameters to use.
  • options_prefix – The prefix to look up items in the global options database (may be None, in which case only entries from parameters will be considered. If no trailing underscore is provided, one is appended. Hence foo_ and foo are treated equivalently. As an exception, if the prefix is the empty string, no underscore is appended.

To use this, you must call its constructor to with the parameters you want in the options database.

You then call set_from_options(), passing the PETSc object you’d like to call setFromOptions on. Note that this will actually only call setFromOptions the first time (so really this parameters object is a once-per-PETSc-object thing).

So that the runtime monitors which look in the options database actually see options, you need to ensure that the options database is populated at the time of a SNESSolve or KSPSolve call. Do that using the inserted_options() context manager.

with self.inserted_options():
    self.snes.solve(...)

This ensures that the options database has the relevant entries for the duration of the with block, before removing them afterwards. This is a much more robust way of dealing with the fixed-size options database than trying to clear it out using destructors.

inserted_options()[source]

Context manager inside which the petsc options database contains the parameters from this object.

options_object = <petsc4py.PETSc.Options object>
set_default_parameter(key, val)[source]

Set a default parameter value.

Parameters:
  • key – The parameter name
  • val – The parameter value.

Ensures that the right thing happens cleaning up the options database.

set_from_options(petsc_obj)[source]

Set up petsc_obj from the options database.

Parameters:petsc_obj – The PETSc object to call setFromOptions on.

Matt says: “Only ever call setFromOptions once”. This function ensures we do so.

firedrake.solving_utils.check_snes_convergence(snes)[source]
firedrake.solving_utils.flatten_parameters(parameters, sep='_')[source]

Flatten a nested parameters dict, joining keys with sep.

Parameters:
  • parameters – a dict to flatten.
  • sep – separator of keys.

Used to flatten parameter dictionaries with nested structure to a flat dict suitable to pass to PETSc. For example:

flatten_parameters({"a": {"b": {"c": 4}, "d": 2}, "e": 1}, sep="_")
=> {"a_b_c": 4, "a_d": 2, "e": 1}

If a “prefix” key already ends with the provided separator, then it is not used to concatenate the keys. Hence:

flatten_parameters({"a_": {"b": {"c": 4}, "d": 2}, "e": 1}, sep="_")
=> {"a_b_c": 4, "a_d": 2, "e": 1}
# rather than
=> {"a__b_c": 4, "a__d": 2, "e": 1}

firedrake.spatialindex module

class firedrake.spatialindex.SpatialIndex

Bases: object

Python class for holding a native spatial index object.

ctypes

Returns a ctypes pointer to the native spatial index.

firedrake.spatialindex.from_regions()

Builds a spatial index from a set of maximum bounding regions (MBRs).

regions_lo and regions_hi must have the same size. regions_lo[i] and regions_hi[i] contain the coordinates of the diagonally opposite lower and higher corners of the i-th MBR, respectively.

firedrake.tsfc_interface module

Provides the interface to TSFC for compiling a form, and transforms the TSFC- generated code in order to make it suitable for passing to the backends.

class firedrake.tsfc_interface.KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_map, needs_cell_facets, pass_layer_arg)

Bases: tuple

Create new instance of KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_map, needs_cell_facets, pass_layer_arg)

coefficient_map

Alias for field number 5

domain_number

Alias for field number 4

integral_type

Alias for field number 1

kernel

Alias for field number 0

needs_cell_facets

Alias for field number 6

oriented

Alias for field number 2

pass_layer_arg

Alias for field number 7

subdomain_id

Alias for field number 3

class firedrake.tsfc_interface.SplitKernel(indices, kinfo)

Bases: tuple

Create new instance of SplitKernel(indices, kinfo)

indices

Alias for field number 0

kinfo

Alias for field number 1

class firedrake.tsfc_interface.TSFCKernel(form, name, parameters, number_map)[source]

Bases: pyop2.caching.Cached

A wrapper object for one or more TSFC kernels compiled from a given Form.

Parameters:
  • form – the Form from which to compile the kernels.
  • name – a prefix to be applied to the compiled kernel names. This is primarily useful for debugging.
  • parameters – a dict of parameters to pass to the form compiler.
  • number_map – a map from local coefficient numbers to global ones (useful for split forms).
firedrake.tsfc_interface.clear_cache(comm=None)[source]

Clear the Firedrake TSFC kernel cache.

firedrake.tsfc_interface.compile_form(form, name, parameters=None, inverse=False)[source]

Compile a form using TSFC.

Parameters:
  • form – the Form to compile.
  • name – a prefix for the generated kernel functions.
  • parameters – optional dict of parameters to pass to the form compiler. If not provided, parameters are read from the form_compiler slot of the Firedrake parameters dictionary (which see).
  • inverse – If True then assemble the inverse of the local tensor.

Returns a tuple of tuples of (index, integral type, subdomain id, coordinates, coefficients, needs_orientations, Kernels).

needs_orientations indicates whether the form requires cell orientation information (for correctly pulling back to reference elements on embedded manifolds).

The coordinates are extracted from the domain of the integral (a Mesh())

firedrake.ufl_expr module

class firedrake.ufl_expr.Argument(function_space, number, part=None)[source]

Bases: ufl.argument.Argument

Representation of the argument to a form.

Parameters:
  • function_space – the FunctionSpace the argument corresponds to.
  • number – the number of the argument being constructed.
  • part – optional index (mostly ignored).

Note

an Argument with a number of 0 is used as a TestFunction(), with a number of 1 it is used as a TrialFunction().

cell_node_map[source]
exterior_facet_node_map[source]
function_space()[source]
interior_facet_node_map[source]
make_dat()[source]
reconstruct(function_space=None, number=None, part=None)[source]
firedrake.ufl_expr.TestFunction(function_space, part=None)[source]

Build a test function on the specified function space.

Parameters:
  • function_space – the FunctionSpace to build the test function on.
  • part – optional index (mostly ignored).
firedrake.ufl_expr.TrialFunction(function_space, part=None)[source]

Build a trial function on the specified function space.

Parameters:
  • function_space – the FunctionSpace to build the trial function on.
  • part – optional index (mostly ignored).
firedrake.ufl_expr.TestFunctions(function_space)[source]

Return a tuple of test functions on the specified function space.

Parameters:function_space – the FunctionSpace to build the test functions on.

This returns len(function_space) test functions, which, if the function space is a MixedFunctionSpace, are indexed appropriately.

firedrake.ufl_expr.TrialFunctions(function_space)[source]

Return a tuple of trial functions on the specified function space.

Parameters:function_space – the FunctionSpace to build the trial functions on.

This returns len(function_space) trial functions, which, if the function space is a MixedFunctionSpace, are indexed appropriately.

firedrake.ufl_expr.derivative(form, u, du=None, coefficient_derivatives=None)[source]

Compute the derivative of a form.

Given a form, this computes its linearization with respect to the provided Function. The resulting form has one additional Argument in the same finite element space as the Function.

Parameters:
  • form – a Form to compute the derivative of.
  • u – a Function to compute the derivative with respect to.
  • du – an optional Argument to use as the replacement in the new form (constructed automatically if not provided).
  • coefficient_derivatives – an optional dict to provide the derivative of a coefficient function.
Raises:

ValueError – If any of the coefficients in form were obtained from u.split(). UFL doesn’t notice that these are related to u and so therefore the derivative is wrong (instead one should have written split(u)).

See also ufl.derivative().

firedrake.ufl_expr.adjoint(form, reordered_arguments=None)[source]

UFL form operator: Given a combined bilinear form, compute the adjoint form by changing the ordering (number) of the test and trial functions.

By default, new Argument objects will be created with opposite ordering. However, if the adjoint form is to be added to other forms later, their arguments must match. In that case, the user must provide a tuple reordered_arguments=(u2,v2).

firedrake.ufl_expr.CellSize(mesh)[source]

A symbolic representation of the cell size of a mesh.

Parameters:mesh – the mesh for which to calculate the cell size.
firedrake.ufl_expr.FacetNormal(mesh)[source]

A symbolic representation of the facet normal on a cell in a mesh.

Parameters:mesh – the mesh over which the normal should be represented.

firedrake.utility_meshes module

firedrake.utility_meshes.IntervalMesh(ncells, length_or_left, right=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a uniform mesh of an interval.

Parameters:
  • ncells – The number of the cells over the interval.
  • length_or_left – The length of the interval (if right is not provided) or else the left hand boundary point.
  • right – (optional) position of the right boundary point (in which case length_or_left should be the left boundary point).
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The left hand boundary point has boundary marker 1, while the right hand point has marker 2.

firedrake.utility_meshes.UnitIntervalMesh(ncells, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a uniform mesh of the interval [0,1].

Parameters:
  • ncells – The number of the cells over the interval.
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The left hand (\(x=0\)) boundary point has boundary marker 1, while the right hand (\(x=1\)) point has marker 2.

firedrake.utility_meshes.PeriodicIntervalMesh(ncells, length, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a periodic mesh of an interval.

Parameters:
  • ncells – The number of cells over the interval.
  • length – The length the interval.
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.PeriodicUnitIntervalMesh(ncells, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a periodic mesh of the unit interval

Parameters:
  • ncells – The number of cells in the interval.
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.UnitTriangleMesh(comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a mesh of the reference triangle

Parameters:comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.RectangleMesh(nx, ny, Lx, Ly, quadrilateral=False, reorder=None, diagonal='left', distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a rectangular mesh

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • Lx – The extent in the x direction
  • Ly – The extent in the y direction
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • reorder – (optional), should the mesh be reordered
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
  • diagonal – For triangular meshes, should the diagonal got from bottom left to top right ("right"), or top left to bottom right ("left").

The boundary edges in this mesh are numbered as follows:

  • 1: plane x == 0
  • 2: plane x == Lx
  • 3: plane y == 0
  • 4: plane y == Ly
firedrake.utility_meshes.SquareMesh(nx, ny, L, reorder=None, quadrilateral=False, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a square mesh

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • L – The extent in the x and y directions
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • reorder – (optional), should the mesh be reordered
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The boundary edges in this mesh are numbered as follows:

  • 1: plane x == 0
  • 2: plane x == L
  • 3: plane y == 0
  • 4: plane y == L
firedrake.utility_meshes.UnitSquareMesh(nx, ny, reorder=None, quadrilateral=False, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a unit square mesh

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • reorder – (optional), should the mesh be reordered
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The boundary edges in this mesh are numbered as follows:

  • 1: plane x == 0
  • 2: plane x == 1
  • 3: plane y == 0
  • 4: plane y == 1
firedrake.utility_meshes.PeriodicRectangleMesh(nx, ny, Lx, Ly, direction='both', quadrilateral=False, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a periodic rectangular mesh

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • Lx – The extent in the x direction
  • Ly – The extent in the y direction
  • direction – The direction of the periodicity, one of "both", "x" or "y".
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • reorder – (optional), should the mesh be reordered
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

If direction == “x” the boundary edges in this mesh are numbered as follows:

  • 1: plane y == 0
  • 2: plane y == Ly

If direction == “y” the boundary edges are:

  • 1: plane x == 0
  • 2: plane x == Lx
firedrake.utility_meshes.PeriodicSquareMesh(nx, ny, L, direction='both', quadrilateral=False, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a periodic square mesh

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • L – The extent in the x and y directions
  • direction – The direction of the periodicity, one of "both", "x" or "y".
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • reorder – (optional), should the mesh be reordered
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

If direction == “x” the boundary edges in this mesh are numbered as follows:

  • 1: plane y == 0
  • 2: plane y == L

If direction == “y” the boundary edges are:

  • 1: plane x == 0
  • 2: plane x == L
firedrake.utility_meshes.PeriodicUnitSquareMesh(nx, ny, direction='both', reorder=None, quadrilateral=False, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a periodic unit square mesh

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • direction – The direction of the periodicity, one of "both", "x" or "y".
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • reorder – (optional), should the mesh be reordered
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

If direction == “x” the boundary edges in this mesh are numbered as follows:

  • 1: plane y == 0
  • 2: plane y == 1

If direction == “y” the boundary edges are:

  • 1: plane x == 0
  • 2: plane x == 1
firedrake.utility_meshes.CircleManifoldMesh(ncells, radius=1, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generated a 1D mesh of the circle, immersed in 2D.

Parameters:
  • ncells – number of cells the circle should be divided into (min 3)
  • radius – (optional) radius of the circle to approximate (defaults to 1).
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.UnitTetrahedronMesh(comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a mesh of the reference tetrahedron.

Parameters:comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.BoxMesh(nx, ny, nz, Lx, Ly, Lz, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a mesh of a 3D box.

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • nz – The number of cells in the z direction
  • Lx – The extent in the x direction
  • Ly – The extent in the y direction
  • Lz – The extent in the z direction
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The boundary surfaces are numbered as follows:

  • 1: plane x == 0
  • 2: plane x == Lx
  • 3: plane y == 0
  • 4: plane y == Ly
  • 5: plane z == 0
  • 6: plane z == Lz
firedrake.utility_meshes.CubeMesh(nx, ny, nz, L, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a mesh of a cube

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • nz – The number of cells in the z direction
  • L – The extent in the x, y and z directions
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The boundary surfaces are numbered as follows:

  • 1: plane x == 0
  • 2: plane x == L
  • 3: plane y == 0
  • 4: plane y == L
  • 5: plane z == 0
  • 6: plane z == L
firedrake.utility_meshes.UnitCubeMesh(nx, ny, nz, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a mesh of a unit cube

Parameters:
  • nx – The number of cells in the x direction
  • ny – The number of cells in the y direction
  • nz – The number of cells in the z direction
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The boundary surfaces are numbered as follows:

  • 1: plane x == 0
  • 2: plane x == 1
  • 3: plane y == 0
  • 4: plane y == 1
  • 5: plane z == 0
  • 6: plane z == 1
firedrake.utility_meshes.IcosahedralSphereMesh(radius, refinement_level=0, degree=1, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate an icosahedral approximation to the surface of the sphere.

Parameters:
  • radius

    The radius of the sphere to approximate. For a radius R the edge length of the underlying icosahedron will be.

    \[a = \frac{R}{\sin(2 \pi / 5)}\]
  • refinement_level – optional number of refinements (0 is an icosahedron).
  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.UnitIcosahedralSphereMesh(refinement_level=0, degree=1, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate an icosahedral approximation to the unit sphere.

Parameters:
  • refinement_level – optional number of refinements (0 is an icosahedron).
  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.OctahedralSphereMesh(radius, refinement_level=0, degree=1, hemisphere='both', z0=0.8, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate an octahedral approximation to the surface of the sphere.

Parameters:
  • radius – The radius of the sphere to approximate.
  • refinement_level – optional number of refinements (0 is an octahedron).
  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
  • hemisphere – One of “both” (default), “north”, or “south”
  • z0 – for abs(z/R)>z0, blend from a mesh where the higher-order non-vertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh. (defaults to z0=0.8).
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.UnitOctahedralSphereMesh(refinement_level=0, degree=1, hemisphere='both', z0=0.8, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate an octahedral approximation to the unit sphere.

Parameters:
  • refinement_level – optional number of refinements (0 is an octahedron).
  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
  • hemisphere – One of “both” (default), “north”, or “south”
  • z0 – for abs(z)>z0, blend from a mesh where the higher-order non-vertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh. (defaults to z0=0.8).
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.CubedSphereMesh(radius, refinement_level=0, degree=1, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate an cubed approximation to the surface of the sphere.

Parameters:
  • radius – The radius of the sphere to approximate.
  • refinement_level – optional number of refinements (0 is a cube).
  • degree – polynomial degree of coordinate space (defaults to 1: bilinear quads)
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.UnitCubedSphereMesh(refinement_level=0, degree=1, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a cubed approximation to the unit sphere.

Parameters:
  • refinement_level – optional number of refinements (0 is a cube).
  • degree – polynomial degree of coordinate space (defaults to 1: bilinear quads)
  • reorder – (optional), should the mesh be reordered?
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.TorusMesh(nR, nr, R, r, quadrilateral=False, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a toroidal mesh

Parameters:
  • nR – The number of cells in the major direction (min 3)
  • nr – The number of cells in the minor direction (min 3)
  • R – The major radius
  • r – The minor radius
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • reorder – (optional), should the mesh be reordered
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
firedrake.utility_meshes.CylinderMesh(nr, nl, radius=1, depth=1, longitudinal_direction='z', quadrilateral=False, reorder=None, distribute=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generates a cylinder mesh.

Parameters:
  • nr – number of cells the cylinder circumference should be divided into (min 3)
  • nl – number of cells along the longitudinal axis of the cylinder
  • radius – (optional) radius of the cylinder to approximate (default 1).
  • depth – (optional) depth of the cylinder to approximate (default 1).
  • longitudinal_direction – (option) direction for the longitudinal axis of the cylinder.
  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

The boundary edges in this mesh are numbered as follows:

  • 1: plane l == 0 (bottom)
  • 2: plane l == depth (top)

firedrake.utils module

firedrake.utils.known_pyop2_safe(f)[source]

Decorator to mark a function as being PyOP2 type-safe.

This switches the current PyOP2 type checking mode to the value given by the parameter “type_check_safe_par_loops”, and restores it after the function completes.

firedrake.utils.unique_name(name, nameset)[source]

Return name if name is not in nameset, or a deterministic uniquified name if name is in nameset. The new name is inserted into nameset to prevent further name clashes.

firedrake.variational_solver module

class firedrake.variational_solver.LinearVariationalProblem(a, L, u, bcs=None, aP=None, form_compiler_parameters=None, constant_jacobian=True)[source]

Bases: firedrake.variational_solver.NonlinearVariationalProblem

Linear variational problem a(u, v) = L(v).

Parameters:
  • a – the bilinear form
  • L – the linear form
  • u – the Function to solve for
  • bcs – the boundary conditions (optional)
  • aP – an optional operator to assemble to precondition the system (if not provided a preconditioner may be computed from a)
  • form_compiler_parameters (dict) – parameters to pass to the form compiler (optional)
  • constant_jacobian – (optional) flag indicating that the Jacobian is constant (i.e. does not depend on varying fields). If your Jacobian can change, set this flag to False.
class firedrake.variational_solver.LinearVariationalSolver(*args, **kwargs)[source]

Bases: firedrake.variational_solver.NonlinearVariationalSolver

Solves a LinearVariationalProblem.

Parameters:
  • problem – A LinearVariationalProblem to solve.
  • solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.
  • nullspace – an optional VectorSpaceBasis (or MixedVectorSpaceBasis) spanning the null space of the operator.
  • transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
  • options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the solver_parameters dict.
invalidate_jacobian()[source]

Forces the matrix to be reassembled next time it is required.

class firedrake.variational_solver.NonlinearVariationalProblem(F, u, bcs=None, J=None, Jp=None, form_compiler_parameters=None)[source]

Bases: object

Nonlinear variational problem F(u; v) = 0.

Parameters:
  • F – the nonlinear form
  • u – the Function to solve for
  • bcs – the boundary conditions (optional)
  • J – the Jacobian J = dF/du (optional)
  • Jp – a form used for preconditioning the linear system, optional, if not supplied then the Jacobian itself will be used.
  • form_compiler_parameters (dict) – parameters to pass to the form compiler (optional)
dm[source]
class firedrake.variational_solver.NonlinearVariationalSolver(problem, **kwargs)[source]

Bases: firedrake.solving_utils.ParametersMixin

Solves a NonlinearVariationalProblem.

Parameters:
  • problem – A NonlinearVariationalProblem to solve.
  • nullspace – an optional VectorSpaceBasis (or MixedVectorSpaceBasis) spanning the null space of the operator.
  • transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
  • near_nullspace – as for the nullspace, but used to specify the near nullspace (for multigrid solvers).
  • solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.
  • options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the solver_parameters dict.
  • pre_jacobian_callback – A user-defined function that will be called immediately before Jacobian assembly. This can be used, for example, to update a coefficient function that has a complicated dependence on the unknown solution.
  • pre_function_callback – As above, but called immediately before residual assembly

Example usage of the solver_parameters option: to set the nonlinear solver type to just use a linear solver, use

{'snes_type': 'ksponly'}

PETSc flag options should be specified with bool values. For example:

{'snes_monitor': True}

To use the pre_jacobian_callback or pre_function_callback functionality, the user-defined function must accept the current solution as a petsc4py Vec. Example usage is given below:

def update_diffusivity(current_solution):
    with cursol.dat.vec_wo as v:
        current_solution.copy(v)
    solve(trial*test*dx == dot(grad(cursol), grad(test))*dx, diffusivity)

solver = NonlinearVariationalSolver(problem,
                                    pre_jacobian_callback=update_diffusivity)
solve(bounds=None)[source]

Solve the variational problem.

Parameters:bounds – Optional bounds on the solution (lower, upper). lower and upper must both be Functions. or Vectors.

Note

If bounds are provided the snes_type must be set to vinewtonssls or vinewtonrsls.

firedrake.vector module

class firedrake.vector.Vector(x)[source]

Bases: object

Build a Vector that wraps a pyop2.Dat for Dolfin compatibilty.

Parameters:x – an Function to wrap or a Vector to copy. The former shares data, the latter copies data.
apply(action)[source]

Finalise vector assembly. This is not actually required in Firedrake but is provided for Dolfin compatibility.

array()[source]

Return a copy of the process local data as a numpy array

axpy(a, x)[source]

Add a*x to self.

Parameters:
copy()[source]

Return a copy of this vector.

dat[source]
gather(global_indices=None)[source]

Gather a Vector to all processes

Parameters:global_indices – the globally numbered indices to gather (should be the same on all processes). If None, gather the entire Vector.
get_local()[source]

Return a copy of the process local data as a numpy array

inner(other)[source]

Return the l2-inner product of self with other

local_range()[source]

Return the global indices of the start and end of the local part of this vector.

local_size()[source]

Return the size of the process local data (without ghost points)

max()[source]

Return the maximum entry in the vector.

set_local(values)[source]

Set process local values

Parameters:values – a numpy array of values of length Vector.local_size()
size()[source]

Return the global size of the data

sum()[source]

Return global sum of vector entries.

firedrake.vector.as_backend_type(tensor)[source]

Compatibility operation for Dolfin’s backend switching operations. This is for Dolfin compatibility only. There is no reason for Firedrake users to ever call this.

firedrake.version module

firedrake.version.check()[source]

Module contents