firedrake package

Subpackages

Submodules

firedrake.assemble module

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

Evaluate expr.

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

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

  • bcs – Iterable of boundary conditions to apply.

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

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.

Note

For 1-form assembly, the resulting object should in fact be a cofunction instead of a Function. However, since cofunctions are not currently supported in UFL, functions are used instead.

firedrake.assemble_expressions module

class firedrake.assemble_expressions.Assign(lvalue, rvalue)[source]

Bases: object

Representation of a pointwise assignment expression.

Parameters:
  • lvalue – The coefficient to assign into.

  • rvalue – The pointwise expression.

property args

Tuple of par_loop arguments for the expression.

coefficients[source]

Tuple of coefficients involved in the assignment.

fast_key[source]

A fast lookup key for this expression.

iterset[source]
lvalue
par_loop_args[source]

Arguments for a parallel loop to evaluate this expression.

If the expression is over a mixed space, this merges kernels for subspaces with the same node_set (resulting in fewer par_loop calls).

rcoefficients[source]

Coefficients appearing in the rvalue.

relabeller = <firedrake.assemble_expressions.IndexRelabeller object>
rvalue
slow_key[source]

A slow lookup key for this expression (relabelling UFL indices).

split[source]

A tuple of assignment expressions, separated by subspace for mixed spaces.

symbol = '='
class firedrake.assemble_expressions.AugmentedAssign(lvalue, rvalue)[source]

Bases: Assign

Base class for augmented pointwise assignment.

Parameters:
  • lvalue – The coefficient to assign into.

  • rvalue – The pointwise expression.

lvalue
rvalue
class firedrake.assemble_expressions.IAdd(lvalue, rvalue)[source]

Bases: AugmentedAssign

Parameters:
  • lvalue – The coefficient to assign into.

  • rvalue – The pointwise expression.

lvalue
rvalue
symbol = '+='
class firedrake.assemble_expressions.IDiv(lvalue, rvalue)[source]

Bases: AugmentedAssign

Parameters:
  • lvalue – The coefficient to assign into.

  • rvalue – The pointwise expression.

lvalue
rvalue
symbol = '/='
class firedrake.assemble_expressions.IMul(lvalue, rvalue)[source]

Bases: AugmentedAssign

Parameters:
  • lvalue – The coefficient to assign into.

  • rvalue – The pointwise expression.

lvalue
rvalue
symbol = '*='
class firedrake.assemble_expressions.ISub(lvalue, rvalue)[source]

Bases: AugmentedAssign

Parameters:
  • lvalue – The coefficient to assign into.

  • rvalue – The pointwise expression.

lvalue
rvalue
symbol = '-='
class firedrake.assemble_expressions.IndexRelabeller[source]

Bases: MultiFunction

expr(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched

as a default rule.

multi_index(o)[source]
class firedrake.assemble_expressions.Translator[source]

Bases: MultiFunction, Mixin

abs(o, expr)[source]
coefficient(o)[source]
component_tensor(o, expression, index)[source]
conditional(o, condition, then, else_)[source]
conj(o, expr)[source]
expr(o)[source]

Trigger error for types with missing handlers.

imag(o, expr)[source]
index_sum(o, summand, indices)[source]
indexed(o, aggregate, index)[source]
real(o, expr)[source]
sum(o, *ops)[source]
firedrake.assemble_expressions.assemble_expression(expr, subset=None)[source]

Evaluate a UFL expression pointwise and assign it to a new Function.

Parameters:
  • expr – The UFL expression.

  • subset – Optional subset to apply the expression on.

Returns:

A new function.

firedrake.assemble_expressions.compile_to_gem(expr, translator)[source]

Compile a single pointwise expression to GEM.

Parameters:
  • expr – The expression to compile.

  • translator – a Translator instance.

Returns:

A (lvalue, rvalue) pair of preprocessed GEM.

class firedrake.assemble_expressions.dereffed(args)[source]

Bases: object

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

Evaluate a pointwise expression.

Parameters:
  • expr – The expression to evaluate.

  • subset – An optional subset to apply the expression on.

Returns:

The lvalue in the provided expression.

firedrake.assemble_expressions.extract_coefficients(expr)[source]
firedrake.assemble_expressions.flatten(shape)[source]
firedrake.assemble_expressions.pointwise_expression_kernel(exprs, scalar_type, is_logging)[source]

Compile a kernel for pointwise expressions.

Parameters:
  • exprs – List of expressions, all on the same iteration set.

  • scalar_type – Default scalar type (numpy.dtype).

  • is_loggingTrue if the kernel is to be annotated with PETSc events.

Returns:

A 2-tuple where the first entry is a PyOP2 kernel for evaluating the expressions and the second is a list of lists containing the indices of the parloop arguments that are needed from exprs.

firedrake.assemble_expressions.reshape(expr, shape)[source]

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 :class:.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 DirichletBCs.

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.

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

filename

The neme of the checkpoint file.

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.

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.

  • 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)[source]

Load a mesh.

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

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

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

Returns:

the loaded mesh.

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)[source]

Save a Function.

Parameters:
  • f – the Function to save.

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

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

Save a mesh.

Parameters:
  • mesh – the mesh to save.

  • 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 be deprecated after 01/01/2023. 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 be deprecated after 01/01/2023. 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.constant module

class firedrake.constant.Constant(*args, **kwargs)[source]

Bases: Coefficient, ConstantMixin

A “constant” coefficient

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

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

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

Note

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

assign(value)[source]

Set the value of this constant.

Parameters:

value – A value of the appropriate shape

cell_node_map(bcs=None)[source]

Return a null cell to node map.

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

Return the evaluation of this Constant.

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

  • mapping – A mapping (ignored).

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

  • index_values – ignored.

exterior_facet_node_map(bcs=None)[source]

Return a null exterior facet to node map.

function_space()[source]

Return a null function space.

interior_facet_node_map(bcs=None)[source]

Return a null interior facet to node map.

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

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

firedrake.dmhooks module

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

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

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

Similarly, when a DM is used in a solver, an application context is attached to it, such that when PETSc calls back into Firedrake, we can grab the relevant information (how to make the Jacobian, etc…). This functions in a similar way using 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.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)[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.

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.

Raises:

ValueError – if communicators mismatch, or function sizes mismatch.

comm

The communicator for spatial parallelism, contains a contiguous chunk of M processes from comm

ensemble_comm

The communicator for ensemble parallelism, contains all processes in comm which have the same rank in comm.

global_comm

The global 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

  • tag – the tag of the message

Returns:

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

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

Returns:

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

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

  • tag – the tag of the message

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

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

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

class IndexInliner[source]

Bases: MultiFunction

Inline fixed index of list tensors

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.Function(function_space, val=None, name=None, dtype=dtype('float64'), count=None)[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:

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

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.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.Subset of this Function’s node_set. The expression will then only be assigned to the nodes on that subset.

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

Evaluate function at points.

Parameters:
  • arg – The point to locate.

  • args – Additional points.

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

  • tolerance – Tolerance to use when checking for points in cell.

copy(deepcopy=False)[source]

Return a copy of this Function.

Parameters:

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

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

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, ad_block_tag=None)[source]

Interpolate an expression onto this Function.

Parameters:
  • expression – a UFL expression to interpolate

  • ad_block_tag – string for tagging the resulting 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.

split()[source]

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

sub(i)[source]

Extract the ith sub Function of this Function.

Parameters:

i – the index to extract

See also split().

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

property topological

The underlying coordinateless function.

vector()[source]

Return a Vector wrapping the data in this Function

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

Bases: Exception

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

Attributes: domain, point

firedrake.functionspace module

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

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

Create a FunctionSpace.

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

  • family – The finite element family.

  • degree – The degree of the finite element.

  • name – An optional name for the function space.

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

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

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

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

Create a MixedFunctionSpace.

Parameters:
  • spaces – An iterable of constituent spaces, or a MixedElement.

  • name – An optional name for the mixed function space.

  • mesh – An optional mesh. Must be provided if spaces is a MixedElement, ignored otherwise.

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

Create a rank-2 FunctionSpace.

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

  • family – The finite element family.

  • degree – The degree of the finite element.

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

  • symmetry – Optional symmetries in the tensor value.

  • name – An optional name for the function space.

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

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

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

Note

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

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

Create a rank-1 FunctionSpace.

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

  • family – The finite element family.

  • degree – The degree of the finite element.

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

  • name – An optional name for the function space.

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

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

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

Note

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

firedrake.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.FunctionSpace(mesh, element, name=None)[source]

Bases: object

A representation of a function space.

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

Parameters:
  • mesh – The Mesh() to build the function space on.

  • element – The FiniteElementBase describing the degrees of freedom.

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

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

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

Warning

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

boundary_nodes(sub_domain)[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.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 dof_count and node_count.

dm[source]

A PETSc DM describing the data layout for this FunctionSpace.

dof_count[source]

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

dof_dset

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

exterior_facet_node_map()[source]

Return the pyop2.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.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.Dat defined on the dof_dset of this Function.

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 rank 0, this is equal to the dof_count, otherwise the dof_count is dim times the node_count.

node_set

A pyop2.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 VectorElement or TensorElement instances have rank equivalent to the number of components of their value_shape().

split()[source]

Split into a tuple of constituent spaces.

sub(i)[source]

Return a view into the ith component.

topological[source]

Function space on a mesh topology.

ufl_element()[source]

The 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: Optional[WithGeometry])[source]

Bases: object

Helper class carrying data for a WithGeometry.

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: Optional[WithGeometry]
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.

  • 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.MixedMap from the Mesh.cell_set of the underlying mesh to the node_set of this MixedFunctionSpace. This is composed of the FunctionSpace.cell_node_maps of the underlying FunctionSpaces of which this MixedFunctionSpace is composed.

component = None
dim()[source]

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

See also dof_count and node_count.

dm[source]

A PETSc DM describing the data layout for fieldsplit solvers.

dof_count[source]

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

dof_dset[source]

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

exterior_facet_node_map()[source]

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

index = None
interior_facet_node_map()[source]

Return the pyop2.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.MixedDat defined on the dof_dset of this MixedFunctionSpace.

mesh()[source]
node_count[source]

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

node_set[source]

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

num_sub_spaces()[source]

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

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

The list of FunctionSpaces of which this MixedFunctionSpace is composed.

sub(i)[source]

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

property topological

Function space on a mesh topology.

ufl_element()[source]

The 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.Dat.

Raises:

ValueError – if no_dats is True.

no_dats = False

Can this proxy make pyop2.Dat objects

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

Bases: FunctionSpace

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

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

bottom_nodes()[source]

RealFunctionSpace objects have no bottom nodes.

cell_node_map(bcs=None)[source]

RealFunctionSpace objects have no cell node map.

dim()[source]

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

See also dof_count and node_count.

exterior_facet_node_map(bcs=None)[source]

RealFunctionSpace objects have no exterior facet node map.

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

RealFunctionSpace objects have no interior facet node map.

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.Global representing the data for a Function on this space.

rank = 0

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

shape = ()
top_nodes()[source]

RealFunctionSpace objects have no bottom nodes.

value_size = 1

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

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

Bases: FunctionSpace

Attach geometric information to a FunctionSpace.

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

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

When instantiating a WithGeometry, users should call 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 WithGeometry.

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().

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
restore_work_function(function)[source]

Restore a work function obtained with get_work_function().

Parameters:

function – The work function to restore

Raises:

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

Warning

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

split()[source]

Split into a tuple of constituent spaces.

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

The Cell this FunctionSpace is defined on.

ufl_function_space()[source]

The FunctionSpace this object represents.

firedrake.halo module

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

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

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

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

Parameters:
  • dat – The Dat to exchange.

  • insert_mode – The insertion mode.

global_to_local_end(dat, insert_mode)[source]

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

Parameters:
  • dat – The Dat to exchange.

  • insert_mode – The insertion mode.

local_to_global_begin(dat, insert_mode)[source]

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

Parameters:
  • dat – The Dat to exchange.

  • insert_mode – The insertion mode.

local_to_global_end(dat, insert_mode)[source]

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

Parameters:
  • dat – The Dat to exchange.

  • insert_mode – The insertion mode.

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

firedrake.interpolation module

class firedrake.interpolation.Interpolator(expr, V, subset=None, freeze_expr=False, access=Access.WRITE)[source]

Bases: object

A reusable interpolation object.

Parameters:
  • expr – The expression to interpolate.

  • V – The FunctionSpace or Function to interpolate into.

  • subset – An optional pyop2.Subset to apply the interpolation over.

  • freeze_expr – Set to True to prevent the expression being re-evaluated on each call.

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)[source]

Compute the interpolation.

Parameters:
  • function – If the expression being interpolated contains an ufl.Argument, then the Function value to interpolate.

  • output – Optional. A Function to contain the output.

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

Returns:

The resulting interpolated Function.

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

Interpolate an expression onto a new function in V.

Parameters:
  • expr – a UFL expression.

  • V – the FunctionSpace to interpolate into (or else an existing Function).

  • subset – An optional pyop2.Subset to apply the interpolation over.

  • access – The access descriptor for combining updates to shared dofs.

  • ad_block_tag – string for tagging the resulting 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.

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

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

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

firedrake.logging.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.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).

assemble()[source]
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.Mat will be built from the remaining arguments, for valid values, see pyop2.Mat.

Note

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

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

Bases: object

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

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

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

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

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.

firedrake.mesh module

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', kernel=None, gdim=None, name=None)[source]

Build an extruded mesh from an input mesh

Parameters:
  • mesh – the unstructured base mesh

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

  • layer_height – the layer height. 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.

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

The various values of extrusion_type have the following meanings:

"uniform"

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

"radial"

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

"radial_hedgehog"

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

"custom"

use a custom kernel to generate the extruded coordinates

For more details see the manual section on extruded meshes.

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

Construct a mesh object.

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

Parameters:
  • meshfile – Mesh file name (or DMPlex object) defining mesh topology. See below for details on supported mesh formats.

  • 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. Ignored if meshfile is a DMPlex object (in which case the communicator will be taken from there).

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

  • GMSH: with extension .msh

  • Exodus: with extension .e, .exo

  • CGNS: with extension .cgns

  • Triangle: with extension .node

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

Note

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

firedrake.mesh.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, missing_points_behaviour=None, tolerance=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.

  • 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 ValueError. Note that setting this will cause all MPI ranks to check that they have the same list of vertices (else the test is not possible): this operation scales with number of vertices and number of ranks.

  • tolerance – the amount by which the local coordinates of a point are allowed to fall outside the cell while still having the point count as in the cell. Increase the default (1.0e-14) somewhat if vertices interior to the domain are being lost in the VertexOnlyMesh construction process.

Note

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

Note

Extruded and immersed manifold meshes are not yet supported.

Note

Modifying the coordinates of the parent mesh is not currently supported. Doing so will cause interpolation to Functions defined on the VertexOnlyMesh to return the wrong values.

Note

When running in parallel, vertexcoords are strictly confined to the local mesh cells of that rank. 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, and rank B has not been supplied with those vertexcoords, then the vertexcoords {X} will be lost.

This can be avoided by either

  1. making sure that all ranks are supplied with the same vertexcoords or by

  2. ensuring that vertexcoords are already found in cells owned by the mesh partition of the given rank.

For more see this github issue.

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)[source]

Bases: object

Build a basis for a vector space.

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

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

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

Note

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

Warning

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

check_orthogonality(orthonormal=True)[source]

Check if the basis is orthogonal.

Parameters:

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

Raises:

ValueError – If the basis is not orthogonal/orthonormal.

is_orthogonal()[source]

Is this vector space basis orthogonal?

is_orthonormal()[source]

Is this vector space basis orthonormal?

nullspace(comm=None)[source]

The PETSc NullSpace object for this VectorSpaceBasis.

Parameters:

comm – Communicator to create the nullspace on.

orthogonalize(b)[source]

Orthogonalize b with respect to this VectorSpaceBasis.

Parameters:

b – a Function

Note

Modifies b in place.

orthonormalize()[source]

Orthonormalize the basis.

Warning

This modifies the basis in place.

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

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

  • 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 switches off all of COFFEE’s kernel compilation optimisations and enables PyOP2’s runtime checking of par_loop arguments in all cases (even those where they are claimed safe). Additionally, it switches to compiling generated code in debug mode.

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

firedrake.parameters.parameters = {'coffee': {'optlevel': 'Ov'}, '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': '/Users/dham/src/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, 'opt_level': 'Ov', '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_hex8_to_hex9(orders)[source]

Produce a list where element i is the vtk9 node number of node i in vtk8. For hexes only. :arg orders: the orders of the hex (the same integer 3 times) :return a list of integers

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, is_loopy_kernel=False, **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 string containing the C code to be executed. Or a 2-tuple of (domains, instructions) to create a loopy kernel (must also set is_loopy_kernel=True). If loopy syntax is used, 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 Kernel constructor

  • kwargs – additional keyword arguments are passed to the underlying par_loop

  • iterate

    Optionally specify which region of an 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)
par_loop('for (int i=0; i<A.dofs; i++) A[i] = fmax(A[i], B[0]);', dx,
    {'A' : (A, RW), 'B': (B, READ)})

The equivalent using loopy kernel syntax is:

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)}, is_loopy_kernel=True)

Argument definitions

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

READ

The variable will be read but not written to.

WRITE

The variable will be written to but not read. If multiple kernel invocations write to the same DoF, then the order of these writes is undefined.

RW

The variable will be both read and written to. If multiple kernel invocations access the same DoF, then the order of these accesses is undefined, but it is guaranteed that no race will occur.

INC

The variable will be added into using +=. As before, the order in which the kernel invocations increment the variable is undefined, but there is a guarantee that no races will occur.

Note

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

The measure

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

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

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

The kernel code

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

  • Only functions from math.h may be called.

  • Pointer operations other than dereferencing arrays are prohibited.

Indirect free variables referencing Functions are all of type double*. 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.plot module

class firedrake.plot.FunctionPlotter(mesh, num_sample_points)[source]

Bases: object

firedrake.plot.plot(function, *args, bezier=False, num_sample_points=10, complex_component='real', **kwargs)[source]

Plot a 1D Firedrake Function

Parameters:
  • function – The Function to plot

  • args – same as for matplotlib plot

  • num_sample_points – number of sample points for high-degree functions

  • complex_component – If plotting complex data, which component? ('real' or 'imag'). Default is 'real'.

  • kwargs – same as for matplotlib

Returns:

list of matplotlib Line2D

firedrake.plot.quiver(function, *, complex_component='real', **kwargs)[source]

Make a quiver plot of a 2D vector Firedrake Function

Parameters:
  • function – the vector field to plot

  • complex_component – If plotting complex data, which component? ('real' or 'imag'). Default is 'real'.

  • kwargs – same as for matplotlib quiver

Returns:

matplotlib Quiver object

firedrake.plot.streamplot(function, resolution=None, min_length=None, max_time=None, start_width=0.5, end_width=1.5, tolerance=0.003, loc_tolerance=1e-10, seed=None, complex_component='real', **kwargs)[source]

Create a streamline plot of a vector field

Similar to matplotlib streamplot

Parameters:
  • function – the Firedrake Function to plot

  • resolution – minimum spacing between streamlines (defaults to domain size / 20)

  • min_length – minimum length of a streamline (defaults to 4x resolution)

  • max_time – maximum time to integrate a streamline

  • start_width – line width at beginning of streamline

  • end_width – line width at end of streamline, to convey direction

  • tolerance – dimensionless tolerance for adaptive ODE integration

  • loc_tolerance – point location tolerance for at()

  • complex_component – If plotting complex data, which component? ('real' or 'imag'). Default is 'real'.

  • kwargs – same as for matplotlib LineCollection

firedrake.plot.tricontour(function, *args, complex_component='real', **kwargs)[source]

Create a contour plot of a 2D Firedrake Function

If the input function is a vector field, the magnitude will be plotted.

Parameters:
  • function – the Firedrake Function to plot

  • args – same as for matplotlib tricontour

  • complex_component – If plotting complex data, which component? ('real' or 'imag'). Default is 'real'.

  • kwargs – same as for matplotlib

Returns:

matplotlib ContourSet object

firedrake.plot.tricontourf(function, *args, complex_component='real', **kwargs)[source]

Create a filled contour plot of a 2D Firedrake Function

If the input function is a vector field, the magnitude will be plotted.

Parameters:
  • function – the Firedrake Function to plot

  • args – same as for matplotlib tricontourf

  • complex_component – If plotting complex data, which component? ('real' or 'imag'). Default is 'real'.

  • kwargs – same as for matplotlib

Returns:

matplotlib ContourSet object

firedrake.plot.tripcolor(function, *args, complex_component='real', **kwargs)[source]

Create a pseudo-color plot of a 2D Firedrake Function

If the input function is a vector field, the magnitude will be plotted.

Parameters:
  • function – the function to plot

  • args – same as for matplotlib tripcolor

  • complex_component – If plotting complex data, which component? ('real' or 'imag'). Default is 'real'.

  • kwargs – same as for matplotlib

Returns:

matplotlib PolyCollection object

firedrake.plot.triplot(mesh, axes=None, interior_kw={}, boundary_kw={})[source]

Plot a mesh colouring marked facet segments

Typically boundary segments will be marked and coloured, but interior facets that are marked will also be coloured.

The interior and boundary keyword arguments can be any keyword argument for LineCollection and related types.

Parameters:
  • mesh – mesh to be plotted

  • axes – matplotlib Axes object on which to plot mesh

  • interior_kw – keyword arguments to apply when plotting the mesh interior

  • boundary_kw – keyword arguments to apply when plotting the mesh boundary

Returns:

list of matplotlib Collection objects

firedrake.plot.trisurf(function, *args, complex_component='real', **kwargs)[source]

Create a 3D surface plot of a 2D Firedrake Function

If the input function is a vector field, the magnitude will be plotted.

Parameters:
  • function – the Firedrake Function to plot

  • args – same as for matplotlib plot_trisurf

  • complex_component – If plotting complex data, which component? ('real' or 'imag'). Default is 'real'.

  • kwargs – same as for matplotlib

Returns:

matplotlib Poly3DCollection object

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.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.compute_celldist(fiat_cell, X='X', celldist='celldist')[source]
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]
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_coordinates(ufl_coordinate_element, parameters)[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:
messagestr

An identifying string to be prepended to the progress bar. This defaults to an empty string.

commmpi4py.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.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:
  • v – the ufl.Expr to project

  • V – the FunctionSpace or Function to project into

  • 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_map, 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_map, needs_cell_facets, pass_layer_arg, needs_cell_sizes, arguments, events)

arguments

Alias for field number 9

coefficient_map

Alias for field number 5

domain_number

Alias for field number 4

events

Alias for field number 10

integral_type

Alias for field number 1

kernel

Alias for field number 0

needs_cell_facets

Alias for field number 6

needs_cell_sizes

Alias for field number 8

oriented

Alias for field number 2

pass_layer_arg

Alias for field number 7

subdomain_id

Alias for field number 3

class firedrake.tsfc_interface.SplitKernel(indices, kinfo)

Bases: tuple

Create new instance of SplitKernel(indices, kinfo)

indices

Alias for field number 0

kinfo

Alias for field number 1

class firedrake.tsfc_interface.TSFCKernel(*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.

  • number_map – a map from local coefficient numbers to the global coefficient numbers.

  • interface – the KernelBuilder interface for TSFC (may be None)

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, coffee=False, 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.

  • coffee – compile coffee kernel instead of loopy kernel

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

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

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

firedrake.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(function_space, number, part=None)[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.

  • part – optional index (mostly ignored).

Note

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

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

A symbolic representation of the cell size of a mesh.

Parameters:

mesh – the mesh for which to calculate the cell size.

firedrake.ufl_expr.FacetNormal(mesh)[source]

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

Parameters:

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

firedrake.ufl_expr.TestFunction(function_space, part=None)[source]

Build a test function on the specified function space.

Parameters:
  • function_space – the FunctionSpace to build the test function on.

  • part – optional index (mostly ignored).

firedrake.ufl_expr.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.

  • 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)[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)[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.split(). UFL doesn’t notice that these are related to u and so therefore the derivative is wrong (instead one should have written split(u)).

See also ufl.derivative().

firedrake.utility_meshes module

firedrake.utility_meshes.BoxMesh(nx, ny, nz, Lx, Ly, Lz, 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

  • 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 (defaults to COMM_WORLD).

The boundary surfaces are numbered as follows:

  • 1: plane x == 0

  • 2: plane x == Lx

  • 3: plane y == 0

  • 4: plane y == Ly

  • 5: plane z == 0

  • 6: plane z == Lz

firedrake.utility_meshes.CircleManifoldMesh(ncells, radius=1, degree=1, distribution_parameters=None, 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)

  • radius – (optional) radius of the circle to approximate (defaults to 1).

  • degree – polynomial degree of coordinate space (defaults to 1: cells are straight line segments)

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

  • refinement_level – optional number of refinements (0 is a cube).

  • degree – polynomial degree of coordinate space (defaults to 1: bilinear quads)

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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

  • radius – (optional) radius of the cylinder to approximate (default 1).

  • depth – (optional) depth of the cylinder to approximate (default 1).

  • longitudinal_direction – (option) direction for the longitudinal axis of the cylinder.

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • diagonal – (optional), one of "crossed", "left", "right". "left" is the default. Not valid for quad meshes.

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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)}\]

  • refinement_level – optional number of refinements (0 is an icosahedron).

  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

  • refinement_level – optional number of refinements (0 is an octahedron).

  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)

  • hemisphere – One of “both” (default), “north”, or “south”

  • z0 – for abs(z/R)>z0, blend from a mesh where the higher-order non-vertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh. (defaults to z0=0.8).

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • diagonal – (optional), one of "crossed", "left", "right". "left" is the default. Not valid for quad meshes. Only used for direction "x" or direction "y".

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • diagonal – (optional), one of "crossed", "left", "right". "left" is the default. Not valid for quad meshes.

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.PeriodicUnitIntervalMesh(ncells, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a periodic mesh of the unit interval

Parameters:
  • ncells – The number of cells in the interval.

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.PeriodicUnitSquareMesh(nx, ny, direction='both', reorder=None, quadrilateral=False, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a periodic unit square mesh

Parameters:
  • nx – The number of cells in the x direction

  • ny – The number of cells in the y direction

  • direction – The direction of the periodicity, one of "both", "x" or "y".

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • diagonal – (optional), one of "crossed", "left", "right". "left" is the default. Not valid for quad meshes.

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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 == 1

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

  • 1: plane x == 0

  • 2: plane x == 1

firedrake.utility_meshes.RectangleMesh(nx, ny, Lx, Ly, quadrilateral=False, reorder=None, diagonal='left', distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a rectangular mesh

Parameters:
  • nx – The number of cells in the x direction

  • ny – The number of cells in the y direction

  • Lx – The extent in the x direction

  • Ly – The extent in the y direction

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • diagonal – For triangular meshes, should the diagonal got from bottom left to top right ("right"), or top left to bottom right ("left"), or put in both diagonals ("crossed").

  • 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 x == 0

  • 2: plane x == Lx

  • 3: plane y == 0

  • 4: plane y == Ly

firedrake.utility_meshes.SquareMesh(nx, ny, L, reorder=None, quadrilateral=False, diagonal='left', distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a square mesh

Parameters:
  • nx – The number of cells in the x direction

  • ny – The number of cells in the y direction

  • L – The extent in the x and y directions

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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 x == 0

  • 2: plane x == L

  • 3: plane y == 0

  • 4: plane y == L

firedrake.utility_meshes.TensorRectangleMesh(xcoords, ycoords, quadrilateral=False, reorder=None, diagonal='left', distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a rectangular mesh

Parameters:
  • xcoords – mesh points for the x direction

  • ycoords – mesh points for the y direction

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • diagonal – For triangular meshes, should the diagonal got from bottom left to top right ("right"), or top left to bottom right ("left"), or put in both diagonals ("crossed").

The boundary edges in this mesh are numbered as follows:

  • 1: plane x == xcoords[0]

  • 2: plane x == xcoords[-1]

  • 3: plane y == ycoords[0]

  • 4: plane y == ycoords[-1]

firedrake.utility_meshes.TorusMesh(nR, nr, R, r, quadrilateral=False, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a toroidal mesh

Parameters:
  • nR – The number of cells in the major direction (min 3)

  • nr – The number of cells in the minor direction (min 3)

  • R – The major radius

  • r – The minor radius

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.UnitBallMesh(refinement_level=0, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a mesh of the unit ball in 3D

Parameters:
  • refinement_level – optional number of refinements (0 is an octahedron)

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional MPI communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.UnitCubeMesh(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 mesh of a unit cube

Parameters:
  • nx – The number of cells in the x direction

  • ny – The number of cells in the y direction

  • nz – The number of cells in the z direction

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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 == 1

  • 3: plane y == 0

  • 4: plane y == 1

  • 5: plane z == 0

  • 6: plane z == 1

firedrake.utility_meshes.UnitCubedSphereMesh(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 a cubed approximation to the unit sphere.

Parameters:
  • refinement_level – optional number of refinements (0 is a cube).

  • degree – polynomial degree of coordinate space (defaults to 1: bilinear quads)

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.UnitDiskMesh(refinement_level=0, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a mesh of the unit disk in 2D

Parameters:
  • refinement_level – optional number of refinements (0 is a diamond)

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.UnitIcosahedralSphereMesh(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 unit sphere.

Parameters:
  • refinement_level – optional number of refinements (0 is an icosahedron).

  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.UnitIntervalMesh(ncells, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

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

Parameters:
  • ncells – The number of the cells over the interval.

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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 (\(x=0\)) boundary point has boundary marker 1, while the right hand (\(x=1\)) point has marker 2.

firedrake.utility_meshes.UnitOctahedralSphereMesh(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 unit sphere.

Parameters:
  • refinement_level – optional number of refinements (0 is an octahedron).

  • degree – polynomial degree of coordinate space (defaults to 1: flat triangles)

  • hemisphere – One of “both” (default), “north”, or “south”

  • z0 – for abs(z)>z0, blend from a mesh where the higher-order non-vertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh. (defaults to z0=0.8).

  • reorder – (optional), should the mesh be reordered?

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.UnitSquareMesh(nx, ny, reorder=None, diagonal='left', quadrilateral=False, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a unit square mesh

Parameters:
  • nx – The number of cells in the x direction

  • ny – The number of cells in the y direction

  • quadrilateral – (optional), creates quadrilateral mesh, defaults to False

  • reorder – (optional), should the mesh be reordered

  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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 x == 0

  • 2: plane x == 1

  • 3: plane y == 0

  • 4: plane y == 1

firedrake.utility_meshes.UnitTetrahedronMesh(comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a mesh of the reference tetrahedron.

Parameters:
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

  • 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.UnitTriangleMesh(comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]

Generate a mesh of the reference triangle

Parameters:
  • comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

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

firedrake.utils.known_pyop2_safe(f)[source]

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

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

firedrake.utils.tuplify(item)[source]

Convert an object into a hashable equivalent.

This is particularly useful for caching dictionaries of parameters such as form_compiler_parameters from firedrake.assemble.assemble().

Parameters:

item – The object to attempt to ‘tuplify’.

Returns:

The object interpreted as a tuple. For hashable objects this is simply a 1-tuple containing item. For dictionaries the function is called recursively on the values of the dict. For example, {“a”: 5, “b”: 8} returns ((“a”, (5,)), (“b”, (8,))).

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

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

firedrake.variational_solver module

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

Bases: NonlinearVariationalProblem

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

Parameters:
  • a – the bilinear form

  • L – the linear form

  • u – the Function to which the solution will be assigned

  • bcs – the boundary conditions (optional)

  • aP – an optional operator to assemble to precondition the system (if not provided a preconditioner may be computed from a)

  • form_compiler_parameters (dict) – parameters to pass to the form compiler (optional)

  • constant_jacobian – (optional) flag indicating that the Jacobian is constant (i.e. does not depend on varying fields). If your Jacobian does not change, set this flag to True.

class firedrake.variational_solver.LinearVariationalSolver(problem, *, solver_parameters=None, options_prefix=None, nullspace=None, transpose_nullspace=None, near_nullspace=None, appctx=None, pre_jacobian_callback=None, post_jacobian_callback=None, pre_function_callback=None, post_function_callback=None)[source]

Bases: NonlinearVariationalSolver

Solves a LinearVariationalProblem.

Parameters:
  • problem – A LinearVariationalProblem to solve.

  • solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.

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

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

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

  • appctx – A dictionary containing application context that is passed to the preconditioner if matrix-free.

  • pre_jacobian_callback – A user-defined function that will be called immediately before Jacobian assembly. This can be used, for example, to update a coefficient function that has a complicated dependence on the unknown solution.

  • post_jacobian_callback – As above, but called after the Jacobian has been assembled.

  • pre_function_callback – As above, but called immediately before residual assembly.

  • post_function_callback – As above, but called immediately after residual assembly.

See also NonlinearVariationalSolver for nonlinear problems.

Parameters:
  • problem – A NonlinearVariationalProblem to solve.

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

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

  • near_nullspace – as for the nullspace, but used to specify the near nullspace (for multigrid solvers).

  • solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.

  • appctx – A dictionary containing application context that is passed to the preconditioner if matrix-free.

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

  • pre_jacobian_callback – A user-defined function that will be called immediately before Jacobian assembly. This can be used, for example, to update a coefficient function that has a complicated dependence on the unknown solution.

  • post_jacobian_callback – As above, but called after the Jacobian has been assembled.

  • pre_function_callback – As above, but called immediately before residual assembly.

  • post_function_callback – As above, but called immediately after residual assembly.

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

{'snes_type': 'ksponly'}

PETSc flag options (where the presence of the option means something) should be specified with None. For example:

{'snes_monitor': None}

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

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

solver = NonlinearVariationalSolver(problem,
                                    pre_jacobian_callback=update_diffusivity)
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'}
DEFAULT_SNES_PARAMETERS = {'snes_type': 'ksponly'}
invalidate_jacobian()[source]

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

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

Bases: NonlinearVariationalProblemMixin

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

Parameters:
  • F – the nonlinear form

  • u – the Function to solve for

  • bcs – the boundary conditions (optional)

  • J – the Jacobian J = dF/du (optional)

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

  • form_compiler_parameters (dict) – parameters to pass to the form compiler (optional)

Is_linear:

internally used to check if all domain/bc forms are given either in ‘A == b’ style or in ‘F == 0’ style.

dirichlet_bcs()[source]
dm[source]
class firedrake.variational_solver.NonlinearVariationalSolver(problem, *, solver_parameters=None, options_prefix=None, nullspace=None, transpose_nullspace=None, near_nullspace=None, appctx=None, pre_jacobian_callback=None, post_jacobian_callback=None, pre_function_callback=None, post_function_callback=None)[source]

Bases: OptionsManager, NonlinearVariationalSolverMixin

Solves a NonlinearVariationalProblem.

Parameters:
  • problem – A NonlinearVariationalProblem to solve.

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

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

  • near_nullspace – as for the nullspace, but used to specify the near nullspace (for multigrid solvers).

  • solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.

  • appctx – A dictionary containing application context that is passed to the preconditioner if matrix-free.

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

  • pre_jacobian_callback – A user-defined function that will be called immediately before Jacobian assembly. This can be used, for example, to update a coefficient function that has a complicated dependence on the unknown solution.

  • post_jacobian_callback – As above, but called after the Jacobian has been assembled.

  • pre_function_callback – As above, but called immediately before residual assembly.

  • post_function_callback – As above, but called immediately after residual assembly.

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

{'snes_type': 'ksponly'}

PETSc flag options (where the presence of the option means something) should be specified with None. For example:

{'snes_monitor': None}

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

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

solver = NonlinearVariationalSolver(problem,
                                    pre_jacobian_callback=update_diffusivity)
DEFAULT_KSP_PARAMETERS = {'ksp_rtol': 1e-05, 'ksp_type': 'preonly', 'mat_mumps_icntl_14': 200, 'mat_type': 'aij', 'pc_factor_mat_solver_type': 'mumps', 'pc_type': 'lu'}
DEFAULT_SNES_PARAMETERS = {'snes_linesearch_type': 'basic', 'snes_type': 'newtonls'}
set_transfer_manager(manager)[source]

Set the object that manages transfer between grid levels. Typically a TransferManager object.

Parameters:

manager – Transfer manager, should conform to the TransferManager interface.

Raises:

ValueError – if called after the transfer manager is setup.

solve(bounds=None)[source]

Solve the variational problem.

Parameters:

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

Note

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

firedrake.vector module

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

Bases: object

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

Parameters:

x – an Function to wrap or a Vector to copy. The former shares data, the latter copies data.

apply(action)[source]

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

array()[source]

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

axpy(a, x)[source]

Add a*x to self.

Parameters:
copy()[source]

Return a copy of this vector.

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

Gather a Vector to all processes

Parameters:

global_indices – the globally numbered indices to gather (should be the same on all processes). If None, gather the entire Vector.

get_local()[source]

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

inner(other)[source]

Return the l2-inner product of self with other

local_range()[source]

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

local_size()[source]

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

max()[source]

Return the maximum entry in the vector.

set_local(values)[source]

Set process local values

Parameters:

values – a numpy array of values of length Vector.local_size()

size()[source]

Return the global size of the data

sum()[source]

Return global sum of vector entries.

firedrake.vector.as_backend_type(tensor)[source]

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

firedrake.version module

firedrake.version.check()[source]

Module contents