firedrake package

Subpackages

Submodules

firedrake.assemble module

firedrake.assemble.assemble(expr, *args, **kwargs)[source]

Evaluate expr.

Parameters:
  • expr – a BaseForm, Expr or a TensorBase expression.

  • tensor – Existing tensor object to place the result in.

  • bcs – Iterable of boundary conditions to apply.

Keyword Arguments:
  • diagonal – If assembling a matrix is it diagonal?

  • form_compiler_parameters – Dictionary of parameters to pass to the form compiler. Ignored if not assembling a Form. Any parameters provided here will be overridden by parameters set on the Measure in the form. For example, if a quadrature_degree of 4 is specified in this argument, but a degree of 3 is requested in the measure, the latter will be used.

  • mat_type – String indicating how a 2-form (matrix) should be assembled – either as a monolithic matrix ("aij" or "baij"), a block matrix ("nest"), or left as a ImplicitMatrix giving matrix-free actions ('matfree'). If not supplied, the default value in parameters["default_matrix_type"] is used. BAIJ differs from AIJ in that only the block sparsity rather than the dof sparsity is constructed. This can result in some memory savings, but does not work with all PETSc preconditioners. BAIJ matrices only make sense for non-mixed matrices.

  • sub_mat_type – String indicating the matrix type to use inside a nested block matrix. Only makes sense if mat_type is nest. May be one of "aij" or "baij". If not supplied, defaults to parameters["default_sub_matrix_type"].

  • appctx – Additional information to hang on the assembled matrix if an implicit matrix is requested (mat_type "matfree").

  • options_prefix – PETSc options prefix to apply to matrices.

  • zero_bc_nodes – If True, set the boundary condition nodes in the output tensor to zero rather than to the values prescribed by the boundary condition. Default is False.

  • weight – weight of the boundary condition, i.e. the scalar in front of the identity matrix corresponding to the boundary nodes. To discretise eigenvalue problems set the weight equal to 0.0.

Returns:

See below.

If expr is a Form or Slate tensor expression then this evaluates the corresponding integral(s) and returns a float for 0-forms, a Function for 1-forms and a Matrix or ImplicitMatrix for 2-forms. In the case of 2-forms the rows correspond to the test functions and the columns to the trial functions.

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

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

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

firedrake.assign module

class firedrake.assign.Assigner(assignee, expression, subset=None)[source]

Bases: object

Class performing pointwise assignment of an expression to a firedrake.function.Function.

Parameters:
assign()[source]

Perform the assignment.

symbol = '='
class firedrake.assign.CoefficientCollector[source]

Bases: MultiFunction

Multifunction used for converting an expression into a weighted sum of coefficients.

Calling map_expr_dag(CoefficientCollector(), expr) will return a tuple whose entries are of the form (coefficient, weight). Expressions that cannot be expressed as a weighted sum will raise an exception.

Note: As well as being simple weighted sums (e.g. u.assign(2*v1 + 3*v2)), one can also assign constant expressions of the appropriate shape (e.g. u.assign(1.0) or u.assign(2*v + 3)). Therefore the returned tuple must be split since coefficient may be either a firedrake.constant.Constant or firedrake.function.Function.

Initialise.

abs(o, a)[source]
coefficient(o)[source]
complex_value(o)
component_tensor(o, a, _)[source]
constant_value(o)[source]
division(o, a, b)[source]
expr(o, *operands)[source]
float_value(o)
indexed(o, a, _)[source]
int_value(o)
multi_index(o)[source]
power(o, a, b)[source]
product(o, a, b)[source]
sum(o, a, b)[source]
zero(o)
class firedrake.assign.IAddAssigner(assignee, expression, subset=None)[source]

Bases: Assigner

Assigner class for firedrake.function.Function.__iadd__.

symbol = '+='
class firedrake.assign.IDivAssigner(assignee, expression, subset=None)[source]

Bases: Assigner

Assigner class for firedrake.function.Function.__itruediv__.

symbol = '/='
class firedrake.assign.IMulAssigner(assignee, expression, subset=None)[source]

Bases: Assigner

Assigner class for firedrake.function.Function.__imul__.

symbol = '*='
class firedrake.assign.ISubAssigner(assignee, expression, subset=None)[source]

Bases: Assigner

Assigner class for firedrake.function.Function.__isub__.

symbol = '-='

firedrake.bcs module

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

Bases: BCBase, DirichletBCMixin

Implementation of a strong Dirichlet boundary condition.

Parameters:
  • V – the FunctionSpace on which the boundary condition should be applied.

  • g – the boundary condition values. This can be a Function on V, or a UFL expression that can be interpolated into V, for example, a Constant , an iterable of literal constants (converted to a UFL expression), or a literal constant which can be pointwise evaluated at the nodes of V.

  • sub_domain – the integer id(s) of the boundary region over which the boundary condition should be applied. The string “on_boundary” may be used to indicate all of the boundaries of the domain. In the case of extrusion the top and bottom strings are used to flag the bcs application on the top and bottom boundaries of the extruded mesh respectively.

  • method – the method for determining boundary nodes. DEPRECATED. The only way boundary nodes are identified is by topological association.

apply(r, u=None)[source]

Apply this boundary condition to r.

Parameters:
  • r – a Function or Matrix to which the boundary condition should be applied.

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

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

dirichlet_bcs()[source]
extract_form(form_type)[source]
property function_arg

The value of this boundary condition.

homogenize()[source]

Convert this boundary condition into a homogeneous one.

Set the value to zero.

integrals()[source]
reconstruct(field=None, V=None, g=None, sub_domain=None, use_split=False)[source]
restore()[source]

Restore the original value of this boundary condition.

This uses the value passed on instantiation of the object.

set_value(val)[source]

Set the value of this boundary condition.

Parameters:

val – The boundary condition values. See DirichletBC for valid values.

class firedrake.bcs.EquationBC(*args, bcs=None, J=None, Jp=None, V=None, is_linear=False, Jp_eq_J=False)[source]

Bases: object

Construct and store EquationBCSplit objects (for F, J, and Jp).

Parameters:
  • eq – the linear/nonlinear form equation

  • u – the Function to solve for

  • sub_domain – see DirichletBC .

  • bcs – a list of DirichletBC s and/or EquationBC s to be applied to this boundary condition equation (optional)

  • J – the Jacobian for this boundary equation (optional)

  • Jp – a form used for preconditioning the linear system, optional, if not supplied then the Jacobian itself will be used.

  • V – the FunctionSpace on which the equation boundary condition is applied (optional)

  • is_linear – this flag is used only with the reconstruct method

  • Jp_eq_J – this flag is used only with the reconstruct method

dirichlet_bcs()[source]
extract_form(form_type)[source]

Return EquationBCSplit associated with the given ‘form_type’.

Parameters:

form_type – Form to extract; ‘F’, ‘J’, or ‘Jp’.

reconstruct(V, subu, u, field)[source]
firedrake.bcs.homogenize(bc)[source]

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

Parameters:

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

firedrake.checkpointing module

class firedrake.checkpointing.CheckpointFile(filename, mode, comm=<mpi4py.MPI.Intracomm object>)[source]

Bases: object

Checkpointing meshes and Function s in an HDF5 file.

Parameters:
  • filename – the name of the HDF5 checkpoint file (.h5 or .hdf5).

  • mode – the file access mode (FILE_READ, FILE_CREATE, FILE_UPDATE) or (‘r’, ‘w’, ‘a’).

  • comm – the communicator.

This object allows for a scalable and flexible checkpointing of states. One can save and load meshes and Function s entirely in parallel without needing to gather them to or scatter them from a single process. One can also use different number of processes for saving and for loading.

close()[source]

Close the checkpoint file.

create_group(name, track_order=None)[source]

Mimic h5py.Group.create_group().

Parameters:

name – The name of the group.

Keyword Arguments:

track_order – Whether to track dataset/group/attribute creation order.

In this method we customise the h5py.h5p.PropGCID object from which we create the h5py.h5g.GroupID object to avoid the “object header message is too large” error and/or “record is not in B-tree” error when storing many (hundreds of) attributes; see this PR.

TODO: Lift this to upstream somehow.

get_attr(path, key)[source]

Get an HDF5 attribute at specified path.

Parameters:
  • path – The path at which the attribute is found.

  • key – The attribute key.

Returns:

The attribute value.

get_timestepping_history(mesh, name)[source]

Retrieve the timestepping history and indices for a specified function within a mesh.

This method is primarily used in checkpointing scenarios during timestepping simulations. It returns the indices associated with each function stored in the timestepping mode, along with any additional timestepping-related information (like time or timestep values) if available. If the specified function has not been stored in timestepping mode, it returns an empty dictionary.

Parameters:
  • mesh (firedrake.mesh.MeshGeometry) – The mesh containing the function to be queried.

  • name (str) – The name of the function whose timestepping history is to be retrieved.

Returns:

  • Returns an empty dictionary if the function name has not been stored in timestepping mode.

  • If the function name is stored in timestepping mode, returns a dictionary with the following contents:
    • ’indices’: A list of all stored indices for the function.

    • Additional key-value pairs representing timestepping information, if available.

Return type:

dict

Raises:

RuntimeError – If the function name is not found within the given mesh in the current file.

See also

CheckpointFile.save_function

Describes how timestepping information should be provided.

Notes

The function internally checks whether the specified function is mixed or exists in the file. It then retrieves the appropriate data paths and extracts the timestepping information as specified in the checkpoint file.

property h5pyfile

An h5py File object pointing at the open file handle.

has_attr(path, key)[source]

Check if an HDF5 attribute exists at specified path.

Parameters:
  • path – The path at which the attribute is sought.

  • key – The attribute key.

Returns:

True if the attribute is found.

load_function(mesh, name, idx=None)[source]

Load a Function defined on mesh.

Parameters:
  • mesh – the mesh on which the function is defined.

  • name – the name of the Function to load.

Keyword Arguments:

idx – optional timestepping index. A function can be loaded with idx only when it was saved with idx.

Returns:

the loaded Function.

load_mesh(name='firedrake_default', reorder=None, distribution_parameters=None, topology=None)[source]

Load a mesh.

Parameters:
  • name (str) – the name of the mesh to load (default to firedrake.mesh.DEFAULT_MESH_NAME).

  • reorder (bool) – whether to reorder the mesh; see firedrake.Mesh.

  • distribution_parameters (dict) – the distribution_parameters used for distributing the mesh; see firedrake.Mesh.

  • topology (firedrake.mesh.MeshTopology) – the underlying mesh topology if already known.

Returns:

the loaded mesh.

Return type:

firedrake.mesh.MeshGeometry

opts

DMPlex HDF5 version options.

require_group(name)[source]

Mimic h5py.Group.require_group().

Parameters:

name – name of the group.

This method uses create_group() instead of h5py.Group.create_group() to create an h5py.Group object from an h5py.h5g.GroupID constructed with a custom h5py.h5p.PropGCID object (often named gcpl); see h5py.Group.create_group().

TODO: Lift this to upstream somehow.

save_function(f, idx=None, name=None, timestepping_info={})[source]

Save a Function.

Parameters:

f – the Function to save.

Keyword Arguments:
  • idx – optional timestepping index. A function can either be saved in timestepping mode or in normal mode (non-timestepping); for each function of interest, this method must always be called with the idx parameter set or never be called with the idx parameter set.

  • name – optional alternative name to save the function under.

  • timestepping_info – optional (requires idx) additional information such as time, timestepping that can be stored along a function for each index.

save_mesh(mesh, distribution_name=None, permutation_name=None)[source]

Save a mesh.

Parameters:

mesh – the mesh to save.

Keyword Arguments:
  • distribution_name – the name under which distribution is saved; if None, auto-generated name will be used.

  • permutation_name – the name under which permutation is saved; if None, auto-generated name will be used.

set_attr(path, key, val)[source]

Set an HDF5 attribute at specified path.

Parameters:
  • path – The path at which the attribute is set.

  • key – The attribute key.

  • val – The attribute value.

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

Bases: object

A very dumb checkpoint object.

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

Parameters:
  • basename – the base name of the checkpoint file.

  • single_file – Should the checkpoint object use only a single on-disk file (irrespective of the number of stored timesteps)? See new_file() for more details.

  • mode – the access mode (one of FILE_READ, FILE_CREATE, or FILE_UPDATE)

  • comm – (optional) communicator the writes should be collective over.

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

Note

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

Warning

DumbCheckpoint class will soon be deprecated. Use CheckpointFile class instead.

close()[source]

Close the checkpoint file (flushing any pending writes)

get_timesteps()[source]

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

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

property h5file

An h5py File object pointing at the open file handle.

has_attribute(obj, name)[source]

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

Parameters:
  • obj – The path to the data object.

  • name – The name of the attribute.

load(function, name=None)[source]

Store a function from the checkpoint file.

Parameters:
  • function – The function to load values into.

  • name – an (optional) name used to find the function values. If not provided, uses function.name().

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

new_file(name=None)[source]

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

Parameters:

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

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

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

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

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

Read an HDF5 attribute on a specified data object.

Parameters:
  • obj – The path to the data object.

  • name – The name of the attribute.

  • default – Optional default value to return. If not provided an AttributeError is raised if the attribute does not exist.

set_timestep(t, idx=None)[source]

Set the timestep for output.

Parameters:
  • t – The timestep value.

  • idx – An optional timestep index to use, otherwise an internal index is used, incremented by 1 every time set_timestep() is called.

store(function, name=None)[source]

Store a function in the checkpoint file.

Parameters:
  • function – The function to store.

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

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

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

firedrake.checkpointing.FILE_CREATE = 1

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

firedrake.checkpointing.FILE_READ = 0

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

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.

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

Bases: object

An object to facilitate checkpointing.

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

Parameters:
  • filename – filename (including suffix .h5) of checkpoint file.

  • file_mode – the access mode, passed directly to h5py, see h5py.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).

Warning

HDF5File class will soon be deprecated. Use CheckpointFile class instead.

attributes(obj)[source]
Parameters:

obj – The path to the group.

close()[source]

Close the checkpoint file (flushing any pending writes)

flush()[source]

Flush any pending writes.

get_timestamps()[source]

Get the timestamps this HDF5File knows about.

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

Store a function from the checkpoint file.

Parameters:
  • function – The function to load values into.

  • path – the path under which the function is stored.

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

Store a function in the checkpoint file.

Parameters:
  • function – The function to store.

  • path – the path to store the function under.

  • timestamp – timestamp associated with function, or None for stationary data

firedrake.cofunction module

class firedrake.cofunction.Cofunction(*args, **kw)[source]

Bases: Cofunction, FunctionMixin

A Cofunction represents a function on a dual space. Like Functions, cofunctions are represented as sums of basis functions:

\[\begin{split}f = \\sum_i f_i \phi_i(x)\end{split}\]

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

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

Parameters:
assign(expr, subset=None)[source]

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

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

f += 2 * g

will add twice g to f.

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

cell_node_map()[source]
copy(deepcopy=True)[source]

Return a copy of this firedrake.function.CoordinatelessFunction.

Keyword Arguments:

deepcopy – If True, the default, the new firedrake.function.CoordinatelessFunction will allocate new space and copy values. If False, then the new firedrake.function.CoordinatelessFunction will share the dof values.

equals(other)[source]

Check equality.

function_space()[source]

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

interpolate(expression)[source]

Interpolate an expression onto this Cofunction.

Parameters:

expression – a UFL expression to interpolate

Returns:

this firedrake.cofunction.Cofunction object

label()[source]

Return the label (a description) of this Cofunction

name()[source]

Return the name of this Cofunction

property node_set

A pyop2.types.set.Set containing the nodes of this Cofunction. One or (for rank-1 and 2 FunctionSpaces) more degrees of freedom are stored at each node.

rename(name=None, label=None)[source]

Set the name and or label of this Cofunction

Parameters:
  • name – The new name of the Cofunction (if not None)

  • label – The new label for the Cofunction (if not None)

riesz_representation(riesz_map='L2', **solver_options)[source]

Return the Riesz representation of this Cofunction with respect to the given Riesz map.

Example: For a L2 Riesz map, the Riesz representation is obtained by solving the linear system Mx = self, where M is the L2 mass matrix, i.e. M = <u, v> with u and v trial and test functions, respectively.

Parameters:
  • riesz_map (str or collections.abc.Callable) – The Riesz map to use (l2, L2, or H1). This can also be a callable.

  • solver_options (dict) –

    Solver options to pass to the linear solver:
    • solver_parameters: optional solver parameters.

    • nullspace: an optional VectorSpaceBasis (or MixedVectorSpaceBasis)

      spanning the null space of the operator.

    • transpose_nullspace: as for the nullspace, but used to make the right hand side consistent.

    • near_nullspace: as for the nullspace, but used to add the near nullspace.

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

Returns:

Riesz representation of this Cofunction with respect to the given Riesz map.

Return type:

firedrake.function.Function

split()[source]
sub(i)[source]

Extract the ith sub Cofunction of this Cofunction.

Parameters:

i – the index to extract

See also subfunctions.

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

subfunctions[source]

Extract any sub Cofunctions defined on the component spaces of this this Cofunction’s FunctionSpace.

ufl_id()[source]
ufl_operands
vector()[source]

Return a Vector wrapping the data in this Cofunction

zero(subset=None)[source]

Set values to zero.

Parameters:

subset (pyop2.types.set.Subset) – A subset of the domain indicating the nodes to zero. If None then the whole function is zeroed.

Returns:

Returns self

Return type:

firedrake.cofunction.Cofunction

firedrake.constant module

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

Bases: ConstantValue, ConstantMixin, TSFCConstantMixin, Counted

A “constant” coefficient

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

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

  • domain – an optional Mesh() on which the constant is defined.

Note

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

assign(value)[source]

Set the value of this constant.

Parameters:

value – A value of the appropriate shape

cell_node_map(bcs=None)[source]

Return a null cell to node map.

count()[source]

Get count.

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

Return the evaluation of this Constant.

Parameters:
  • x – The coordinate to evaluate at (ignored).

  • mapping – A mapping (ignored).

  • component – The requested component of the constant (may be None or () to obtain all components).

  • index_values – ignored.

exterior_facet_node_map(bcs=None)[source]

Return a null exterior facet to node map.

function_space()[source]

Return a null function space.

interior_facet_node_map(bcs=None)[source]

Return a null interior facet to node map.

split()[source]
subfunctions[source]
property ufl_shape
values()[source]

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

firedrake.dmhooks module

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

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

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

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

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

class firedrake.dmhooks.SetupHooks[source]

Bases: object

Hooks run for setup and teardown of DMs inside solvers.

Used for transferring problem-specific data onto subproblems.

You probably don’t want to use this directly, instead see add_hooks or add_hook().

add_setup(f)[source]
add_teardown(f)[source]
setup()[source]
teardown()[source]
firedrake.dmhooks.add_hook(dm, setup=None, teardown=None, call_setup=False, call_teardown=False)[source]

Add a hook to a DM to be called for setup/teardown of subproblems.

Parameters:
  • dm – The DM to save the hooks on. This is normally the DM associated with the Firedrake solver.

  • setup – function of no arguments to call to set up subproblem data.

  • teardown – function of no arguments to call to remove subproblem data.

  • call_setup – Should the setup function be called now?

  • call_teardown – Should the teardown function be called now?

See also add_hooks which provides a context manager which manages everything.

class firedrake.dmhooks.add_hooks(dm, obj, *, save=True, appctx=None)[source]

Bases: object

Context manager for adding subproblem setup hooks to a DM.

Parameters:
  • DM – The DM to remember setup/teardown for.

  • obj – The object that we’re going to setup, typically a solver of some kind: this is where the hooks are saved.

  • save – Save this round of setup? Set this to False if all you’re going to do is setFromOptions.

  • appctx – An application context to attach to the top-level DM that describes the problem-specific data.

This is your normal entry-point for setting up problem specific data on subdms. You would likely do something like, for a Python PC.

# In setup
pc = ...
pc.setDM(dm)
with dmhooks.add_hooks(dm, self, appctx=ctx, save=False):
    pc.setFromOptions()

...

# in apply
dm = pc.getDM()
with dmhooks.add_hooks(dm, self, appctx=self.ctx):
   pc.apply(...)
firedrake.dmhooks.attach_hooks(dm, level=None, sf=None, section=None)[source]

Attach callback hooks to a DM.

Parameters:
  • DM – The DM to attach callbacks to.

  • level – Optional refinement level.

  • sf – Optional PETSc SF object describing the DM’s points.

  • section – Optional PETSc Section object describing the DM’s data layout.

firedrake.dmhooks.coarsen(dm, comm)[source]

Callback to coarsen a DM.

Parameters:
  • DM – The DM to coarsen.

  • comm – The communicator for the new DM (ignored)

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

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

Callback to decompose a DM.

Parameters:

DM – The DM.

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

firedrake.dmhooks.create_matrix(dm)[source]

Callback to create a matrix from this DM.

Parameters:

DM – The DM.

Note

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

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

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

Parameters:
  • DM – The DM.

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

class firedrake.dmhooks.ctx_coarsener(V, coarsen=None)[source]

Bases: object

firedrake.dmhooks.get_appctx(dm, default=None)
firedrake.dmhooks.get_attr(attr, dm, default=None)[source]
firedrake.dmhooks.get_ctx_coarsener(dm)[source]
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.get_parent(dm)[source]
firedrake.dmhooks.get_transfer_manager(dm)[source]
firedrake.dmhooks.pop_appctx(dm, match=None)
firedrake.dmhooks.pop_attr(attr, dm, match=None)[source]
firedrake.dmhooks.pop_ctx_coarsener(dm, match=None)
firedrake.dmhooks.pop_parent(dm, match=None)
firedrake.dmhooks.push_appctx(dm, obj)
firedrake.dmhooks.push_attr(attr, dm, obj)[source]
firedrake.dmhooks.push_ctx_coarsener(dm, obj)
firedrake.dmhooks.push_parent(dm, obj)
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_function_space(dm, V)[source]

Set the FunctionSpace on this DM.

Parameters:
  • dm – The DM

  • V – The function space.

Note

This stores the information necessary to make a function space given a DM.

firedrake.eigensolver module

Specify and solve finite element eigenproblems.

class firedrake.eigensolver.LinearEigenproblem(A, M=None, bcs=None, bc_shift=0.0)[source]

Bases: object

Generalised linear eigenvalue problem.

The problem has the form, find u, λ such that:

A(u, v) = λM(u, v)    ∀ v ∈ V
Parameters:
  • A (ufl.Form) – The bilinear form A(u, v).

  • M (ufl.Form) – The mass form M(u, v), defaults to inner(u, v) * dx.

  • bcs (DirichletBC or list of DirichletBC) – The boundary conditions.

  • bc_shift (float) – The value to shift the boundary condition eigenvalues by.

Notes

If Dirichlet boundary conditions are supplied then these will result in the eigenproblem having a nullspace spanned by the basis functions with support on the boundary. To facilitate solution, this is shifted by the specified amount. It is the user’s responsibility to ensure that the shift is not close to an actual eigenvalue of the system.

dirichlet_bcs()[source]

Return an iterator over the Dirichlet boundary conditions.

dm[source]

Return the dm associated with the output space.

class firedrake.eigensolver.LinearEigensolver(problem, n_evals, *, options_prefix=None, solver_parameters=None, ncv=None, mpd=None)[source]

Bases: OptionsManager

Solve a LinearEigenproblem.

Parameters:
  • problem (LinearEigenproblem) – The eigenproblem to solve.

  • n_evals (int) – The number of eigenvalues to compute.

  • options_prefix (str) – The options prefix to use for the eigensolver.

  • solver_parameters (dict) – PETSc options for the eigenvalue problem.

  • ncv (int) – Maximum dimension of the subspace to be used by the solver. See SLEPc.EPS.setDimensions.

  • mpd (int) – Maximum dimension allowed for the projected problem. See SLEPc.EPS.setDimensions.

Notes

Users will typically wish to set solver parameters specifying the symmetry of the eigenproblem and which eigenvalues to search for first.

The former is set using the options available for EPSSetProblemType.

For example if the bilinear form is symmetric (Hermitian in complex mode), one would add this entry to solver_options:

"eps_gen_hermitian": None

As always when specifying PETSc options, None indicates that the option in question is a flag and hence doesn’t take an argument.

The eigenvalues to search for first are specified using the options for EPSSetWhichEigenPairs.

For example, to look for the eigenvalues with largest real part, one would add this entry to solver_options:

"eps_largest_real": None
DEFAULT_EPS_PARAMETERS = {'eps_target': 0.0, 'eps_tol': 1e-10, 'eps_type': 'krylovschur'}
check_es_convergence()[source]

Check the convergence of the eigenvalue problem.

eigenfunction(i)[source]

Return the i-th eigenfunction of the solved problem.

Returns:

The real and imaginary parts of the eigenfunction.

Return type:

(Function, Function)

eigenvalue(i)[source]

Return the i-th eigenvalue of the solved problem.

solve()[source]

Solve the eigenproblem.

Returns:

The number of Eigenvalues found.

Return type:

int

firedrake.embedding module

Module for utility functions for scalable HDF5 I/O.

firedrake.embedding.get_embedding_dg_element(element)[source]
firedrake.embedding.get_embedding_element_for_checkpointing(element)[source]

Convert the given UFL element to an element that CheckpointFile can handle.

firedrake.embedding.get_embedding_method_for_checkpointing(element)[source]

Return the method used to embed element in dg space.

firedrake.ensemble module

class firedrake.ensemble.Ensemble(comm, M, **kwargs)[source]

Bases: object

Create a set of space and ensemble subcommunicators.

Parameters:
  • comm – The communicator to split.

  • M – the size of the communicators used for spatial parallelism.

Keyword Arguments:

ensemble_name – string used as communicator name prefix, for debugging.

Raises:

ValueError – if M does not divide comm.size exactly.

allreduce(f, f_reduced, op=<mpi4py.MPI.Op object>)[source]

Allreduce a function f into f_reduced over ensemble_comm .

Parameters:
  • f – The a Function to allreduce.

  • f_reduced – the result of the reduction.

  • op – MPI reduction operator. Defaults to MPI.SUM.

Raises:

ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or if the functions are in different spaces

bcast(f, root=0)[source]

Broadcast a function f over ensemble_comm from rank root

Parameters:
  • f – The Function to broadcast.

  • root – rank to broadcast from. Defaults to 0.

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

iallreduce(f, f_reduced, op=<mpi4py.MPI.Op object>)[source]

Allreduce (non-blocking) a function f into f_reduced over ensemble_comm .

Parameters:
  • f – The a Function to allreduce.

  • f_reduced – the result of the reduction.

  • op – MPI reduction operator. Defaults to MPI.SUM.

Returns:

list of MPI.Request objects (one for each of f.subfunctions).

Raises:

ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or if the functions are in different spaces

ibcast(f, root=0)[source]

Broadcast (non-blocking) a function f over ensemble_comm from rank root

Parameters:
  • f – The Function to broadcast.

  • root – rank to broadcast from. Defaults to 0.

Returns:

list of MPI.Request objects (one for each of f.subfunctions).

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

irecv(f, source=-2, tag=-1)[source]

Receive (non-blocking) a function f over ensemble_comm from another ensemble rank.

Parameters:
  • f – The a Function to receive into

  • source – the rank to receive from. Defaults to MPI.ANY_SOURCE.

  • tag – the tag of the message. Defaults to MPI.ANY_TAG.

Returns:

list of MPI.Request objects (one for each of f.subfunctions).

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

ireduce(f, f_reduced, op=<mpi4py.MPI.Op object>, root=0)[source]

Reduce (non-blocking) a function f into f_reduced over ensemble_comm to rank root

Parameters:
  • f – The a Function to reduce.

  • f_reduced – the result of the reduction on rank root.

  • op – MPI reduction operator. Defaults to MPI.SUM.

  • root – rank to reduce to. Defaults to 0.

Returns:

list of MPI.Request objects (one for each of f.subfunctions).

Raises:

ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or is the functions are in different spaces

isend(f, dest, tag=0)[source]

Send (non-blocking) a function f over ensemble_comm to another ensemble rank.

Parameters:
  • f – The a Function to send

  • dest – the rank to send to

  • tag – the tag of the message. Defaults to 0.

Returns:

list of MPI.Request objects (one for each of f.subfunctions).

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

isendrecv(fsend, dest, sendtag=0, frecv=None, source=-2, recvtag=-1)[source]

Send a function fsend and receive a function frecv over ensemble_comm to another ensemble rank.

Parameters:
  • fsend – The a Function to send.

  • dest – the rank to send to.

  • sendtag – the tag of the send message. Defaults to 0.

  • frecv – The a Function to receive into.

  • source – the rank to receive from. Defaults to MPI.ANY_SOURCE.

  • recvtag – the tag of the received message. Defaults to MPI.ANY_TAG.

Returns:

list of MPI.Request objects (one for each of fsend.subfunctions and frecv.subfunctions).

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

recv(f, source=-2, tag=-1, statuses=None)[source]

Receive (blocking) a function f over ensemble_comm from another ensemble rank.

Parameters:
  • f – The a Function to receive into

  • source – the rank to receive from. Defaults to MPI.ANY_SOURCE.

  • tag – the tag of the message. Defaults to MPI.ANY_TAG.

  • statuses – MPI.Status objects (one for each of f.subfunctions or None).

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

reduce(f, f_reduced, op=<mpi4py.MPI.Op object>, root=0)[source]

Reduce a function f into f_reduced over ensemble_comm to rank root

Parameters:
  • f – The a Function to reduce.

  • f_reduced – the result of the reduction on rank root.

  • op – MPI reduction operator. Defaults to MPI.SUM.

  • root – rank to reduce to. Defaults to 0.

Raises:

ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or is the functions are in different spaces

send(f, dest, tag=0)[source]

Send (blocking) a function f over ensemble_comm to another ensemble rank.

Parameters:
  • f – The a Function to send

  • dest – the rank to send to

  • tag – the tag of the message. Defaults to 0

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

sendrecv(fsend, dest, sendtag=0, frecv=None, source=-2, recvtag=-1, status=None)[source]

Send (blocking) a function fsend and receive a function frecv over ensemble_comm to another ensemble rank.

Parameters:
  • fsend – The a Function to send.

  • dest – the rank to send to.

  • sendtag – the tag of the send message. Defaults to 0.

  • frecv – The a Function to receive into.

  • source – the rank to receive from. Defaults to MPI.ANY_SOURCE.

  • recvtag – the tag of the received message. Defaults to MPI.ANY_TAG.

  • status – MPI.Status object or None.

Raises:

ValueError – if function communicator mismatches the ensemble spatial communicator.

firedrake.exceptions module

exception firedrake.exceptions.ConvergenceError[source]

Bases: Exception

Error raised when a solver fails to converge

firedrake.extrusion_utils module

firedrake.extrusion_utils.calculate_dof_offset(finat_element)[source]

Return the offset between the neighbouring cells of a column for each DoF.

Parameters:

finat_element – A FInAT element.

Returns:

A numpy array containing the offset for each DoF.

firedrake.extrusion_utils.calculate_dof_offset_quotient(finat_element)[source]

Return the offset quotient for each DoF within the base cell.

Parameters:

finat_element – A FInAT element.

Returns:

A numpy array containing the offset quotient for each DoF.

offset_quotient q of each DoF (in a local cell) is defined as i // o, where i is the local DoF ID of the DoF on the entity and o is the offset of that DoF computed in calculate_dof_offset().

Let DOF(e, l, i) represent a DoF on (base-)entity e on layer l that has local ID i and suppose this DoF has offset o and offset_quotient q. In periodic extrusion it is convenient to identify DOF(e, l, i) as DOF(e, l + q, i % o); this transformation allows one to always work with the “unit cell” in which i < o always holds.

In FEA offset_quotient is 0 or 1.

Example:

       local ID   offset     offset_quotient

       2--2--2    2--2--2    1--1--1
       |     |    |     |    |     |
CG2    1  1  1    2  2  2    0  0  0
       |     |    |     |    |     |
       0--0--0    2--2--2    0--0--0

       +-----+    +-----+    +-----+
       | 1 3 |    | 4 4 |    | 0 0 |
DG1    |     |    |     |    |     |
       | 0 2 |    | 4 4 |    | 0 0 |
       +-----+    +-----+    +-----+
firedrake.extrusion_utils.entity_closures(cell)[source]

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

Parameters:

cell – a FIAT cell.

firedrake.extrusion_utils.entity_indices(cell)[source]

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

This provides an iteration ordering for entities on extruded meshes.

Parameters:

cell – a FIAT cell.

firedrake.extrusion_utils.entity_reordering(cell)[source]

Return an array reordering extruded cell entities.

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

Parameters:

cell – a FIAT tensor product cell.

firedrake.extrusion_utils.flat_entity_dofs(entity_dofs)[source]
firedrake.extrusion_utils.flat_entity_permutations(entity_permutations)[source]
firedrake.extrusion_utils.is_real_tensor_product_element(element)[source]

Is the provided FInAT element a tensor product involving the real space?

Parameters:

element – A scalar FInAT element.

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 – the height for each layer. Either a scalar, where layers will be equi-spaced at the specified height, or a 1D array of variable layer heights to use through the extrusion.

  • extrusion_type – the type of extrusion to use. Predefined options are either “uniform” (creating equi-spaced layers by extruding in the (n+1)dth direction), “radial” (creating equi-spaced layers by extruding in the outward direction from the origin) or “radial_hedgehog” (creating equi-spaced layers by extruding coordinates in the outward cell-normal direction, needs a P1dgxP1 coordinate field).

  • kernel – an optional kernel to carry out coordinate extrusion.

The kernel signature (if provided) is:

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

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

firedrake.formmanipulation module

class firedrake.formmanipulation.ExtractSubBlock[source]

Bases: MultiFunction

Extract a sub-block from a form.

Initialise.

class IndexInliner[source]

Bases: MultiFunction

Inline fixed index of list tensors

Initialise.

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.

indexed(o, child, multiindex)[source]
multi_index(o)[source]
argument(o)[source]
coefficient_derivative(o, expr, coefficients, arguments, cds)[source]
expr(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched

as a default rule.

expr_list(o, *operands)[source]
index_inliner = <firedrake.formmanipulation.ExtractSubBlock.IndexInliner object>
multi_index(o)[source]
split(form, argument_indices)[source]

Split a form.

Parameters:
  • form – the form to split.

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

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

class firedrake.formmanipulation.SplitForm(indices, form)

Bases: tuple

Create new instance of SplitForm(indices, form)

form

Alias for field number 1

indices

Alias for field number 0

firedrake.formmanipulation.split_form(form, diagonal=False)[source]

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

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

For example, consider the following code:

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

Then splitting the form returns a tuple of two forms.

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

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

firedrake.function module

class firedrake.function.CoordinatelessFunction(*args, **kw)[source]

Bases: Coefficient

A function on a mesh topology.

Parameters:
cell_node_map()[source]

Return the pyop2.types.map.Map from cels to function space nodes.

property cell_set

The pyop2.types.set.Set of cells for the mesh on which this Function is defined.

copy(deepcopy=False)[source]

Return a copy of this CoordinatelessFunction.

Keyword Arguments:

deepcopy – If True, the new CoordinatelessFunction will allocate new space and copy values. If False, the default, then the new CoordinatelessFunction will share the dof values.

property dof_dset

A pyop2.types.dataset.DataSet containing the degrees of freedom of this Function.

exterior_facet_node_map()[source]

Return the pyop2.types.map.Map from exterior facets to function space nodes.

function_space()[source]

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

interior_facet_node_map()[source]

Return the pyop2.types.map.Map from interior facets to function space nodes.

label()[source]

Return the label (a description) of this Function

name()[source]

Return the name of this Function

property node_set

A pyop2.types.set.Set containing the nodes of this Function. One or (for rank-1 and 2 FunctionSpaces) more degrees of freedom are stored at each node.

rename(name=None, label=None)[source]

Set the name and or label of this Function

Parameters:
  • name – The new name of the Function (if not None)

  • label – The new label for the Function (if not None)

split()[source]
sub(i)[source]

Extract the ith sub Function of this Function.

Parameters:

i – the index to extract

See also subfunctions.

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

subfunctions[source]

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

topological[source]

The underlying coordinateless function.

ufl_id()[source]
vector()[source]

Return a Vector wrapping the data in this Function

class firedrake.function.Function(*args, **kwargs)[source]

Bases: Coefficient, FunctionMixin

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

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

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

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

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

  • val – NumPy array-like (or pyop2.types.dat.Dat) providing initial values (optional). If val is an existing Function, then the data will be shared.

  • name – user-defined name for this Function (optional).

  • dtype – optional data type for this Function (defaults to ScalarType).

  • count – The ufl.Coefficient count which creates the symbolic identity of this Function.

assign(expr, subset=None)[source]

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

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

f += 2 * g

will add twice g to f.

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

Note

Assignment can only be performed for simple weighted sum expressions and constant values. Things like u.assign(2*v + Constant(3.0)). For more complicated expressions (e.g. involving the product of functions) Function.interpolate() should be used.

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

Evaluate function at points.

Parameters:
  • arg – The point to locate.

  • args – Additional points.

Keyword Arguments:
  • dont_raise – Do not raise an error if a point is not found.

  • tolerance – Tolerence to use when checking if a point is in a cell. Default is the tolerance provided when creating the Mesh() the function is defined on. Changing this from default will cause the spatial index to be rebuilt which can take some time.

copy(deepcopy=False)[source]

Return a copy of this Function.

Keyword Arguments:

deepcopy – If True, the new Function will allocate new space and copy values. If False, the default, then the new Function will share the dof values.

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

Get self from mapping and return the component asked for.

function_space()[source]

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

interpolate(expression, subset=None, allow_missing_dofs=False, default_missing_val=None, ad_block_tag=None)[source]

Interpolate an expression onto this Function.

Parameters:

expression – a UFL expression to interpolate

Keyword Arguments:
  • subset – An optional pyop2.types.set.Subset to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is a VertexOnlyMesh().

  • allow_missing_dofs – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When False this raises a ValueError should this occur. When True the corresponding values are set to zero or to the value default_missing_val if given. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh() (the behaviour of a VertexOnlyMesh() in this scenario is, at present, set when it is created).

  • default_missing_val – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then zero is used. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh().

  • ad_block_tag – An optional string for tagging the resulting assemble block on the Pyadjoint tape.

Returns:

this Function object

project(b, *args, **kwargs)[source]

Project b onto self. b must be a Function or a UFL expression.

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

riesz_representation(riesz_map='L2')[source]

Return the Riesz representation of this Function with respect to the given Riesz map.

Example: For a L2 Riesz map, the Riesz representation is obtained by taking the action of M on self, where M is the L2 mass matrix, i.e. M = <u, v> with u and v trial and test functions, respectively.

Parameters:

riesz_map (str or collections.abc.Callable) – The Riesz map to use (l2, L2, or H1). This can also be a callable.

Returns:

Riesz representation of this Function with respect to the given Riesz map.

Return type:

firedrake.cofunction.Cofunction

split()[source]
sub(i)[source]

Extract the ith sub Function of this Function.

Parameters:

i – the index to extract

See also subfunctions.

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

subfunctions[source]

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

property topological

The underlying coordinateless function.

vector()[source]

Return a Vector wrapping the data in this Function

zero(subset=None)[source]

Set all values to zero.

Parameters:

subset (pyop2.types.set.Subset) – A subset of the domain indicating the nodes to zero. If None then the whole function is zeroed.

Returns:

Returns self

Return type:

firedrake.function.Function

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

Bases: Exception

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

Attributes: domain, point

firedrake.functionspace module

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

firedrake.functionspace.FunctionSpace(mesh, family, degree=None, name=None, vfamily=None, vdegree=None, variant=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).

  • variant – The variant of the finite element.

Notes

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

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

Create a MixedFunctionSpace.

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

Create a rank-2 FunctionSpace.

Parameters:
  • mesh – The mesh to determine the cell from.

  • family – The finite element family.

  • degree – The degree of the finite element.

  • shape – An optional shape for the tensor-valued degrees of freedom at each function space node (defaults to a square tensor using the geometric dimension of the mesh).

  • symmetry – Optional symmetries in the tensor value.

  • name – An optional name for the function space.

  • vfamily – The finite element in the vertical dimension (extruded meshes only).

  • vdegree – The degree of the element in the vertical dimension (extruded meshes only).

  • variant – The variant of the finite element.

Notes

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

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

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

Create a rank-1 FunctionSpace.

Parameters:
  • mesh – The mesh to determine the cell from.

  • family – The finite element family.

  • degree – The degree of the finite element.

  • dim – An optional number of degrees of freedom per function space node (defaults to the geometric dimension of the mesh).

  • name – An optional name for the function space.

  • vfamily – The finite element in the vertical dimension (extruded meshes only).

  • vdegree – The degree of the element in the vertical dimension (extruded meshes only).

  • variant – The variant of the finite element.

Notes

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

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

firedrake.functionspacedata module

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

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

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

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

Return the FunctionSpaceData for the given element.

Parameters:
  • mesh – The mesh to build the function space data on.

  • ufl_element – A UFL element.

Raises:

ValueError – if mesh or ufl_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() or TensorFunctionSpace().

Parameters:
  • parent – The parent space (a FunctionSpace with a VectorElement or TensorElement).

  • component – The component to represent.

Returns:

A new ProxyFunctionSpace with the component set.

class firedrake.functionspaceimpl.FiredrakeDualSpace(mesh, element, component=None, cargo=None)[source]

Bases: WithGeometryBase, DualSpace

Initialise.

dual()[source]

Get the dual of the space.

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:
Keyword Arguments:

name – An optional name for this FunctionSpace, useful for later identification.

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

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

Warning

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

boundary_nodes(sub_domain)[source]

Return the boundary nodes for this FunctionSpace.

Parameters:

sub_domain – the mesh marker selecting which subset of facets to consider.

Returns:

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

See also DirichletBC for details of the arguments.

cell_node_list[source]

A numpy array mapping mesh cells to function space nodes.

cell_node_map()[source]

Return the pyop2.types.map.Map from cels to function space nodes.

collapse()[source]
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 FunctionSpace.dof_count and FunctionSpace.node_count .

dm[source]

A PETSc DM describing the data layout for this FunctionSpace.

dof_count[source]

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

dof_dset

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

exterior_facet_node_map()[source]

Return the pyop2.types.map.Map from exterior facets to function space nodes.

index = None

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

interior_facet_node_map()[source]

Return the pyop2.types.map.Map from interior facets to function space nodes.

local_to_global_map(bcs, lgmap=None)[source]

Return a map from process local dof numbering to global dof numbering.

If BCs is provided, mask out those dofs which match the BC nodes.

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

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

make_dof_dset()[source]
mesh()[source]
name

The (optional) descriptive name for this space.

node_count[source]

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

node_set

A pyop2.types.set.Set representing the function space nodes.

parent = None

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

rank

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

set_shared_data()[source]
split()[source]
sub(i)[source]

Return a view into the ith component.

subfunctions[source]

Split into a tuple of constituent spaces.

topological[source]

Function space on a mesh topology.

ufl_element()[source]

The finat.ufl.finiteelementbase.FiniteElementBase associated with this space.

ufl_function_space()[source]

The FunctionSpace associated with this space.

value_size

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

class firedrake.functionspaceimpl.FunctionSpaceCargo(topological: FunctionSpace, parent: WithGeometryBase | None)[source]

Bases: object

Helper class carrying data for a WithGeometryBase.

It is required because it permits Firedrake to have stripped forms that still know Firedrake-specific information (e.g. that they are a component of a parent function space).

parent: WithGeometryBase | None
topological: FunctionSpace
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.

Keyword Arguments:

name – An optional name for the mixed space.

Warning

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

cell_node_map()[source]

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

component = None
dim()[source]

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

See also FunctionSpace.dof_count and FunctionSpace.node_count.

dm[source]

A PETSc DM describing the data layout for fieldsplit solvers.

dof_count[source]

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

dof_dset[source]

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

exterior_facet_node_map()[source]

Return the pyop2.types.map.Map from exterior facets to function space nodes.

index = None
interior_facet_node_map()[source]

Return the pyop2.types.map.MixedMap from interior facets to function space nodes.

local_to_global_map(bcs)[source]

Return a map from process local dof numbering to global dof numbering.

If BCs is provided, mask out those dofs which match the BC nodes.

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

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

mesh()[source]
node_count[source]

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

node_set[source]

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

num_sub_spaces()[source]

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

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

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

subfunctions[source]

The list of FunctionSpaces of which this MixedFunctionSpace is composed.

property topological

Function space on a mesh topology.

ufl_element()[source]

The finat.ufl.mixedelement.MixedElement associated with this space.

ufl_function_space()[source]

The FunctionSpace associated with this space.

value_size[source]

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

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

Bases: FunctionSpace

A FunctionSpace that one can attach extra properties to.

Parameters:
  • mesh – The mesh to use.

  • element – The UFL element.

  • name – The name of the function space.

Warning

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

identifier = None

An optional identifier, for debugging purposes.

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

Create a pyop2.types.dat.Dat.

Raises:

ValueError – if no_dats is True.

no_dats = False

Can this proxy make pyop2.types.dat.Dat objects

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

Bases: 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.

exterior_facet_node_map(bcs=None)[source]

RealFunctionSpace objects have no exterior facet node map.

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

RealFunctionSpace objects have no interior facet node map.

local_to_global_map(bcs, lgmap=None)[source]

Return a map from process local dof numbering to global dof numbering.

If BCs is provided, mask out those dofs which match the BC nodes.

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

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

make_dof_dset()[source]
set_shared_data()[source]
top_nodes()[source]

RealFunctionSpace objects have no bottom nodes.

class firedrake.functionspaceimpl.WithGeometry(mesh, element, component=None, cargo=None)[source]

Bases: WithGeometryBase, FunctionSpace

Initialise.

dual()[source]

Get the dual of the space.

class firedrake.functionspaceimpl.WithGeometryBase(mesh, element, component=None, cargo=None)[source]

Bases: object

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 WithGeometryBase object explicitly except in a small number of cases.

When instantiating a WithGeometryBase, users should call WithGeometryBase.create() rather than __init__.

Parameters:
  • mesh – The mesh with geometric information to use.

  • element – The UFL element.

  • component – The component of this space in a parent vector element space, or None.

  • cargoFunctionSpaceCargo instance carrying Firedrake-specific data that is not required for code generation.

boundary_nodes(sub_domain)[source]

Return the boundary nodes for this WithGeometryBase.

Parameters:

sub_domain – the mesh marker selecting which subset of facets to consider.

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.

collapse()[source]
classmethod create(function_space, mesh)[source]

Create a WithGeometry.

Parameters:
  • function_space – The topological function space to attach geometry to.

  • mesh – The mesh with geometric information to use.

dm[source]
get_work_function(zero=True)[source]

Get a temporary work Function on this FunctionSpace.

Parameters:

zero – Should the Function be guaranteed zero? If zero is False the returned function may or may not be zeroed, and the user is responsible for appropriate zeroing.

Raises:

ValueError – if max_work_functions are already checked out.

Note

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

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

classmethod make_function_space(mesh, element, name=None)[source]

Factory method for WithGeometryBase.

property max_work_functions

The maximum number of work functions this FunctionSpace supports.

See get_work_function() for obtaining work functions.

mesh()

Return ufl domain.

property num_work_functions

The number of checked out work functions.

property parent
reconstruct(mesh=None, name=None, **kwargs)[source]

Reconstruct this WithGeometryBase .

Keyword Arguments:
  • mesh – the new Mesh() (defaults to same mesh)

  • name – the new name (defaults to None)

Returns:

the new function space of the same class as self.

Any extra kwargs are used to reconstruct the finite element. For details see finat.ufl.finiteelement.FiniteElement.reconstruct().

restore_work_function(function)[source]

Restore a work function obtained with get_work_function().

Parameters:

function – The work function to restore

Raises:

ValueError – if the provided function was not obtained with get_work_function() or it has already been restored.

Warning

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

split()[source]
sub(i)[source]
subfunctions[source]

Split into a tuple of constituent spaces.

property topological
ufl_cell()[source]

The Cell this FunctionSpace is defined on.

ufl_function_space()[source]

The FunctionSpace this object represents.

firedrake.functionspaceimpl.check_element(element, top=True)[source]

Run some checks on the provided element.

The finat.ufl.mixedelement.VectorElement and finat.ufl.mixedelement.TensorElement modifiers must be “outermost” for function space construction to work, excepting that they should not wrap a finat.ufl.mixedelement.MixedElement. Similarly, a base finat.ufl.mixedelement.MixedElement must be outermost (it can contain finat.ufl.mixedelement.MixedElement instances, provided they satisfy the other rules). This function checks that.

Parameters:
  • element – The UFL element to check.

  • top (bool) – Are we at the top element (in which case the modifier is legal).

Return type:

None if the element is legal.

Raises:

ValueError – If the element is illegal.

firedrake.halo module

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

Bases: Halo

Build a Halo for a function space.

Parameters:
  • dm – The DM 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.types.halo.Halo .

comm[source]
global_to_local_begin(dat, insert_mode)[source]

Begin an exchange from global (assembled) to local (ghosted) representation.

Parameters:
global_to_local_end(dat, insert_mode)[source]

Finish an exchange from global (assembled) to local (ghosted) representation.

Parameters:
local_to_global_begin(dat, insert_mode)[source]

Begin an exchange from local (ghosted) to global (assembled) representation.

Parameters:
local_to_global_end(dat, insert_mode)[source]

Finish an exchange from local (ghosted) to global (assembled) representation.

Parameters:
local_to_global_numbering[source]
sf[source]
firedrake.halo.reduction_op(op, invec, inoutvec, datatype)[source]

firedrake.interpolation module

class firedrake.interpolation.CrossMeshInterpolator(expr, V, **kwargs)[source]

Bases: Interpolator

Interpolate a function from one mesh and function space to another.

For arguments, see Interpolator.

exception firedrake.interpolation.DofNotDefinedError(src_mesh, dest_mesh)[source]

Bases: Exception

Raised when attempting to interpolate across function spaces where the target function space contains degrees of freedom (i.e. nodes) which cannot be defined in the source function space. This typically occurs when the target mesh covers a larger domain than the source mesh.

src_mesh

The source mesh.

Type:

Mesh()

dest_mesh

The destination mesh.

Type:

Mesh()

class firedrake.interpolation.Interpolate(expr, v, subset=None, access=Access.WRITE, allow_missing_dofs=False, default_missing_val=None)[source]

Bases: Interpolate

Symbolic representation of the interpolation operator.

Parameters:
  • expr (ufl.core.expr.Expr or ufl.BaseForm) – The UFL expression to interpolate.

  • v (firedrake.functionspaceimpl.WithGeometryBase or firedrake.ufl_expr.Coargument) – The function space to interpolate into or the coargument defined on the dual of the function space to interpolate into.

  • subset (pyop2.types.set.Subset) – An optional subset to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is a VertexOnlyMesh().

  • access (pyop2.types.access.Access) – The pyop2 access descriptor for combining updates to shared DoFs. Possible values include WRITE and INC. Only WRITE is supported at present when interpolating across meshes. See note in interpolate() if changing this from default.

  • allow_missing_dofs (bool) – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When False this raises a ValueError should this occur. When True the corresponding values are either (a) unchanged if some output is given to the interpolate() method or (b) set to zero. Can be overwritten with the default_missing_val kwarg of interpolate(). This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh() (the behaviour of a VertexOnlyMesh() in this scenario is, at present, set when it is created).

  • default_missing_val (float) – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then the values are either (a) unchanged if some output is given to the interpolate() method or (b) set to zero. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh().

function_space()[source]
ufl_operands
class firedrake.interpolation.Interpolator(expr, V, **kwargs)[source]

Bases: ABC

A reusable interpolation object.

Parameters:
Keyword Arguments:
  • subset – An optional pyop2.types.set.Subset to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is a VertexOnlyMesh().

  • freeze_expr – Set to True to prevent the expression being re-evaluated on each call. Cannot, at present, be used when interpolating across meshes unless the target mesh is a VertexOnlyMesh().

  • access – The pyop2 access descriptor for combining updates to shared DoFs. Possible values include WRITE and INC. Only WRITE is supported at present when interpolating across meshes. See note in interpolate() if changing this from default.

  • bcs – An optional list of boundary conditions to zero-out in the output function space. Interpolator rows or columns which are associated with boundary condition nodes are zeroed out when this is specified.

  • allow_missing_dofs – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When False this raises a ValueError should this occur. When True the corresponding values are either (a) unchanged if some output is given to the interpolate() method or (b) set to zero. Can be overwritten with the default_missing_val kwarg of interpolate(). This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh() (the behaviour of a VertexOnlyMesh() in this scenario is, at present, set when it is created).

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

Note

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

interpolate(*function, output=None, transpose=False, default_missing_val=None, ad_block_tag=None)[source]

Compute the interpolation by assembling the appropriate Interpolate object.

Parameters:
  • *function (firedrake.function.Function or firedrake.cofunction.Cofunction) – If the expression being interpolated contains an argument, then the function value to interpolate.

  • output (firedrake.function.Function or firedrake.cofunction.Cofunction) – A function to contain the output.

  • transpose (bool) – Set to true to apply the transpose (adjoint) of the interpolation operator.

  • default_missing_val (bool) – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then the values are either (a) unchanged if some output is specified to the interpolate() method or (b) set to zero. This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh().

  • ad_block_tag (str) – An optional string for tagging the resulting assemble block on the Pyadjoint tape.

Returns:

The resulting interpolated function.

Return type:

firedrake.function.Function or firedrake.cofunction.Cofunction

class firedrake.interpolation.SameMeshInterpolator(expr, V, **kwargs)[source]

Bases: Interpolator

An interpolator for interpolation within the same mesh or onto a validly- defined VertexOnlyMesh().

For arguments, see Interpolator.

firedrake.interpolation.interpolate(expr, V, subset=None, access=Access.WRITE, allow_missing_dofs=False, default_missing_val=None, ad_block_tag=None)[source]

Interpolate an expression onto a new function in V.

Parameters:
Keyword Arguments:
  • subset – An optional pyop2.types.set.Subset to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is a VertexOnlyMesh().

  • access – The pyop2 access descriptor for combining updates to shared DoFs. Possible values include WRITE and INC. Only WRITE is supported at present when interpolating across meshes unless the target mesh is a VertexOnlyMesh(). See note below.

  • allow_missing_dofs – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When False this raises a ValueError should this occur. When True the corresponding values are either (a) unchanged if some output is given to the interpolate() method or (b) set to zero. In either case, if default_missing_val is specified, that value is used. This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh() (the behaviour of a VertexOnlyMesh() in this scenario is, at present, set when it is created).

  • default_missing_val – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then the values are either (a) unchanged if some output is given to the interpolate() method or (b) set to zero. Ignored if interpolating within the same mesh or onto a VertexOnlyMesh().

  • ad_block_tag – An optional string for tagging the resulting assemble block on the Pyadjoint tape.

Returns:

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

Note

If you use an access descriptor other than WRITE, the behaviour of interpolation is changes if interpolating into a function space, or an existing function. If the former, then the newly allocated function will be initialised with appropriate values (e.g. for MIN access, it will be initialised with MAX_FLOAT). On the other hand, if you provide a function, then it is assumed that its values should take part in the reduction (hence using MIN will compute the MIN between the existing values and any new values).

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 an Interpolator instead.

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: OptionsManager

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

Parameters:
  • A – a MatrixBase (the operator).

  • P – an optional MatrixBase to construct any preconditioner from; if none is supplied A is used to construct the preconditioner.

Keyword Arguments:
  • parameters – (optional) dict of solver parameters.

  • nullspace – an optional VectorSpaceBasis (or MixedVectorSpaceBasis spanning the null space of the operator.

  • transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.

  • near_nullspace – as for the nullspace, but used to set the near nullpace.

  • options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the solver_parameters dict.

Note

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

DEFAULT_KSP_PARAMETERS = {'ksp_rtol': 1e-07, 'ksp_type': 'preonly', 'mat_mumps_icntl_14': 200, 'mat_type': 'aij', 'pc_factor_mat_solver_type': 'mumps', 'pc_type': 'lu'}
solve(x, b)[source]
test_space[source]
trial_space[source]

firedrake.logging module

firedrake.logging.critical(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

firedrake.logging.debug(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘DEBUG’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

firedrake.logging.error(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘ERROR’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.error(“Houston, we have a %s”, “major problem”, exc_info=1)

firedrake.logging.info(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘INFO’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

firedrake.logging.info_blue(message, *args, **kwargs)[source]

Write info message in blue.

Parameters:

message – the message to be printed.

firedrake.logging.info_green(message, *args, **kwargs)[source]

Write info message in green.

Parameters:

message – the message to be printed.

firedrake.logging.info_red(message, *args, **kwargs)[source]

Write info message in red.

Parameters:

message – the message to be printed.

firedrake.logging.log(level, msg, *args, **kwargs)[source]

Log ‘msg % args’ with the integer severity ‘level’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.log(level, “We have a %s”, “mysterious problem”, exc_info=1)

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_handlers(handlers=None, comm=<mpi4py.MPI.Intracomm object>)[source]

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

Keyword Arguments:
  • handlers – Optional dict of handlers keyed by the name of the logger. If not provided, a separate logging.StreamHandler will be created for each logger.

  • comm – The communicator the handler should be collective over. If provided, only rank-0 on that communicator will write to the handler, other ranks will use a logging.NullHandler. If set to None, all ranks will use the provided handler. This could be used, for example, if you want to log to one file per rank.

firedrake.logging.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.warning(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘WARNING’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.warning(“Houston, we have a %s”, “bit of a problem”, exc_info=1)

firedrake.matrix module

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

Bases: MatrixBase

A representation of a matrix that doesn’t require knowing the underlying form.

This class wraps the relevant information for Python PETSc matrix.

Parameters:
  • a – A tuple of the arguments the matrix represents

  • bcs – an iterable of boundary conditions to apply to this Matrix. May be None if there are no boundary conditions to apply.

  • petscmat – the already constructed petsc matrix this object represents.

Initialise.

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

Bases: MatrixBase

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

Parameters:
  • a – the bilinear form this Matrix represents.

  • bcs – an iterable of boundary conditions to apply to this Matrix. May be None if there are no boundary conditions to apply.

Note

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

Initialise.

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

Bases: MatrixBase

A representation of an assembled bilinear form.

Parameters:
  • a – the bilinear form this Matrix represents.

  • bcs – an iterable of boundary conditions to apply to this Matrix. May be None if there are no boundary conditions to apply.

  • mat_type – matrix type of assembled matrix.

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

Note

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

Initialise.

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

Bases: Matrix

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

Parameters:
  • a – the bilinear form this MatrixBase represents or a tuple of the arguments it represents

  • bcs – an iterable of boundary conditions to apply to this MatrixBase. May be None if there are no boundary conditions to apply.

  • mat_type – matrix type of assembled matrix, or ‘matfree’ for matrix-free

Initialise.

arguments()[source]

Return all Argument objects found in form.

property bcs

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

property has_bcs

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

mat_type

Matrix type.

Matrix type used in the assembly of the PETSc matrix: ‘aij’, ‘baij’, ‘dense’ or ‘nest’, or ‘matfree’ for matrix-free.

ufl_operands

firedrake.mesh module

class firedrake.mesh.AbstractMeshTopology(topology_dm, name, reorder, sfXB, perm_is, distribution_name, permutation_name, comm)[source]

Bases: object

A representation of an abstract mesh topology without a concrete PETSc DM implementation

Initialise a mesh topology.

Parameters:
  • topology_dm (PETSc.DMPlex or PETSc.DMSwarm) – PETSc.DMPlex or PETSc.DMSwarm representing the mesh topology.

  • name (str) – Name of the mesh topology.

  • reorder (bool) – Whether to reorder the mesh entities.

  • sfXB (PETSc.PetscSF) – PETSc.SF that pushes forward the global point number slab [0, NX) to input (naive) plex (only significant when the mesh topology is loaded from file and only passed from inside ~.CheckpointFile).

  • perm_is (PETSc.IS) – PETSc.IS that is used as _dm_renumbering; only makes sense if we know the exact parallel distribution of plex at the time of mesh topology construction like when we load mesh along with its distribution. If given, reorder param will be ignored.

  • distribution_name (str) – Name of the parallel distribution; if None, automatically generated.

  • permutation_name (str) – Name of the entity permutation (reordering); if None, automatically generated.

  • comm (mpi4py.MPI.Comm) – Communicator.

abstract property cell_closure

2D array of ordered cell closures

Each row contains ordered cell entities for a cell, one row per cell.

cell_dimension()[source]

Returns the cell dimension.

abstract property cell_set
cell_subset(subdomain_id, all_integer_subdomain_ids=None)[source]

Return a subset over cells with the given subdomain_id.

Parameters:
  • subdomain_id – The subdomain of the mesh to iterate over. Either an integer, an iterable of integers or the special subdomains "everywhere" or "otherwise".

  • all_integer_subdomain_ids

    Information to interpret the

    "otherwise" subdomain. "otherwise" means all entities not explicitly enumerated by the integer subdomains provided here. For example, if all_integer_subdomain_ids is empty, then "otherwise" == "everywhere". If it contains (1, 2), then "otherwise" is all entities except those marked by subdomains 1 and 2.

    returns:

    A pyop2.types.set.Subset for iteration.

abstract property cell_to_facets

Returns a pyop2.types.dat.Dat that maps from a cell index to the local facet types on each cell, including the relevant subdomain markers.

The i-th local facet on a cell with index c has data cell_facet[c][i]. The local facet is exterior if cell_facet[c][i][0] == 0, and interior if the value is 1. The value cell_facet[c][i][1] returns the subdomain marker of the facet.

property comm
create_section(nodes_per_entity, real_tensorproduct=False, block_size=1)[source]

Create a PETSc Section describing a function space.

Parameters:
  • nodes_per_entity – number of function space nodes per topological entity.

  • real_tensorproduct – If True, assume extruded space is actually Foo x Real.

  • block_size – The integer by which nodes_per_entity is uniformly multiplied to get the true data layout.

Returns:

a new PETSc Section.

abstract property entity_orientations

2D array of entity orientations

entity_orientations has the same shape as cell_closure. Each row of this array contains orientations of the entities in the closure of the associated cell. Here, for each cell in the mesh, orientation of an entity, say e, encodes how the the canonical representation of the entity defined by Cone(e) compares to that of the associated entity in the reference FInAT (FIAT) cell. (Note that cell_closure defines how each cell in the mesh is mapped to the FInAT (FIAT) reference cell and each entity of the FInAT (FIAT) reference cell has a canonical representation based on the entity ids of the lower dimensional entities.) Orientations of vertices are always 0. See FIAT.reference_element.Simplex and FIAT.reference_element.UFCQuadrilateral for example computations of orientations.

abstract property exterior_facets
extruded_periodic[source]
facet_dimension()[source]

Returns the facet dimension.

init()[source]

Finish the initialisation of the mesh.

abstract property interior_facets
layers = None

No layers on unstructured mesh

make_cell_node_list(global_numbering, entity_dofs, entity_permutations, offsets)[source]

Builds the DoF mapping.

Parameters:
  • global_numbering – Section describing the global DoF numbering

  • entity_dofs – FInAT element entity DoFs

  • entity_permutations – FInAT element entity permutations

  • offsets – layer offsets for each entity dof (may be None).

make_dofs_per_plex_entity(entity_dofs)[source]

Returns the number of DoFs per plex entity for each stratum, i.e. [#dofs / plex vertices, #dofs / plex edges, …].

Parameters:

entity_dofs – FInAT element entity DoFs

make_offset(entity_dofs, ndofs, real_tensorproduct=False)[source]

Returns None (only for extruded use).

abstract mark_entities(tf, label_value, label_name=None)[source]

Mark selected entities.

Parameters:
  • tf – The CoordinatelessFunction object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.

  • lable_value – The value used in the label.

  • label_name – The name of the label to store entity selections.

All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.

measure_set(integral_type, subdomain_id, all_integer_subdomain_ids=None)[source]

Return an iteration set appropriate for the requested integral type.

Parameters:
  • integral_type – The type of the integral (should be a valid UFL measure).

  • subdomain_id – The subdomain of the mesh to iterate over. Either an integer, an iterable of integers or the special subdomains "everywhere" or "otherwise".

  • all_integer_subdomain_ids

    Information to interpret the

    "otherwise" subdomain. "otherwise" means all entities not explicitly enumerated by the integer subdomains provided here. For example, if all_integer_subdomain_ids is empty, then "otherwise" == "everywhere". If it contains (1, 2), then "otherwise" is all entities except those marked by subdomains 1 and 2. This should be a dict mapping integral_type to the explicitly enumerated subdomain ids.

    returns:

    A pyop2.types.set.Subset for iteration.

mpi_comm()[source]

The MPI communicator this mesh is built on (an mpi4py object).

node_classes(nodes_per_entity, real_tensorproduct=False)[source]

Compute node classes given nodes per entity.

Parameters:

nodes_per_entity – number of function space nodes per topological entity.

Returns:

the number of nodes in each of core, owned, and ghost classes.

abstract num_cells()[source]
abstract num_edges()[source]
abstract num_entities(d)[source]
abstract num_faces()[source]
abstract num_facets()[source]
abstract num_vertices()[source]
sfBC

The PETSc SF that pushes the input (naive) plex to current (good) plex.

sfXB

The PETSc SF that pushes the global point number slab [0, NX) to input (naive) plex.

size(d)[source]
property topological

Alias of topology.

This is to ensure consistent naming for some multigrid codes.

property topology

The underlying mesh topology object.

topology_dm

The PETSc DM representation of the mesh topology.

ufl_cell()[source]

The UFL Cell associated with the mesh.

Note

By convention, the UFL cells which specifically represent a mesh topology have geometric dimension equal their topological dimension. This is true even for immersed manifold meshes.

ufl_mesh()[source]

The UFL Mesh associated with the mesh.

Note

By convention, the UFL cells which specifically represent a mesh topology have geometric dimension equal their topological dimension. This convention will be reflected in this UFL mesh and is true even for immersed manifold meshes.

variable_layers = False

No variable layers on unstructured mesh

firedrake.mesh.DEFAULT_MESH_NAME = 'firedrake_default'

The default name of the mesh.

class firedrake.mesh.DistributedMeshOverlapType(value)[source]

Bases: Enum

How should the mesh overlap be grown for distributed meshes?

Possible options are:

  • NONE: Don’t overlap distributed meshes, only useful for problems with

    no interior facet integrals.

  • FACET: Add ghost entities in the closure of the star of

    facets.

  • VERTEX: Add ghost entities in the closure of the star

    of vertices.

Defaults to FACET.

FACET = 2
NONE = 1
VERTEX = 3
firedrake.mesh.ExtrudedMesh(mesh, layers, layer_height=None, extrusion_type='uniform', periodic=False, kernel=None, gdim=None, name=None, tolerance=0.5)[source]

Build an extruded mesh from an input mesh

Parameters:
  • mesh – the unstructured base mesh

  • layers – number of extruded cell layers in the “vertical” direction. One may also pass an array of shape (cells, 2) to specify a variable number of layers. In this case, each entry is a pair [a, b] where a indicates the starting cell layer of the column and b the number of cell layers in that column.

  • layer_height – the layer height. A scalar value will result in evenly-spaced layers, whereas an array of values will vary the layer height through the extrusion. 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.

  • periodic – the flag for periodic extrusion; if True, only constant layer extrusion is allowed. Can be used with any “extrusion_type” to make annulus, torus, etc.

  • kernel – a pyop2.Kernel to produce coordinates for the extruded mesh. See make_extruded_coords() for more details.

  • gdim – number of spatial dimensions of the resulting mesh (this is only used if a custom kernel is provided)

  • name – optional name for the extruded mesh.

Keyword Arguments:

tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.

The various values of extrusion_type have the following meanings:

"uniform"

the extruded mesh has an extra spatial dimension compared to the base mesh. The layers exist in this dimension only.

"radial"

the extruded mesh has the same number of spatial dimensions as the base mesh; the cells are radially extruded outwards from the origin. This requires the base mesh to have topological dimension strictly smaller than geometric dimension.

"radial_hedgehog"

similar to radial, but the cells are extruded in the direction of the outward-pointing cell normal (this produces a P1dgxP1 coordinate field). In this case, a radially extruded coordinate field (generated with extrusion_type="radial") is available in the radial_coordinates attribute.

"custom"

use a custom kernel to generate the extruded coordinates

For more details see the manual section on extruded meshes.

class firedrake.mesh.ExtrudedMeshTopology(mesh, layers, periodic=False, name=None)[source]

Bases: MeshTopology

Representation of an extruded mesh topology.

Build an extruded mesh topology from an input mesh topology

Parameters:
  • mesh – the unstructured base mesh topology

  • layers – number of occurence of base layer in the “vertical” direction.

  • periodic – the flag for periodic extrusion; if True, only constant layer extrusion is allowed.

  • name – optional name of the extruded mesh topology.

cell_closure[source]

2D array of ordered cell closures

Each row contains ordered cell entities for a cell, one row per cell.

cell_dimension()[source]

Returns the cell dimension.

entity_layers(height, label=None)[source]

Return the number of layers on each entity of a given plex height.

Parameters:
  • height – The height of the entity to compute the number of layers (0 -> cells, 1 -> facets, etc…)

  • label – An optional label name used to select points of the given height (if None, then all points are used).

Returns:

a numpy array of the number of layers on the asked for entities (or a single layer number for the constant layer case).

entity_orientations[source]
facet_dimension()[source]

Returns the facet dimension.

Note

This only returns the dimension of the “side” (vertical) facets, not the “top” or “bottom” (horizontal) facets.

layer_extents

The layer extents for all mesh points.

For variable layers, the layer extent does not match those for cells. A numpy array of layer extents (in PyOP2 format \([start, stop)\)), of shape (num_mesh_points, 4) where the first two extents are used for allocation and the last two for iteration.

layers[source]

No layers on unstructured mesh

make_cell_node_list(global_numbering, entity_dofs, entity_permutations, offsets)[source]

Builds the DoF mapping.

Parameters:
  • global_numbering – Section describing the global DoF numbering

  • entity_dofs – FInAT element entity DoFs

  • entity_permutations – FInAT element entity permutations

  • offsets – layer offsets for each entity dof.

make_dofs_per_plex_entity(entity_dofs)[source]

Returns the number of DoFs per plex entity for each stratum, i.e. [#dofs / plex vertices, #dofs / plex edges, …].

each entry is a 2-tuple giving the number of dofs on, and above the given plex entity.

Parameters:

entity_dofs – FInAT element entity DoFs

mark_entities(tf, label_value, label_name=None)[source]

Mark selected entities.

Parameters:
  • tf – The CoordinatelessFunction object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.

  • lable_value – The value used in the label.

  • label_name – The name of the label to store entity selections.

All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.

node_classes(nodes_per_entity, real_tensorproduct=False)[source]

Compute node classes given nodes per entity.

Parameters:

nodes_per_entity – number of function space nodes per topological entity.

Returns:

the number of nodes in each of core, owned, and ghost classes.

topology_dm

The PETSc DM representation of the mesh topology.

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 – the mesh file name, a DMPlex object or a Netgen mesh object defining mesh topology. See below for details on supported mesh formats.

  • name – optional name of the mesh object.

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

  • distribution_parameters

    an optional dictionary of options for parallel mesh distribution. Supported keys are:

    • "partition": which may take the value None (use

      the default choice), False (do not) True (do), or a 2-tuple that specifies a partitioning of the cells (only really useful for debugging).

    • "partitioner_type": which may take "chaco",

      "ptscotch", "parmetis", or "shell".

    • "overlap_type": a 2-tuple indicating how to grow

      the mesh overlap. The first entry should be a DistributedMeshOverlapType instance, the second the number of levels of overlap.

  • distribution_name – the name of parallel distribution used when checkpointing; if not given, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if not given, the name is automatically generated.

  • comm – the communicator to use when creating the mesh. If not supplied, then the mesh will be created on COMM_WORLD. If meshfile is a DMPlex object then must be indentical to or congruent with the DMPlex communicator.

  • tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell. Defaults to 0.5. Increase this if point at mesh boundaries (either rank local or global) are reported as being outside the mesh, for example when creating a VertexOnlyMesh. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.

  • netgen_flags – The dictionary of flags to be passed to ngsPETSc.

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

  • HDF5: with extension .h5, .hdf5 (Can only load HDF5 files created by save_mesh() method.)

Note

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

class firedrake.mesh.MeshGeometry(element)[source]

Bases: Mesh, MeshGeometryMixin

A representation of mesh topology and geometry.

Initialise a mesh geometry from coordinates.

Parameters:

coordinates (CoordinatelessFunction) – The CoordinatelessFunction containing the coordinates.

cell_orientations()[source]

Return the orientation of each cell in the mesh.

Use init_cell_orientations() to initialise.

cell_sizes[source]

A Function in the \(P^1\) space containing the local mesh size.

This is computed by the \(L^2\) projection of the local mesh element size.

clear_cell_sizes()[source]

Reset the cell_sizes field on this mesh geometry.

Use this if you move the mesh.

clear_spatial_index()[source]

Reset the spatial_index on this mesh geometry.

Use this if you move the mesh (for example by reassigning to the coordinate field).

property coordinates

The Function containing the coordinates of this mesh.

init()[source]

Finish the initialisation of the mesh. Most of the time this is carried out automatically, however, in some cases (for example accessing a property of the mesh directly after constructing it) you need to call this manually.

init_cell_orientations(expr)[source]

Compute and initialise meth:cell_orientations relative to a specified orientation.

Parameters:

expr – a UFL expression evaluated to produce a reference normal direction.

input_ordering[source]

Return the input ordering of the mesh vertices as a VertexOnlyMesh() whilst preserving other information, such as the global indices and parent mesh cell information.

Notes

If redundant=True at mesh creation, all the vertices will be returned on rank 0.

Any points that were not found in the original mesh when it was created will still be present here in their originally supplied order.

locate_cell(x, tolerance=None)[source]

Locate cell containing a given point.

Parameters:

x – point coordinates

Keyword Arguments:

tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s tolerance property. Changing this from default will cause the spatial index to be rebuilt which can take some time.

Returns:

cell number (int), or None (if the point is not in the domain)

locate_cell_and_reference_coordinate(x, tolerance=None)[source]

Locate cell containing a given point and the reference coordinates of the point within the cell.

Parameters:

x – point coordinates

Keyword Arguments:

tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s tolerance property. Changing this from default will cause the spatial index to be rebuilt which can take some time.

Returns:

tuple either (cell number, reference coordinates) of type (int, numpy array), or, when point is not in the domain, (None, None).

locate_cells_ref_coords_and_dists(xs, tolerance=None)[source]

Locate cell containing a given point and the reference coordinates of the point within the cell.

Parameters:

xs – 1 or more point coordinates of shape (npoints, gdim)

Keyword Arguments:

tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s tolerance property. Changing this from default will cause the spatial index to be rebuilt which can take some time.

Returns:

tuple either (cell numbers array, reference coordinates array, ref_cell_dists_l1 array) of type (array of ints, array of floats of size (npoints, gdim), array of floats). The cell numbers array contains -1 for points not in the domain: the reference coordinates and distances are meaningless for these points.

locate_reference_coordinate(x, tolerance=None)[source]

Get reference coordinates of a given point in its cell. Which cell the point is in can be queried with the locate_cell method.

Parameters:

x – point coordinates

Keyword Arguments:

tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s tolerance property. Changing this from default will cause the spatial index to be rebuilt which can take some time.

Returns:

reference coordinates within cell (numpy array) or None (if the point is not in the domain)

mark_entities(f, label_value, label_name=None)[source]

Mark selected entities.

Parameters:
  • f – The Function object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.

  • lable_value – The value used in the label.

  • label_name – The name of the label to store entity selections.

All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.

spatial_index[source]

Spatial index to quickly find which cell contains a given point.

Notes

If this mesh has a tolerance property, which should be a float, this tolerance is added to the extrama of the spatial index so that points just outside the mesh, within tolerance, can be found.

property tolerance

The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell.

Increase this if points at mesh boundaries (either rank local or global) are reported as being outside the mesh, for example when creating a VertexOnlyMesh. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.

If this property is not set (i.e. set to None) no tolerance is added to the bounding box and points deemed at all outside the mesh, even by floating point error distances, will be deemed to be outside it.

Notes

After changing tolerance any requests for spatial_index will cause the spatial index to be rebuilt with the new tolerance which may take some time.

property topological

Alias of topology.

This is to ensure consistent naming for some multigrid codes.

property topology

The underlying mesh topology object.

class firedrake.mesh.MeshTopology(plex, name, reorder, distribution_parameters, sfXB=None, perm_is=None, distribution_name=None, permutation_name=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Bases: AbstractMeshTopology

A representation of mesh topology implemented on a PETSc DMPlex.

Initialise a mesh topology.

Parameters:
  • plex (PETSc.DMPlex) – PETSc.DMPlex representing the mesh topology.

  • name (str) – Name of the mesh topology.

  • reorder (bool) – Whether to reorder the mesh entities.

  • distribution_parameters (dict) – Options controlling mesh distribution; see Mesh for details.

  • sfXB (PETSc.PetscSF) – PETSc.SF that pushes forward the global point number slab [0, NX) to input (naive) plex (only significant when the mesh topology is loaded from file and only passed from inside ~.CheckpointFile).

  • perm_is (PETSc.IS) – PETSc.IS that is used as _dm_renumbering; only makes sense if we know the exact parallel distribution of plex at the time of mesh topology construction like when we load mesh along with its distribution. If given, reorder param will be ignored.

  • distribution_name (str) – Name of the parallel distribution; if None, automatically generated.

  • permutation_name (str) – Name of the entity permutation (reordering); if None, automatically generated.

  • comm (mpi4py.MPI.Comm) – Communicator.

cell_closure[source]

2D array of ordered cell closures

Each row contains ordered cell entities for a cell, one row per cell.

cell_set[source]
cell_to_facets[source]

Returns a pyop2.types.dat.Dat that maps from a cell index to the local facet types on each cell, including the relevant subdomain markers.

The i-th local facet on a cell with index c has data cell_facet[c][i]. The local facet is exterior if cell_facet[c][i][0] == 0, and interior if the value is 1. The value cell_facet[c][i][1] returns the subdomain marker of the facet.

entity_orientations[source]
exterior_facets[source]
interior_facets[source]
mark_entities(tf, label_value, label_name=None)[source]

Mark selected entities.

Parameters:
  • tf – The CoordinatelessFunction object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.

  • lable_value – The value used in the label.

  • label_name – The name of the label to store entity selections.

All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.

num_cells()[source]
num_edges()[source]
num_entities(d)[source]
num_faces()[source]
num_facets()[source]
num_vertices()[source]
firedrake.mesh.RelabeledMesh(mesh, indicator_functions, subdomain_ids, **kwargs)[source]

Construct a new mesh that has new subdomain ids.

Parameters:
  • mesh – base MeshGeometry object using which the new one is constructed.

  • indicator_functions – list of indicator functions that mark selected entities (cells or facets) as 1; must use “DP”/”DQ” (degree 0) functions to mark cell entities and “P” (degree 1) functions in 1D or “HDiv Trace” (degree 0) functions in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.

  • subdomain_ids – list of subdomain ids associated with the indicator functions in indicator_functions; thus, must have the same length as indicator_functions.

Keyword Arguments:

name – optional name of the output mesh object.

firedrake.mesh.SubDomainData(geometric_expr)[source]

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

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

x = mesh.coordinates
sd = SubDomainData(x[0] < 0.5)
assemble(f*dx(subdomain_data=sd))
firedrake.mesh.VertexOnlyMesh(mesh, vertexcoords, reorder=None, missing_points_behaviour='error', tolerance=None, redundant=True, name=None)[source]

Create a vertex only mesh, immersed in a given mesh, with vertices defined by a list of coordinates.

Parameters:
  • mesh – The unstructured mesh in which to immerse the vertex only mesh.

  • vertexcoords – A list of coordinate tuples which defines the vertices.

Keyword Arguments:
  • reorder – optional flag indicating whether to reorder meshes for better cache locality. If not supplied the default value in parameters["reorder_meshes"] is used.

  • missing_points_behaviour – optional string argument for what to do when vertices which are outside of the mesh are discarded. If 'warn', will print a warning. If 'error' will raise a VertexOnlyMeshMissingPointsError.

  • tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a mesh cell and still be considered to be in the cell. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh. The default is the parent mesh’s tolerance property. Changing this from default will cause the parent mesh’s spatial index to be rebuilt which can take some time.

  • redundant – If True, the mesh will be built using just the vertices which are specified on rank 0. If False, the mesh will be built using the vertices specified by each rank. Care must be taken when using redundant = False: see the note below for more information.

  • name – Optional name for the new VertexOnlyMesh. If none is specified a name will be generated from the parent mesh name.

Note

The vertex only mesh uses the same communicator as the input mesh.

Note

Extruded meshes with variable extrusion layers are not yet supported. See note below about VertexOnlyMesh as input.

Note

When running in parallel with redundant = False, vertexcoords will redistribute to the mesh partition where they are located. This means that if rank A has vertexcoords {X} that are not found in the mesh cells owned by rank A but are found in the mesh cells owned by rank B, then they will be moved to rank B.

Note

If the same coordinates are supplied more than once, they are always assumed to be a new vertex.

exception firedrake.mesh.VertexOnlyMeshMissingPointsError(n_missing_points)[source]

Bases: Exception

Exception raised when 1 or more points are not found by a VertexOnlyMesh() in its parent mesh.

n_missing_points

The number of points which were not found in the parent mesh.

Type:

int

class firedrake.mesh.VertexOnlyMeshTopology(swarm, parentmesh, name, reorder, input_ordering_swarm=None, perm_is=None, distribution_name=None, permutation_name=None)[source]

Bases: AbstractMeshTopology

Representation of a vertex-only mesh topology immersed within another mesh.

Initialise a mesh topology.

Parameters:
  • swarm (PETSc.DMSwarm) – PETSc.DMSwarm representing Particle In Cell (PIC) vertices immersed within a PETSc.DM stored in the parentmesh.

  • parentmesh (AbstractMeshTopology) – Mesh topology within which the vertex-only mesh topology is immersed.

  • name (str) – Name of the mesh topology.

  • reorder (bool) – Whether to reorder the mesh entities.

  • input_ordering_swarm (PETSc.DMSwarm) – The swarm from which the input-ordering vertex-only mesh is constructed.

  • perm_is (PETSc.IS) – PETSc.IS that is used as _dm_renumbering; only makes sense if we know the exact parallel distribution of plex at the time of mesh topology construction like when we load mesh along with its distribution. If given, reorder param will be ignored.

  • distribution_name (str) – Name of the parallel distribution; if None, automatically generated.

  • permutation_name (str) – Name of the entity permutation (reordering); if None, automatically generated.

cell_closure[source]

2D array of ordered cell closures

Each row contains ordered cell entities for a cell, one row per cell.

cell_global_index[source]

Return a list of unique cell IDs in vertex only mesh cell order.

cell_parent_base_cell_list[source]

Return a list of parent mesh base cells numbers in vertex only mesh cell order.

cell_parent_base_cell_map[source]

Return the pyop2.types.map.Map from vertex only mesh cells to parent mesh base cells.

cell_parent_cell_list[source]

Return a list of parent mesh cells numbers in vertex only mesh cell order.

cell_parent_cell_map[source]

Return the pyop2.types.map.Map from vertex only mesh cells to parent mesh cells.

cell_parent_extrusion_height_list[source]

Return a list of parent mesh extrusion heights in vertex only mesh cell order.

cell_parent_extrusion_height_map[source]

Return the pyop2.types.map.Map from vertex only mesh cells to parent mesh extrusion heights.

cell_set[source]
cell_to_facets[source]

Raises an AttributeError since cells in a VertexOnlyMeshTopology have no facets.

entity_orientations = None
exterior_facets[source]
input_ordering[source]

Return the input ordering of the mesh vertices as a VertexOnlyMeshTopology whilst preserving other information, such as the global indices and parent mesh cell information.

Notes

If redundant=True at mesh creation, all the vertices will be returned on rank 0.

Any points that were not found in the original mesh when it was created will still be present here in their originally supplied order.

input_ordering_sf[source]

Return a PETSc SF which has VertexOnlyMesh() input ordering vertices as roots and this mesh’s vertices (including any halo cells) as leaves.

input_ordering_without_halos_sf[source]

Return a PETSc SF which has VertexOnlyMesh() input ordering vertices as roots and this mesh’s non-halo vertices as leaves.

interior_facets[source]
mark_entities(tf, label_value, label_name=None)[source]

Mark selected entities.

Parameters:
  • tf – The CoordinatelessFunction object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.

  • lable_value – The value used in the label.

  • label_name – The name of the label to store entity selections.

All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.

num_cells()[source]
num_edges()[source]
num_entities(d)[source]
num_faces()[source]
num_facets()[source]
num_vertices()[source]
firedrake.mesh.unmarked = -1

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

firedrake.norms module

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

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

Parameters:
  • u – a Function or UFL expression containing an “exact” solution

  • uh – a Function containing the approximate solution

  • norm_type – the type of norm to compute, see norm() for details of supported norm types.

  • degree_rise – ignored.

  • mesh – an optional mesh on which to compute the error norm (currently ignored).

firedrake.norms.norm(v, norm_type='L2', mesh=None)[source]

Compute the norm of v.

Parameters:
  • v – a ufl expression (Expr) to compute the norm of

  • norm_type – the type of norm to compute, see below for options.

  • mesh – an optional mesh on which to compute the norm (currently ignored).

Available norm types are:

  • Lp \(||v||_{L^p} = (\int |v|^p)^{\frac{1}{p}} \mathrm{d}x\)

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

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

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

firedrake.nullspace module

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

Bases: object

A basis for a mixed vector space

Parameters:
  • function_space – the MixedFunctionSpace this vector space is a basis for.

  • bases – an iterable of bases for the null spaces of the subspaces in the mixed space.

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

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

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

W = V*Q

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

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

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

nullspace = MixedVectorSpaceBasis(W, [W[0], VectorSpaceBasis(constant=True)])
solve(a == ..., nullspace=nullspace)
class firedrake.nullspace.VectorSpaceBasis(vecs=None, constant=False, comm=None)[source]

Bases: object

Build a basis for a vector space.

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

Parameters:
  • vecs – a list of Vectors or Functions spanning the space.

  • constant – does the null space include the constant vector? If you pass constant=True you should not also include the constant vector in the list of vecs you supply.

  • comm – Communicator to create the nullspace on.

Note

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

Warning

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

check_orthogonality(orthonormal=True)[source]

Check if the basis is orthogonal.

Parameters:

orthonormal – If True check that the basis is also orthonormal.

Raises:

ValueError – If the basis is not orthogonal/orthonormal.

is_orthogonal()[source]

Is this vector space basis orthogonal?

is_orthonormal()[source]

Is this vector space basis orthonormal?

nullspace(comm=None)[source]

The PETSc NullSpace object for this VectorSpaceBasis.

Keyword Arguments:

comm – DEPRECATED pass to VectorSpaceBasis.__init__().

orthogonalize(b)[source]

Orthogonalize b with respect to this VectorSpaceBasis.

Parameters:

b – a Function

Note

Modifies b in place.

orthonormalize()[source]

Orthonormalize the basis.

Warning

This modifies the basis in place.

firedrake.optimizer module

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

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

  • Mesh coordinates

  • All available maps binding sets of mesh components

firedrake.output module

class firedrake.output.File(filename, project_output=False, comm=None, mode='w', target_degree=None, target_continuity=None, adaptive=False)[source]

Bases: object

Create an object for outputting data for visualisation.

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

Parameters:

filename – The name of the output file (must end in .pvd).

Keyword Arguments:
  • project_output – Should the output be projected to a computed output space? Default is to use interpolation.

  • comm – The MPI communicator to use.

  • mode – “w” to overwrite any existing file, “a” to append to an existing file.

  • target_degree – override the degree of the output space.

  • target_continuity – override the continuity of the output space; A UFL ufl.sobolevspace.SobolevSpace object: H1 for a continuous output and L2 for a discontinuous output.

  • adaptive – allow different meshes at different exports if True.

Note

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

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

Write functions to this File.

Parameters:

functions – list of functions to write.

Keyword Arguments:

time – optional timestep value.

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

firedrake.parameters module

The parameters dictionary contains global parameter settings.

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

Bases: dict

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

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

Parameters:

callable – the function.

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

firedrake.parameters.disable_performance_optimisations()[source]

Switches off performance optimisations in Firedrake.

This is mostly useful for debugging purposes.

This 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.parameters.parameters = {'default_matrix_type': 'aij', 'default_sub_matrix_type': 'baij', 'form_compiler': {'mode': 'spectral', 'quadrature_degree': 'auto', 'quadrature_rule': 'auto', 'scalar_type': dtype('float64'), 'scalar_type_c': 'double', 'unroll_indexsum': 3}, 'pyop2_options': {'block_sparsity': True, 'cache_dir': '/home/firedrake/firedrake/.cache/pyop2', 'cc': '', 'cflags': '', 'check_src_hashes': True, 'compute_kernel_flops': False, 'cxx': '', 'cxxflags': '', 'debug': False, 'ld': '', 'ldflags': '', 'log_level': 'WARNING', 'matnest': True, 'no_fork_available': False, 'node_local_compilation': True, 'print_cache_size': False, 'simd_width': 4, 'type_check': True}, 'reorder_meshes': True, 'slate_compiler': {'optimise': True, 'replace_mul': False}, 'type_check_safe_par_loops': False}

A nested dictionary of parameters used by Firedrake

firedrake.paraview_reordering module

firedrake.paraview_reordering.bary_to_cart(bar)[source]
firedrake.paraview_reordering.firedrake_local_to_cart(element)[source]

Gets the list of nodes for an element (provided they exist.) :arg element: a ufl element. :returns: a list of arrays of floats where each array is a node.

firedrake.paraview_reordering.invert(list1, list2)[source]

Given two maps (lists) from [0..N] to nodes, finds a permutations between them. :arg list1: a list of nodes. :arg list2: a second list of nodes. :returns: a list of integers, l, such that list1[x] = list2[l[x]]

firedrake.paraview_reordering.tet_barycentric_index(tet, index, order)[source]

Wrapper for vtkLagrangeTetra::BarycentricIndex.

firedrake.paraview_reordering.vtk_hex_local_to_cart(orders)[source]

Produces a list of nodes for VTK’s lagrange hex basis. :arg order: the three orders of the hex basis. :return a list of arrays of floats.

firedrake.paraview_reordering.vtk_interval_local_coord(i, order)[source]

See vtkLagrangeCurve::PointIndexFromIJK.

firedrake.paraview_reordering.vtk_lagrange_hex_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_interval_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_quad_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_tet_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_triangle_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_wedge_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_quad_local_to_cart(orders)[source]

Produces a list of nodes for VTK’s lagrange quad basis. :arg order: the order of the quad basis. :return a list of arrays of floats.

firedrake.paraview_reordering.vtk_tet_local_to_cart(order)[source]

Produces a list of nodes for VTK’s lagrange tet basis. :arg order: the order of the tet :return a list of arrays of floats

firedrake.paraview_reordering.vtk_triangle_index_cart(tri, index, order)[source]

Wrapper for vtkLagrangeTriangle::BarycentricIndex

firedrake.paraview_reordering.vtk_triangle_local_to_cart(order)[source]
firedrake.paraview_reordering.vtk_wedge_local_to_cart(ordersp)[source]

Produces a list of nodes for VTK’s lagrange wedge basis. :arg order: the orders of the wedge (triangle, interval) :return a list of arrays of floats

firedrake.parloops module

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

firedrake.parloops.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.parloops.par_loop(kernel, measure, args, kernel_kwargs=None, **kwargs)[source]

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

Parameters:
  • kernel – A 2-tuple of (domains, instructions) to create a loopy kernel . The domains and instructions should be specified in loopy kernel syntax. See the loopy tutorial for details.

  • measure – is a UFL Measure which determines the manner in which the iteration over the mesh is to occur. Alternatively, you can pass direct to designate a direct loop.

  • args – is a dictionary mapping variable names in the kernel to Functions or components of mixed Functions and indicates how these Functions are to be accessed.

  • kernel_kwargs – keyword arguments to be passed to the pyop2.Kernel constructor

  • kwargs – additional keyword arguments are passed to the underlying pyop2.par_loop

Keyword Arguments:

iterate

Optionally specify which region of an pyop2.types.set.ExtrudedSet to iterate over. Valid values are the following objects from pyop2:

  • ON_BOTTOM: iterate over the bottom layer of cells.

  • ON_TOP iterate over the top layer of cells.

  • ALL iterate over all cells (the default if unspecified)

  • ON_INTERIOR_FACETS iterate over all the layers except the top layer, accessing data two adjacent (in the extruded direction) cells at a time.

Example

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

A.assign(numpy.finfo(0.).min)
domain = '{[i]: 0 <= i < A.dofs}'
instructions = '''
for i
    A[i] = max(A[i], B[0])
end
'''
par_loop((domain, instructions), dx, {'A' : (A, RW), 'B': (B, READ)})

Argument definitions

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

READ

The variable will be read but not written to.

WRITE

The variable will be written to but not read. If multiple kernel invocations write to the same DoF, then the order of these writes is undefined.

RW

The variable will be both read and written to. If multiple kernel invocations access the same DoF, then the order of these accesses is undefined, but it is guaranteed that no race will occur.

INC

The variable will be added into using +=. As before, the order in which the kernel invocations increment the variable is undefined, but there is a guarantee that no races will occur.

Note

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

The measure

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

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

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

The kernel code

Indirect free variables referencing Functions are all of type double*. For spaces with rank greater than zero (Vector or TensorElement), the data are laid out XYZ… XYZ… XYZ…. With the vector/tensor component moving fastest.

In loopy syntax, these may be addressed using 2D indexing:

A[i, j]

Where i runs over nodes, and j runs over components.

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

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

firedrake.petsc module

class firedrake.petsc.OptionsManager(parameters, options_prefix)[source]

Bases: object

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

Mixin class that helps with managing setting petsc options.

Parameters:
  • parameters – The dictionary of parameters to use.

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

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

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

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

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

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

This object can also be used only to manage insertion and deletion into the PETSc options database, by using the context manager.

inserted_options()[source]

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

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

Set a default parameter value.

Parameters:
  • key – The parameter name

  • val – The parameter value.

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

set_from_options(petsc_obj)[source]

Set up petsc_obj from the options database.

Parameters:

petsc_obj – The PETSc object to call setFromOptions on.

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

firedrake.petsc.get_petsc_variables()[source]

Get dict of PETSc environment variables from the file: $PETSC_DIR/$PETSC_ARCH/lib/petsc/conf/petscvariables

The result is memoized to avoid constantly reading the file.

firedrake.pointeval_utils module

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

Generates C code for point evaluations.

Parameters:
  • expression – UFL expression

  • coordinates – coordinate field

  • parameters – form compiler parameters

Returns:

C code as string

firedrake.pointquery_utils module

firedrake.pointquery_utils.X_isub_dX(topological_dimension)[source]
firedrake.pointquery_utils.celldist_l1_c_expr(fiat_cell, X='X')[source]

Generate a C expression of type PetscReal to compute the L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) to a FIAT reference cell.

Parameters:
  • fiat_cell (FIAT.finite_element.FiniteElement) – The FIAT cell with same geometric dimension as the coordinate X.

  • X (str) – The name of the input pointer variable to use.

  • celldist (str) – The name of the output variable.

Returns:

A string of C code.

Return type:

str

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

Generates C code for changing to reference coordinates.

Parameters:

ufl_coordinate_element – UFL element of the coordinates

Returns:

C code as string

firedrake.pointquery_utils.dX_norm_square(topological_dimension)[source]
firedrake.pointquery_utils.init_X(fiat_cell, parameters)[source]
firedrake.pointquery_utils.inside_check(fiat_cell, eps, X='X')[source]

Generate a C expression which is true if a point is inside a FIAT reference cell and false otherwise.

Parameters:
  • fiat_cell (FIAT.finite_element.FiniteElement) – The FIAT cell with same geometric dimension as the coordinate X.

  • eps (float) – The tolerance to use for the check. Usually some small number like 1e-14.

  • X (str) – The name of the input pointer variable to use in the generated C code: it should be a pointer to a type that is an acceptable input to the PetscRealPart function. Default is “X”.

  • celldist (str) – The name of the output variable.

Returns:

A C expression which is true if the point is inside the cell and false otherwise.

Return type:

str

firedrake.pointquery_utils.is_affine(ufl_element)[source]
firedrake.pointquery_utils.make_args(function)[source]
firedrake.pointquery_utils.make_wrapper(function, **kwargs)[source]
firedrake.pointquery_utils.src_locate_cell(mesh, tolerance=None)[source]
firedrake.pointquery_utils.to_reference_coords_newton_step(ufl_coordinate_element, parameters, x0_dtype='double', dX_dtype=dtype('float64'))[source]

firedrake.progress_bar module

A module providing progress bars.

class firedrake.progress_bar.ProgressBar(*args, comm=<mpi4py.MPI.Intracomm object>, **kwargs)[source]

Bases: FillingSquaresBar

A progress bar for simulation execution.

This is a subclass of progress.bar.FillingSquaresBar which is configured to be suitable for tracking progress in forward and adjoint simulations. It is also extended to only output on rank 0 in parallel.

Parameters:
  • message (str) – An identifying string to be prepended to the progress bar. This defaults to an empty string.

  • comm (mpi4py.MPI.Intracomm) – The MPI communicator over which the simulation is run. Defaults to COMM_WORLD

Notes

Further parameters can be passed as per the progress package documentation, or you can customise further by subclassing.

Examples

To apply a progress bar to a loop, wrap the loop iterator in the iter method of a ProgressBar:

>>> for t in ProgressBar("Timestep").iter(np.linspace(0.0, 1.0, 10)):
...    sleep(0.2)
...
Timestep ▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣▣ 10/10 [0:00:02]

To see progress bars for functional, adjoint and Hessian evaluations in an adjoint simulation, set the progress_bar attribute of the tape to ProgressBar:

>>> get_working_tape().progress_bar = ProgressBar

This use case is covered in the documentation for pyadjoint.Tape.

check_tty = False
suffix = '%(index)s/%(max)s [%(elapsed_td)s]'
width = 50

firedrake.projection module

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

A projector projects a UFL expression into a function space and places the result in a function from that function space, allowing the solver to be reused. Projection reverts to an assign operation if v is a Function and belongs to the same function space as v_out. It is possible to project onto the trace space ‘DGT’, but not onto other trace spaces e.g. into the restriction of CG onto the facets.

Parameters:
  • v – the ufl.core.expr.Expr or Function to project

  • VFunction (or FunctionSpace) 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.

  • constant_jacobian – Is the projection matrix constant between calls? Say False if you have moving meshes.

  • use_slate_for_inverse – compute mass inverse cell-wise using SLATE (only valid for DG function spaces).

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

Project a UFL expression into a FunctionSpace It is possible to project onto the trace space ‘DGT’, but not onto other trace spaces e.g. into the restriction of CG onto the facets.

Parameters:
Keyword Arguments:
  • bcs – boundary conditions to apply in the projection

  • solver_parameters – parameters to pass to the solver used when projecting.

  • form_compiler_parameters – parameters to the form compiler

  • use_slate_for_inverse – compute mass inverse cell-wise using SLATE (ignored for non-DG function spaces).

  • name – name of the resulting Function

  • ad_block_tag – string for tagging the resulting block on the Pyadjoint tape

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

firedrake.randomfunctiongen module

Overview

This module wraps numpy.random, and enables users to generate a randomised Function from a FunctionSpace. This module inherits almost all attributes from numpy.random with the following changes:

Generator

A Generator wraps numpy.random.Generator. Generator inherits almost all distribution methods from numpy.random.Generator, and they can be used to generate a randomised Function by passing a FunctionSpace as the first argument.

Example:

from firedrake import *

mesh = UnitSquareMesh(2, 2)
V = FunctionSpace(mesh, 'CG', 1)
pcg = PCG64(seed=123456789)
rg = Generator(pcg)
f_beta = rg.beta(V, 1.0, 2.0)
print(f_beta.dat.data)
# prints:
# [0.0075147 0.40893448 0.18390776 0.46192167 0.20055854 0.02231147 0.47424777 0.24177973 0.55937075]

BitGenerator

A .BitGenerator is the base class for bit generators; see numpy.random.BitGenerator. A .BitGenerator takes an additional keyword argument comm (defaulting to COMM_WORLD). If comm.Get_rank() > 1, .PCG64, .PCG64DXSM, or .Philox should be used, as these bit generators are known to be parallel-safe.

PCG64

.PCG64 wraps numpy.random.PCG64. If seed keyword is not provided by the user, it is set using numpy.random.SeedSequence. To make .PCG64 automatically generate multiple streams in parallel, Firedrake preprocesses the seed as the following before passing it to numpy.random.PCG64:

rank = comm.Get_rank()
size = comm.Get_size()
sg = numpy.random.SeedSequence(seed)
seed = sg.spawn(size)[rank]

Note

inc is no longer a valid keyword for .PCG64 constructor. However, one can reset the state after construction as:

pcg = PCG64()
state = pcg.state
state['state'] = {'state': seed, 'inc': inc}
pcg.state = state
PCG64DXSM

.PCG64DXSM wraps numpy.random.PCG64DXSM. If seed keyword is not provided by the user, it is set using numpy.random.SeedSequence. To make .PCG64DXSM automatically generate multiple streams in parallel, Firedrake preprocesses the seed as the following before passing it to numpy.random.PCG64DXSM:

rank = comm.Get_rank()
size = comm.Get_size()
sg = numpy.random.SeedSequence(seed)
seed = sg.spawn(size)[rank]

Note

inc is no longer a valid keyword for .PCG64DXSM constructor. However, one can reset the state after construction as:

pcg = PCG64DXSM()
state = pcg.state
state['state'] = {'state': seed, 'inc': inc}
pcg.state = state
Philox

.Philox wraps numpy.random.Philox. If the key keyword is not provided by the user, .Philox computes a default key as:

key = np.zeros(2, dtype=np.uint64)
key[0] = comm.Get_rank()

firedrake.solving module

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

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

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

1. Solving linear systems

A linear system Ax = b may be solved by calling

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

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

2. Solving linear variational problems

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

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

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

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

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

3. Solving nonlinear variational problems

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

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

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

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

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

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

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

firedrake.solving_utils module

firedrake.solving_utils.check_snes_convergence(snes)[source]
firedrake.solving_utils.set_defaults(solver_parameters, arguments, *, ksp_defaults={}, snes_defaults={})[source]

Set defaults for solver parameters.

Parameters:
  • solver_parameters – dict of user solver parameters to override/extend defaults

  • arguments – arguments for the bilinear form (need to know if we have a Real block).

  • ksp_defaults – Default KSP parameters.

  • snes_defaults – Default SNES parameters.

firedrake.supermeshing module

firedrake.supermeshing.assemble_mixed_mass_matrix(V_A, V_B)[source]

Construct the mixed mass matrix of two function spaces, using the TrialFunction from V_A and the TestFunction from V_B.

firedrake.supermeshing.intersection_finder()

firedrake.tsfc_interface module

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

class firedrake.tsfc_interface.KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_numbers, constant_numbers, needs_cell_facets, pass_layer_arg, needs_cell_sizes, arguments, events)

Bases: tuple

Create new instance of KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_numbers, constant_numbers, needs_cell_facets, pass_layer_arg, needs_cell_sizes, arguments, events)

arguments

Alias for field number 10

coefficient_numbers

Alias for field number 5

constant_numbers

Alias for field number 6

domain_number

Alias for field number 4

events

Alias for field number 11

integral_type

Alias for field number 1

kernel

Alias for field number 0

needs_cell_facets

Alias for field number 7

needs_cell_sizes

Alias for field number 9

oriented

Alias for field number 2

pass_layer_arg

Alias for field number 8

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(*args, **kwargs)[source]

Bases: 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.

  • coefficient_numbers – Map from coefficient numbers in the provided (split) form to coefficient numbers in the original form.

  • constant_numbers – Map from local constant numbers in the provided (split) form to constant numbers in the original form.

  • interface – the KernelBuilder interface for TSFC (may be None)

  • diagonal – If assembling a matrix is it diagonal?

firedrake.tsfc_interface.as_pyop2_local_kernel(ast, name, nargs, access=Access.INC, **kwargs)[source]

Convert a loopy kernel to a PyOP2 pyop2.LocalKernel.

Parameters:
  • ast – The kernel code. This could be, for example, a loopy kernel.

  • name – The kernel name.

  • nargs – The number of arguments expected by the kernel.

  • access – Access descriptor for the first kernel argument.

firedrake.tsfc_interface.clear_cache(comm=None)[source]

Clear the Firedrake TSFC kernel cache.

firedrake.tsfc_interface.compile_form(form, name, parameters=None, split=True, interface=None, diagonal=False)[source]

Compile a form using TSFC.

Parameters:
  • form – the Form to compile.

  • name – a prefix for the generated kernel functions.

  • parameters – optional dict of parameters to pass to the form compiler. If not provided, parameters are read from the form_compiler slot of the Firedrake parameters dictionary (which see).

  • split – If False, then don’t split mixed forms.

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

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

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

firedrake.tsfc_interface.extract_numbered_coefficients(expr, numbers)[source]

Return expression coefficients specified by a numbering.

Parameters:
  • expr – A UFL expression.

  • numbers – Iterable of indices used for selecting the correct coefficients from expr.

Returns:

A list of UFL coefficients.

firedrake.tsfc_interface.gather_integer_subdomain_ids(knls)[source]

Gather a dict of all integer subdomain IDs per integral type.

This is needed to correctly interpret the "otherwise" subdomain ID.

Parameters:

knls – Iterable of SplitKernel objects.

firedrake.ufl_expr module

class firedrake.ufl_expr.Argument(*args, **kwargs)[source]

Bases: 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.

Keyword Arguments:

part – optional index (mostly ignored).

Note

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

Initialise.

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

A symbolic representation of the cell size of a mesh.

Parameters:

mesh – the mesh for which to calculate the cell size.

class firedrake.ufl_expr.Coargument(*args, **kw)[source]

Bases: Coargument

Representation of an argument to a form in a dual space.

Parameters:
  • function_space – the FunctionSpace the argument corresponds to.

  • number – the number of the argument being constructed.

Keyword Arguments:

part – optional index (mostly ignored).

Initialise.

cell_node_map[source]
equals(other)[source]

Check equality.

exterior_facet_node_map[source]
function_space()[source]
interior_facet_node_map[source]
make_dat()[source]
reconstruct(function_space=None, number=None, part=None)[source]
ufl_operands
firedrake.ufl_expr.FacetNormal(mesh)[source]

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

Parameters:

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

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

Keyword Arguments:

part – optional index (mostly ignored).

firedrake.ufl_expr.TestFunctions(function_space)[source]

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

Parameters:

function_space – the FunctionSpace to build the test functions on.

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

firedrake.ufl_expr.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.

Keyword Arguments:

part – optional index (mostly ignored).

firedrake.ufl_expr.TrialFunctions(function_space)[source]

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

Parameters:

function_space – the FunctionSpace to build the trial functions on.

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

firedrake.ufl_expr.action(form, coefficient, derivatives_expanded=None)[source]

Compute the action of a form on a coefficient.

Parameters:
  • form – A UFL form, or a Slate tensor.

  • coefficient – The Function to act on.

Returns:

a symbolic expression for the action.

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

Compute the adjoint of a form.

Parameters:
  • form – A UFL form, or a Slate tensor.

  • reordered_arguments – arguments to use when creating the adjoint. Ignored if form is a Slate tensor.

If the form is a slate tensor, this just returns its transpose. Otherwise, given a bilinear form, compute the adjoint form by changing the ordering (number) of the test and trial functions.

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

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

Compute the derivative of a form.

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

Parameters:
  • form – a Form to compute the derivative of.

  • u – a Function to compute the derivative with respect to.

  • du – an optional Argument to use as the replacement in the new form (constructed automatically if not provided).

  • coefficient_derivatives – an optional dict to provide the derivative of a coefficient function.

Raises:

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

See also ufl.derivative().

firedrake.utility_meshes module

firedrake.utility_meshes.AnnulusMesh(R, r, nr=4, nt=32, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate an annulus mesh periodically extruding an interval mesh

Parameters:
  • R – The outer radius

  • r – The inner radius

Keyword Arguments:
  • nr – (optional), number of cells in the radial direction

  • nt – (optional), number of cells in the circumferential direction (min 3)

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

firedrake.utility_meshes.BoxMesh(nx, ny, nz, Lx, Ly, Lz, hexahedral=False, reorder=None, distribution_parameters=None, diagonal='default', comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[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

Keyword Arguments:
  • hexahedral – (optional), creates hexahedral mesh.

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • diagonal – Two ways of cutting hexadra, should be cut into 6 tetrahedra ("default"), or 5 tetrahedra thus less biased ("crossed")

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on.

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.CircleManifoldMesh(ncells, radius=1, degree=1, distribution_parameters=None, reorder=False, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

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

Parameters:

ncells – number of cells the circle should be divided into (min 3)

Keyword Arguments:
  • radius – (optional) radius of the circle to approximate.

  • degree – polynomial degree of coordinate space (e.g., cells are straight line segments if degree=1).

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

firedrake.utility_meshes.CubeMesh(nx, ny, nz, L, hexahedral=False, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[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

Keyword Arguments:
  • hexahedral – (optional), creates hexahedral mesh.

  • reorder – (optional), should the mesh be reordered?

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

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.CubedSphereMesh(radius, refinement_level=0, degree=1, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate an cubed approximation to the surface of the sphere.

Parameters:

radius – The radius of the sphere to approximate.

Keyword Arguments:
  • refinement_level – optional number of refinements (0 is a cube).

  • degree – polynomial degree of coordinate space (e.g., bilinear quads if degree=1).

  • reorder – (optional), should the mesh be reordered?

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

firedrake.utility_meshes.CylinderMesh(nr, nl, radius=1, depth=1, longitudinal_direction='z', quadrilateral=False, reorder=None, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[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

Keyword Arguments:
  • radius – (optional) radius of the cylinder to approximate.

  • depth – (optional) depth of the cylinder to approximate.

  • longitudinal_direction – (option) direction for the longitudinal axis of the cylinder.

  • quadrilateral – (optional), creates quadrilateral mesh.

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • diagonal – (optional), one of "crossed", "left", "right". Not valid for quad meshes.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

The boundary edges in this mesh are numbered as follows:

  • 1: plane l == 0 (bottom)

  • 2: plane l == depth (top)

firedrake.utility_meshes.IcosahedralSphereMesh(radius, refinement_level=0, degree=1, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[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)}\]

Keyword Arguments:
  • refinement_level – optional number of refinements (0 is an icosahedron).

  • degree – polynomial degree of coordinate space (e.g., flat triangles if degree=1).

  • reorder – (optional), should the mesh be reordered?

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

firedrake.utility_meshes.IntervalMesh(ncells, length_or_left, right=None, distribution_parameters=None, reorder=False, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[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).

Keyword Arguments:
  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

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

firedrake.utility_meshes.OctahedralSphereMesh(radius, refinement_level=0, degree=1, hemisphere='both', z0=0.8, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate an octahedral approximation to the surface of the sphere.

Parameters:

radius – The radius of the sphere to approximate.

Keyword Arguments:
  • refinement_level – optional number of refinements (0 is an octahedron).

  • degree – polynomial degree of coordinate space (e.g., flat triangles if degree=1).

  • hemisphere – One of “both”, “north”, or “south”

  • z0 – for abs(z/R)>z0, blend from a mesh where the higher-order non-vertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh.

  • reorder – (optional), should the mesh be reordered?

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

firedrake.utility_meshes.PeriodicBoxMesh(nx, ny, nz, Lx, Ly, Lz, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a periodic 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

Keyword Arguments:
  • reorder – (optional), should the mesh be reordered?

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

firedrake.utility_meshes.PeriodicIntervalMesh(ncells, length, distribution_parameters=None, reorder=False, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a periodic mesh of an interval.

Parameters:
  • ncells – The number of cells over the interval.

  • length – The length the interval.

Keyword Arguments:
  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

firedrake.utility_meshes.PeriodicRectangleMesh(nx, ny, Lx, Ly, direction='both', quadrilateral=False, reorder=None, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[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".

Keyword Arguments:
  • quadrilateral – (optional), creates quadrilateral mesh.

  • reorder – (optional), should the mesh be reordered

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • diagonal – (optional), one of "crossed", "left", "right". Not valid for quad meshes. Only used for direction "x" or direction "y".

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

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, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[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".

Keyword Arguments:
  • quadrilateral – (optional), creates quadrilateral mesh.

  • reorder – (optional), should the mesh be reordered

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • diagonal – (optional), one of "crossed", "left", "right". Not valid for quad meshes.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.

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.PeriodicUnitCubeMesh(nx, ny, nz, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a periodic 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

Keyword Arguments:
  • reorder – (optional), should the mesh be reordered?

  • distribution_parameters – options controlling mesh distribution, see Mesh() for details.

  • comm – Optional communicator to build the mesh on.

  • name – Optional name of the mesh.

  • distribution_name – the name of parallel distribution used when checkpointing; if None, the name is automatically generated.

  • permutation_name – the name of entity permutation (reordering) used when checkpointing; if None, the name is automatically generated.