firedrake package¶
Subpackages¶
- firedrake.adjoint package
- firedrake.adjoint_utils package
- Subpackages
- firedrake.adjoint_utils.blocks package
- Submodules
- firedrake.adjoint_utils.blocks.assembly module
- firedrake.adjoint_utils.blocks.block_utils module
- firedrake.adjoint_utils.blocks.constant module
- firedrake.adjoint_utils.blocks.dirichlet_bc module
- firedrake.adjoint_utils.blocks.function module
- firedrake.adjoint_utils.blocks.mesh module
- firedrake.adjoint_utils.blocks.solving module
- Module contents
- firedrake.adjoint_utils.blocks package
- Submodules
- firedrake.adjoint_utils.assembly module
- firedrake.adjoint_utils.checkpointing module
- firedrake.adjoint_utils.constant module
- firedrake.adjoint_utils.dirichletbc module
- firedrake.adjoint_utils.function module
- firedrake.adjoint_utils.mesh module
- firedrake.adjoint_utils.projection module
- firedrake.adjoint_utils.solving module
- firedrake.adjoint_utils.variational_solver module
- Module contents
- Subpackages
- firedrake.cython package
- Submodules
- firedrake.cython.dmcommon module
cell_facet_labeling()
clear_adjacency_callback()
closure_ordering()
complete_facet_labels()
compute_point_cone_global_sizes()
count_labelled_points()
create_cell_closure()
create_halo_exchange_sf()
create_section()
entity_orientations()
exchange_cell_orientations()
facet_closure_nodes()
facet_numbering()
get_cell_markers()
get_cell_nodes()
get_cell_remote_ranks()
get_entity_classes()
get_facet_nodes()
get_facet_ordering()
get_facets_by_class()
get_topological_dimension()
label_facets()
make_global_numbering()
mark_entity_classes()
mark_entity_classes_using_cell_dm()
mark_points_with_function_array()
orientations_facet2cell()
plex_renumbering()
quadrilateral_closure_ordering()
quadrilateral_facet_orientations()
reordered_coords()
set_adjacency_callback()
submesh_correct_entity_classes()
submesh_create()
submesh_create_cell_closure_cell_submesh()
submesh_update_facet_labels()
to_petsc_local_numbering()
transform_vec_from_firedrake_to_petsc()
validate_mesh()
- firedrake.cython.extrusion_numbering module
- firedrake.cython.hdf5interface module
- firedrake.cython.mgimpl module
- firedrake.cython.patchimpl module
- firedrake.cython.spatialindex module
- firedrake.cython.supermeshimpl module
- Module contents
- firedrake.external_operators package
- firedrake.fml package
- firedrake.matrix_free package
- Submodules
- firedrake.matrix_free.operators module
ImplicitMatrixContext
ImplicitMatrixContext.createSubMatrix()
ImplicitMatrixContext.duplicate()
ImplicitMatrixContext.getDiagonal()
ImplicitMatrixContext.getInfo()
ImplicitMatrixContext.missingDiagonal()
ImplicitMatrixContext.mult()
ImplicitMatrixContext.multTranspose()
ImplicitMatrixContext.on_diag
ImplicitMatrixContext.view()
- Module contents
- firedrake.mg package
- Submodules
- firedrake.mg.embedded module
TransferManager
TransferManager.Cache
TransferManager.DG_inv_mass()
TransferManager.DG_work()
TransferManager.V_DG_mass()
TransferManager.V_approx_inv_mass()
TransferManager.V_dof_weights()
TransferManager.V_inv_mass_ksp()
TransferManager.cache()
TransferManager.cache_dat_versions()
TransferManager.inject()
TransferManager.is_native()
TransferManager.op()
TransferManager.prolong()
TransferManager.requires_transfer()
TransferManager.restrict()
TransferManager.work_vec()
- firedrake.mg.interface module
- firedrake.mg.kernels module
- firedrake.mg.mesh module
- firedrake.mg.opencascade_mh module
- firedrake.mg.ufl_utils module
- firedrake.mg.utils module
- Module contents
- firedrake.ml package
- firedrake.output 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.hiptmair 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.pyplot package
- firedrake.slate package
- Subpackages
- Submodules
- firedrake.slate.slate module
Add
AssembledVector
AssembledVector.arg_function_spaces
AssembledVector.arguments()
AssembledVector.assembled
AssembledVector.coefficients()
AssembledVector.constants()
AssembledVector.form
AssembledVector.integrals
AssembledVector.operands
AssembledVector.prec
AssembledVector.slate_coefficients()
AssembledVector.subdomain_data()
AssembledVector.terminal
AssembledVector.ufl_domains()
Block
BlockAssembledVector
DiagonalTensor
Factorization
Inverse
Mul
Negative
Reciprocal
Solve
Tensor
Transpose
- Module contents
- firedrake.slope_limiter package
Submodules¶
firedrake.assemble module¶
- firedrake.assemble.assemble(expr, *args, **kwargs)[source]¶
Assemble.
- Parameters:
expr (ufl.classes.Expr or ufl.classes.BaseForm or slate.TensorBase) – Object to assemble.
tensor (firedrake.function.Function or firedrake.cofunction.Cofunction or matrix.MatrixBase or None) – Existing tensor object to place the result in.
bcs (Sequence) – Iterable of boundary conditions to apply.
form_compiler_parameters (dict) – Dictionary of parameters to pass to the form compiler. Ignored if not assembling a ufl.classes.Form. Any parameters provided here will be overridden by parameters set on the ufl.classes.Measure in the form. For example, if a
quadrature_degree
of 4 is specified in this argument, but a degree of 3 is requested in the measure, the latter will be used.mat_type (str) – String indicating how a 2-form (matrix) should be assembled – either as a monolithic matrix (
"aij"
or"baij"
), a block matrix ("nest"
), or left as a matrix.ImplicitMatrix 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 (str) – 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"]
.options_prefix (str) – PETSc options prefix to apply to matrices.
appctx (dict) – Additional information to hang on the assembled matrix if an implicit matrix is requested (mat_type
"matfree"
).zero_bc_nodes (bool) – If True, set the boundary condition nodes in the output tensor to zero rather than to the values prescribed by the boundary condition. Default is False.
diagonal (bool) – If assembling a matrix is it diagonal?
weight (float) – Weight of the boundary condition, i.e. the scalar in front of the identity matrix corresponding to the boundary nodes. To discretise eigenvalue problems set the weight equal to 0.0.
allocation_integral_types (Sequence) – Sequence of integral types to be used when allocating the output matrix.Matrix.
is_base_form_preprocessed (bool) – If True, skip preprocessing of the form.
- Returns:
Result of assembly.
- Return type:
float or firedrake.function.Function or firedrake.cofunction.Cofunction or matrix.MatrixBase
Notes
Input arguments are all optional, except
expr
.If expr is a ufl.classes.Form or slate.TensorBase then this evaluates the corresponding integral(s) and returns a float for 0-forms, a firedrake.function.Function or a firedrake.cofunction.Cofunction for 1-forms and a matrix.Matrix or a matrix.ImplicitMatrix for 2-forms. In the case of 2-forms the rows correspond to the test functions and the columns to the trial functions.
If expr is an expression other than a form, it will be evaluated pointwise on the firedrake.function.Function`s in the expression. This will only succeed if all the Functions are on the same `firedrake.functionspace.FunctionSpace.
If
tensor
is supplied, the assembled result will be placed there, otherwise a new object of the appropriate type will be returned.If
bcs
is supplied andexpr
is a 2-form, the rows and columns of the resulting matrix.Matrix 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.
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:
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
.Initialise.
- complex_value(o)¶
- float_value(o)¶
- int_value(o)¶
- zero(o)¶
- class firedrake.assign.IAddAssigner(assignee, expression, subset=None)[source]¶
Bases:
Assigner
Assigner class for
firedrake.function.Function.__iadd__
.- symbol = '+='¶
- class firedrake.assign.IDivAssigner(assignee, expression, subset=None)[source]¶
Bases:
Assigner
Assigner class for
firedrake.function.Function.__itruediv__
.- symbol = '/='¶
firedrake.bcs module¶
- class firedrake.bcs.DirichletBC(V, g, sub_domain, method=None)[source]¶
Bases:
BCBase
,DirichletBCMixin
Implementation of a strong Dirichlet boundary condition.
- Parameters:
V – the
FunctionSpace
on which the boundary condition should be applied.g – the boundary condition values. This can be a
Function
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.
- Keyword Arguments:
track_order – Whether to track dataset/group/attribute creation order.
In this method we customise the
h5py.h5p.PropGCID
object from which we create the h5py.h5g.GroupID object to avoid the “object header message is too large” error and/or “record is not in B-tree” error when storing many (hundreds of) attributes; see this PR.TODO: Lift this to upstream somehow.
- get_attr(path, key)[source]¶
Get an HDF5 attribute at specified path.
- Parameters:
path – The path at which the attribute is found.
key – The attribute key.
- Returns:
The attribute value.
- get_timestepping_history(mesh, name)[source]¶
Retrieve the timestepping history and indices for a specified function within a mesh.
This method is primarily used in checkpointing scenarios during timestepping simulations. It returns the indices associated with each function stored in the timestepping mode, along with any additional timestepping-related information (like time or timestep values) if available. If the specified function has not been stored in timestepping mode, it returns an empty dictionary.
- Parameters:
mesh (firedrake.mesh.MeshGeometry) – The mesh containing the function to be queried.
name (str) – The name of the function whose timestepping history is to be retrieved.
- Returns:
Returns an empty dictionary if the function name has not been stored in timestepping mode.
- If the function name is stored in timestepping mode, returns a dictionary with the following contents:
’indices’: A list of all stored indices for the function.
Additional key-value pairs representing timestepping information, if available.
- Return type:
- Raises:
RuntimeError – If the function name is not found within the given mesh in the current file.
See also
CheckpointFile.save_function
Describes how timestepping information should be provided.
Notes
The function internally checks whether the specified function is mixed or exists in the file. It then retrieves the appropriate data paths and extracts the timestepping information as specified in the checkpoint file.
- property h5pyfile¶
An h5py File object pointing at the open file handle.
- has_attr(path, key)[source]¶
Check if an HDF5 attribute exists at specified path.
- Parameters:
path – The path at which the attribute is sought.
key – The attribute key.
- Returns:
True if the attribute is found.
- latest_version = '3.0.0'¶
- load_mesh(name='firedrake_default', reorder=None, distribution_parameters=None, topology=None)[source]¶
Load a mesh.
- Parameters:
name (str) – the name of the mesh to load (default to firedrake.mesh.DEFAULT_MESH_NAME).
reorder (bool) – whether to reorder the mesh; see firedrake.Mesh.
distribution_parameters (dict) – the distribution_parameters used for distributing the mesh; see firedrake.Mesh.
topology (firedrake.mesh.MeshTopology) – the underlying mesh topology if already known.
- Returns:
the loaded mesh.
- Return type:
- 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, timestepping_info={})[source]¶
Save a
Function
.- Parameters:
f – the
Function
to save.- Keyword Arguments:
idx – optional timestepping index. A function can either be saved in timestepping mode or in normal mode (non-timestepping); for each function of interest, this method must always be called with the idx parameter set or never be called with the idx parameter set.
name – optional alternative name to save the function under.
timestepping_info – optional (requires idx) additional information such as time, timestepping that can be stored along a function for each index.
- save_mesh(mesh, distribution_name=None, permutation_name=None)[source]¶
Save a mesh.
- Parameters:
mesh – the mesh to save.
- Keyword Arguments:
distribution_name – the name under which distribution is saved; if None, auto-generated name will be used.
permutation_name – the name under which permutation is saved; if None, auto-generated name will be used.
- 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 soon be deprecated. 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 soon be deprecated. Use
CheckpointFile
class instead.
firedrake.cofunction module¶
- class firedrake.cofunction.Cofunction(*args, **kw)[source]¶
Bases:
Cofunction
,FunctionMixin
A
Cofunction
represents a function on a dual space. Like Functions, cofunctions are represented as sums of basis functions:\[\begin{split}f = \\sum_i f_i \phi_i(x)\end{split}\]The
Cofunction
class provides storage for the coefficients \(f_i\) and associates them with aFunctionSpace
object which provides the basis functions \(\\phi_i(x)\).Note that the coefficients are always scalars: if the
Cofunction
is vector-valued then this is specified in theFunctionSpace
.- Parameters:
function_space – the
FunctionSpace
, orMixedFunctionSpace
on which to build thisCofunction
. Alternatively, anotherCofunction
may be passed here and its function space will be used to build thisCofunction
. 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 existingCofunction
, then the data will be shared.name – user-defined name for this
Cofunction
(optional).dtype – optional data type for this
Cofunction
(defaults toScalarType
).
- assign(expr, subset=None, expr_from_assemble=False)[source]¶
Set the
Cofunction
value to the pointwise value of expr. expr may only containCofunction
s on the sameFunctionSpace
as theCofunction
being assigned to.Similar functionality is available for the augmented assignment operators +=, -=, *= and /=. For example, if f and g are both Cofunctions on the same
FunctionSpace
then:f += 2 * g
will add twice g to f.
If present, subset must be an
pyop2.types.set.Subset
of thisCofunction
’snode_set
. The expression will then only be assigned to the nodes on that subset.The expr_from_assemble optional argument indicates whether the expression results from an assemble operation performed within the current method. expr_from_assemble is required for the CofunctionAssignBlock.
- copy(deepcopy=True)[source]¶
Return a copy of this
firedrake.function.CoordinatelessFunction
.- Keyword Arguments:
deepcopy – If
True
, the default, the newfiredrake.function.CoordinatelessFunction
will allocate new space and copy values. IfFalse
, then the newfiredrake.function.CoordinatelessFunction
will share the dof values.
- function_space()[source]¶
Return the
FunctionSpace
, orMixedFunctionSpace
on which thisCofunction
is defined.
- interpolate(expression)[source]¶
Interpolate an expression onto this
Cofunction
.- Parameters:
expression – a UFL expression to interpolate
- Returns:
this
firedrake.cofunction.Cofunction
object
- label()[source]¶
Return the label (a description) of this
Cofunction
- name()[source]¶
Return the name of this
Cofunction
- property node_set¶
A
pyop2.types.set.Set
containing the nodes of thisCofunction
. 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
Cofunction
- Parameters:
name – The new name of the Cofunction (if not None)
label – The new label for the Cofunction (if not None)
- riesz_representation(riesz_map='L2', **solver_options)[source]¶
Return the Riesz representation of this
Cofunction
with respect to the given Riesz map.Example: For a L2 Riesz map, the Riesz representation is obtained by solving the linear system
Mx = self
, where M is the L2 mass matrix, i.e. M = <u, v> with u and v trial and test functions, respectively.- Parameters:
riesz_map (str or collections.abc.Callable) – The Riesz map to use (l2, L2, or H1). This can also be a callable.
solver_options (dict) –
- Solver options to pass to the linear solver:
solver_parameters: optional solver parameters.
- nullspace: an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
) spanning the null space of the operator.
- nullspace: an optional
transpose_nullspace: as for the nullspace, but used to make the right hand side consistent.
near_nullspace: as for the nullspace, but used to add the near nullspace.
- options_prefix: an optional prefix used to distinguish PETSc options.
If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the
solver_parameters
dict.
- Returns:
Riesz representation of this
Cofunction
with respect to the given Riesz map.- Return type:
- sub(i)[source]¶
Extract the ith sub
Cofunction
of thisCofunction
.- Parameters:
i – the index to extract
See also
subfunctions
.If the
Cofunction
is defined on aVectorFunctionSpace()
orTensorFunctionSpace()
this returns a proxy object indexing the ith component of the space, suitable for use in boundary condition application.
- property subfunctions¶
Extract any sub
Cofunction
s defined on the component spaces of this thisCofunction
’sFunctionSpace
.
- ufl_operands¶
- vector()[source]¶
Return a
Vector
wrapping the data in thisCofunction
- zero(subset=None)[source]¶
Set values to zero.
- Parameters:
subset (pyop2.types.set.Subset) – A subset of the domain indicating the nodes to zero. If None then the whole function is zeroed.
- Returns:
Returns self
- Return type:
firedrake.constant module¶
- class firedrake.constant.Constant(value, domain=None, name=None, count=None)[source]¶
Bases:
ConstantValue
,ConstantMixin
,TSFCConstantMixin
,Counted
A “constant” coefficient
A
Constant
takes one value over the 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.
- property subfunctions¶
- property ufl_shape¶
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.eigensolver module¶
Specify and solve finite element eigenproblems.
- class firedrake.eigensolver.LinearEigenproblem(A, M=None, bcs=None, bc_shift=0.0, restrict=True)[source]¶
Bases:
object
Generalised linear eigenvalue problem.
The problem has the form, find u, λ such that:
A(u, v) = λM(u, v) ∀ v ∈ V
- Parameters:
A (ufl.Form) – The bilinear form A(u, v).
M (ufl.Form) – The mass form M(u, v), defaults to inner(u, v) * dx.
bcs (DirichletBC or list of DirichletBC) – The boundary conditions.
bc_shift (float) – The value to shift the boundary condition eigenvalues by. This value will be ignored if restrict==True.
restrict (bool) – If True, replace the function spaces of u and v with their restricted version. The output space remains unchanged.
Notes
If restrict==True, the arguments of A and M will be replaced, such that their function space is replaced by the equivalent RestrictedFunctionSpace class. This avoids the computation of eigenvalues associated with the Dirichlet boundary conditions. This in turn prevents convergence failures, and allows only the non-boundary eigenvalues to be returned. The eigenvectors will be in the original, non-restricted space.
If restrict==False and Dirichlet boundary conditions are supplied, then these conditions will result in the eigenproblem having a nullspace spanned by the basis functions with support on the boundary. To facilitate solution, this is shifted by the specified amount. It is the user’s responsibility to ensure that the shift is not close to an actual eigenvalue of the system.
- property dm¶
Return the dm associated with the output space.
- class firedrake.eigensolver.LinearEigensolver(problem, n_evals, *, options_prefix=None, solver_parameters=None, ncv=None, mpd=None)[source]¶
Bases:
OptionsManager
Solve a LinearEigenproblem.
- Parameters:
problem (LinearEigenproblem) – The eigenproblem to solve.
n_evals (int) – The number of eigenvalues to compute.
options_prefix (str) – The options prefix to use for the eigensolver.
solver_parameters (dict) – PETSc options for the eigenvalue problem.
ncv (int) – Maximum dimension of the subspace to be used by the solver. See SLEPc.EPS.setDimensions.
mpd (int) – Maximum dimension allowed for the projected problem. See SLEPc.EPS.setDimensions.
Notes
Users will typically wish to set solver parameters specifying the symmetry of the eigenproblem and which eigenvalues to search for first.
The former is set using the options available for EPSSetProblemType.
For example if the bilinear form is symmetric (Hermitian in complex mode), one would add this entry to solver_options:
"eps_gen_hermitian": None
As always when specifying PETSc options, None indicates that the option in question is a flag and hence doesn’t take an argument.
The eigenvalues to search for first are specified using the options for EPSSetWhichEigenPairs.
For example, to look for the eigenvalues with largest real part, one would add this entry to solver_options:
"eps_largest_real": None
- DEFAULT_EPS_PARAMETERS = {'eps_target': 0.0, 'eps_tol': 1e-10, 'eps_type': 'krylovschur'}¶
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, **kwargs)[source]¶
Bases:
object
Create a set of space and ensemble subcommunicators.
- Parameters:
comm – The communicator to split.
M – the size of the communicators used for spatial parallelism.
- Keyword Arguments:
ensemble_name – string used as communicator name prefix, for debugging.
- Raises:
ValueError – if
M
does not 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.calculate_dof_offset_quotient(finat_element)[source]¶
Return the offset quotient for each DoF within the base cell.
- Parameters:
finat_element – A FInAT element.
- Returns:
A numpy array containing the offset quotient for each DoF.
offset_quotient q of each DoF (in a local cell) is defined as i // o, where i is the local DoF ID of the DoF on the entity and o is the offset of that DoF computed in
calculate_dof_offset()
.Let DOF(e, l, i) represent a DoF on (base-)entity e on layer l that has local ID i and suppose this DoF has offset o and offset_quotient q. In periodic extrusion it is convenient to identify DOF(e, l, i) as DOF(e, l + q, i % o); this transformation allows one to always work with the “unit cell” in which i < o always holds.
In FEA offset_quotient is 0 or 1.
Example:
local ID offset offset_quotient 2--2--2 2--2--2 1--1--1 | | | | | | CG2 1 1 1 2 2 2 0 0 0 | | | | | | 0--0--0 2--2--2 0--0--0 +-----+ +-----+ +-----+ | 1 3 | | 4 4 | | 0 0 | DG1 | | | | | | | 0 2 | | 4 4 | | 0 0 | +-----+ +-----+ +-----+
- firedrake.extrusion_utils.entity_closures(cell)[source]¶
Map entities in a cell to points in the topological closure of the entity.
- Parameters:
cell – a FIAT cell.
- firedrake.extrusion_utils.entity_indices(cell)[source]¶
Return a dict mapping topological entities on a cell to their integer index.
This provides an iteration ordering for entities on extruded meshes.
- Parameters:
cell – a FIAT cell.
- firedrake.extrusion_utils.entity_reordering(cell)[source]¶
Return an array reordering extruded cell entities.
If we iterate over the base cell, it is natural to then go over all the entities induced by the product with an interval. This iteration order is not the same as the natural iteration order, so we need a reordering.
- Parameters:
cell – a FIAT tensor product cell.
- firedrake.extrusion_utils.is_real_tensor_product_element(element)[source]¶
Is the provided FInAT element a tensor product involving the real space?
- Parameters:
element – A scalar FInAT element.
- firedrake.extrusion_utils.make_extruded_coords(extruded_topology, base_coords, ext_coords, layer_height, extrusion_type='uniform', kernel=None)[source]¶
Given either a kernel or a (fixed) layer_height, compute an extruded coordinate field for an extruded mesh.
- Parameters:
extruded_topology – an
ExtrudedMeshTopology
to extrude a coordinate field for.base_coords – a
Function
to read the base coordinates from.ext_coords – a
Function
to write the extruded coordinates into.layer_height – the height for each layer. Either a scalar, where layers will be equi-spaced at the specified height, or a 1D array of variable layer heights to use through the extrusion.
extrusion_type – the type of extrusion to use. Predefined options are either “uniform” (creating equi-spaced layers by extruding in the (n+1)dth direction), “radial” (creating equi-spaced layers by extruding in the outward direction from the origin) or “radial_hedgehog” (creating equi-spaced layers by extruding coordinates in the outward cell-normal direction, needs a P1dgxP1 coordinate field).
kernel – an optional kernel to carry out coordinate extrusion.
The kernel signature (if provided) is:
void kernel(double **base_coords, double **ext_coords, double *layer_height, int layer)
The kernel iterates over the cells of the mesh and receives as arguments the coordinates of the base cell (to read), the coordinates on the extruded cell (to write to), the fixed layer height, and the current cell layer.
firedrake.formmanipulation module¶
- class firedrake.formmanipulation.ExtractSubBlock[source]¶
Bases:
MultiFunction
Extract a sub-block from a form.
Initialise.
- class IndexInliner[source]¶
Bases:
MultiFunction
Inline fixed index of list tensors
Initialise.
- expr(o, *ops)¶
Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.
- 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(*args, **kw)[source]¶
Bases:
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.
- Keyword Arguments:
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.
- property subfunctions¶
Extract any sub
Function
s defined on the component spaces of this thisFunction
’sFunctionSpace
.
- property topological¶
The underlying coordinateless function.
- class firedrake.function.Function(*args, **kwargs)[source]¶
Bases:
Coefficient
,FunctionMixin
A
Function
represents a discretised field over the domain defined by the underlyingMesh()
. Functions are represented as sums of basis functions:\[f = \sum_i f_i \phi_i(x)\]The
Function
class provides storage for the coefficients \(f_i\) and associates them with aFunctionSpace
object which provides the basis functions \(\phi_i(x)\).Note that the coefficients are always scalars: if the
Function
is 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.
- Keyword Arguments:
dont_raise – Do not raise an error if a point is not found.
tolerance – Tolerence to use when checking if a point is in a cell. Default is the
tolerance
provided when creating theMesh()
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, allow_missing_dofs=False, default_missing_val=None, ad_block_tag=None)[source]¶
Interpolate an expression onto this
Function
.- Parameters:
expression – a UFL expression to interpolate
- Keyword Arguments:
subset – An optional
pyop2.types.set.Subset
to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is aVertexOnlyMesh()
.allow_missing_dofs – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When
False
this raises aValueError
should this occur. WhenTrue
the corresponding values are set to zero or to the valuedefault_missing_val
if given. Ignored if interpolating within the same mesh or onto aVertexOnlyMesh()
(the behaviour of aVertexOnlyMesh()
in this scenario is, at present, set when it is created).default_missing_val – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then zero is used. Ignored if interpolating within the same mesh or onto a
VertexOnlyMesh()
.ad_block_tag – An optional string for tagging the resulting assemble block on the Pyadjoint tape.
- Returns:
this
Function
object
- project(b, *args, **kwargs)[source]¶
Project
b
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.
- riesz_representation(riesz_map='L2')[source]¶
Return the Riesz representation of this
Function
with respect to the given Riesz map.Example: For a L2 Riesz map, the Riesz representation is obtained by taking the action of
M
onself
, where M is the L2 mass matrix, i.e. M = <u, v> with u and v trial and test functions, respectively.- Parameters:
riesz_map (str or collections.abc.Callable) – The Riesz map to use (l2, L2, or H1). This can also be a callable.
- Returns:
Riesz representation of this
Function
with respect to the given Riesz map.- Return type:
- 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.
- property subfunctions¶
Extract any sub
Function
s defined on the component spaces of this thisFunction
’sFunctionSpace
.
- property topological¶
The underlying coordinateless function.
- zero(subset=None)[source]¶
Set all values to zero.
- Parameters:
subset (pyop2.types.set.Subset) – A subset of the domain indicating the nodes to zero. If None then the whole function is zeroed.
- Returns:
Returns self
- Return type:
firedrake.functionspace module¶
This module implements the user-visible API for constructing
FunctionSpace
and MixedFunctionSpace
objects. The
API is functional, rather than object-based, to allow for simple
backwards-compatibility, argument checking, and dispatch.
- firedrake.functionspace.FunctionSpace(mesh, family, degree=None, name=None, vfamily=None, vdegree=None, variant=None)[source]¶
Create a
FunctionSpace
.- Parameters:
mesh – The mesh to determine the cell from.
family – The finite element family.
degree – The degree of the finite element.
name – An optional name for the function space.
vfamily – The finite element in the vertical dimension (extruded meshes only).
vdegree – The degree of the element in the vertical dimension (extruded meshes only).
variant – The variant of the finite element.
Notes
The
family
argument may be an existingfinat.ufl.finiteelementbase.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
finat.ufl.mixedelement.MixedElement
.name – An optional name for the mixed function space.
mesh – An optional mesh. Must be provided if spaces is a
finat.ufl.mixedelement.MixedElement
, ignored otherwise.
- firedrake.functionspace.RestrictedFunctionSpace(function_space, name=None, boundary_set=[])[source]¶
Create a
RestrictedFunctionSpace
.- Parameters:
function_space – FunctionSpace object to restrict
name – An optional name for the function space.
boundary_set – A set of subdomains of the mesh in which Dirichlet boundary conditions will be applied.
- firedrake.functionspace.TensorFunctionSpace(mesh, family, degree=None, shape=None, symmetry=None, name=None, vfamily=None, vdegree=None, variant=None)[source]¶
Create a rank-2 FunctionSpace.
- Parameters:
mesh – The mesh to determine the cell from.
family – The finite element family.
degree – The degree of the finite element.
shape – An optional shape for the tensor-valued degrees of freedom at each function space node (defaults to a square tensor using the geometric dimension of the mesh).
symmetry – Optional symmetries in the tensor value.
name – An optional name for the function space.
vfamily – The finite element in the vertical dimension (extruded meshes only).
vdegree – The degree of the element in the vertical dimension (extruded meshes only).
variant – The variant of the finite element.
Notes
The
family
argument may be an existingfinat.ufl.finiteelementbase.FiniteElementBase
, in which case all other arguments are ignored and the appropriate FunctionSpace is returned. In this case, the provided element must have an emptyfinat.ufl.finiteelementbase.FiniteElementBase.value_shape
.The element that you provide must be a scalar element (with empty
value_shape
). If you already have an existingfinat.ufl.mixedelement.TensorElement
, you should pass it to FunctionSpace directly instead.
- firedrake.functionspace.VectorFunctionSpace(mesh, family, degree=None, dim=None, name=None, vfamily=None, vdegree=None, variant=None)[source]¶
Create a rank-1
FunctionSpace
.- Parameters:
mesh – The mesh to determine the cell from.
family – The finite element family.
degree – The degree of the finite element.
dim – An optional number of degrees of freedom per function space node (defaults to the geometric dimension of the mesh).
name – An optional name for the function space.
vfamily – The finite element in the vertical dimension (extruded meshes only).
vdegree – The degree of the element in the vertical dimension (extruded meshes only).
variant – The variant of the finite element.
Notes
The
family
argument may be an existingfinat.ufl.finiteelementbase.FiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned. In this case, the provided element must have an emptyfinat.ufl.finiteelementbase.FiniteElementBase.value_shape
.The element that you provide need be a scalar element (with empty
value_shape
), however, it should not be an existingfinat.ufl.mixedelement.VectorElement
. If you already have an existingfinat.ufl.mixedelement.VectorElement
, 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.
boundary_set – A set of boundary markers, indicating the subdomains a boundary condition is specified on.
- 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.FiredrakeDualSpace(mesh, element, component=None, cargo=None)[source]¶
Bases:
WithGeometryBase
,DualSpace
Initialise.
- 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
finat.ufl.finiteelementbase.FiniteElementBase
describing the degrees of freedom.
- Keyword Arguments:
name – An optional name for this
FunctionSpace
, useful for later identification.
The element can be a essentially any
finat.ufl.finiteelementbase.FiniteElementBase
, except for afinat.ufl.mixedelement.MixedElement
, 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.
- boundary_set = frozenset({})¶
- property cell_node_list¶
A numpy array mapping mesh cells to function space nodes.
- cell_node_map()[source]¶
Return the
pyop2.types.map.Map
from cels to function space nodes.
- 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
.
- property dm¶
A PETSc DM describing the data layout for this FunctionSpace.
- property dof_count¶
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.
- entity_node_map(source_mesh, source_integral_type, source_subdomain_id, source_all_integer_subdomain_ids)[source]¶
Return entity node map rebased on
source_mesh
.- Parameters:
source_mesh (MeshTopology) – Source (base) mesh topology.
source_integral_type (str) – Integral type on source_mesh.
source_subdomain_id (int) – Subdomain ID on source_mesh.
source_all_integer_subdomain_ids (dict) – All integer subdomain ids on source_mesh.
- Returns:
Entity node map.
- Return type:
pyop2.types.map.Map or None
- 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.
- property node_count¶
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 onfinat.ufl.mixedelement.VectorElement
orfinat.ufl.mixedelement.TensorElement
instances have rank equivalent to the number of components of theirfinat.ufl.finiteelementbase.FiniteElementBase.value_shape
.
- property subfunctions¶
Split into a tuple of constituent spaces.
- property topological¶
Function space on a mesh topology.
- ufl_element()[source]¶
The
finat.ufl.finiteelementbase.FiniteElementBase
associated with this space.
- ufl_function_space()[source]¶
The
FunctionSpace
associated with this space.
- value_size¶
The total number of degrees of freedom at each function space node.
- class firedrake.functionspaceimpl.FunctionSpaceCargo(topological: FunctionSpace, parent: WithGeometryBase | None)[source]¶
Bases:
object
Helper class carrying data for a
WithGeometryBase
.It is required because it permits Firedrake to have stripped forms that still know Firedrake-specific information (e.g. that they are a component of a parent function space).
- parent: WithGeometryBase | None¶
- topological: FunctionSpace¶
- firedrake.functionspaceimpl.IndexedFunctionSpace(index, space, parent)[source]¶
Build a new FunctionSpace that remembers it is a particular subspace of a
MixedFunctionSpace
.- Parameters:
index – The index into the parent space.
space – The subspace to represent
parent – The parent mixed space.
- Returns:
A new
ProxyFunctionSpace
with index and parent set.
- class firedrake.functionspaceimpl.MixedFunctionSpace(spaces, name=None)[source]¶
Bases:
object
A function space on a mixed finite element.
This is essentially just a bag of individual
FunctionSpace
objects.- Parameters:
spaces – The constituent spaces.
- Keyword Arguments:
name – An optional name for the mixed space.
Warning
Users should not build a
MixedFunctionSpace
directly, but should instead use the functional interface provided 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
.
- property dm¶
A PETSc DM describing the data layout for fieldsplit solvers.
- property dof_count¶
Return a tuple of
FunctionSpace.dof_count
s of theFunctionSpace
s of which thisMixedFunctionSpace
is composed.
- property dof_dset¶
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.
- entity_node_map(source_mesh, source_integral_type, source_subdomain_id, source_all_integer_subdomain_ids)[source]¶
Return entity node map rebased on
source_mesh
.- Parameters:
source_mesh (MeshTopology) – Source (base) mesh topology.
source_integral_type (str) – Integral type on source_mesh.
source_subdomain_id (int) – Subdomain ID on source_mesh.
source_all_integer_subdomain_ids (dict) – All integer subdomain ids on source_mesh.
- Returns:
Entity node map.
- Return type:
- 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
.
- property node_count¶
Return a tuple of
FunctionSpace.node_count
s of theFunctionSpace
s of which thisMixedFunctionSpace
is composed.
- property node_set¶
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
.
- property subfunctions¶
The list of
FunctionSpace
s of which thisMixedFunctionSpace
is composed.
- property topological¶
Function space on a mesh topology.
- ufl_element()[source]¶
The
finat.ufl.mixedelement.MixedElement
associated with this space.
- ufl_function_space()[source]¶
The
FunctionSpace
associated with this space.
- property value_size¶
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:
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.ProxyRestrictedFunctionSpace(function_space, name=None, boundary_set=frozenset({}))[source]¶
Bases:
RestrictedFunctionSpace
A
RestrictedFunctionSpace
that one can attach extra properties to.- Parameters:
function_space – The function space to be restricted.
- Keyword Arguments:
name – The name of the restricted function space.
boundary_set – The boundary domains on which boundary conditions will be specified
Warning
Users should not build a
ProxyRestrictedFunctionSpace
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=None)[source]¶
Bases:
FunctionSpace
FunctionSpace
based on elements of family “Real”. A :class`RealFunctionSpace` only has a single global value for the whole mesh.This class should not be directly instantiated by users. Instead, FunctionSpace objects will transform themselves into
RealFunctionSpace
objects as appropriate.- bottom_nodes()[source]¶
RealFunctionSpace
objects have no bottom nodes.
- cell_node_map(bcs=None)[source]¶
RealFunctionSpace
objects have no cell node map.
- entity_node_map(source_mesh, source_integral_type, source_subdomain_id, source_all_integer_subdomain_ids)[source]¶
Return entity node map rebased on
source_mesh
.- Parameters:
source_mesh (MeshTopology) – Source (base) mesh topology.
source_integral_type (str) – Integral type on source_mesh.
source_subdomain_id (int) – Subdomain ID on source_mesh.
source_all_integer_subdomain_ids (dict) – All integer subdomain ids on source_mesh.
- Returns:
Entity node map.
- Return type:
pyop2.types.map.Map or None
- exterior_facet_node_map(bcs=None)[source]¶
RealFunctionSpace
objects have no exterior facet node map.
- finat_element = None¶
- global_numbering = None¶
- interior_facet_node_map(bcs=None)[source]¶
RealFunctionSpace
objects have no interior facet node map.
- local_to_global_map(bcs, lgmap=None)[source]¶
Return a map from process local dof numbering to global dof numbering.
If BCs is provided, mask out those dofs which match the BC nodes.
- make_dat(val=None, valuetype=None, name=None)[source]¶
Return a newly allocated
pyop2.types.glob.Global
representing the data for aFunction
on this space.
- top_nodes()[source]¶
RealFunctionSpace
objects have no bottom nodes.
- class firedrake.functionspaceimpl.RestrictedFunctionSpace(function_space, name=None, boundary_set=frozenset({}))[source]¶
Bases:
FunctionSpace
A representation of a function space, with additional information about where boundary conditions are to be applied.
If a
FunctionSpace
is represented as V, we can decompose V into V = V0 + VΓ, where V0 contains functions in the basis of V that vanish on the boundary where a boundary condition is applied, and VΓ contains all other basis functions. TheRestrictedFunctionSpace
corresponding to V takes functions only from V0 when solving problems, or when creating a TestFunction and TrialFunction. The values on the boundary set will remain constant when solving, but are present in the output of the solver.- Parameters:
function_space – The
FunctionSpace
to restrict.- Keyword Arguments:
name – An optional name for this
RestrictedFunctionSpace
, useful for later identification.boundary_set – A set of subdomains on which a DirichletBC will be applied.
Notes
If using this class to solve or similar, a list of DirichletBCs will still need to be specified on this space and passed into the function.
- 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.
- class firedrake.functionspaceimpl.WithGeometry(mesh, element, component=None, cargo=None)[source]¶
Bases:
WithGeometryBase
,FunctionSpace
Initialise.
- class firedrake.functionspaceimpl.WithGeometryBase(mesh, element, component=None, cargo=None)[source]¶
Bases:
object
Attach geometric information to a
FunctionSpace
.Function spaces on meshes with different geometry but the same topology can share data, except for their UFL cell. This class facilitates that.
Users should not instantiate a
WithGeometryBase
object explicitly except in a small number of cases.When instantiating a
WithGeometryBase
, users should callWithGeometryBase.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
WithGeometryBase
.- Parameters:
sub_domain – the mesh marker selecting which subset of facets to consider.
- Returns:
A numpy array of the unique function space nodes on the selected portion of the boundary.
See also
DirichletBC
for details of the arguments.
- 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.
- property dm¶
- 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()
.
- classmethod make_function_space(mesh, element, name=None)[source]¶
Factory method for
WithGeometryBase
.
- property max_work_functions¶
The maximum number of work functions this
FunctionSpace
supports.See
get_work_function()
for obtaining work functions.
- mesh()¶
Return ufl domain.
- property num_work_functions¶
The number of checked out work functions.
- property parent¶
- reconstruct(mesh=None, name=None, **kwargs)[source]¶
Reconstruct this
WithGeometryBase
.- Keyword Arguments:
mesh – the new
Mesh()
(defaults to same mesh)name – the new name (defaults to None)
- Returns:
the new function space of the same class as
self
.
Any extra kwargs are used to reconstruct the finite element. For details see
finat.ufl.finiteelement.FiniteElement.reconstruct()
.
- restore_work_function(function)[source]¶
Restore a work function obtained with
get_work_function()
.- Parameters:
function – The work function to restore
- Raises:
ValueError – if the provided function was not obtained with
get_work_function()
or it has already been restored.
Warning
This does not invalidate the name in the calling scope, it is the user’s responsibility not to use a work function after restoring it.
- property subfunctions¶
Split into a tuple of constituent spaces.
- property topological¶
- ufl_function_space()[source]¶
The
FunctionSpace
this object represents.
- firedrake.functionspaceimpl.check_element(element, top=True)[source]¶
Run some checks on the provided element.
The
finat.ufl.mixedelement.VectorElement
andfinat.ufl.mixedelement.TensorElement
modifiers must be “outermost” for function space construction to work, excepting that they should not wrap afinat.ufl.mixedelement.MixedElement
. Similarly, a basefinat.ufl.mixedelement.MixedElement
must be outermost (it can containfinat.ufl.mixedelement.MixedElement
instances, provided they satisfy the other rules). This function checks that.- Parameters:
element – The
UFL element
to check.top (bool) – Are we at the top element (in which case the modifier is legal).
- Return type:
None
if the element is legal.- Raises:
ValueError – If the element is illegal.
firedrake.halo module¶
- class firedrake.halo.Halo(dm, section, comm)[source]¶
Bases:
Halo
Build a Halo for a function space.
- Parameters:
dm – The DM describing the topology.
section – The data layout.
The halo is implemented using a PETSc SF (star forest) object and is usable as a PyOP2
pyop2.types.halo.Halo
.- property comm¶
The MPI communicator for this 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.
- property local_to_global_numbering¶
The mapping from process-local to process-global numbers for this halo.
- property sf¶
firedrake.interpolation module¶
- class firedrake.interpolation.CrossMeshInterpolator(expr, V, **kwargs)[source]¶
Bases:
Interpolator
Interpolate a function from one mesh and function space to another.
For arguments, see
Interpolator
.
- exception firedrake.interpolation.DofNotDefinedError(src_mesh, dest_mesh)[source]¶
Bases:
Exception
Raised when attempting to interpolate across function spaces where the target function space contains degrees of freedom (i.e. nodes) which cannot be defined in the source function space. This typically occurs when the target mesh covers a larger domain than the source mesh.
- class firedrake.interpolation.Interpolate(expr, v, subset=None, access=Access.WRITE, allow_missing_dofs=False, default_missing_val=None)[source]¶
Bases:
Interpolate
Symbolic representation of the interpolation operator.
- Parameters:
expr (ufl.core.expr.Expr or ufl.BaseForm) – The UFL expression to interpolate.
v (firedrake.functionspaceimpl.WithGeometryBase or firedrake.ufl_expr.Coargument) – The function space to interpolate into or the coargument defined on the dual of the function space to interpolate into.
subset (pyop2.types.set.Subset) – An optional subset to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is a
VertexOnlyMesh()
.access (pyop2.types.access.Access) – The pyop2 access descriptor for combining updates to shared DoFs. Possible values include
WRITE
andINC
. OnlyWRITE
is supported at present when interpolating across meshes. See note ininterpolate()
if changing this from default.allow_missing_dofs (bool) – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When
False
this raises aValueError
should this occur. WhenTrue
the corresponding values are either (a) unchanged if someoutput
is given to theinterpolate()
method or (b) set to zero. Can be overwritten with thedefault_missing_val
kwarg ofinterpolate()
. This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto aVertexOnlyMesh()
(the behaviour of aVertexOnlyMesh()
in this scenario is, at present, set when it is created).default_missing_val (float) – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then the values are either (a) unchanged if some
output
is given to theinterpolate()
method or (b) set to zero. Ignored if interpolating within the same mesh or onto aVertexOnlyMesh()
.
- ufl_operands¶
- class firedrake.interpolation.Interpolator(expr, V, **kwargs)[source]¶
Bases:
ABC
A reusable interpolation object.
- Parameters:
expr – The expression to interpolate.
V – The
FunctionSpace
orFunction
to interpolate into.
- Keyword Arguments:
subset – An optional
pyop2.types.set.Subset
to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is aVertexOnlyMesh()
.freeze_expr – Set to True to prevent the expression being re-evaluated on each call. Cannot, at present, be used when interpolating across meshes unless the target mesh is a
VertexOnlyMesh()
.access – The pyop2 access descriptor for combining updates to shared DoFs. Possible values include
WRITE
andINC
. OnlyWRITE
is supported at present when interpolating across meshes. See note ininterpolate()
if changing this from default.bcs – An optional list of boundary conditions to zero-out in the output function space. Interpolator rows or columns which are associated with boundary condition nodes are zeroed out when this is specified.
allow_missing_dofs – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When
False
this raises aValueError
should this occur. WhenTrue
the corresponding values are either (a) unchanged if someoutput
is given to theinterpolate()
method or (b) set to zero. Can be overwritten with thedefault_missing_val
kwarg ofinterpolate()
. This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto aVertexOnlyMesh()
(the behaviour of aVertexOnlyMesh()
in this scenario is, at present, set when it is created).
This object can be used to carry out the same interpolation multiple times (for example in a timestepping loop).
Note
The
Interpolator
holds a reference to the provided arguments (such that they won’t be collected until theInterpolator
is also collected).- interpolate(*function, output=None, transpose=False, default_missing_val=None, ad_block_tag=None)[source]¶
Compute the interpolation by assembling the appropriate
Interpolate
object.- Parameters:
*function (firedrake.function.Function or firedrake.cofunction.Cofunction) – If the expression being interpolated contains an argument, then the function value to interpolate.
output (firedrake.function.Function or firedrake.cofunction.Cofunction) – A function to contain the output.
transpose (bool) – Set to true to apply the transpose (adjoint) of the interpolation operator.
default_missing_val (bool) – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then the values are either (a) unchanged if some
output
is specified to theinterpolate()
method or (b) set to zero. This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto aVertexOnlyMesh()
.ad_block_tag (str) – An optional string for tagging the resulting assemble block on the Pyadjoint tape.
- Returns:
The resulting interpolated function.
- Return type:
firedrake.function.Function or firedrake.cofunction.Cofunction
- class firedrake.interpolation.SameMeshInterpolator(expr, V, **kwargs)[source]¶
Bases:
Interpolator
An interpolator for interpolation within the same mesh or onto a validly- defined
VertexOnlyMesh()
.For arguments, see
Interpolator
.
- firedrake.interpolation.interpolate(expr, V, subset=None, access=Access.WRITE, allow_missing_dofs=False, default_missing_val=None, ad_block_tag=None)[source]¶
Interpolate an expression onto a new function in V.
- Parameters:
expr – a UFL expression.
V – the
FunctionSpace
to interpolate into (or else an existingFunction
).
- Keyword Arguments:
subset – An optional
pyop2.types.set.Subset
to apply the interpolation over. Cannot, at present, be used when interpolating across meshes unless the target mesh is aVertexOnlyMesh()
.access – The pyop2 access descriptor for combining updates to shared DoFs. Possible values include
WRITE
andINC
. OnlyWRITE
is supported at present when interpolating across meshes unless the target mesh is aVertexOnlyMesh()
. See note below.allow_missing_dofs – For interpolation across meshes: allow degrees of freedom (aka DoFs/nodes) in the target mesh that cannot be defined on the source mesh. For example, where nodes are point evaluations, points in the target mesh that are not in the source mesh. When
False
this raises aValueError
should this occur. WhenTrue
the corresponding values are either (a) unchanged if someoutput
is given to theinterpolate()
method or (b) set to zero. In either case, ifdefault_missing_val
is specified, that value is used. This does not affect transpose interpolation. Ignored if interpolating within the same mesh or onto aVertexOnlyMesh()
(the behaviour of aVertexOnlyMesh()
in this scenario is, at present, set when it is created).default_missing_val – For interpolation across meshes: the optional value to assign to DoFs in the target mesh that are outside the source mesh. If this is not set then the values are either (a) unchanged if some
output
is given to theinterpolate()
method or (b) set to zero. Ignored if interpolating within the same mesh or onto aVertexOnlyMesh()
.ad_block_tag – An optional string for tagging the resulting assemble 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:
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.
- Keyword Arguments:
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 = mappingproxy({'mat_type': 'aij', 'ksp_type': 'preonly', 'ksp_rtol': 1e-07, 'pc_type': 'lu', 'pc_factor_mat_solver_type': 'mumps', 'pc_factor_mat_mumps_icntl_14': 200})¶
- property test_space¶
- property trial_space¶
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=True)
- 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=True)
- 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=True)
- 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”, “notable problem”, exc_info=True)
- 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=True)
- firedrake.logging.set_level(level)¶
Set the log level for Firedrake components.
- Parameters:
level – The level to use.
This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.
- firedrake.logging.set_log_handlers(handlers=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶
Set handlers for the log messages of the different Firedrake components.
- Keyword Arguments:
handlers – Optional dict of handlers keyed by the name of the logger. If not provided, a separate
logging.StreamHandler
will be created for each logger.comm – The communicator the handler should be collective over. If provided, only rank-0 on that communicator will write to the handler, other ranks will use a
logging.NullHandler
. If set 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.AssembledMatrix(a, bcs, petscmat, *args, **kwargs)[source]¶
Bases:
MatrixBase
- A representation of a matrix that doesn’t require knowing the underlying form.
This class wraps the relevant information for Python PETSc matrix.
- Parameters:
a – A tuple of the arguments the matrix represents
bcs – an iterable of boundary conditions to apply to this
Matrix
. May be None if there are no boundary conditions to apply.petscmat – the already constructed petsc matrix this object represents.
Initialise.
- ufl_operands¶
- class firedrake.matrix.ImplicitMatrix(a, bcs, *args, **kwargs)[source]¶
Bases:
MatrixBase
A representation of the action of bilinear form operating without explicitly assembling the associated matrix. This class wraps the relevant information for Python PETSc matrix.
- Parameters:
Note
This object acts to the right on an assembled
Function
and to the left on an assembled cofunction (currently represented by aFunction
).Initialise.
- ufl_operands¶
- class firedrake.matrix.Matrix(a, bcs, mat_type, *args, **kwargs)[source]¶
Bases:
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.Note
This object acts to the right on an assembled
Function
and to the left on an assembled cofunction (currently represented by aFunction
).Initialise.
- ufl_operands¶
- class firedrake.matrix.MatrixBase(a, bcs, mat_type)[source]¶
Bases:
Matrix
A representation of the linear operator associated with a bilinear form and bcs. Explicitly assembled matrices and matrix-free matrix classes will derive from this
- Parameters:
a – the bilinear form this
MatrixBase
represents or a tuple of the arguments it representsbcs – an iterable of boundary conditions to apply to this
MatrixBase
. May be None if there are no boundary conditions to apply.mat_type – matrix type of assembled matrix, or ‘matfree’ for matrix-free
Initialise.
- property bcs¶
The set of boundary conditions attached to this
MatrixBase
(may be empty).
- property has_bcs¶
Return True if this
MatrixBase
has any boundary conditions attached to it.
- mat_type¶
Matrix type.
Matrix type used in the assembly of the PETSc matrix: ‘aij’, ‘baij’, ‘dense’ or ‘nest’, or ‘matfree’ for matrix-free.
- ufl_operands¶
firedrake.mesh module¶
- class firedrake.mesh.AbstractMeshTopology(topology_dm, name, reorder, sfXB, perm_is, distribution_name, permutation_name, comm)[source]¶
Bases:
object
A representation of an abstract mesh topology without a concrete PETSc DM implementation
Initialise a mesh topology.
- Parameters:
topology_dm (PETSc.DMPlex or PETSc.DMSwarm) – PETSc.DMPlex or PETSc.DMSwarm representing the mesh topology.
name (str) – Name of the mesh topology.
reorder (bool) – Whether to reorder the mesh entities.
sfXB (PETSc.PetscSF) – PETSc.SF that pushes forward the global point number slab
[0, NX)
to input (naive) plex (only significant when the mesh topology is loaded from file and only passed from inside ~.CheckpointFile).perm_is (PETSc.IS) – PETSc.IS that is used as
_dm_renumbering
; only makes sense if we know the exact parallel distribution ofplex
at the time of mesh topology construction like when we load mesh along with its distribution. If given,reorder
param will be ignored.distribution_name (str) – Name of the parallel distribution; if None, automatically generated.
permutation_name (str) – Name of the entity permutation (reordering); if None, automatically generated.
comm (mpi4py.MPI.Comm) – Communicator.
- abstract property cell_closure¶
2D array of ordered cell closures
Each row contains ordered cell entities for a cell, one row per cell.
- 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, boundary_set=None)[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.
boundary_set – A set of boundary markers, indicating the subdomains a boundary condition is specified on.
- 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¶
- property extruded_periodic¶
- abstract property interior_facets¶
- layers = None¶
No layers on unstructured mesh
- make_cell_node_list(global_numbering, entity_dofs, entity_permutations, offsets)[source]¶
Builds the DoF mapping.
- Parameters:
global_numbering – Section describing the global DoF numbering
entity_dofs – FInAT element entity DoFs
entity_permutations – FInAT element entity permutations
offsets – layer offsets for each entity dof (may be None).
- make_dofs_per_plex_entity(entity_dofs)[source]¶
Returns the number of DoFs per plex entity for each stratum, i.e. [#dofs / plex vertices, #dofs / plex edges, …].
- Parameters:
entity_dofs – FInAT element entity DoFs
- make_offset(entity_dofs, ndofs, real_tensorproduct=False)[source]¶
Returns None (only for extruded use).
- abstract mark_entities(tf, label_value, label_name=None)[source]¶
Mark selected entities.
- Parameters:
tf – The
CoordinatelessFunction
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.lable_value – The value used in the label.
label_name – The name of the label to store entity selections.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- measure_set(integral_type, subdomain_id, all_integer_subdomain_ids=None)[source]¶
Return an iteration set appropriate for the requested integral type.
- Parameters:
integral_type – The type of the integral (should be a valid UFL measure).
subdomain_id – The subdomain of the mesh to iterate over. Either an integer, an iterable of integers or the special subdomains
"everywhere"
or"otherwise"
.all_integer_subdomain_ids –
- Information to interpret the
"otherwise"
subdomain."otherwise"
means all entities not explicitly enumerated by the integer subdomains provided here. For example, if all_integer_subdomain_ids is empty, then"otherwise" == "everywhere"
. If it contains(1, 2)
, then"otherwise"
is all entities except those marked by subdomains 1 and 2. This should be a dict 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.
- 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.
- property submesh_ancesters¶
Tuple of submesh ancesters.
- submesh_map_child_parent(source_integral_type, source_subset_points, reverse=False)[source]¶
Return the map from submesh child entities to submesh parent entities or its reverse.
- Parameters:
source_integral_type (str) – Integral type on the source mesh.
source_subset_points (numpy.ndarray) – Subset points on the source mesh.
reverse (bool) – If True, return the map from parent entities to child entities.
- Returns:
(map from source to target, integral type on the target mesh, subset points on the target mesh).
- Return type:
- submesh_map_composed(other, other_integral_type, other_subset_points)[source]¶
Create entity-entity map from
other
to self.- Parameters:
other (AbstractMeshTopology) – Base mesh topology.
other_integral_type (str) – Integral type on
other
.other_subset_points (numpy.ndarray) – Subset points on
other
; only used to identify (facet) integral_type onself
.
- Returns:
Tuple of op2.ComposedMap from other to self, integral_type on self, and points on self.
- Return type:
- submesh_youngest_common_ancester(other)[source]¶
Return the youngest common ancester of self and other.
- Parameters:
other (AbstractMeshTopology) – The other mesh.
- Returns:
Youngest common ancester or None if not found.
- Return type:
AbstractMeshTopology or None
- 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.
- trans_mesh_entity_map(base_mesh, base_integral_type, base_subdomain_id, base_all_integer_subdomain_ids)[source]¶
Create entity-entity (composed) map from base_mesh to self.
- Parameters:
base_mesh (AbstractMeshTopology) – Base mesh topology.
base_integral_type (str) – Integral type on
base_mesh
.base_subdomain_id (int) – Subdomain ID on
base_mesh
.base_all_integer_subdomain_ids (tuple) –
all_integer_subdomain_ids
corresponding tobase_mesh
andbase_integral_type
.
- Returns:
tuple of op2.ComposedMap from base_mesh to self and integral_type on self.
- Return type:
- 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=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Bases:
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', periodic=False, kernel=None, gdim=None, name=None, tolerance=0.5)[source]¶
Build an extruded mesh from an input mesh
- Parameters:
mesh – the unstructured base mesh
layers – number of extruded cell layers in the “vertical” direction. One may also pass an array of shape (cells, 2) to specify a variable number of layers. In this case, each entry is a pair
[a, b]
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.
periodic – the flag for periodic extrusion; if True, only constant layer extrusion is allowed. Can be used with any “extrusion_type” to make annulus, torus, etc.
kernel – a
pyop2.Kernel
to produce coordinates for the extruded mesh. 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.
- Keyword Arguments:
tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.
The various values of
extrusion_type
have the following meanings:"uniform"
the extruded mesh has an extra spatial dimension compared to the base mesh. The layers exist in this dimension only.
"radial"
the extruded mesh has the same number of spatial dimensions as the base mesh; the cells are radially extruded outwards from the origin. This requires the base mesh to have topological dimension strictly smaller than geometric dimension.
"radial_hedgehog"
similar to radial, but the cells are extruded in the direction of the outward-pointing cell normal (this produces a P1dgxP1 coordinate field). In this case, a radially extruded coordinate field (generated with
extrusion_type="radial"
) is available in theradial_coordinates
attribute."custom"
use a custom kernel to generate the extruded coordinates
For more details see the manual section on extruded meshes.
- class firedrake.mesh.ExtrudedMeshTopology(mesh, layers, periodic=False, name=None)[source]¶
Bases:
MeshTopology
Representation of an extruded mesh topology.
Build an extruded mesh topology from an input mesh topology
- Parameters:
mesh – the unstructured base mesh topology
layers – number of occurence of base layer in the “vertical” direction.
periodic – the flag for periodic extrusion; if True, only constant layer extrusion is allowed.
name – optional name of the extruded mesh topology.
- property cell_closure¶
2D array of ordered cell closures
Each row contains ordered cell entities for a cell, one row per cell.
- entity_layers(height, label=None)[source]¶
Return the number of layers on each entity of a given plex height.
- Parameters:
height – The height of the entity to compute the number of layers (0 -> cells, 1 -> facets, etc…)
label – An optional label name used to select points of the given height (if None, then all points are used).
- Returns:
a numpy array of the number of layers on the asked for entities (or a single layer number for the constant layer case).
- 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.
- facet_dimension()[source]¶
Returns the facet dimension.
Note
This only returns the dimension of the “side” (vertical) facets, not the “top” or “bottom” (horizontal) facets.
- layer_extents¶
The layer extents for all mesh points.
For variable layers, the layer extent does not match those for cells. A numpy array of layer extents (in PyOP2 format \([start, stop)\)), of shape
(num_mesh_points, 4)
where the first two extents are used for allocation and the last two for iteration.
- property layers¶
Return the layers parameter used to construct the mesh topology, which is the number of layers represented by the number of occurences of the base mesh for non-variable layer mesh and an array of size (num_cells, 2), each row representing the (first layer index, last layer index + 1) pair for the associated cell, for variable layer mesh.
- make_cell_node_list(global_numbering, entity_dofs, entity_permutations, offsets)[source]¶
Builds the DoF mapping.
- Parameters:
global_numbering – Section describing the global DoF numbering
entity_dofs – FInAT element entity DoFs
entity_permutations – FInAT element entity permutations
offsets – layer offsets for each entity dof.
- make_dofs_per_plex_entity(entity_dofs)[source]¶
Returns the number of DoFs per plex entity for each stratum, i.e. [#dofs / plex vertices, #dofs / plex edges, …].
each entry is a 2-tuple giving the number of dofs on, and above the given plex entity.
- Parameters:
entity_dofs – FInAT element entity DoFs
- mark_entities(tf, label_value, label_name=None)[source]¶
Mark selected entities.
- Parameters:
tf – The
CoordinatelessFunction
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.lable_value – The value used in the label.
label_name – The name of the label to store entity selections.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- node_classes(nodes_per_entity, real_tensorproduct=False)[source]¶
Compute node classes given nodes per entity.
- Parameters:
nodes_per_entity – number of function space nodes per topological entity.
- Returns:
the number of nodes in each of core, owned, and ghost classes.
- topology_dm¶
The PETSc DM representation of the mesh topology.
- firedrake.mesh.Mesh(meshfile, **kwargs)[source]¶
Construct a mesh object.
Meshes may either be created by reading from a mesh file, or by providing a PETSc DMPlex object defining the mesh topology.
- Parameters:
meshfile – the mesh file name, a DMPlex object or a Netgen mesh object defining mesh topology. See below for details on supported mesh formats.
name – optional name of the mesh object.
dim – optional specification of the geometric dimension of the mesh (ignored if not reading from mesh file). If not supplied the geometric dimension is deduced from the topological dimension of entities in the mesh.
reorder – optional flag indicating whether to reorder meshes for better cache locality. If not supplied the default value in
parameters["reorder_meshes"]
is used.distribution_parameters –
an optional dictionary of options for parallel mesh distribution. Supported keys are:
"partition"
: which may take the 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 0.5. Increase this if point at mesh boundaries (either rank local or global) are reported as being outside the mesh, for example when creating a
VertexOnlyMesh
. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.netgen_flags – The dictionary of flags to be passed to ngsPETSc.
When the mesh is read from a file the following mesh formats are supported (determined, case insensitively, from the filename extension):
GMSH: with extension .msh
Exodus: with extension .e, .exo
CGNS: with extension .cgns
Triangle: with extension .node
HDF5: with extension .h5, .hdf5 (Can only load HDF5 files created by
save_mesh()
method.)
Note
When the mesh is created directly from a DMPlex object or a Netgen mesh object, the
dim
parameter is ignored (the DMPlex already knows its geometric and topological dimensions).
- class firedrake.mesh.MeshGeometry(element, comm)[source]¶
Bases:
Mesh
,MeshGeometryMixin
A representation of mesh topology and geometry.
Initialise a mesh geometry from coordinates.
- Parameters:
coordinates (CoordinatelessFunction) – The CoordinatelessFunction containing the coordinates.
- cell_orientations()[source]¶
Return the orientation of each cell in the mesh.
Use
init_cell_orientations()
to initialise.
- property cell_sizes¶
A
Function
in the \(P^1\) space containing the local mesh size.This is computed by the \(L^2\) projection of the local mesh element size.
- clear_cell_sizes()[source]¶
Reset the
cell_sizes
field on this mesh geometry.Use this if you move the mesh.
- clear_spatial_index()[source]¶
Reset the
spatial_index
on this mesh geometry.Use this if you move the mesh (for example by reassigning to the coordinate field).
- 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.
- property input_ordering¶
Return the input ordering of the mesh vertices as a
VertexOnlyMesh()
whilst preserving other information, such as the global indices and parent mesh cell information.Notes
If
redundant=True
at mesh creation, all the vertices will be returned on rank 0.Any points that were not found in the original mesh when it was created will still be present here in their originally supplied order.
- locate_cell(x, tolerance=None)[source]¶
Locate cell containing a given point.
- Parameters:
x – point coordinates
- Keyword Arguments:
tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s
tolerance
property. Changing this from default will cause the spatial index to be rebuilt which can take some time.- Returns:
cell number (int), or None (if the point is not in the domain)
- locate_cell_and_reference_coordinate(x, tolerance=None)[source]¶
Locate cell containing a given point and the reference coordinates of the point within the cell.
- Parameters:
x – point coordinates
- Keyword Arguments:
tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s
tolerance
property. Changing this from default will cause the spatial index to be rebuilt which can take some time.- Returns:
tuple either (cell number, reference coordinates) of type (int, numpy array), or, when point is not in the domain, (None, None).
- locate_cells_ref_coords_and_dists(xs, tolerance=None)[source]¶
Locate cell containing a given point and the reference coordinates of the point within the cell.
- Parameters:
xs – 1 or more point coordinates of shape (npoints, gdim)
- Keyword Arguments:
tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s
tolerance
property. Changing this from default will cause the spatial index to be rebuilt which can take some time.- Returns:
tuple either (cell numbers array, reference coordinates array, ref_cell_dists_l1 array) of type (array of ints, array of floats of size (npoints, gdim), array of floats). The cell numbers array contains -1 for points not in the domain: the reference coordinates and distances are meaningless for these points.
- locate_reference_coordinate(x, tolerance=None)[source]¶
Get reference coordinates of a given point in its cell. Which cell the point is in can be queried with the locate_cell method.
- Parameters:
x – point coordinates
- Keyword Arguments:
tolerance – Tolerance for checking if a point is in a cell. Default is this mesh’s
tolerance
property. Changing this from default will cause the spatial index to be rebuilt which can take some time.- Returns:
reference coordinates within cell (numpy array) or None (if the point is not in the domain)
- mark_entities(f, label_value, label_name=None)[source]¶
Mark selected entities.
- Parameters:
f – The
Function
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.lable_value – The value used in the label.
label_name – The name of the label to store entity selections.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- property spatial_index¶
Spatial index to quickly find which cell contains a given point.
Notes
If this mesh has a
tolerance
property, which should be a float, this tolerance is added to the extrama of the spatial index so that points just outside the mesh, within tolerance, can be found.
- property tolerance¶
The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a cell and still be considered to be in the cell.
Increase this if points at mesh boundaries (either rank local or global) are reported as being outside the mesh, for example when creating a
VertexOnlyMesh
. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh.If this property is not set (i.e. set to
None
) no tolerance is added to the bounding box and points deemed at all outside the mesh, even by floating point error distances, will be deemed to be outside it.Notes
After changing tolerance any requests for
spatial_index
will cause the spatial index to be rebuilt with the new tolerance which may take some time.
- property topological¶
Alias of topology.
This is to ensure consistent naming for some multigrid codes.
- property topology¶
The underlying mesh topology object.
- class firedrake.mesh.MeshTopology(plex, name, reorder, distribution_parameters, sfXB=None, perm_is=None, distribution_name=None, permutation_name=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶
Bases:
AbstractMeshTopology
A representation of mesh topology implemented on a PETSc DMPlex.
Initialise a mesh topology.
- Parameters:
plex (PETSc.DMPlex) – PETSc.DMPlex representing the mesh topology.
name (str) – Name of the mesh topology.
reorder (bool) – Whether to reorder the mesh entities.
distribution_parameters (dict) – Options controlling mesh distribution; see Mesh for details.
sfXB (PETSc.PetscSF) – PETSc.SF that pushes forward the global point number slab
[0, NX)
to input (naive) plex (only significant when the mesh topology is loaded from file and only passed from inside ~.CheckpointFile).perm_is (PETSc.IS) – PETSc.IS that is used as
_dm_renumbering
; only makes sense if we know the exact parallel distribution ofplex
at the time of mesh topology construction like when we load mesh along with its distribution. If given,reorder
param will be ignored.distribution_name (str) – Name of the parallel distribution; if None, automatically generated.
permutation_name (str) – Name of the entity permutation (reordering); if None, automatically generated.
comm (mpi4py.MPI.Comm) – Communicator.
- property cell_closure¶
2D array of ordered cell closures
Each row contains ordered cell entities for a cell, one row per cell.
- property cell_set¶
- 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 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.
- property exterior_facets¶
- property interior_facets¶
- mark_entities(tf, label_value, label_name=None)[source]¶
Mark selected entities.
- Parameters:
tf – The
CoordinatelessFunction
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.lable_value – The value used in the label.
label_name – The name of the label to store entity selections.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- property submesh_child_cell_parent_cell_map¶
- property submesh_child_exterior_facet_parent_exterior_facet_map¶
- property submesh_child_exterior_facet_parent_interior_facet_map¶
- property submesh_child_interior_facet_parent_exterior_facet_map¶
- property submesh_child_interior_facet_parent_interior_facet_map¶
- submesh_map_child_parent(source_integral_type, source_subset_points, reverse=False)[source]¶
Return the map from submesh child entities to submesh parent entities or its reverse.
- Parameters:
source_integral_type (str) – Integral type on the source mesh.
source_subset_points (numpy.ndarray) – Subset points on the source mesh.
reverse (bool) – If True, return the map from parent entities to child entities.
- Returns:
(map from source to target, integral type on the target mesh, subset points on the target mesh).
- Return type:
- property submesh_parent_cell_child_cell_map¶
- property submesh_parent_exterior_facet_child_exterior_facet_map¶
- property submesh_parent_exterior_facet_child_interior_facet_map¶
- property submesh_parent_interior_facet_child_exterior_facet_map¶
- property submesh_parent_interior_facet_child_interior_facet_map¶
- trans_mesh_entity_map(base_mesh, base_integral_type, base_subdomain_id, base_all_integer_subdomain_ids)[source]¶
Create entity-entity (composed) map from base_mesh to self.
- Parameters:
base_mesh (AbstractMeshTopology) – Base mesh topology.
base_integral_type (str) – Integral type on
base_mesh
.base_subdomain_id (int) – Subdomain ID on
base_mesh
.base_all_integer_subdomain_ids (tuple) –
all_integer_subdomain_ids
corresponding tobase_mesh
andbase_integral_type
.
- Returns:
tuple of op2.ComposedMap from base_mesh to self and integral_type on self.
- Return type:
- firedrake.mesh.RelabeledMesh(mesh, indicator_functions, subdomain_ids, **kwargs)[source]¶
Construct a new mesh that has new subdomain ids.
- Parameters:
mesh – base
MeshGeometry
object using which the new one is constructed.indicator_functions – list of indicator functions that mark selected entities (cells or facets) as 1; must use “DP”/”DQ” (degree 0) functions to mark cell entities and “P” (degree 1) functions in 1D or “HDiv Trace” (degree 0) functions in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.
subdomain_ids – list of subdomain ids associated with the indicator functions in indicator_functions; thus, must have the same length as indicator_functions.
- Keyword Arguments:
name – optional name of the output mesh object.
- firedrake.mesh.SubDomainData(geometric_expr)[source]¶
Creates a subdomain data object from a boolean-valued UFL expression.
The result can be attached as the subdomain_data field of a
ufl.Measure
. For example:x = mesh.coordinates sd = SubDomainData(x[0] < 0.5) assemble(f*dx(subdomain_data=sd))
- firedrake.mesh.Submesh(mesh, subdim, subdomain_id, label_name=None, name=None)[source]¶
Construct a submesh from a given mesh.
- Parameters:
mesh (MeshGeometry) – Parent mesh (MeshGeometry).
subdim (int) – Topological dimension of the submesh.
subdomain_id (int) – Subdomain ID representing the submesh.
label_name (str) – Name of the label to search
subdomain_id
in.name (str) – Name of the submesh.
- Returns:
Submesh.
- Return type:
Notes
Currently, one can only make submeshes that have the same topological dimension as the parent mesh.
Examples
dim = 2 mesh = RectangleMesh(2, 1, 2., 1., quadrilateral=True) x, y = SpatialCoordinate(mesh) DQ0 = FunctionSpace(mesh, "DQ", 0) indicator_function = Function(DQ0).interpolate(conditional(x > 1., 1, 0)) mesh.mark_entities(indicator_function, 999) mesh = RelabeledMesh(mesh, [indicator_function], [999]) subm = Submesh(mesh, dim, 999) V0 = FunctionSpace(mesh, "CG", 1) V1 = FunctionSpace(subm, "CG", 1) V = V0 * V1 u = TrialFunction(V) v = TestFunction(V) u0, u1 = split(u) v0, v1 = split(v) dx0 = Measure("dx", domain=mesh) dx1 = Measure("dx", domain=subm) a = inner(u1, v0) * dx0(999) + inner(u0, v1) * dx1 A = assemble(a)
- firedrake.mesh.VertexOnlyMesh(mesh, vertexcoords, reorder=None, missing_points_behaviour='error', tolerance=None, redundant=True, name=None)[source]¶
Create a vertex only mesh, immersed in a given mesh, with vertices defined by a list of coordinates.
- Parameters:
mesh – The unstructured mesh in which to immerse the vertex only mesh.
vertexcoords – A list of coordinate tuples which defines the vertices.
- Keyword Arguments:
reorder – optional flag indicating whether to reorder meshes for better cache locality. If not supplied the default value in
parameters["reorder_meshes"]
is used.missing_points_behaviour – optional string argument for what to do when vertices which are outside of the mesh are discarded. If
'warn'
, will print a warning. If'error'
will raise aVertexOnlyMeshMissingPointsError
.tolerance – The relative tolerance (i.e. as defined on the reference cell) for the distance a point can be from a mesh cell and still be considered to be in the cell. Note that this tolerance uses an L1 distance (aka ‘manhattan’, ‘taxicab’ or rectilinear distance) so will scale with the dimension of the mesh. The default is the parent mesh’s
tolerance
property. Changing this from default will cause the parent mesh’s spatial index to be rebuilt which can take some time.redundant – If True, the mesh will be built using just the vertices which are specified on rank 0. If False, the mesh will be built using the vertices specified by each rank. Care must be taken when using
redundant = False
: see the note below for more information.name – Optional name for the new
VertexOnlyMesh
. If none is specified a name will be generated from the parent mesh name.
Note
The vertex only mesh uses the same communicator as the input
mesh
.Note
Extruded meshes with variable extrusion layers are not yet supported. See note below about
VertexOnlyMesh
as input.Note
When running in parallel with
redundant = False
,vertexcoords
will redistribute to the mesh partition where they are located. This means that if rank A hasvertexcoords
{X} that are not found in the mesh cells owned by rank A but are found in the mesh cells owned by rank B, then they will be moved to rank B.Note
If the same coordinates are supplied more than once, they are always assumed to be a new vertex.
- exception firedrake.mesh.VertexOnlyMeshMissingPointsError(n_missing_points)[source]¶
Bases:
Exception
Exception raised when 1 or more points are not found by a
VertexOnlyMesh()
in its parent mesh.
- class firedrake.mesh.VertexOnlyMeshTopology(swarm, parentmesh, name, reorder, input_ordering_swarm=None, perm_is=None, distribution_name=None, permutation_name=None)[source]¶
Bases:
AbstractMeshTopology
Representation of a vertex-only mesh topology immersed within another mesh.
Initialise a mesh topology.
- Parameters:
swarm (PETSc.DMSwarm) – PETSc.DMSwarm representing Particle In Cell (PIC) vertices immersed within a PETSc.DM stored in the
parentmesh
.parentmesh (AbstractMeshTopology) – Mesh topology within which the vertex-only mesh topology is immersed.
name (str) – Name of the mesh topology.
reorder (bool) – Whether to reorder the mesh entities.
input_ordering_swarm (PETSc.DMSwarm) – The swarm from which the input-ordering vertex-only mesh is constructed.
perm_is (PETSc.IS) – PETSc.IS that is used as
_dm_renumbering
; only makes sense if we know the exact parallel distribution ofplex
at the time of mesh topology construction like when we load mesh along with its distribution. If given,reorder
param will be ignored.distribution_name (str) – Name of the parallel distribution; if None, automatically generated.
permutation_name (str) – Name of the entity permutation (reordering); if None, automatically generated.
- property cell_closure¶
2D array of ordered cell closures
Each row contains ordered cell entities for a cell, one row per cell.
- property cell_global_index¶
Return a list of unique cell IDs in vertex only mesh cell order.
- property cell_parent_base_cell_list¶
Return a list of parent mesh base cells numbers in vertex only mesh cell order.
- property cell_parent_base_cell_map¶
Return the
pyop2.types.map.Map
from vertex only mesh cells to parent mesh base cells.
- property cell_parent_cell_list¶
Return a list of parent mesh cells numbers in vertex only mesh cell order.
- property cell_parent_cell_map¶
Return the
pyop2.types.map.Map
from vertex only mesh cells to parent mesh cells.
- property cell_parent_extrusion_height_list¶
Return a list of parent mesh extrusion heights in vertex only mesh cell order.
- property cell_parent_extrusion_height_map¶
Return the
pyop2.types.map.Map
from vertex only mesh cells to parent mesh extrusion heights.
- property cell_set¶
- property cell_to_facets¶
Raises an AttributeError since cells in a VertexOnlyMeshTopology have no facets.
- entity_orientations = None¶
- property exterior_facets¶
- property input_ordering¶
Return the input ordering of the mesh vertices as a
VertexOnlyMeshTopology
whilst preserving other information, such as the global indices and parent mesh cell information.Notes
If
redundant=True
at mesh creation, all the vertices will be returned on rank 0.Any points that were not found in the original mesh when it was created will still be present here in their originally supplied order.
- property input_ordering_sf¶
Return a PETSc SF which has
VertexOnlyMesh()
input ordering vertices as roots and this mesh’s vertices (including any halo cells) as leaves.
- property input_ordering_without_halos_sf¶
Return a PETSc SF which has
VertexOnlyMesh()
input ordering vertices as roots and this mesh’s non-halo vertices as leaves.
- property interior_facets¶
- mark_entities(tf, label_value, label_name=None)[source]¶
Mark selected entities.
- Parameters:
tf – The
CoordinatelessFunction
object that marks selected entities as 1. f.function_space().ufl_element() must be “DP” or “DQ” (degree 0) to mark cell entities and “P” (degree 1) in 1D or “HDiv Trace” (degree 0) in 2D or 3D to mark facet entities. Can use “Q” (degree 2) functions for 3D hex meshes until we support “HDiv Trace” elements on hex.lable_value – The value used in the label.
label_name – The name of the label to store entity selections.
All entities must live on the same topological dimension. Currently, one can only mark cell or facet entities.
- 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
.- Keyword Arguments:
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.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 enables PyOP2’s runtime checking of par_loop arguments in all cases (even those where they are claimed safe). Additionally, it switches to compiling generated code in debug mode.
Returns a function that can be called with no arguments, to restore the state of the parameters dict.
- firedrake.parameters.parameters = {'default_matrix_type': 'aij', 'default_sub_matrix_type': 'baij', 'form_compiler': {'mode': 'spectral', 'quadrature_degree': 'auto', 'quadrature_rule': 'auto', 'scalar_type': dtype('float64'), 'scalar_type_c': 'double', 'unroll_indexsum': 3}, 'pyop2_options': {'block_sparsity': True, 'cache_dir': '/home/firedrake/firedrake/.cache/pyop2', 'cc': '', 'cflags': '', 'check_src_hashes': True, 'compute_kernel_flops': False, 'cxx': '', 'cxxflags': '', 'debug': False, 'ld': '', 'ldflags': '', 'log_level': 'WARNING', 'matnest': True, 'no_fork_available': False, 'node_local_compilation': True, 'print_cache_info': False, 'simd_width': 4, 'spmd_strict': False, '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.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, **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 2-tuple of (domains, instructions) to create a loopy kernel . The domains and instructions should be specified in loopy kernel syntax. See the loopy tutorial for details.
measure – is a UFL
Measure
which determines the manner in which the iteration over the mesh is to occur. Alternatively, you can 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
- Keyword Arguments:
iterate –
Optionally specify which region of an
pyop2.types.set.ExtrudedSet
to iterate over. Valid values are the following objects from pyop2:ON_BOTTOM
: iterate over the bottom layer of cells.ON_TOP
iterate over the top layer of cells.ALL
iterate over all cells (the default if unspecified)ON_INTERIOR_FACETS
iterate over all the layers except the top layer, accessing data two adjacent (in the extruded direction) cells at a time.
Example
Assume that A is a
Function
in CG1 and B is 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) domain = '{[i]: 0 <= i < A.dofs}' instructions = ''' for i A[i] = max(A[i], B[0]) end ''' par_loop((domain, instructions), dx, {'A' : (A, RW), 'B': (B, READ)})
Argument definitions
Each item in the args dictionary maps a string to a tuple containing a
Function
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
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.petsc.get_external_packages()[source]¶
Return a list of PETSc external packages that are installed.
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 ‘manhattan’, ‘taxicab’ or rectilinear distance) to a FIAT reference cell.
- Parameters:
fiat_cell (FIAT.finite_element.FiniteElement) – The FIAT cell with same geometric dimension as the coordinate X.
X (str) – The name of the input pointer variable to use.
celldist (str) – The name of the output variable.
- Returns:
A string of C code.
- Return type:
- 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_cell (FIAT.finite_element.FiniteElement) – The FIAT cell with same geometric dimension as the coordinate X.
eps (float) – The tolerance to use for the check. Usually some small number like 1e-14.
X (str) – The name of the input pointer variable to use in the generated C code: it should be a pointer to a type that is an acceptable input to the PetscRealPart function. Default is “X”.
celldist (str) – The name of the output variable.
- Returns:
A C expression which is true if the point is inside the cell and false otherwise.
- Return type:
firedrake.progress_bar module¶
A module providing progress bars.
- class firedrake.progress_bar.ProgressBar(*args, comm=<mpi4py.MPI.Intracomm object>, **kwargs)[source]¶
Bases:
FillingSquaresBar
A progress bar for simulation execution.
This is a subclass of
progress.bar.FillingSquaresBar
which is configured to be suitable for tracking progress in forward and adjoint simulations. It is also extended to only output on rank 0 in parallel.- Parameters:
message (str) – An identifying string to be prepended to the progress bar. This defaults to an empty string.
comm (mpi4py.MPI.Intracomm) – The MPI communicator over which the simulation is run. Defaults to COMM_WORLD
Notes
Further parameters can be passed as per the progress package documentation, or you can customise further by subclassing.
Examples
To apply a progress bar to a loop, wrap the loop iterator in the
iter
method of 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: Expr, v_out: WithGeometry | Function, bcs: BCBase | None = None, solver_parameters: dict | None = None, form_compiler_parameters: dict | None = None, constant_jacobian: bool | None = True, use_slate_for_inverse: bool | None = False, quadrature_degree: int | tuple[int] | None = None)[source]¶
Projection class.
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
to project.v_out – The
FunctionSpace
orFunction
to project into.bcs – Boundary conditions to apply in the projection.
solver_parameters – Parameters to pass to the solver used when projecting.
form_compiler_parameters – Parameters to the form compiler.
constant_jacobian – Whether the projection matrix constant between calls. Set to
False
if using moving meshes.use_slate_for_inverse – Compute mass inverse cell-wise using SLATE (ignored for non-DG function spaces)(only valid for DG function spaces).
quadrature_degree – Quadrature degree to use when approximating integrands.
- firedrake.projection.project(v: Expr, V: WithGeometry | Function, bcs: BCBase | None = None, solver_parameters: dict | None = None, form_compiler_parameters: dict | None = None, use_slate_for_inverse: bool | None = True, quadrature_degree: int | tuple[int] | None = None, name: str | None = None, ad_block_tag: str | None = None) Function [source]¶
Project a UFL expression into a
FunctionSpace
.- Parameters:
v – The
ufl.core.expr.Expr
to project.V – The
FunctionSpace
orFunction
to project into.bcs – Boundary conditions to apply in the projection.
solver_parameters – Parameters to pass to the solver used when projecting.
form_compiler_parameters – Parameters to the form compiler.
use_slate_for_inverse – Compute mass inverse cell-wise using SLATE (ignored for non-DG function spaces).
quadrature_degree – Quadrature degree to use when approximating integrands.
name – The name of the resulting
Function
.ad_block_tag – String for tagging the resulting block on the Pyadjoint tape.
- Returns:
The
Function
on the newFunctionSpace
.- Return type:
Notes
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.
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 aMatrix
andx
andb
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 ofsolver_parameters
see below.Optionally, an argument
P
of typeMatrixBase
can be passed to construct any preconditioner from; if none is suppliedA
is used to construct the preconditioner.solve(A, x, b, P=P, bcs=bcs, solver_parameters={...})
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.To exclude Dirichlet boundary condition nodes through the use of a :class`.RestrictedFunctionSpace`, set the
restrict
keyword argument to be True.
firedrake.solving_utils module¶
- firedrake.solving_utils.set_defaults(solver_parameters, arguments, *, ksp_defaults=None, snes_defaults=None)[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(mesh_A, mesh_B)¶
firedrake.tsfc_interface module¶
Provides the interface to TSFC for compiling a form, and transforms the TSFC-generated code to make it suitable for passing to the backends.
- class firedrake.tsfc_interface.KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_numbers, constant_numbers, needs_cell_facets, pass_layer_arg, needs_cell_sizes, arguments, events)¶
Bases:
tuple
Create new instance of KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_numbers, constant_numbers, needs_cell_facets, pass_layer_arg, needs_cell_sizes, arguments, events)
- arguments¶
Alias for field number 10
- coefficient_numbers¶
Alias for field number 5
- constant_numbers¶
Alias for field number 6
- domain_number¶
Alias for field number 4
- events¶
Alias for field number 11
- integral_type¶
Alias for field number 1
- kernel¶
Alias for field number 0
- needs_cell_facets¶
Alias for field number 7
- needs_cell_sizes¶
Alias for field number 9
- oriented¶
Alias for field number 2
- pass_layer_arg¶
Alias for field number 8
- subdomain_id¶
Alias for field number 3
- class firedrake.tsfc_interface.SplitKernel(indices, kinfo)¶
Bases:
tuple
Create new instance of SplitKernel(indices, kinfo)
- indices¶
Alias for field number 0
- kinfo¶
Alias for field number 1
- class firedrake.tsfc_interface.TSFCKernel(form, name, parameters, coefficient_numbers, constant_numbers, interface, diagonal=False)[source]¶
Bases:
object
A wrapper object for one or more TSFC kernels compiled from a given
Form
.- Parameters:
form – the
Form
from which to compile the kernels.name – a prefix to be applied to the compiled kernel names. This is primarily useful for debugging.
parameters – a dict of parameters to pass to the form compiler.
coefficient_numbers – Map from coefficient numbers in the provided (split) form to coefficient numbers in the original form.
constant_numbers – Map from local constant numbers in the provided (split) form to constant numbers in the original form.
interface – the KernelBuilder interface for TSFC (may be None)
diagonal – If assembling a matrix is it diagonal?
- firedrake.tsfc_interface.as_pyop2_local_kernel(ast, name, nargs, access=Access.INC, **kwargs)[source]¶
Convert a loopy kernel to a PyOP2
pyop2.LocalKernel
.- Parameters:
ast – The kernel code. This could be, for example, a loopy kernel.
name – The kernel name.
nargs – The number of arguments expected by the kernel.
access – Access descriptor for the first kernel argument.
- firedrake.tsfc_interface.compile_form(form, name, parameters=None, split=True, interface=None, diagonal=False)[source]¶
Compile a form using TSFC.
- Parameters:
form – the
Form
to compile.name – a prefix for the generated kernel functions.
parameters – optional dict of parameters to pass to the form compiler. If not provided, parameters are read from the
form_compiler
slot of the Firedrakeparameters
dictionary (which see).split – If
False
, then don’t split mixed forms.
Returns a tuple of tuples of (index, integral type, subdomain id, coordinates, coefficients, needs_orientations,
pyop2.op2.Kernel
).needs_orientations
indicates whether the form requires cell orientation information (for correctly pulling back to reference elements on embedded manifolds).The coordinates are extracted from the domain of the integral (a
Mesh()
)
- firedrake.tsfc_interface.extract_numbered_coefficients(expr, numbers)[source]¶
Return expression coefficients specified by a numbering.
- Parameters:
expr – A UFL expression.
numbers – Iterable of indices used for selecting the correct coefficients from
expr
.
- Returns:
A list of UFL coefficients.
- firedrake.tsfc_interface.gather_integer_subdomain_ids(knls)[source]¶
Gather a dict of all integer subdomain IDs per integral type.
This is needed to correctly interpret the
"otherwise"
subdomain ID.- Parameters:
knls – Iterable of
SplitKernel
objects.
firedrake.ufl_expr module¶
- class firedrake.ufl_expr.Argument(*args, **kwargs)[source]¶
Bases:
Argument
Representation of the argument to a form.
- Parameters:
function_space – the
FunctionSpace
the argument corresponds to.number – the number of the argument being constructed.
- Keyword Arguments:
part – optional index (mostly ignored).
Note
an
Argument
with a number of0
is used as aTestFunction()
, with a number of1
it is used as aTrialFunction()
.Initialise.
- property cell_node_map¶
- property exterior_facet_node_map¶
- property interior_facet_node_map¶
- firedrake.ufl_expr.CellSize(mesh)[source]¶
A symbolic representation of the cell size of a mesh.
- Parameters:
mesh – the mesh for which to calculate the cell size.
- class firedrake.ufl_expr.Coargument(*args, **kw)[source]¶
Bases:
Coargument
Representation of an argument to a form in a dual space.
- Parameters:
function_space – the
FunctionSpace
the argument corresponds to.number – the number of the argument being constructed.
- Keyword Arguments:
part – optional index (mostly ignored).
Initialise.
- property cell_node_map¶
- property exterior_facet_node_map¶
- property interior_facet_node_map¶
- ufl_operands¶
- firedrake.ufl_expr.FacetNormal(mesh)[source]¶
A symbolic representation of the facet normal on a cell in a mesh.
- Parameters:
mesh – the mesh over which the normal should be represented.
- firedrake.ufl_expr.TestFunction(function_space, part=None)[source]¶
Build a test function on the specified function space.
- Parameters:
function_space – the
FunctionSpace
to build the test function on.- Keyword Arguments:
part – optional index (mostly ignored).