firedrake package¶
Subpackages¶
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 aTensorBase
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 theMeasure
in the form. For example, if aquadrature_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 2form, then assemble the inverse of the local matrices.
 mat_type – (optional) string indicating how a 2form (matrix) should be
assembled – either as a monolithic matrix (‘aij’ or ‘baij’), a block matrix
(‘nest’), or left as a
ImplicitMatrix
giving matrixfree actions (‘matfree’). If not supplied, the default value inparameters["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 nonmixed matrices.  sub_mat_type – (optional) string indicating the matrix type to
use inside a nested block matrix. Only makes sense if
mat_type
isnest
. May be one of ‘aij’ or ‘baij’. If not supplied, defaults toparameters["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 afloat
for 0forms, aFunction
for 1forms and aMatrix
orImplicitMatrix
for 2forms.If f is an expression other than a form, it will be evaluated pointwise on the
Function
s in the expression. This will only succeed if all the Functions are on the sameFunctionSpace
.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 andf
is a 2form, the rows and columns of the resultingMatrix
corresponding to boundary nodes will be set to 0 and the diagonal entries to 1. Iff
is a 1form, the vector entries at boundary nodes are set to the boundary condition values. f – a
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
.
indexed
(o, *operands)[source]¶ Reconstruct the
ufl.indexed.Indexed
only if the coefficient is defined on aFunctionSpace
with rank 1.


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_untouchedas a default rule.

condition
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouchedas 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_untouchedas a default rule.

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_untouchedas a default rule.


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
Function
s pointwise and assigns into a newFunction
.

firedrake.assemble_expressions.
evaluate_expression
(expr, subset=None)[source]¶ Evaluates UFL expressions on
Function
s.

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
onV
, aConstant
, anExpression
, an iterable of literal constants (converted to anExpression
), or a literal constant which can be pointwise evaluated at the nodes ofV
.Expression
s are projected ontoV
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
andbottom
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 noslip conditions on HDiv spaces.

apply
(r, u=None)[source]¶ Apply this boundary condition to
r
.Parameters:  r – a
Function
orMatrix
to which the boundary condition should be applied.  u – an optional current state. If
u
is supplied thenr
is taken to be a residual and the boundary condition nodes are set to the valueubc
. Supplyingu
has no effect ifr
is aMatrix
rather than aFunction
. Ifu
is absent, then the boundary condition nodes ofr
are set to the boundary condition values.
If
r
is aMatrix
, it will be assembled with a 1 on diagonals where the boundary condition applies and 0 in the corresponding rows and columns. r – a

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.

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.
 V – the

firedrake.bcs.
homogenize
(bc)[source]¶ Create a homogeneous version of a
DirichletBC
object and return it. Ifbc
is an iterable containing one or moreDirichletBC
objects, then return a list of the homogeneous versions of thoseDirichletBC
s.Parameters: bc – a DirichletBC
, or iterable object comprisingDirichletBC
(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
Function
s to disk in parallel (using HDF5) and reloading them on the same number of processes and aMesh()
constructed identically.Parameters:  basename – the base name of the checkpoint file.
 single_file – Should the checkpoint object use only a single
ondisk file (irrespective of the number of stored
timesteps)? See
new_file()
for more details.  mode – the access mode (one of
FILE_READ
,FILE_CREATE
, orFILE_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 loadingFunction
data, and anFile
opened on the same file handle. DO NOT callFile.close()
on the latter, this will cause breakages.
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 timestepaware and reads from the appropriate place if
set_timestep()
has been called.

new_file
(name=None)[source]¶ Open a new ondisk 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 thebasename
used when creating theDumbCheckpoint
object. Ifsingle_file
isTrue
, then we write toBASENAME.h5
otherwise, each timenew_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 timestepaware 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
Function
s to disk in parallel (using HDF5) and reloading them on the same number of processes and aMesh()
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).

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.constant module¶

class
firedrake.constant.
Constant
(value, domain=None)[source]¶ Bases:
ufl.coefficient.Coefficient
A “constant” coefficient
A
Constant
takes one value over the wholeMesh()
. The advantage of using aConstant
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 vectorvalued constant), or an iterable of iterables (or numpy array with 2dimensional shape) for a tensorvalued constant.
 domain – an optional
Mesh()
on which the constant is defined.
Note
If you intend to use this
Constant
in aForm
on its own you need to pass aMesh()
as the domain argument.
assign
(value)[source]¶ Set the value of this constant.
Parameters: value – A value of the appropriate shape

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.
firedrake.dmhooks module¶
Firedrake uses PETSc for its linear and nonlinear solvers. The interaction is carried out through DM objects. These carry around any userdefined application context and can be used to inform the solvers how to create field decompositions (for fieldsplit preconditioning) as well as creating subDMs (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 multilevel 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 subDM describing the specified fields.
Parameters:  DM – The DM.
 fields – The fields in the new subDM.
Note
This should, but currently does not, transfer appropriately split application contexts onto the subDMs.

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 ith local facet is represented as:
cell_facets[c, i]
If this result is
0
, then the local facetci
is an exterior facet, otherwise if the result is1
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 nonincident 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 (localtoglobal) exchange be performed.
Forward exchanges are implemented using
PetscSFBcastBegin
, reverse exchanges withPetscSFReduceBegin
.

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 (localtoglobal) exchange be performed.
Forward exchanges are implemented using
PetscSFBcastEnd
, reverse exchanges withPetscSFReduceEnd
.

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 depthfirst 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) nonowned 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¶
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 settingFunction
values to userdetermined values.To use an Expression, we can either
interpolate()
it onto aFunction
, orproject()
it into aFunctionSpace
. Note that not allFunctionSpace
s support interpolation, but all do support projection.Expression
s 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 variablex
, withx[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 variablepi
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 userspecified eval` method. For example, the following expression sets the outputFunction
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 theFunction
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 vectorvaluedFunction
then it is necessary to explicitly override thevalue_shape()
method of thatExpression
. 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 –
userdefined 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 onedimensional mesh:
x0x1x2x
Extruded to form the following twodimensional mesh:
xx
 
 
2  
 
xxxx
  
  
1   
  
xxx
 
 
0  
 
xx
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 minmax on the cell bounds, iteration bounds use maxmin.
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:
xx
 o 
o o o
o o o
 o 
ooo
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:
810
 
 
 
 
2579
  
  
  
  
146
 
 
 
 
03
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:
810
 
 
 
 
2579
  
  
  
  
146
 
 
 
 
03
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 lowerdimensional entities, because if a codim 2 or greater entity is exposed in a column, then the codim 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 pointp
(in plex ordering), whilenpoints[p, 2:4]
gives the start and stop layers for iteration over mesh pointp
(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.
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 equispaced height for each layer.
 extrusion_type – the type of extrusion to use. Predefined options are either “uniform” (creating equispaced layers by extruding in the (n+1)dth direction), “radial” (creating equispaced layers by extruding in the outward direction from the origin) or “radial_hedgehog” (creating equispaced layers by extruding coordinates in the outward cellnormal 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.
 extruded_topology – an
firedrake.formmanipulation module¶

class
firedrake.formmanipulation.
ExtractSubBlock
[source]¶ Bases:
ufl.corealg.multifunction.MultiFunction
Extract a subblock from a form.

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.

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 2tuple (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 subforms 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 underlyingMesh()
. 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 aFunctionSpace
object which provides the basis functions \(\phi_i(x)\).Note that the coefficients are always scalars: if the
Function
is vectorvalued then this is specified in theFunctionSpace
.Parameters: function_space – the FunctionSpace
, orMixedFunctionSpace
on which to build thisFunction
. Alternatively, anotherFunction
may be passed here and its function space will be used to build thisFunction
. In thiscase, the function values are copied. :param val: NumPy arraylike (or
pyop2.Dat
) providing initial values (optional).If val is an existingFunction
, then the data will be shared.Parameters: 
assign
(expr, subset=None)[source]¶ Set the
Function
value to the pointwise value of expr. expr may only containFunction
s on the sameFunctionSpace
as theFunction
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 thisFunction
’snode_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 newFunction
will allocate new space and copy values. IfFalse
, the default, then the newFunction
will share the dof values.

function_space
()[source]¶ Return the
FunctionSpace
, orMixedFunctionSpace
on which thisFunction
is defined.

interpolate
(expression, subset=None)[source]¶ Interpolate an expression onto this
Function
.Parameters: expression – Expression
or a UFL expression to interpolateReturns: this Function
object

project
(b, *args, **kwargs)[source]¶ Project
b
ontoself
.b
must be aFunction
or anExpression
.This is equivalent to
project(b, self)
. Any of the additional arguments toproject()
may also be passed, and they will have their usual effect.

split
()[source]¶ Extract any sub
Function
s defined on the component spaces of this thisFunction
’sFunctionSpace
.

sub
(i)[source]¶ Extract the ith sub
Function
of thisFunction
.Parameters: i – the index to extract See also
split()
.If the
Function
is defined on aVectorFunctionSpace
, this returns a proxy object indexing the ith component of the space, suitable for use in boundary condition application.

topological
¶ The underlying coordinateless function.

firedrake.functionspace module¶
This module implements the uservisible API for constructing
FunctionSpace
and MixedFunctionSpace
objects. The
API is functional, rather than objectbased, to allow for simple
backwardscompatibility, 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.
 spaces – An iterable of constituent spaces, or a

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 existingufl.FiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned.

firedrake.functionspace.
VectorFunctionSpace
(mesh, family, degree=None, dim=None, name=None, vfamily=None, vdegree=None)[source]¶ Create a rank1
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 existingufl.FiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned. In this case, the provided element must have an emptyufl.FiniteElementBase.value_shape()
.Note
The element that you provide need be a scalar element (with empty
value_shape
), however, it should not be an existingVectorElement
. If you already have an existingVectorElement
, you should pass it toFunctionSpace()
directly instead.

firedrake.functionspace.
TensorFunctionSpace
(mesh, family, degree=None, shape=None, symmetry=None, name=None, vfamily=None, vdegree=None)[source]¶ Create a rank2
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 tensorvalued 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 existingFiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned. In this case, the provided element must have an emptyvalue_shape()
.Note
The element that you provide must be a scalar element (with empty
value_shape
). If you already have an existingTensorElement
, you should pass it toFunctionSpace()
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
meshspecific. 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.
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 aMixedElement
, for which one should use theMixedFunctionSpace
constructor.To determine whether the space is scalar, vector or tensorvalued, one should inspect the
rank
of the resulting object. Note that function spaces created on intrinsically vectorvalued finite elements (such as the RaviartThomas space) haverank
0.Warning
Users should not build a
FunctionSpace
directly, instead they should use the utilityFunctionSpace()
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_map
(bcs=None)[source]¶ Return the
pyop2.Map
from interior facets to function space nodes. If present, bcs must be a tuple ofDirichletBC
s. 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
andnode_count
.

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 ofDirichletBC
s. 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
, orNone
.

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 ofDirichletBC
s. 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 thedof_dset
of thisFunction
.

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
hasrank
0, this is equal to thedof_count
, otherwise thedof_count
isdim
times thenode_count
.

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 scalarvalued (or intrinsically vectorvalued) have rank zero. Spaces built onVectorElement
orTensorElement
instances have rank equivalent to the number of components of theirvalue_shape()
.

topological
¶ Function space on a mesh topology.

value_size
= None¶ The total number of degrees of freedom at each function space node.
 mesh – The

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 byMixedFunctionSpace()
.
cell_node_map
(bcs=None)[source]¶ A
pyop2.MixedMap
from theMesh.cell_set
of the underlying mesh to thenode_set
of thisMixedFunctionSpace
. This is composed of theFunctionSpace.cell_node_map
s of the underlyingFunctionSpace
s of which thisMixedFunctionSpace
is composed.

component
= None¶

dim
()[source]¶ The global number of degrees of freedom for this function space.
See also
dof_count
andnode_count
.

dof_count
[source]¶ Return a tuple of
FunctionSpace.dof_count
s of theFunctionSpace
s of which thisMixedFunctionSpace
is composed.

dof_dset
[source]¶ A
pyop2.MixedDataSet
containing the degrees of freedom of thisMixedFunctionSpace
. This is composed of theFunctionSpace.dof_dset
s of the underlyingFunctionSpace
s of which thisMixedFunctionSpace
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 ofDirichletBC
s. 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 ofDirichletBC
s. 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 thedof_dset
of thisMixedFunctionSpace
.

node_count
[source]¶ Return a tuple of
FunctionSpace.node_count
s of theFunctionSpace
s of which thisMixedFunctionSpace
is composed.

node_set
[source]¶ A
pyop2.MixedSet
containing the nodes of thisMixedFunctionSpace
. This is composed of theFunctionSpace.node_set
s of the underlyingFunctionSpace
s thisMixedFunctionSpace
is composed of one or (for VectorFunctionSpaces) more degrees of freedom are stored at each node.

num_sub_spaces
()[source]¶ Return the number of
FunctionSpace
s of which thisMixedFunctionSpace
is composed.

parent
= None¶

rank
= 1¶

split
()[source]¶ The list of
FunctionSpace
s of which thisMixedFunctionSpace
is composed.

sub
(i)[source]¶ Return the i`th :class:`FunctionSpace in this
MixedFunctionSpace
.

topological
¶ Function space on a mesh topology.

value_size
[source]¶ Return the sum of the
FunctionSpace.value_size
s of theFunctionSpace
s thisMixedFunctionSpace
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.

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 aFunction
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.

get_work_function
(zero=True)[source]¶ Get a temporary work
Function
on thisFunctionSpace
.Parameters: zero – Should the Function
be guaranteed zero? Ifzero
isFalse
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 shortlived 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.

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
.
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:  expr – an
Expression
.  V – the
FunctionSpace
to interpolate into (or else an existingFunction
).  subset – An optional
pyop2.Subset
to apply the interpolation over.
Returns a new
Function
in the spaceV
(orV
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. expr – an

class
firedrake.interpolation.
Interpolator
(expr, V, subset=None)[source]¶ Bases:
object
A reusable interpolation object.
Parameters:  expr – The expression to interpolate.
 V – The
FunctionSpace
orFunction
to interpolate into.
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 theInterpolator
is also collected).
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 suppliedA
is used to construct the preconditioner.  parameters – (optional) dict of solver parameters.
 nullspace – an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
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.
 A – a
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 rank0 on that communicator will
write to the handler, other ranks will use a
logging.NullHandler
. If set toNone
, all ranks will use the provided handler. This could be used, for example, if you want to log to one file per rank.
 handlers – Optional dict of handlers keyed by the name of the logger.
If not provided, a separate

firedrake.logging.
info_red
(message, *args, **kwargs)[source]¶ Write info message in red.
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: Note
This object acts to the right on an assembled
Function
and to the left on an assembled cofunction (currently represented by aFunction
).
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
pyop2.Mat
will be built from the remaining arguments, for valid values, seepyop2.Mat
.Note
This object acts to the right on an assembled
Function
and to the left on an assembled cofunction (currently represented by aFunction
).
M
¶ The
pyop2.Mat
representing the assembled formNote
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.


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 matrixfree 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 theMatrixBase
.

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.
 a – the bilinear form this
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 2tuple 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]
wherea
indicates the starting cell layer of the column andb
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. Seemake_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 outwardpointing
cell normal (this produces a P1dgxP1 coordinate field).
In this case, a radially extruded coordinate field
(generated with
extrusion_type="radial"
) is available in theradial_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 booleanvalued 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).
 u – a

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\]
 v – a ufl expression (
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
Vector
s orFunctions
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 ofvecs
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.

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 thisVectorSpaceBasis
.Parameters: b – a Function
Note
Modifies
b
in place.
 vecs – a list of

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 theQxQ
block. We can do this like sonullspace = MixedVectorSpaceBasis(W, [W[0], VectorSpaceBasis(constant=True)]) solve(a == ..., nullspace=nullspace)
 function_space – the
firedrake.optimizer module¶
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 VTKcapable 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.
 filename – The name of the output file (must end in
firedrake.parameters module¶
The parameters dictionary contains global parameter settings.

firedrake.parameters.
parameters
= {'form_compiler': {'quadrature_rule': 'auto', 'quadrature_degree': 'auto', 'mode': 'spectral', 'unroll_indexsum': 3, 'precision': 15}, 'coffee': {'optlevel': 'Ov'}, 'default_sub_matrix_type': 'baij', 'default_matrix_type': 'nest', 'reorder_meshes': True, 'pyop2_options': {'debug': False, 'simd_isa': 'sse', 'node_local_compilation': True, 'block_sparsity': True, 'cache_dir': '/data/dham/src/firedrake/.cache/pyop2', 'compiler': 'gnu', 'log_level': 'WARNING', 'print_summary': False, 'opt_level': 'Ov', 'cflags': '', 'matnest': True, 'dump_gencode': False, 'blas': '', 'lazy_evaluation': True, 'check_src_hashes': True, 'dump_gencode_path': '/tmp/pyop2gencode', 'type_check': True, 'ldflags': '', 'print_cache_size': False, 'loop_fusion': False, 'lazy_max_trace_length': 100, 'no_fork_available': False}, 'type_check_safe_par_loops': False}¶ 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
Function
s. This provides a mechanism for implementing
nonfinite element operations such as slope limiters.

firedrake.parloops.
par_loop
(kernel, measure, args, **kwargs)[source]¶ A
par_loop()
is a userdefined operation which reads and writesFunction
s 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 passdirect
to designate a direct loop.  args – is a dictionary mapping variable names in the kernel to
Function
s or components of mixedFunction
s and indicates how theseFunction
s 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 aFunction
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
orConstant
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 beFunction
s in the sameFunctionSpace
.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
Function
s 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 toFunction
s over aFunctionSpace
withFunctionSpace.rank
greater than zero (spaces with a VectorElement or TensorElement). In the case of scalarFunctionSpace
s, 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.Constant
s are always of type double*, both for indirect and directpar_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
orMesh()
to plot. An iterable ofFunction
s 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 piecewise 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
.
 function_or_mesh – The
firedrake.pointeval_utils module¶
firedrake.pointquery_utils module¶
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
orFunction
into aFunctionSpace
Parameters:  v – the
Expression
,ufl.Expr
orFunction
to project  V – the
FunctionSpace
orFunction
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 aFunction
thenv
is projected intoV
andV
is returned. If V is aFunctionSpace
thenv
is projected into a newFunction
and thatFunction
is returned.The
mesh
andform_compiler_parameters
are currently ignored. v – the

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 aFunction
and belongs to the same function space asv_out
.Parameters:  v – the
ufl.Expr
orFunction
to project  v_out –
Function
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.
 v – the
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 areFunction
s. If present, bcs should be a list ofDirichletBC
s 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 NewtonKrylov 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
(orMixedVectorSpaceBasis
) spanning the null space of the operator to the solve call using thenullspace
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 fromparameters
will be considered. If no trailing underscore is provided, one is appended. Hencefoo_
andfoo
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 callsetFromOptions
on. Note that this will actually only callsetFromOptions
the first time (so really this parameters object is a onceperPETScobject 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
orKSPSolve
call. Do that using theinserted_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 fixedsize 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>¶


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 ith 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).
 form – the

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 Firedrakeparameters
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()
) form – the
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 of0
is used as aTestFunction()
, with a number of1
it is used as aTrialFunction()
. function_space – the

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).
 function_space – the

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).
 function_space – the

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 aMixedFunctionSpace
, 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 aMixedFunctionSpace
, 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 additionalArgument
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 fromu.split()
. UFL doesn’t notice that these are related tou
and so therefore the derivative is wrong (instead one should have writtensplit(u)
).See also
ufl.derivative()
. form – a

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.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).
 radius –

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 higherorder nonvertex 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 higherorder nonvertex 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.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
(orMixedVectorSpaceBasis
) 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.  appctx – A dictionary containing application context that is passed to the preconditioner if matrixfree.
 problem – A

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)

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
(orMixedVectorSpaceBasis
) 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.
 appctx – A dictionary containing application context that is passed to the preconditioner if matrixfree.
 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 userdefined 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
orpre_function_callback
functionality, the userdefined 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)
 problem – A
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 aVector
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.

gather
(global_indices=None)[source]¶ Gather a
Vector
to all processesParameters: global_indices – the globally numbered indices to gather (should be the same on all processes). If None, gather the entire Vector
.

local_range
()[source]¶ Return the global indices of the start and end of the local part of this vector.

set_local
(values)[source]¶ Set process local values
Parameters: values – a numpy array of values of length Vector.local_size()
