firedrake package¶
Subpackages¶
- firedrake.adjoint package
- Submodules
- firedrake.adjoint.assembly module
- firedrake.adjoint.blocks module
- firedrake.adjoint.checkpointing module
- firedrake.adjoint.constant module
- firedrake.adjoint.dirichletbc module
- firedrake.adjoint.function module
- firedrake.adjoint.interpolate module
- firedrake.adjoint.mesh module
- firedrake.adjoint.projection module
- firedrake.adjoint.solving module
- firedrake.adjoint.variational_solver module
- Module contents
- firedrake.cython package
- firedrake.matrix_free package
- firedrake.mg package
- firedrake.preconditioners package
- Submodules
- firedrake.preconditioners.asm module
- firedrake.preconditioners.assembled module
- firedrake.preconditioners.base module
- firedrake.preconditioners.facet_split module
- firedrake.preconditioners.fdm module
- firedrake.preconditioners.gtmg module
- firedrake.preconditioners.hypre_ads module
- firedrake.preconditioners.hypre_ams module
- firedrake.preconditioners.low_order module
- firedrake.preconditioners.massinv module
- firedrake.preconditioners.patch module
- firedrake.preconditioners.pcd module
- firedrake.preconditioners.pmg module
- Module contents
- firedrake.slate package
- firedrake.slope_limiter package
Submodules¶
firedrake.assemble module¶
- firedrake.assemble.assemble(expr, *args, **kwargs)[source]¶
Evaluate expr.
- Parameters
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 theMeasure
in the form. For example, if aquadrature_degree
of 4 is specified in this argument, but a degree of 3 is requested in the measure, the latter will be used.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 aImplicitMatrix
giving matrix-free actions ('matfree'
). If not supplied, the default value inparameters["default_matrix_type"]
is used. BAIJ differs from AIJ in that only the block sparsity rather than the dof sparsity is constructed. This can result in some memory savings, but does not work with all PETSc preconditioners. BAIJ matrices only make sense for non-mixed matrices.sub_mat_type – String indicating the matrix type to use inside a nested block matrix. Only makes sense if
mat_type
isnest
. May be one of"aij"
or"baij"
. If not supplied, defaults toparameters["default_sub_matrix_type"]
.appctx – Additional information to hang on the assembled matrix if an implicit matrix is requested (mat_type
"matfree"
).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 isFalse
.
- Returns
See below.
If expr is a
Form
or Slate tensor expression then this evaluates the corresponding integral(s) and returns afloat
for 0-forms, aFunction
for 1-forms and aMatrix
orImplicitMatrix
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
Function
s in the expression. This will only succeed if all the Functions are on the sameFunctionSpace
.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 andexpr
is a 2-form, the rows and columns of the resultingMatrix
corresponding to boundary nodes will be set to 0 and the diagonal entries to 1. Ifexpr
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.assign module¶
- class firedrake.assign.Assigner(assignee, expression, subset=None)[source]¶
Bases:
object
Class performing pointwise assignment of an expression to a
firedrake.function.Function
.- Parameters
assignee – The
Function
being assigned to.expression – The
ufl.core.expr.Expr
to evaluate.subset – Optional subset (
pyop2.types.set.Subset
) to apply the assignment over.
- symbol = '='¶
- class firedrake.assign.CoefficientCollector[source]¶
Bases:
ufl.corealg.multifunction.MultiFunction
Multifunction used for converting an expression into a weighted sum of coefficients.
Calling
map_expr_dag(CoefficientCollector(), expr)
will return a tuple whose entries are of the form(coefficient, weight)
. Expressions that cannot be expressed as a weighted sum will raise an exception.Note: As well as being simple weighted sums (e.g.
u.assign(2*v1 + 3*v2)
), one can also assign constant expressions of the appropriate shape (e.g.u.assign(1.0)
oru.assign(2*v + 3)
). Therefore the returned tuple must be split sincecoefficient
may be either afiredrake.constant.Constant
orfiredrake.function.Function
.- float_value(o)¶
- int_value(o)¶
- zero(o)¶
- class firedrake.assign.IAddAssigner(assignee, expression, subset=None)[source]¶
Bases:
firedrake.assign.Assigner
Assigner class for
firedrake.function.Function.__iadd__
.- symbol = '+='¶
- class firedrake.assign.IDivAssigner(assignee, expression, subset=None)[source]¶
Bases:
firedrake.assign.Assigner
Assigner class for
firedrake.function.Function.__itruediv__
.- symbol = '/='¶
- class firedrake.assign.IMulAssigner(assignee, expression, subset=None)[source]¶
Bases:
firedrake.assign.Assigner
Assigner class for
firedrake.function.Function.__imul__
.- symbol = '*='¶
- class firedrake.assign.ISubAssigner(assignee, expression, subset=None)[source]¶
Bases:
firedrake.assign.Assigner
Assigner class for
firedrake.function.Function.__isub__
.- symbol = '-='¶
firedrake.bcs module¶
- class firedrake.bcs.DirichletBC(V, g, sub_domain, method=None)[source]¶
Bases:
firedrake.bcs.BCBase
,firedrake.adjoint.dirichletbc.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
onV
, or a UFL expression that can be interpolated intoV
, for example, aConstant
, an iterable of literal constants (converted to a UFL expression), or a literal constant which can be pointwise evaluated at the nodes ofV
.sub_domain – the integer id(s) of the boundary region over which the boundary condition should be applied. The string “on_boundary” may be used to indicate all of the boundaries of the domain. In the case of extrusion the
top
andbottom
strings are used to flag the bcs application on the top and bottom boundaries of the extruded mesh respectively.method – the method for determining boundary nodes. 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
orMatrix
to which the boundary condition should be applied.u – an optional current state. If
u
is supplied thenr
is taken to be a residual and the boundary condition nodes are set to the valueu-bc
. Supplyingu
has no effect ifr
is aMatrix
rather than aFunction
. Ifu
is absent, then the boundary condition nodes ofr
are set to the boundary condition values.
If
r
is aMatrix
, it will be assembled with a 1 on diagonals where the boundary condition applies and 0 in the corresponding rows and columns.
- property function_arg¶
The value of this boundary condition.
- homogenize()[source]¶
Convert this boundary condition into a homogeneous one.
Set the value to zero.
- restore()[source]¶
Restore the original value of this boundary condition.
This uses the value passed on instantiation of the object.
- set_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 forsub_domain – see
DirichletBC
.bcs – a list of
DirichletBC
s and/orEquationBC
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
- firedrake.bcs.homogenize(bc)[source]¶
Create a homogeneous version of a
DirichletBC
object and return it. Ifbc
is an iterable containing one or moreDirichletBC
objects, then return a list of the homogeneous versions of thoseDirichletBC
s.- Parameters
bc – a
DirichletBC
, or iterable object comprisingDirichletBC
(s).
firedrake.checkpointing module¶
- class firedrake.checkpointing.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.- 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.
- 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_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 ofh5py.Group.create_group()
to create anh5py.Group
object from anh5py.h5g.GroupID
constructed with a customh5py.h5p.PropGCID
object (often named gcpl); seeh5py.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.
- class firedrake.checkpointing.DumbCheckpoint(basename, single_file=True, mode=2, comm=None)[source]¶
Bases:
object
A very dumb checkpoint object.
This checkpoint object is capable of writing
Function
s to disk in parallel (using HDF5) and reloading them on the same number of processes and aMesh()
constructed identically.- Parameters
basename – the base name of the checkpoint file.
single_file – Should the checkpoint object use only a single 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
, orFILE_UPDATE
)comm – (optional) communicator the writes should be collective over.
This object can be used in a context manager (in which case it closes the file when the scope is exited).
Note
This object contains both a PETSc
Viewer
, used for storing and loadingFunction
data, and anh5py.File
opened on the same file handle. DO NOT callh5py.File.close()
on the latter, this will cause breakages.Warning
DumbCheckpoint class will be deprecated after 01/01/2023. Use
CheckpointFile
class instead.- 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 thebasename
used when creating theDumbCheckpoint
object. Ifsingle_file
isTrue
, then we write toBASENAME.h5
otherwise, each timenew_file()
is called, we create a new file with an increasing index. In this case the files created are:BASENAME_0.h5 BASENAME_1.h5 ... BASENAME_n.h5
with the index incremented on each invocation of
new_file()
(whenever the custom name is not provided).
- read_attribute(obj, name, default=None)[source]¶
Read an HDF5 attribute on a specified data object.
- Parameters
obj – The path to the data object.
name – The name of the attribute.
default – Optional default value to return. If not provided an
AttributeError
is raised if the attribute does not exist.
- set_timestep(t, idx=None)[source]¶
Set the timestep for output.
- Parameters
t – The timestep value.
idx – An optional timestep index to use, otherwise an internal index is used, incremented by 1 every time
set_timestep()
is called.
- store(function, name=None)[source]¶
Store a function in the checkpoint file.
- Parameters
function – The function to store.
name – an (optional) name to store the function under. If not provided, uses
function.name()
.
This function is 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
Function
s to disk in parallel (using HDF5) and reloading them on the same number of processes and aMesh()
constructed identically.- Parameters
filename – filename (including suffix .h5) of checkpoint file.
file_mode – the access mode, passed directly to h5py, see
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.
firedrake.constant module¶
- class firedrake.constant.Constant(*args, **kwargs)[source]¶
Bases:
ufl.coefficient.Coefficient
,firedrake.adjoint.constant.ConstantMixin
A “constant” coefficient
A
Constant
takes one value over the wholeMesh()
. The advantage of using aConstant
in a form rather than a literal value is that the constant will be passed as an argument to the generated kernel which avoids the need to recompile the kernel if the form is assembled for a different value of the constant.- Parameters
value – the value of the constant. May either be a scalar, an iterable of values (for a 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 aForm
on its own you need to pass aMesh()
as the domain argument.- assign(value)[source]¶
Set the value of this constant.
- Parameters
value – A value of the appropriate shape
- evaluate(x, mapping, component, index_values)[source]¶
Return the evaluation of this
Constant
.- Parameters
x – The coordinate to evaluate at (ignored).
mapping – A mapping (ignored).
component – The requested component of the constant (may be
None
or()
to obtain all components).index_values – ignored.
firedrake.dmhooks module¶
Firedrake uses PETSc for its linear and nonlinear solvers. The interaction is carried out through DM objects. These carry around any 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
oradd_hook()
.
- 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.
- firedrake.dmhooks.get_appctx(dm, default=None)¶
- 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.pop_appctx(dm, match=None)¶
- firedrake.dmhooks.pop_ctx_coarsener(dm, match=None)¶
- firedrake.dmhooks.pop_parent(dm, match=None)¶
- firedrake.dmhooks.push_appctx(dm, obj)¶
- 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_element_for_checkpointing(element)[source]¶
Convert the given UFL element to an element that
CheckpointFile
can handle.
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 dividecomm.size
exactly.
- allreduce(f, f_reduced, op=<mpi4py.MPI.Op object>)[source]¶
Allreduce a function f into f_reduced over
ensemble_comm
.- Parameters
f – The a
Function
to allreduce.f_reduced – the result of the reduction.
op – MPI reduction operator. Defaults to MPI.SUM.
- Raises
ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or if the functions are in different spaces
- bcast(f, root=0)[source]¶
Broadcast a function f over
ensemble_comm
from rank root- Parameters
f – The
Function
to broadcast.root – rank to broadcast from. Defaults to 0.
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
- iallreduce(f, f_reduced, op=<mpi4py.MPI.Op object>)[source]¶
Allreduce (non-blocking) a function f into f_reduced over
ensemble_comm
.- Parameters
f – The a
Function
to allreduce.f_reduced – the result of the reduction.
op – MPI reduction operator. Defaults to MPI.SUM.
- Returns
list of MPI.Request objects (one for each of f.subfunctions).
- Raises
ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or if the functions are in different spaces
- ibcast(f, root=0)[source]¶
Broadcast (non-blocking) a function f over
ensemble_comm
from rank root- Parameters
f – The
Function
to broadcast.root – rank to broadcast from. Defaults to 0.
- Returns
list of MPI.Request objects (one for each of f.subfunctions).
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
- irecv(f, source=- 2, tag=- 1)[source]¶
Receive (non-blocking) a function f over
ensemble_comm
from another ensemble rank.- Parameters
f – The a
Function
to receive intosource – the rank to receive from. Defaults to MPI.ANY_SOURCE.
tag – the tag of the message. Defaults to MPI.ANY_TAG.
- Returns
list of MPI.Request objects (one for each of f.subfunctions).
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
- ireduce(f, f_reduced, op=<mpi4py.MPI.Op object>, root=0)[source]¶
Reduce (non-blocking) a function f into f_reduced over
ensemble_comm
to rank root- Parameters
f – The a
Function
to reduce.f_reduced – the result of the reduction on rank root.
op – MPI reduction operator. Defaults to MPI.SUM.
root – rank to reduce to. Defaults to 0.
- Returns
list of MPI.Request objects (one for each of f.subfunctions).
- Raises
ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or is the functions are in different spaces
- isend(f, dest, tag=0)[source]¶
Send (non-blocking) a function f over
ensemble_comm
to another ensemble rank.- Parameters
f – The a
Function
to senddest – the rank to send to
tag – the tag of the message. Defaults to 0.
- Returns
list of MPI.Request objects (one for each of f.subfunctions).
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
- isendrecv(fsend, dest, sendtag=0, frecv=None, source=- 2, recvtag=- 1)[source]¶
Send a function fsend and receive a function frecv over
ensemble_comm
to another ensemble rank.- Parameters
- Returns
list of MPI.Request objects (one for each of fsend.subfunctions and frecv.subfunctions).
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
- recv(f, source=- 2, tag=- 1, statuses=None)[source]¶
Receive (blocking) a function f over
ensemble_comm
from another ensemble rank.- Parameters
f – The a
Function
to receive intosource – the rank to receive from. Defaults to MPI.ANY_SOURCE.
tag – the tag of the message. Defaults to MPI.ANY_TAG.
statuses – MPI.Status objects (one for each of f.subfunctions or None).
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
- reduce(f, f_reduced, op=<mpi4py.MPI.Op object>, root=0)[source]¶
Reduce a function f into f_reduced over
ensemble_comm
to rank root- Parameters
f – The a
Function
to reduce.f_reduced – the result of the reduction on rank root.
op – MPI reduction operator. Defaults to MPI.SUM.
root – rank to reduce to. Defaults to 0.
- Raises
ValueError – if function communicators mismatch each other or the ensemble spatial communicator, or is the functions are in different spaces
- send(f, dest, tag=0)[source]¶
Send (blocking) a function f over
ensemble_comm
to another ensemble rank.- Parameters
f – The a
Function
to senddest – the rank to send to
tag – the tag of the message. Defaults to 0
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
- sendrecv(fsend, dest, sendtag=0, frecv=None, source=- 2, recvtag=- 1, status=None)[source]¶
Send (blocking) a function fsend and receive a function frecv over
ensemble_comm
to another ensemble rank.- Parameters
fsend – The a
Function
to send.dest – the rank to send to.
sendtag – the tag of the send message. Defaults to 0.
frecv – The a
Function
to receive into.source – the rank to receive from. Defaults to MPI.ANY_SOURCE.
recvtag – the tag of the received message. Defaults to MPI.ANY_TAG.
status – MPI.Status object or None.
- Raises
ValueError – if function communicator mismatches the ensemble spatial communicator.
firedrake.exceptions module¶
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.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:
ufl.corealg.multifunction.MultiFunction
Extract a sub-block from a form.
- class IndexInliner[source]¶
Bases:
ufl.corealg.multifunction.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.
- 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.
- index_inliner = <firedrake.formmanipulation.ExtractSubBlock.IndexInliner object>¶
- split(form, argument_indices)[source]¶
Split a form.
- Parameters
form – the form to split.
argument_indices – indices of test and trial spaces to extract. This should be 0-, 1-, or 2-tuple (whose length is the same as the number of arguments as the
form
) whose entries are either an integer index, or else an iterable of indices.
Returns a new
ufl.classes.Form
on the selected subspace.
- class firedrake.formmanipulation.SplitForm(indices, form)¶
Bases:
tuple
Create new instance of SplitForm(indices, form)
- form¶
Alias for field number 1
- indices¶
Alias for field number 0
- firedrake.formmanipulation.split_form(form, diagonal=False)[source]¶
Split a form into a tuple of sub-forms defined on the component spaces.
Each entry is a
SplitForm
tuple of the indices into the component arguments and the form defined on that block.For example, consider the following code:
V = FunctionSpace(m, 'CG', 1) W = V*V*V u, v, w = TrialFunctions(W) p, q, r = TestFunctions(W) a = q*u*dx + p*w*dx
Then splitting the form returns a tuple of two forms.
((0, 2), w*p*dx), (1, 0), q*u*dx))
Due to the limited amount of simplification that UFL does, some of the returned forms may eventually evaluate to zero. The form compiler will remove these in its more complex simplification stages.
firedrake.function module¶
- class firedrake.function.CoordinatelessFunction(function_space, val=None, name=None, dtype=dtype('float64'))[source]¶
Bases:
ufl.coefficient.Coefficient
A function on a mesh topology.
- Parameters
function_space –
the
FunctionSpace
, orMixedFunctionSpace
on which to build thisFunction
.Alternatively, another
Function
may be passed here and its function space will be used to build thisFunction
.val – NumPy array-like (or
pyop2.types.dat.Dat
orVector
) providing initial values (optional). ThisFunction
will share data with the provided value.name – user-defined name for this
Function
(optional).dtype – optional data type for this
Function
(defaults toScalarType
).
- cell_node_map()[source]¶
Return the
pyop2.types.map.Map
from cels to function space nodes.
- property cell_set¶
The
pyop2.types.set.Set
of cells for the mesh on which thisFunction
is defined.
- copy(deepcopy=False)[source]¶
Return a copy of this CoordinatelessFunction.
- Parameters
deepcopy – If
True
, the newCoordinatelessFunction
will allocate new space and copy values. IfFalse
, the default, then the newCoordinatelessFunction
will share the dof values.
- property dof_dset¶
A
pyop2.types.dataset.DataSet
containing the degrees of freedom of thisFunction
.
- exterior_facet_node_map()[source]¶
Return the
pyop2.types.map.Map
from exterior facets to function space nodes.
- function_space()[source]¶
Return the
FunctionSpace
, orMixedFunctionSpace
on which thisFunction
is defined.
- interior_facet_node_map()[source]¶
Return the
pyop2.types.map.Map
from interior facets to function space nodes.
- property node_set¶
A
pyop2.types.set.Set
containing the nodes of thisFunction
. One or (for rank-1 and 2FunctionSpace
s) more degrees of freedom are stored at each node.
- rename(name=None, label=None)[source]¶
Set the name and or label of this
Function
- Parameters
name – The new name of the Function (if not None)
label – The new label for the Function (if not None)
- sub(i)[source]¶
Extract the ith sub
Function
of thisFunction
.- Parameters
i – the index to extract
See also
subfunctions
.If the
Function
is defined on a rank-nFunctionSpace
, this returns a proxy object indexing the ith component of the space, suitable for use in boundary condition application.
- subfunctions[source]¶
Extract any sub
Function
s defined on the component spaces of this thisFunction
’sFunctionSpace
.
- class firedrake.function.Function(function_space, val=None, name=None, dtype=dtype('float64'), count=None)[source]¶
Bases:
ufl.coefficient.Coefficient
,firedrake.adjoint.function.FunctionMixin
A
Function
represents a discretised field over the domain defined by the underlyingMesh()
. 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 aFunctionSpace
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 theFunctionSpace
.- Parameters
function_space – the
FunctionSpace
, orMixedFunctionSpace
on which to build thisFunction
. Alternatively, anotherFunction
may be passed here and its function space will be used to build thisFunction
. In this case, the function values are copied.val – NumPy array-like (or
pyop2.types.dat.Dat
) providing initial values (optional). If val is an existingFunction
, then the data will be shared.name – user-defined name for this
Function
(optional).dtype – optional data type for this
Function
(defaults toScalarType
).count – The
ufl.Coefficient
count which creates the symbolic identity of thisFunction
.
- assign(expr, subset=None)[source]¶
Set the
Function
value to the pointwise value of expr. expr may only containFunction
s on the sameFunctionSpace
as theFunction
being assigned to.Similar functionality is available for the augmented assignment operators +=, -=, *= and /=. For example, if f and g are both Functions on the same
FunctionSpace
then:f += 2 * g
will add twice g to f.
If present, subset must be an
pyop2.types.set.Subset
of thisFunction
’snode_set
. The expression will then only be assigned to the nodes on that subset.Note
Assignment can only be performed for simple weighted sum expressions and constant values. Things like
u.assign(2*v + Constant(3.0))
. For more complicated expressions (e.g. involving the product of functions)Function.interpolate()
should be used.
- at(arg, *args, **kwargs)[source]¶
Evaluate function at points.
- Parameters
arg – The point to locate.
args – Additional points.
dont_raise – Do not raise an error if a point is not found.
tolerance – Tolerence to use when checking if a point is in a cell. Default is the
MeshTopology.tolerance
of the mesh the function is defined on. Changing this from default will cause the spatial index to be rebuilt which can take some time.
- evaluate(coord, mapping, component, index_values)[source]¶
Get self from mapping and return the component asked for.
- function_space()[source]¶
Return the
FunctionSpace
, orMixedFunctionSpace
on which thisFunction
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
ontoself
.b
must be aFunction
or a UFL expression.This is equivalent to
project(b, self)
. Any of the additional arguments toproject()
may also be passed, and they will have their usual effect.
- sub(i)[source]¶
Extract the ith sub
Function
of thisFunction
.- Parameters
i – the index to extract
See also
subfunctions
.If the
Function
is defined on aVectorFunctionSpace()
orTensorFunctionSpace()
this returns a proxy object indexing the ith component of the space, suitable for use in boundary condition application.
- subfunctions[source]¶
Extract any sub
Function
s defined on the component spaces of this thisFunction
’sFunctionSpace
.
- property topological¶
The underlying coordinateless function.
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 existingufl.FiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
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 existingFiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned. In this case, the provided element must have an emptyvalue_shape()
.Note
The element that you provide must be a scalar element (with empty
value_shape
). If you already have an existingTensorElement
, you should pass it toFunctionSpace()
directly instead.
- firedrake.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 existingufl.FiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned. In this case, the provided element must have an emptyufl.FiniteElementBase.value_shape()
.Note
The element that you provide need be a scalar element (with empty
value_shape
), however, it should not be an existingVectorElement
. If you already have an existingVectorElement
, you should pass it toFunctionSpace()
directly instead.
firedrake.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.
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()
orTensorFunctionSpace()
.- 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 aMixedElement
, for which one should use theMixedFunctionSpace
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) haverank
0.Warning
Users should not build a
FunctionSpace
directly, instead they should use the utilityFunctionSpace()
function, which provides extra error checking and argument sanitising.- boundary_nodes(sub_domain)[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_map()[source]¶
Return the
pyop2.types.map.Map
from cels to function space nodes.
- component = None¶
The component of this space in its parent VectorElement space, or
None
.
- dim()[source]¶
The global number of degrees of freedom for this function space.
See also
FunctionSpace.dof_count
andFunctionSpace.node_count
.
- dof_count[source]¶
The number of degrees of freedom (includes halo dofs) of this function space on this process. Cf.
FunctionSpace.node_count
.
- dof_dset¶
A
pyop2.types.dataset.DataSet
representing the function space degrees of freedom.
- exterior_facet_node_map()[source]¶
Return the
pyop2.types.map.Map
from exterior facets to function space nodes.
- index = None¶
The position of this space in its parent
MixedFunctionSpace
, orNone
.
- interior_facet_node_map()[source]¶
Return the
pyop2.types.map.Map
from interior facets to function space nodes.
- local_to_global_map(bcs, lgmap=None)[source]¶
Return a map from process local dof numbering to global dof numbering.
If BCs is provided, mask out those dofs which match the BC nodes.
- make_dat(val=None, valuetype=None, name=None)[source]¶
Return a newly allocated
pyop2.types.dat.Dat
defined on thedof_dset
of thisFunction
.
- 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
hasFunctionSpace.rank
0, this is equal to theFunctionSpace.dof_count
, otherwise theFunctionSpace.dof_count
isdim
times thenode_count
.
- node_set¶
A
pyop2.types.set.Set
representing the function space nodes.
- parent = None¶
The parent space if this space was extracted from one, or
None
.
- rank¶
The rank of this
FunctionSpace
. Spaces where the element is scalar-valued (or intrinsically vector-valued) have rank zero. Spaces built onVectorElement
orTensorElement
instances have rank equivalent to the number of components of theirvalue_shape()
.
- 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: firedrake.functionspaceimpl.FunctionSpace, parent: Optional[firedrake.functionspaceimpl.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[firedrake.functionspaceimpl.WithGeometry]¶
- topological: firedrake.functionspaceimpl.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 byMixedFunctionSpace()
.- cell_node_map()[source]¶
A
pyop2.types.map.MixedMap
from theMesh.cell_set
of the underlying mesh to thenode_set
of thisMixedFunctionSpace
. This is composed of theFunctionSpace.cell_node_map
s of the underlyingFunctionSpace
s of which thisMixedFunctionSpace
is composed.
- component = None¶
- dim()[source]¶
The global number of degrees of freedom for this function space.
See also
FunctionSpace.dof_count
andFunctionSpace.node_count
.
- dof_count[source]¶
Return a tuple of
FunctionSpace.dof_count
s of theFunctionSpace
s of which thisMixedFunctionSpace
is composed.
- dof_dset[source]¶
A
pyop2.types.dataset.MixedDataSet
containing the degrees of freedom of thisMixedFunctionSpace
. This is composed of theFunctionSpace.dof_dset
s of the underlyingFunctionSpace
s of which thisMixedFunctionSpace
is composed.
- exterior_facet_node_map()[source]¶
Return the
pyop2.types.map.Map
from exterior facets to function space nodes.
- index = None¶
- interior_facet_node_map()[source]¶
Return the
pyop2.types.map.MixedMap
from interior facets to function space nodes.
- local_to_global_map(bcs)[source]¶
Return a map from process local dof numbering to global dof numbering.
If BCs is provided, mask out those dofs which match the BC nodes.
- make_dat(val=None, valuetype=None, name=None)[source]¶
Return a newly allocated
pyop2.types.dat.MixedDat
defined on thedof_dset
of thisMixedFunctionSpace
.
- node_count[source]¶
Return a tuple of
FunctionSpace.node_count
s of theFunctionSpace
s of which thisMixedFunctionSpace
is composed.
- node_set[source]¶
A
pyop2.types.set.MixedSet
containing the nodes of thisMixedFunctionSpace
. This is composed of theFunctionSpace.node_set
s of the underlyingFunctionSpace
s thisMixedFunctionSpace
is composed of one or (for VectorFunctionSpaces) more degrees of freedom are stored at each node.
- num_sub_spaces()[source]¶
Return the number of
FunctionSpace
s of which thisMixedFunctionSpace
is composed.
- parent = None¶
- rank = 1¶
- sub(i)[source]¶
Return the i`th :class:`FunctionSpace in this
MixedFunctionSpace
.
- subfunctions[source]¶
The list of
FunctionSpace
s of which thisMixedFunctionSpace
is composed.
- 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_size
s of theFunctionSpace
s thisMixedFunctionSpace
is composed of.
- class firedrake.functionspaceimpl.ProxyFunctionSpace(mesh, element, name=None)[source]¶
Bases:
firedrake.functionspaceimpl.FunctionSpace
A
FunctionSpace
that one can attach extra properties to.- Parameters
mesh – The mesh to use.
element – The UFL element.
name – The name of the function space.
Warning
Users should not build a
ProxyFunctionSpace
directly, it is mostly used as an internal implementation detail.- identifier = None¶
An optional identifier, for debugging purposes.
- make_dat(*args, **kwargs)[source]¶
Create a
pyop2.types.dat.Dat
.- Raises
ValueError – if
no_dats
isTrue
.
- no_dats = False¶
Can this proxy make
pyop2.types.dat.Dat
objects
- class firedrake.functionspaceimpl.RealFunctionSpace(mesh, element, name)[source]¶
Bases:
firedrake.functionspaceimpl.FunctionSpace
FunctionSpace
based on elements of family “Real”. A :class`RealFunctionSpace` only has a single global value for the whole mesh.This class should not be directly instantiated by users. Instead, FunctionSpace objects will transform themselves into
RealFunctionSpace
objects as appropriate.- bottom_nodes()[source]¶
RealFunctionSpace
objects have no bottom nodes.
- cell_node_map(bcs=None)[source]¶
RealFunctionSpace
objects have no cell node map.
- dim()[source]¶
The global number of degrees of freedom for this function space.
See also
FunctionSpace.dof_count
andFunctionSpace.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.types.glob.Global
representing the data for aFunction
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 onVectorElement
orTensorElement
instances have rank equivalent to the number of components of theirvalue_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:
ufl.functionspace.FunctionSpace
Attach geometric information to a
FunctionSpace
.Function spaces on meshes with different geometry but the same topology can share data, except for their UFL cell. This class facilitates that.
Users should not instantiate a
WithGeometry
object explicitly except in a small number of cases.When instantiating a
WithGeometry
, users should callWithGeometry.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
.cargo –
FunctionSpaceCargo
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.
- 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.
- get_work_function(zero=True)[source]¶
Get a temporary work
Function
on thisFunctionSpace
.- Parameters
zero – Should the
Function
be guaranteed zero? Ifzero
isFalse
the returned function may or may not be zeroed, and the user is responsible for appropriate zeroing.- Raises
ValueError – if
max_work_functions
are already checked out.
Note
This method is intended to be used for 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.
- property topological¶
- ufl_function_space()[source]¶
The
FunctionSpace
this object represents.
firedrake.halo module¶
- class firedrake.halo.Halo(dm, section, comm)[source]¶
Bases:
pyop2.types.halo.Halo
Build a Halo for a function space.
- Parameters
dm – The DM describing the topology.
section – The data layout.
The halo is implemented using a PETSc SF (star forest) object and is usable as a PyOP2
pyop2.types.halo.Halo
.- global_to_local_begin(dat, insert_mode)[source]¶
Begin an exchange from global (assembled) to local (ghosted) representation.
- Parameters
dat – The
pyop2.types.dat.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
pyop2.types.dat.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
pyop2.types.dat.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
pyop2.types.dat.Dat
to exchange.insert_mode – The insertion mode.
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
orFunction
to interpolate into.subset – An optional
pyop2.types.set.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 theInterpolator
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 theFunction
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 existingFunction
).subset – An optional
pyop2.types.set.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 spaceV
(orV
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:
firedrake.petsc.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 suppliedA
is used to construct the preconditioner.parameters – (optional) dict of solver parameters.
nullspace – an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
spanning the null space of the operator.transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
near_nullspace – as for the nullspace, but used to set the near nullpace.
options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the
solver_parameters
dict.
Note
Any boundary conditions for this solve must have been applied when assembling the operator.
- 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'}¶
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 toNone
, all ranks will use the provided handler. This could be used, for example, if you want to log to one file per rank.
firedrake.matrix module¶
- class firedrake.matrix.ImplicitMatrix(a, bcs, *args, **kwargs)[source]¶
Bases:
firedrake.matrix.MatrixBase
A representation of the action of bilinear form operating without explicitly assembling the associated matrix. This class wraps the relevant information for Python PETSc matrix.
- Parameters
- class firedrake.matrix.Matrix(a, bcs, mat_type, *args, **kwargs)[source]¶
Bases:
firedrake.matrix.MatrixBase
A representation of an assembled bilinear form.
- Parameters
A
pyop2.types.mat.Mat
will be built from the remaining arguments, for valid values, seepyop2.types.mat.Mat
source code.
- 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¶
- class firedrake.mesh.AbstractMeshTopology(name, tolerance=1.0)[source]¶
Bases:
object
A representation of an abstract mesh topology without a concrete PETSc DM implementation
Initialise an abstract mesh topology.
- Parameters
name – name of the mesh
tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell. Defaults to 1.0. Note that this tolerance uses an L1 distance (aka ‘manhatten’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.
- abstract property cell_closure¶
2D array of ordered cell closures
Each row contains ordered cell entities for a cell, one row per cell.
- cell_orientations()[source]¶
Return the orientation of each cell in the mesh.
Use
init_cell_orientations()
on the mesh geometry to initialise.
- abstract property cell_set¶
- cell_subset(subdomain_id, all_integer_subdomain_ids=None)[source]¶
Return a subset over cells with the given subdomain_id.
- Parameters
subdomain_id – The subdomain of the mesh to iterate over. Either an integer, an iterable of integers or the special subdomains
"everywhere"
or"otherwise"
.all_integer_subdomain_ids –
- Information to interpret the
"otherwise"
subdomain."otherwise"
means all entities not explicitly enumerated by the integer subdomains provided here. For example, if all_integer_subdomain_ids is empty, then"otherwise" == "everywhere"
. If it contains(1, 2)
, then"otherwise"
is all entities except those marked by subdomains 1 and 2.
- returns
A
pyop2.types.set.Subset
for iteration.
- abstract property cell_to_facets¶
Returns a
pyop2.types.dat.Dat
that maps from a cell index to the local facet types on each cell, including the relevant subdomain markers.The i-th local facet on a cell with index c has data cell_facet[c][i]. The local facet is exterior if cell_facet[c][i][0] == 0, and interior if the value is 1. The value cell_facet[c][i][1] returns the subdomain marker of the facet.
- property comm¶
- create_section(nodes_per_entity, real_tensorproduct=False, block_size=1)[source]¶
Create a PETSc Section describing a function space.
- Parameters
nodes_per_entity – number of function space nodes per topological entity.
real_tensorproduct – If True, assume extruded space is actually Foo x Real.
block_size – The integer by which nodes_per_entity is uniformly multiplied to get the true data layout.
- Returns
a new PETSc Section.
- abstract property entity_orientations¶
2D array of entity orientations
entity_orientations has the same shape as cell_closure. Each row of this array contains orientations of the entities in the closure of the associated cell. Here, for each cell in the mesh, orientation of an entity, say e, encodes how the the canonical representation of the entity defined by Cone(e) compares to that of the associated entity in the reference FInAT (FIAT) cell. (Note that cell_closure defines how each cell in the mesh is mapped to the FInAT (FIAT) reference cell and each entity of the FInAT (FIAT) reference cell has a canonical representation based on the entity ids of the lower dimensional entities.) Orientations of vertices are always 0. See
FIAT.reference_element.Simplex
andFIAT.reference_element.UFCQuadrilateral
for example computations of orientations.
- abstract property exterior_facets¶
- abstract property interior_facets¶
- layers = None¶
No layers on unstructured mesh
- make_cell_node_list(global_numbering, entity_dofs, entity_permutations, offsets)[source]¶
Builds the DoF mapping.
- Parameters
global_numbering – Section describing the global DoF numbering
entity_dofs – FInAT element entity DoFs
entity_permutations – FInAT element entity permutations
offsets – layer offsets for each entity dof (may be None).
- make_dofs_per_plex_entity(entity_dofs)[source]¶
Returns the number of DoFs per plex entity for each stratum, i.e. [#dofs / plex vertices, #dofs / plex edges, …].
- Parameters
entity_dofs – FInAT element entity DoFs
- make_offset(entity_dofs, ndofs, real_tensorproduct=False)[source]¶
Returns None (only for extruded use).
- abstract mark_entities(tf, label_name, label_value)[source]¶
Mark selected entities.
- Parameters
tf – The
CoordinatelessFunction
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “HDiv Trace ” (degree 0) to mark facet entities.label_name – The name of the label to store entity selections.
lable_value – The value used in the label.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- measure_set(integral_type, subdomain_id, all_integer_subdomain_ids=None)[source]¶
Return an iteration set appropriate for the requested integral type.
- Parameters
integral_type – The type of the integral (should be a valid UFL measure).
subdomain_id – The subdomain of the mesh to iterate over. Either an integer, an iterable of integers or the special subdomains
"everywhere"
or"otherwise"
.all_integer_subdomain_ids –
- Information to interpret the
"otherwise"
subdomain."otherwise"
means all entities not explicitly enumerated by the integer subdomains provided here. For example, if all_integer_subdomain_ids is empty, then"otherwise" == "everywhere"
. If it contains(1, 2)
, then"otherwise"
is all entities except those marked by subdomains 1 and 2. This should be a dict mappingintegral_type
to the explicitly enumerated subdomain ids.
- returns
A
pyop2.types.set.Subset
for iteration.
- node_classes(nodes_per_entity, real_tensorproduct=False)[source]¶
Compute node classes given nodes per entity.
- Parameters
nodes_per_entity – number of function space nodes per topological entity.
- Returns
the number of nodes in each of core, owned, and ghost classes.
- property tolerance¶
The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell.
Should always be set via the
MeshGeometry.tolerance
to ensure the spatial index is updated as necessary.
- property topological¶
Alias of topology.
This is to ensure consistent naming for some multigrid codes.
- property topology¶
The underlying mesh topology object.
- topology_dm¶
The PETSc DM representation of the mesh topology.
- ufl_cell()[source]¶
The UFL
Cell
associated with the mesh.Note
By convention, the UFL cells which specifically represent a mesh topology have geometric dimension equal their topological dimension. This is true even for immersed manifold meshes.
- ufl_mesh()[source]¶
The UFL
Mesh
associated with the mesh.Note
By convention, the UFL cells which specifically represent a mesh topology have geometric dimension equal their topological dimension. This convention will be reflected in this UFL mesh and is true even for immersed manifold meshes.
- variable_layers = False¶
No variable layers on unstructured mesh
- firedrake.mesh.DEFAULT_MESH_NAME = 'firedrake_default'¶
The default name of the mesh.
- class firedrake.mesh.DistributedMeshOverlapType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Bases:
enum.Enum
How should the mesh overlap be grown for distributed meshes?
Possible options are:
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, tolerance=1.0)[source]¶
Build an extruded mesh from an input mesh
- Parameters
mesh – the unstructured base mesh
layers – number of extruded cell layers in the “vertical” direction. One may also pass an array of shape (cells, 2) to specify a variable number of layers. In this case, each entry is a pair
[a, b]
wherea
indicates the starting cell layer of the column andb
the number of cell layers in that column.layer_height – the layer height. 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. Seemake_extruded_coords()
for more details.gdim – number of spatial dimensions of the resulting mesh (this is only used if a custom kernel is provided)
name – optional name for the extruded mesh.
tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell. Default is 1.0. Note that this tolerance uses an L1 distance (aka ‘manhatten’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.
The various values of
extrusion_type
have the following meanings:"uniform"
the extruded mesh has an extra spatial dimension compared to the base mesh. The layers exist in this dimension only.
"radial"
the extruded mesh has the same number of spatial dimensions as the base mesh; the cells are radially extruded outwards from the origin. This requires the base mesh to have topological dimension strictly smaller than geometric dimension.
"radial_hedgehog"
similar to radial, but the cells are extruded in the direction of the outward-pointing cell normal (this produces a P1dgxP1 coordinate field). In this case, a radially extruded coordinate field (generated with
extrusion_type="radial"
) is available in theradial_coordinates
attribute."custom"
use a custom kernel to generate the extruded coordinates
For more details see the manual section on extruded meshes.
- firedrake.mesh.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 valueNone
(usethe 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 growthe mesh overlap. The first entry should be a
DistributedMeshOverlapType
instance, the second the number of levels of overlap.
distribution_name – the name of parallel distribution used when checkpointing; if not given, the name is automatically generated.
permutation_name – the name of entity permutation (reordering) used when checkpointing; if not given, the name is automatically generated.
comm – the communicator to use when creating the mesh. If not supplied, then the mesh will be created on COMM_WORLD. If
meshfile
is a DMPlex object then must be indentical to or congruent with the DMPlex communicator.tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell. Defaults to 1.0. Increase this if point at mesh boundaries (either rank local or global) are reported as being outside the mesh, for example when creating a
VertexOnlyMesh
. Note that this tolerance uses an L1 distance (aka ‘manhatten’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.
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).
- class firedrake.mesh.MeshGeometry(element)[source]¶
Bases:
ufl.domain.Mesh
,firedrake.adjoint.mesh.MeshGeometryMixin
A representation of mesh topology and geometry.
Initialise a mesh geometry from coordinates.
- Parameters
coordinates – a coordinateless function containing the coordinates
- cell_sizes[source]¶
A :class`~.Function` in the \(P^1\) space containing the local mesh size.
This is computed by the \(L^2\) projection of the local mesh element size.
- clear_cell_sizes()[source]¶
Reset the
cell_sizes
field on this mesh geometry.Use this if you move the mesh.
- clear_spatial_index()[source]¶
Reset the
spatial_index
on this mesh geometry.Use this if you move the mesh (for example by reassigning to the coordinate field).
- init()[source]¶
Finish the initialisation of the mesh. Most of the time this is carried out automatically, however, in some cases (for example accessing a property of the mesh directly after constructing it) you need to call this manually.
- init_cell_orientations(expr)[source]¶
Compute and initialise meth:cell_orientations relative to a specified orientation.
- Parameters
expr – a UFL expression evaluated to produce a reference normal direction.
- locate_cell(x, tolerance=None)[source]¶
Locate cell containing a given point.
- Parameters
x – point coordinates
tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s
tolerance
property. Changing this from default will cause the spatial index to be rebuilt which can take some time.
- Returns
cell number (int), or None (if the point is not in the domain)
- locate_cell_and_reference_coordinate(x, tolerance=None)[source]¶
Locate cell containing a given point and the reference coordinates of the point within the cell.
- Parameters
x – point coordinates
tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s :attr:` property. Changing this from default will cause the spatial index to be rebuilt which can take some time.
- Returns
tuple either (cell number, reference coordinates) (int, numpy array), or (None, None) (point is not in the domain)
- locate_reference_coordinate(x, tolerance=None)[source]¶
Get reference coordinates of a given point in its cell. Which cell the point is in can be queried with the locate_cell method.
- Parameters
x – point coordinates
tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s
tolerance
property. Changing this from default will cause the spatial index to be rebuilt which can take some time.
- Returns
reference coordinates within cell (numpy array) or None (if the point is not in the domain)
- mark_entities(f, label_name, label_value)[source]¶
Mark selected entities.
- Parameters
f – The
Function
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “HDiv Trace ” (degree 0) to mark facet entities.label_name – The name of the label to store entity selections.
lable_value – The value used in the label.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- spatial_index[source]¶
Spatial index to quickly find which cell contains a given point.
Notes
If this mesh has a
tolerance
property, which should be a float, this tolerance is added to the extrama of the spatial index so that points just outside the mesh, within tolerance, can be found.
- property tolerance¶
The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell.
Increase this if points at mesh boundaries (either rank local or global) are reported as being outside the mesh, for example when creating a
VertexOnlyMesh
. Note that this tolerance uses an L1 distance (aka ‘manhatten’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.If this property is not set (i.e. set to
None
) no tolerance is added to the bounding box and points deemed at all outside the mesh, even by floating point error distances, will be deemed to be outside it.Notes
Modifying this property will modify the
MeshTopology.tolerance
property of the underlying mesh topology. Furthermore, after changing it any requests forspatial_index
will cause the spatial index to be rebuilt with the new tolerance which may take some time.
- property topological¶
Alias of topology.
This is to ensure consistent naming for some multigrid codes.
- property topology¶
The underlying mesh topology object.
- class firedrake.mesh.MeshTopology(plex, name, reorder, distribution_parameters, sfXB=None, perm_is=None, distribution_name=None, permutation_name=None, comm=<mpi4py.MPI.Intracomm object>, tolerance=1.0)[source]¶
Bases:
firedrake.mesh.AbstractMeshTopology
A representation of mesh topology implemented on a PETSc DMPlex.
Half-initialise a mesh topology.
- Parameters
plex – PETSc DMPlex representing the mesh topology
name – name of the mesh
reorder – whether to reorder the mesh (bool)
distribution_parameters – options controlling mesh distribution, see
Mesh()
for details.sfXB – PETSc PetscSF that pushes forward the global point number slab \([0, NX)\) to input (naive) plex (only significant when the mesh topology is loaded from file and only passed from inside
CheckpointFile
).perm_is – PETSc IS that is used as _plex_renumbering; only makes sense if we know the exact parallel distribution of plex at the time of mesh topology construction like when we load mesh along with its distribution. If given, reorder param will be ignored.
distribution_name – name of the parallel distribution; if None, automatically generated.
permutation_name – name of the entity permutation (reordering); if None, automatically generated.
comm – MPI communicator
tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell. Default is 1.0. Note that this tolerance uses an L1 distance (aka ‘manhatten’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.
- cell_closure[source]¶
2D array of ordered cell closures
Each row contains ordered cell entities for a cell, one row per cell.
- cell_to_facets[source]¶
Returns a
pyop2.types.dat.Dat
that maps from a cell index to the local facet types on each cell, including the relevant subdomain markers.The i-th local facet on a cell with index c has data cell_facet[c][i]. The local facet is exterior if cell_facet[c][i][0] == 0, and interior if the value is 1. The value cell_facet[c][i][1] returns the subdomain marker of the facet.
- get_partitioner()[source]¶
Get partitioner actually used for (re)distributing underlying plex over comm.
- mark_entities(tf, label_name, label_value)[source]¶
Mark selected entities.
- Parameters
tf – The
CoordinatelessFunction
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “HDiv Trace ” (degree 0) to mark facet entities.label_name – The name of the label to store entity selections.
lable_value – The value used in the label.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- set_partitioner(distribute, partitioner_type=None)[source]¶
Set partitioner for (re)distributing underlying plex over comm.
- Parameters
distribute – Boolean or (sizes, points)-tuple. If (sizes, point)- tuple is given, it is used to set shell partition. If Boolean, no-op.
partitioner_type – Partitioner to be used: “chaco”, “ptscotch”, “parmetis”, “shell”, or None (unspecified). Ignored if the distribute parameter specifies the distribution.
- sfBC¶
The PETSc SF that pushes the input (naive) plex to current (good) plex.
- sfXB¶
The PETSc SF that pushes the global point number slab [0, NX) to input (naive) plex.
- topology_dm¶
The PETSc DM representation of the mesh topology.
- firedrake.mesh.RelabeledMesh(mesh, indicator_functions, subdomain_ids, **kwargs)[source]¶
Construct a new mesh that has new subdomain ids.
- Parameters
mesh – base
MeshGeometry
object using which the new one is constructed.indicator_functions – list of indicator functions that mark selected entities (cells or facets) as 1; must use “DP”/”DQ” (degree 0) functions to mark cell entities and “HDiv Trace” (degree 0) functions to mark facet entities.
subdomain_ids – list of subdomain ids associated with the indicator functions in indicator_functions; thus, must have the same length as indicator_functions.
name – optional name of the output mesh object.
- firedrake.mesh.SubDomainData(geometric_expr)[source]¶
Creates a subdomain data object from a boolean-valued UFL expression.
The result can be attached as the subdomain_data field of a
ufl.Measure
. For example:x = mesh.coordinates sd = SubDomainData(x[0] < 0.5) assemble(f*dx(subdomain_data=sd))
- firedrake.mesh.VertexOnlyMesh(mesh, vertexcoords, missing_points_behaviour=None, tolerance=None, redundant=True)[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 relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a mesh cell and still be considered to be in the cell. Note that this tolerance uses an L1 distance (aka ‘manhatten’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh. The default is the parent mesh’s
tolerance
property. Changing this from default will cause the parent mesh’s spatial index to be rebuilt which can take some time.redundant – If True, the mesh will be built using just the vertices which are specified on rank 0. If False, the mesh will be built using the vertices specified by each rank. Care must be taken when using
redundant = False
: see the note below for more information.
Note
The vertex only mesh uses the same communicator as the input
mesh
.Note
Manifold meshes and extruded meshes with variable extrusion layers are not yet supported.
Note
When running in parallel with
redundant = False
,vertexcoords
are strictly confined to the localmesh
cells of that rank. This means that if rank A hasvertexcoords
{X} that are not found in the mesh cells owned by rank A but are found in the mesh cells owned by ank B, and rank B has not been supplied with thosevertexcoords
, then thevertexcoords
{X} will be lost.This can be avoided by either
making sure that rank 0 has all vertex coordinates and setting
redundant = True
or byensuring that
vertexcoords
are already found in cells owned by themesh
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” solutionuh – a
Function
containing the approximate solutionnorm_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 ofnorm_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 theQxQ
block. We can do this like sonullspace = MixedVectorSpaceBasis(W, [W[0], VectorSpaceBasis(constant=True)]) solve(a == ..., nullspace=nullspace)
- class firedrake.nullspace.VectorSpaceBasis(vecs=None, constant=False, comm=None)[source]¶
Bases:
object
Build a basis for a vector space.
You can use this basis to express the null space of a singular operator.
- Parameters
Note
Before using this object in a solver, you must ensure that the basis is orthonormal. You can do this by calling
orthonormalize()
, this modifies the provided vectors in place.Warning
The vectors you pass in to this object are not copied. You should therefore not modify them after instantiation since the basis will then be incorrect.
- check_orthogonality(orthonormal=True)[source]¶
Check if the basis is orthogonal.
- Parameters
orthonormal – If True check that the basis is also orthonormal.
- Raises
ValueError – If the basis is not orthogonal/orthonormal.
- nullspace(comm=None)[source]¶
The PETSc NullSpace object for this
VectorSpaceBasis
.- Parameters
comm – DEPRECATED pass to VectorSpaceBasis.__init__().
- orthogonalize(b)[source]¶
Orthogonalize
b
with respect to thisVectorSpaceBasis
.- Parameters
b – a
Function
Note
Modifies
b
in place.
firedrake.optimizer module¶
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
ufl.sobolevspace.SobolevSpace
object: H1 for a continuous output and L2 for a discontinuous output.adaptive – allow different meshes at different exports if True.
Note
Visualisation is only possible for Lagrange fields (either continuous or discontinuous). All other fields are first either projected or interpolated to Lagrange elements before storing for visualisation purposes.
firedrake.parameters module¶
The parameters dictionary contains global parameter settings.
- 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.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_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.parloops module¶
This module implements parallel loops reading and writing
Function
s. 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 writesFunction
s 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 passdirect
to designate a direct loop.args – is a dictionary mapping variable names in the kernel to
Function
s or components of mixedFunction
s and indicates how theseFunction
s are to be accessed.kernel_kwargs – keyword arguments to be passed to the
pyop2.Kernel
constructorkwargs – additional keyword arguments are passed to the underlying
pyop2.par_loop
iterate –
Optionally specify which region of an
pyop2.types.set.ExtrudedSet
to iterate over. Valid values are the following objects from pyop2:ON_BOTTOM
: iterate over the bottom layer of cells.ON_TOP
iterate over the top layer of cells.ALL
iterate over all cells (the default if unspecified)ON_INTERIOR_FACETS
iterate over all the layers except the top layer, accessing data two adjacent (in the extruded direction) cells at a time.
Example
Assume that A is a
Function
in CG1 and B is aFunction
in DG0. Then the following code sets each DoF in A to the maximum value that B attains in the cells adjacent to that DoF:A.assign(numpy.finfo(0.).min) par_loop('for (int i=0; i<A.dofs; i++) A[i] = 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
orConstant
and an argument intent. The string is the c language variable name by which this function will be accessed in the kernel. The argument intent indicates how the kernel will access this variable:- READ
The variable will be read but not written to.
- WRITE
The variable will be written to but not read. If multiple kernel invocations write to the same DoF, then the order of these writes is undefined.
- RW
The variable will be both read and written to. If multiple kernel invocations access the same DoF, then the order of these accesses is undefined, but it is guaranteed that no race will occur.
- INC
The variable will be added into using +=. As before, the order in which the kernel invocations increment the variable is undefined, but there is a guarantee that no races will occur.
Note
Only READ intents are valid for
Constant
coefficients, and an error will be raised in other cases.The measure
The measure determines the mesh entities over which the iteration will occur, and the size of the kernel stencil. The iteration will occur over the same mesh entities as if the measure had been used to define an integral, and the stencil will likewise be the same as the integral case. That is to say, if the measure is a volume measure, the kernel will be called once per cell and the DoFs accessible to the kernel will be those associated with the cell, its facets, edges and vertices. If the measure is a facet measure then the iteration will occur over the corresponding class of facets and the accessible DoFs will be those on the cell(s) adjacent to the facet, and on the facets, edges and vertices adjacent to those facets.
For volume measures the DoFs are guaranteed to be in the FInAT local DoFs order. For facet measures, the DoFs will be in sorted first by the cell to which they are adjacent. Within each cell, they will be in FInAT order. Note that if a continuous
Function
is accessed via an internal facet measure, the DoFs on the interface between the two facets will be accessible twice: once via each cell. The orientation of the cell(s) relative to the current facet is currently arbitrary.A direct loop over nodes without any indirections can be specified by passing
direct
as the measure. In this case, all of the arguments must beFunction
s in the sameFunctionSpace
.The kernel code
The kernel code is plain C in which the variables specified in the args dictionary are available to be read or written in according to the argument intent specified. Most basic C operations are permitted. However there are some restrictions:
Only functions from math.h may be called.
Pointer operations other than dereferencing arrays are prohibited.
Indirect free variables referencing
Function
s are all of type double*. 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, andj
runs over components.In a direct
par_loop()
, the variables will all be of type double* with the single index being the vector component.Constant
s are always of type double*, both for indirect and directpar_loop()
calls.
firedrake.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 fromparameters
will be considered. If no trailing underscore is provided, one is appended. Hencefoo_
andfoo
are treated equivalently. As an exception, if the prefix is the empty string, no underscore is appended.
To use this, you must call its constructor to with the parameters you want in the options database.
You then call
set_from_options()
, passing the PETSc object you’d like to callsetFromOptions
on. Note that this will actually only callsetFromOptions
the first time (so really this parameters object is a 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
orKSPSolve
call. Do that using theinserted_options()
context manager.with self.inserted_options(): self.snes.solve(...)
This ensures that the options database has the relevant entries for the duration of the
with
block, before removing them afterwards. This is a much more robust way of dealing with the 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>¶
firedrake.plot module¶
- firedrake.plot.plot(function, *args, bezier=False, num_sample_points=10, complex_component='real', **kwargs)[source]¶
Plot a 1D Firedrake
Function
- Parameters
- Returns
list of matplotlib
Line2D
- firedrake.plot.quiver(function, *, complex_component='real', **kwargs)[source]¶
Make a quiver plot of a 2D vector Firedrake
Function
- 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 plotresolution – 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 plotargs – 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 plotargs – 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 meshinterior_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 plotargs – 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.pointquery_utils module¶
- firedrake.pointquery_utils.celldist_l1_c_expr(fiat_cell, X='X')[source]¶
Generate a C expression of type PetscReal to compute the L1 distance (aka ‘manhatten’, ‘taxicab’ or rectilinear distance) to a FIAT reference cell.
- Parameters
- fiat_cellFIAT cell
The FIAT cell with same geometric dimension as the coordinate X.
- Xstr
The name of the input pointer variable to use.
- celldiststr
The name of the output variable.
- Returns
- str
A string of C code.
- 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.inside_check(fiat_cell, eps, X='X')[source]¶
Generate a C expression which is true if a point is inside a FIAT reference cell and false otherwise.
- Parameters
- fiat_cellFIAT Cell
The FIAT cell with same geometric dimension as the coordinate X.
- epsfloat
The tolerance to use for the check. Usually some small number like 1e-14.
- Xstr
The name of the input pointer variable to use in the generated C code: it should be a pointer to a type that is an acceptable input to the PetscRealPart function. Default is “X”.
- celldiststr
The name of the output variable.
- Returns
- str
A C expression which is true if the point is inside the cell and false otherwise.
firedrake.progress_bar module¶
A module providing progress bars.
- class firedrake.progress_bar.ProgressBar(*args, comm=<mpi4py.MPI.Intracomm object>, **kwargs)[source]¶
Bases:
progress.bar.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 aProgressBar
:>>> 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 aFunction
and belongs to the same function space asv_out
. It is possible to project onto the trace space ‘DGT’, but not onto other trace spaces e.g. into the restriction of CG onto the facets.- Parameters
v – the
ufl.core.expr.Expr
orFunction
to projectV –
Function
(orFunctionSpace
) 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.core.expr.Expr
to projectV – the
FunctionSpace
orFunction
to project intobcs – 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 aFunction
thenv
is projected intoV
andV
is returned. If V is aFunctionSpace
thenv
is projected into a newFunction
and thatFunction
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 areFunction
s. If present, bcs should be a list ofDirichletBC
s andEquationBC
s 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
(orMixedVectorSpaceBasis
) spanning the null space of the operator to the solve call using thenullspace
keyword argument.If you need to project the transpose nullspace out of the right hand side, you can do so by using the
transpose_nullspace
keyword argument.In the same fashion you can add the near nullspace using the
near_nullspace
keyword argument.
firedrake.solving_utils module¶
- 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:
pyop2.caching.Cached
A wrapper object for one or more TSFC kernels compiled from a given
Form
.- Parameters
form – the
Form
from which to compile the kernels.name – a prefix to be applied to the compiled kernel names. This is primarily useful for debugging.
parameters – a dict of parameters to pass to the form compiler.
number_map – a map from local coefficient numbers to 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.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 Firedrakeparameters
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,
pyop2.op2.Kernel
).needs_orientations
indicates whether the form requires cell orientation information (for correctly pulling back to reference elements on embedded manifolds).The coordinates are extracted from the domain of the integral (a
Mesh()
)
- firedrake.tsfc_interface.extract_numbered_coefficients(expr, numbers)[source]¶
Return expression coefficients specified by a numbering.
- Parameters
expr – A UFL expression.
numbers – Iterable of indices used for selecting the correct coefficients from
expr
.
- Returns
A list of UFL coefficients.
- firedrake.tsfc_interface.gather_integer_subdomain_ids(knls)[source]¶
Gather a dict of all integer subdomain IDs per integral type.
This is needed to correctly interpret the
"otherwise"
subdomain ID.- Parameters
knls – Iterable of
SplitKernel
objects.
firedrake.ufl_expr module¶
- class firedrake.ufl_expr.Argument(function_space, number, part=None)[source]¶
Bases:
ufl.argument.Argument
Representation of the argument to a form.
- Parameters
function_space – the
FunctionSpace
the argument corresponds to.number – the number of the argument being constructed.
part – optional index (mostly ignored).
Note
an
Argument
with a number of0
is used as aTestFunction()
, with a number of1
it is used as aTrialFunction()
.
- 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 aMixedFunctionSpace
, 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 aMixedFunctionSpace
, 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 additionalArgument
in the same finite element space as the Function.- Parameters
form – a
Form
to compute the derivative of.u – a
Function
to compute the derivative with respect to.du – an optional
Argument
to use as the replacement in the new form (constructed automatically if not provided).coefficient_derivatives – an optional
dict
to provide the derivative of a coefficient function.
- Raises
ValueError – If any of the coefficients in
form
were obtained fromu.subfunctions
. UFL doesn’t notice that these are related tou
and so therefore the derivative is wrong (instead one should have writtensplit(u)
).
See also
ufl.derivative()
.
firedrake.utility_meshes module¶
- firedrake.utility_meshes.BoxMesh(nx, ny, nz, Lx, Ly, Lz, hexahedral=False, reorder=None, distribution_parameters=None, diagonal='default', comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]¶
Generate a mesh of a 3D box.
- Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
nz – The number of cells in the z direction
Lx – The extent in the x direction
Ly – The extent in the y direction
Lz – The extent in the z direction
hexahedral – (optional), creates hexahedral mesh, defaults to False
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, hexahedral=False, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]¶
Generate a mesh of a cube
- Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
nz – The number of cells in the z direction
L – The extent in the x, y and z directions
hexahedral – (optional), creates hexahedral 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 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, hexahedral=False, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>, name='firedrake_default', distribution_name=None, permutation_name=None)[source]¶
Generate a mesh of a 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
hexahedral – (optional), creates hexahedral 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 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.split_by(condition, items)[source]¶
Split an iterable in two according to some condition.
- Parameters
condition – Callable applied to each item in
items
, returningTrue
orFalse
.items – Iterable to split apart.
- Returns
A 2-tuple of the form
(yess, nos)
, whereyess
is a tuple containing the entries ofitems
wherecondition
isTrue
andnos
is a tuple of those wherecondition
isFalse
.
- 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.variational_solver module¶
- class firedrake.variational_solver.LinearVariationalProblem(a, L, u, bcs=None, aP=None, form_compiler_parameters=None, constant_jacobian=False)[source]¶
Bases:
firedrake.variational_solver.NonlinearVariationalProblem
Linear variational problem a(u, v) = L(v).
- Parameters
a – the bilinear form
L – the linear form
u – the
Function
to which the solution will be assignedbcs – 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:
firedrake.variational_solver.NonlinearVariationalSolver
Solves a
LinearVariationalProblem
.- Parameters
problem – A
LinearVariationalProblem
to solve.solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.
nullspace – an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
) spanning the null space of the operator.transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the
solver_parameters
dict.appctx – A dictionary containing application context that is passed to the preconditioner if 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
(orMixedVectorSpaceBasis
) spanning the null space of the operator.transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
near_nullspace – as for the nullspace, but used to specify the near nullspace (for multigrid solvers).
solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.
appctx – A dictionary containing application context that is passed to the preconditioner if 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
orpre_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'}¶
- class firedrake.variational_solver.NonlinearVariationalProblem(F, u, bcs=None, J=None, Jp=None, form_compiler_parameters=None, is_linear=False)[source]¶
Bases:
firedrake.adjoint.variational_solver.NonlinearVariationalProblemMixin
Nonlinear variational problem F(u; v) = 0.
- Parameters
F – the nonlinear form
u – the
Function
to solve forbcs – 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.
- 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:
firedrake.petsc.OptionsManager
,firedrake.adjoint.variational_solver.NonlinearVariationalSolverMixin
Solves a
NonlinearVariationalProblem
.- Parameters
problem – A
NonlinearVariationalProblem
to solve.nullspace – an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
) spanning the null space of the operator.transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
near_nullspace – as for the nullspace, but used to specify the near nullspace (for multigrid solvers).
solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.
appctx – A dictionary containing application context that is passed to the preconditioner if 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
orpre_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.
firedrake.vector module¶
- class firedrake.vector.Vector(x)[source]¶
Bases:
object
Build a Vector that wraps a
pyop2.types.dat.Dat
for Dolfin compatibilty.- Parameters
x – an
Function
to wrap or aVector
to copy. The former shares data, the latter copies data.
- apply(action)[source]¶
Finalise vector assembly. This is not actually required in Firedrake but is provided for Dolfin compatibility.
- gather(global_indices=None)[source]¶
Gather a
Vector
to all processes- Parameters
global_indices – the globally numbered indices to gather (should be the same on all processes). If None, gather the entire
Vector
.
- local_range()[source]¶
Return the global indices of the start and end of the local part of this vector.
- set_local(values)[source]¶
Set process local values
- Parameters
values – a numpy array of values of length
Vector.local_size()