firedrake package¶
Subpackages¶
Submodules¶
firedrake.assemble module¶

firedrake.assemble.
assemble
(f, tensor=None, bcs=None, form_compiler_parameters=None, inverse=False, mat_type=None, sub_mat_type=None, appctx={}, options_prefix=None, **kwargs)[source]¶ Evaluate f.
 Parameters
tensor – an existing tensor object to place the result in (optional).
bcs – a list of boundary conditions to apply (optional).
form_compiler_parameters – (optional) dict of parameters to pass to the form compiler. Ignored if not assembling a
Form
. Any parameters provided here will be overridden by parameters set on theMeasure
in the form. For example, if aquadrature_degree
of 4 is specified in this argument, but a degree of 3 is requested in the measure, the latter will be used.inverse – (optional) if f is a 2form, then assemble the inverse of the local matrices.
mat_type – (optional) string indicating how a 2form (matrix) should be assembled – either as a monolithic matrix (‘aij’ or ‘baij’), a block matrix (‘nest’), or left as a
ImplicitMatrix
giving matrixfree actions (‘matfree’). If not supplied, the default value inparameters["default_matrix_type"]
is used. BAIJ differs from AIJ in that only the block sparsity rather than the dof sparsity is constructed. This can result in some memory savings, but does not work with all PETSc preconditioners. BAIJ matrices only make sense for nonmixed matrices.sub_mat_type – (optional) string indicating the matrix type to use inside a nested block matrix. Only makes sense if
mat_type
isnest
. May be one of ‘aij’ or ‘baij’. If not supplied, defaults toparameters["default_sub_matrix_type"]
.appctx – Additional information to hang on the assembled matrix if an implicit matrix is requested (mat_type “matfree”).
options_prefix – PETSc options prefix to apply to matrices.
If f is a
Form
then this evaluates the corresponding integral(s) and returns afloat
for 0forms, aFunction
for 1forms and aMatrix
orImplicitMatrix
for 2forms.If f is an expression other than a form, it will be evaluated pointwise on the
Function
s in the expression. This will only succeed if all the Functions are on the sameFunctionSpace
.If f is a Slate tensor expression, then it will be compiled using Slate’s linear algebra compiler.
If
tensor
is supplied, the assembled result will be placed there, otherwise a new object of the appropriate type will be returned.If
bcs
is supplied andf
is a 2form, the rows and columns of the resultingMatrix
corresponding to boundary nodes will be set to 0 and the diagonal entries to 1. Iff
is a 1form, the vector entries at boundary nodes are set to the boundary condition values.
firedrake.assemble_expressions module¶

class
firedrake.assemble_expressions.
Assign
(lhs, rhs)[source]¶ Bases:
firedrake.assemble_expressions.AssignmentBase
A UFL assignment operator.

ufl_free_indices
= ()¶

ufl_index_dimensions
= ()¶

ufl_shape
¶


class
firedrake.assemble_expressions.
AssignmentBase
(lhs, rhs)[source]¶ Bases:
ufl.core.operator.Operator
Base class for UFL augmented assignments.

ufl_shape
¶


class
firedrake.assemble_expressions.
AugmentedAssignment
(lhs, rhs)[source]¶ Bases:
firedrake.assemble_expressions.AssignmentBase
Base for the augmented assignment operators +=, =, *=, /=

class
firedrake.assemble_expressions.
Bag
[source]¶ Bases:
object
An empty class which will be used to store arbitrary properties.

class
firedrake.assemble_expressions.
DummyFunction
(function, argnum, intent=Access('READ'))[source]¶ Bases:
ufl.coefficient.Coefficient
A dummy object to take the place of a
Function
in the expression. This has the sole role of producing the right strings when the expression is unparsed and when the arguments are formatted.
arg
¶


class
firedrake.assemble_expressions.
ExpressionSplitter
(variable_cache=None)[source]¶ Bases:
ufl.algorithms.transformer.ReuseTransformer
Split an expression tree into a subtree for each component of the appropriate
FunctionSpace
.
indexed
(o, *operands)[source]¶ Reconstruct the
ufl.indexed.Indexed
only if the coefficient is defined on aFunctionSpace
with rank 1.


class
firedrake.assemble_expressions.
ExpressionWalker
[source]¶ Bases:
ufl.algorithms.transformer.ReuseTransformer

algebra_operator
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.

condition
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.

conditional
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.

math_function
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.


class
firedrake.assemble_expressions.
IAdd
(lhs, rhs)[source]¶ Bases:
firedrake.assemble_expressions.AugmentedAssignment
A UFL += operator.

ufl_free_indices
= ()¶

ufl_index_dimensions
= ()¶


class
firedrake.assemble_expressions.
IDiv
(lhs, rhs)[source]¶ Bases:
firedrake.assemble_expressions.AugmentedAssignment
A UFL /= operator.

ufl_free_indices
= ()¶

ufl_index_dimensions
= ()¶


class
firedrake.assemble_expressions.
IMul
(lhs, rhs)[source]¶ Bases:
firedrake.assemble_expressions.AugmentedAssignment
A UFL *= operator.

ufl_free_indices
= ()¶

ufl_index_dimensions
= ()¶


class
firedrake.assemble_expressions.
ISub
(lhs, rhs)[source]¶ Bases:
firedrake.assemble_expressions.AugmentedAssignment
A UFL = operator.

ufl_free_indices
= ()¶

ufl_index_dimensions
= ()¶


class
firedrake.assemble_expressions.
IndexRelabeller
[source]¶ Bases:
ufl.corealg.multifunction.MultiFunction

expr
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.


firedrake.assemble_expressions.
assemble_expression
(expr, subset=None)[source]¶ Evaluates UFL expressions on
Function
s pointwise and assigns into a newFunction
.

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

firedrake.assemble_expressions.
expression_kernel
(expr, args)[source]¶ Produce a
pyop2.Kernel
from the processed UFL expression expr and the corresponding args.

firedrake.assemble_expressions.
ufl_type
(*args, **kwargs)[source]¶ Decorator mimicing
ufl.core.ufl_type.ufl_type()
.Additionally adds the class decorated to the appropriate set of ufl classes.
firedrake.bcs module¶

class
firedrake.bcs.
DirichletBC
(V, g, sub_domain, method='topological')[source]¶ Bases:
firedrake.bcs.BCBase
Implementation of a strong Dirichlet boundary condition.
 Parameters
V – the
FunctionSpace
on which the boundary condition should be applied.g – the boundary condition values. This can be a
Function
onV
, aConstant
, anExpression
, an iterable of literal constants (converted to anExpression
), or a literal constant which can be pointwise evaluated at the nodes ofV
.Expression
s are projected ontoV
if it does not support pointwise evaluation.sub_domain – the integer id(s) of the boundary region over which the boundary condition should be applied. The string “on_boundary” may be used to indicate all of the boundaries of the domain. In the case of extrusion the
top
andbottom
strings are used to flag the bcs application on the top and bottom boundaries of the extruded mesh respectively.method – the method for determining boundary nodes. The default is “topological”, indicating that nodes topologically associated with a boundary facet will be included. The alternative value is “geometric”, which indicates that nodes associated with basis functions which do not vanish on the boundary will be included. This can be used to impose strong boundary conditions on DG spaces, or noslip conditions on HDiv spaces.

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

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.

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

class
firedrake.bcs.
EquationBC
(*args, bcs=None, J=None, Jp=None, method='topological', 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/or :class:
.EquationBC`s to be applied to this boundary condition equation (optional)J – the Jacobian for this boundary equation (optional)
Jp – a form used for preconditioning the linear system, optional, if not supplied then the Jacobian itself will be used.
method – see
DirichletBC
(optional)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.checkpointing module¶

class
firedrake.checkpointing.
DumbCheckpoint
(basename, single_file=True, mode=2, comm=None)[source]¶ Bases:
object
A very dumb checkpoint object.
This checkpoint object is capable of writing
Function
s to disk in parallel (using HDF5) and reloading them on the same number of processes and aMesh()
constructed identically. Parameters
basename – the base name of the checkpoint file.
single_file – Should the checkpoint object use only a single ondisk file (irrespective of the number of stored timesteps)? See
new_file()
for more details.mode – the access mode (one of
FILE_READ
,FILE_CREATE
, orFILE_UPDATE
)comm – (optional) communicator the writes should be collective over.
This object can be used in a context manager (in which case it closes the file when the scope is exited).
Note
This object contains both a PETSc
Viewer
, used for storing and loadingFunction
data, and anFile
opened on the same file handle. DO NOT callFile.close()
on the latter, this will cause breakages.
get_timesteps
()[source]¶ Return all the time steps (and time indices) in the current checkpoint file.
This is useful when reloading from a checkpoint file that contains multiple timesteps and one wishes to determine the final available timestep in the file.

h5file
¶ An h5py File object pointing at the open file handle.

has_attribute
(obj, name)[source]¶ Check for existance of an HDF5 attribute on a specified data object.
 Parameters
obj – The path to the data object.
name – The name of the attribute.

load
(function, name=None)[source]¶ Store a function from the checkpoint file.
 Parameters
function – The function to load values into.
name – an (optional) name used to find the function values. If not provided, uses
function.name()
.
This function is timestepaware and reads from the appropriate place if
set_timestep()
has been called.

new_file
(name=None)[source]¶ Open a new ondisk file for writing checkpoint data.
 Parameters
name – An optional name to use for the file, an extension of
.h5
is automatically appended.
If
name
is not provided, a filename is generated from thebasename
used when creating theDumbCheckpoint
object. Ifsingle_file
isTrue
, then we write toBASENAME.h5
otherwise, each timenew_file()
is called, we create a new file with an increasing index. In this case the files created are:BASENAME_0.h5 BASENAME_1.h5 ... BASENAME_n.h5
with the index incremented on each invocation of
new_file()
(whenever the custom name is not provided).

read_attribute
(obj, name, default=None)[source]¶ Read an HDF5 attribute on a specified data object.
 Parameters
obj – The path to the data object.
name – The name of the attribute.
default – Optional default value to return. If not provided an
AttributeError
is raised if the attribute does not exist.

set_timestep
(t, idx=None)[source]¶ Set the timestep for output.
 Parameters
t – The timestep value.
idx – An optional timestep index to use, otherwise an internal index is used, incremented by 1 every time
set_timestep()
is called.

store
(function, name=None)[source]¶ Store a function in the checkpoint file.
 Parameters
function – The function to store.
name – an (optional) name to store the function under. If not provided, uses
function.name()
.
This function is timestepaware and stores to the appropriate place if
set_timestep()
has been called.

vwr
¶ The PETSc Viewer used to store and load function data.

class
firedrake.checkpointing.
HDF5File
(filename, file_mode, comm=None)[source]¶ Bases:
object
An object to facilitate checkpointing.
This checkpoint object is capable of writing
Function
s to disk in parallel (using HDF5) and reloading them on the same number of processes and aMesh()
constructed identically. Parameters
filename – filename (including suffix .h5) of checkpoint file.
file_mode – the access mode, passed directly to h5py, see
File
for details on the meaning.comm – communicator the writes should be collective over.
This object can be used in a context manager (in which case it closes the file when the scope is exited).

firedrake.checkpointing.
FILE_READ
= 0¶ Open a checkpoint file for reading. Raises an error if file does not exist.

firedrake.checkpointing.
FILE_CREATE
= 1¶ Create a checkpoint file. Truncates the file if it exists.

firedrake.checkpointing.
FILE_UPDATE
= 2¶ Open a checkpoint file for updating. Creates the file if it does not exist, providing both read and write access.
firedrake.constant module¶

class
firedrake.constant.
Constant
(value, domain=None)[source]¶ Bases:
ufl.coefficient.Coefficient
A “constant” coefficient
A
Constant
takes one value over the wholeMesh()
. The advantage of using aConstant
in a form rather than a literal value is that the constant will be passed as an argument to the generated kernel which avoids the need to recompile the kernel if the form is assembled for a different value of the constant. Parameters
value – the value of the constant. May either be a scalar, an iterable of values (for a vectorvalued constant), or an iterable of iterables (or numpy array with 2dimensional shape) for a tensorvalued constant.
domain – an optional
Mesh()
on which the constant is defined.
Note
If you intend to use this
Constant
in aForm
on its own you need to pass aMesh()
as the domain argument.
assign
(value)[source]¶ Set the value of this constant.
 Parameters
value – A value of the appropriate shape

evaluate
(x, mapping, component, index_values)[source]¶ Return the evaluation of this
Constant
. Parameters
x – The coordinate to evaluate at (ignored).
mapping – A mapping (ignored).
component – The requested component of the constant (may be
None
or()
to obtain all components).index_values – ignored.
firedrake.dmhooks module¶
Firedrake uses PETSc for its linear and nonlinear solvers. The interaction is carried out through DM objects. These carry around any userdefined application context and can be used to inform the solvers how to create field decompositions (for fieldsplit preconditioning) as well as creating subDMs (which only contain some fields), along with multilevel information (for geometric multigrid)
The way Firedrake interacts with these DMs is, broadly, as follows:
A DM is tied to a FunctionSpace
and remembers what function
space that is. To avoid reference cycles defeating the garbage
collector, the DM holds a weakref to the FunctionSpace (which holds a
strong reference to the DM). Use get_function_space()
to get
the function space attached to the DM, and set_function_space()
to attach it.
Similarly, when a DM is used in a solver, an application context is
attached to it, such that when PETSc calls back into Firedrake, we can
grab the relevant information (how to make the Jacobian, etc…).
This functions in a similar way using 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 multilevel solvers
(pc_type mg
and snes_type fas
) is decomposing the DMs. When
a field decomposition is created, the callback
create_field_decomposition()
checks to see if an application
context exists. If so, it splits it apart (one for each of fields)
and attaches these split contexts to the subdms returned to PETSc.
This facilitates runtime composition with multilevel solvers. When
coarsening a DM, the application context is coarsened and transferred
to the coarse DM. The combination of these two symbolic transfer
operations allow us to nest geometric multigrid preconditioning inside
fieldsplit preconditioning, without having to set everything up in
advance.

class
firedrake.dmhooks.
SetupHooks
[source]¶ Bases:
object
Hooks run for setup and teardown of DMs inside solvers.
Used for transferring problemspecific 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 toplevel DM that describes the problemspecific data.
This is your normal entrypoint 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 subDM describing the specified fields.
 Parameters
DM – The DM.
fields – The fields in the new subDM.

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.
pop_transfer_operators
(dm, match=None)¶

firedrake.dmhooks.
push_appctx
(dm, obj)¶

firedrake.dmhooks.
push_ctx_coarsener
(dm, obj)¶

firedrake.dmhooks.
push_parent
(dm, obj)¶

firedrake.dmhooks.
push_transfer_operators
(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.

class
firedrake.dmhooks.
transfer_operators
(V, prolong=None, restrict=None, inject=None)[source]¶ Bases:
object
Run a code block with custom grid transfer operators attached.
 Parameters
V – the functionspace to attach the transfer to.
prolong – prolongation coarse > fine.
restrict – restriction fine^* > coarse^*.
inject – injection fine > coarse.
firedrake.dmplex module¶

firedrake.dmplex.
boundary_nodes
()¶ Extract boundary nodes from a function space..
 Parameters
V – the function space
sub_domain – a mesh marker selecting the part of the boundary (may be “on_boundary” indicating the entire boundary).
method – how to identify boundary dofs on the reference cell.
 Returns
a numpy array of unique nodes on the boundary of the requested subdomain.

firedrake.dmplex.
cell_facet_labeling
()¶ Computes a labeling for the facet numbers on a particular cell (interior and exterior facet labels with subdomain markers). The ith local facet is represented as:
cell_facets[c, i]
If cell_facets[c, i, 0] is
0
, then the local faceti
is an exterior facet, otherwise if the result is1
it is interior. cell_facets[c, i, 1] returns the subdomain marker for the local facet. Parameters
plex – The DMPlex object representing the mesh topology.
cell_numbering – PETSc.Section describing the global cell numbering
cell_closures – 2D array of ordered cell closures.

firedrake.dmplex.
clear_adjacency_callback
()¶ Clear the callback for DMPlexGetAdjacency.
 Parameters
dm – The DMPlex object

firedrake.dmplex.
closure_ordering
()¶ Apply Fenics local numbering to a cell closure.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
vertex_numbering – Section describing the universal vertex numbering
cell_numbering – Section describing the global cell numbering
entity_per_cell – List of the number of entity points in each dimension
 Vertices := Ordered according to global/universal
vertex numbering
 Edges/faces := Ordered according to lexicographical
ordering of nonincident vertices

firedrake.dmplex.
create_section
()¶ Create the section describing a global numbering.
 Parameters
mesh – The mesh.
nodes_per_entity – Number of nodes on each type of topological entity of the mesh. Or, if the mesh is extruded, the number of nodes on, and on top of, each topological entity in the base mesh.
on_base – If True, assume extruded space is actually Foo x Real.
 Returns
A PETSc Section providing the number of dofs, and offset of each dof, on each mesh point.

firedrake.dmplex.
exchange_cell_orientations
()¶ Halo exchange of cell orientations.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
section – Section describing the cell numbering
orientations – Cell orientations to exchange, values in the halo will be overwritten.

firedrake.dmplex.
facet_numbering
()¶ Compute the parent cell(s) and the local facet number within each parent cell for each given facet.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
kind – String indicating the facet kind (interior or exterior)
facets – Array of input facets
cell_numbering – Section describing the global cell numbering
cell_closures – 2D array of ordered cell closures

firedrake.dmplex.
get_cell_markers
()¶ Get the cells marked by a given subdomain_id.
 Parameters
plex – The DM for the mesh topology
cell_numbering – Section mapping plex cell points to firedrake cell indices.
subdomain_id – The subdomain_id to look for.
 Raises
ValueError – if the subdomain_id is not valid.
 Returns
A numpy array (possibly empty) of the cell ids.

firedrake.dmplex.
get_cell_nodes
()¶ Builds the DoF mapping.
 Parameters
mesh – The mesh
global_numbering – Section describing the global DoF numbering
entity_dofs – FInAT element entity dofs for the cell
offset – offsets for each entity dof walking up a column.
Preconditions: This function assumes that cell_closures contains mesh entities ordered by dimension, i.e. vertices first, then edges, faces, and finally the cell. For quadrilateral meshes, edges corresponding to dimension (0, 1) in the FInAT element must precede edges corresponding to dimension (1, 0) in the FInAT element.

firedrake.dmplex.
get_cell_remote_ranks
()¶ Returns an array assigning the rank of the owner to each locally visible cell. Locally owned cells have 1 assigned to them.
 Parameters
plex – The DMPlex object encapsulating the mesh topology

firedrake.dmplex.
get_entity_classes
()¶ Builds PyOP2 entity class offsets for all entity levels.
 Parameters
plex – The DMPlex object encapsulating the mesh topology

firedrake.dmplex.
get_facet_markers
()¶ Get an array of facet labels in the mesh.
 Parameters
dm – The DM that contains labels.
facets – The array of facet points.
 Returns
a numpy array of facet ids (or None if all facets had the default marker).

firedrake.dmplex.
get_facet_nodes
()¶ Build to DoF mapping from facets.
 Parameters
mesh – The mesh.
cell_nodes – numpy array mapping from cells to function space nodes.
label – which set of facets to ask for (interior_facets or exterior_facets).
offset – optional offset (extruded only).
 Returns
numpy array mapping from facets to nodes in the closure of the support of that facet.

firedrake.dmplex.
get_facet_ordering
()¶ Builds a list of all facets ordered according to the given numbering.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
facet_numbering – A Section describing the global facet numbering

firedrake.dmplex.
get_facets_by_class
()¶ Builds a list of all facets ordered according to PyOP2 entity classes and computes the respective class offsets.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
ordering – An array giving the global traversal order of facets
label – Label string that marks the facets to order

firedrake.dmplex.
halo_begin
()¶ Begin a halo exchange.
 Parameters
sf – the PETSc SF to use for exchanges
dat – the
pyop2.Dat
to perform the exchange ondtype – an MPI datatype describing the unit of data
reverse – should a reverse (localtoglobal) exchange be performed.
Forward exchanges are implemented using
PetscSFBcastBegin
, reverse exchanges withPetscSFReduceBegin
.

firedrake.dmplex.
halo_end
()¶ End a halo exchange.
 Parameters
sf – the PETSc SF to use for exchanges
dat – the
pyop2.Dat
to perform the exchange ondtype – an MPI datatype describing the unit of data
reverse – should a reverse (localtoglobal) exchange be performed.
Forward exchanges are implemented using
PetscSFBcastEnd
, reverse exchanges withPetscSFReduceEnd
.

firedrake.dmplex.
label_facets
()¶ Add labels to facets in the the plex
Facets on the boundary are marked with “exterior_facets” while all others are marked with “interior_facets”.
 Parameters
label_boundary – if False, don’t label the boundary faces (they must have already been labelled).

firedrake.dmplex.
make_global_numbering
()¶ Build an array of global numbers for local dofs
 Parameters
lsec – Section describing local dof layout and numbers.
gsec – Section describing global dof layout and numbers.

firedrake.dmplex.
mark_entity_classes
()¶ Mark all points in a given Plex according to the PyOP2 entity classes:
core : owned and not in send halo owned : owned and in send halo ghost : in halo
 Parameters
plex – The DMPlex object encapsulating the mesh topology

firedrake.dmplex.
orientations_facet2cell
()¶ Converts local quadrilateral facet orientations into global quadrilateral cell orientations.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
vertex_numbering – Section describing the universal vertex numbering
facet_orientations – Facet orientations (edge directions) relative to the local DMPlex ordering.
cell_numbering – Section describing the cell numbering

firedrake.dmplex.
plex_renumbering
()¶ Build a global node renumbering as a permutation of Plex points.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
entity_classes – Array of entity class offsets for each dimension.
reordering – A reordering from reordered to original plex points used to provide the traversal order of the cells (i.e. the inverse of the ordering obtained from DMPlexGetOrdering). Optional, if not provided (or
None
), no reordering is applied and the plex is traversed in original order.
The node permutation is derived from a depthfirst traversal of the Plex graph over each entity class in turn. The returned IS is the Plex > PyOP2 permutation.

firedrake.dmplex.
prune_sf
()¶ Prune an SF of roots referencing the local rank
 Parameters
sf – The PETSc SF to prune.

firedrake.dmplex.
quadrilateral_closure_ordering
()¶ Cellwise orders mesh entities according to the given cell orientations.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
vertex_numbering – Section describing the universal vertex numbering
cell_numbering – Section describing the cell numbering
cell_orientations – Specifies the starting vertex for each cell, and the order of traversal (CCW or CW).

firedrake.dmplex.
quadrilateral_facet_orientations
()¶ Returns globally synchronised facet orientations (edge directions) incident to locally owned quadrilateral cells.
 Parameters
plex – The DMPlex object encapsulating the mesh topology
vertex_numbering – Section describing the universal vertex numbering
cell_ranks – MPI rank of the owner of each (visible) nonowned cell, or 1 for (locally) owned cell.

firedrake.dmplex.
reordered_coords
()¶ Return coordinates for the plex, reordered according to the global numbering permutation for the coordinate function space.
Shape is a tuple of (plex.numVertices(), geometric_dim).

firedrake.dmplex.
set_adjacency_callback
()¶ Set the callback for DMPlexGetAdjacency.
 Parameters
dm – The DMPlex object.
This is used during DMPlexDistributeOverlap to determine where to grow the halos.

firedrake.dmplex.
validate_mesh
()¶ Perform some validation of the input mesh.
 Parameters
plex – The DMPlex object encapsulating the mesh topology.
firedrake.ensemble module¶

class
firedrake.ensemble.
Ensemble
(comm, M)[source]¶ Bases:
object
Create a set of space and ensemble subcommunicators.
 Parameters
comm – The communicator to split.
M – the size of the communicators used for spatial parallelism.
 Raises
ValueError – if
M
does not dividecomm.size
exactly.

allreduce
(f, f_reduced, op=<mpi4py.MPI.Op object>)[source]¶ Allreduce a function f into f_reduced over
ensemble_comm
. Parameters
f – The a
Function
to allreduce.f_reduced – the result of the reduction.
op – MPI reduction operator.
 Raises
ValueError – if communicators mismatch, or function sizes mismatch.

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

ensemble_comm
= None¶ The communicator for ensemble parallelism, contains all processes in
comm
which have the same rank incomm
.

global_comm
= None¶ The global communicator.

irecv
(f, source=2, tag=1)[source]¶ Receive (nonblocking) a function f over
ensemble_comm
from another ensemble rank.Returns a Request object.
 Parameters
f – The a
Function
to receive intosource – the rank to receive from
tag – the tag of the message

isend
(f, dest, tag=0)[source]¶ Send (nonblocking) a function f over
ensemble_comm
to another ensemble rank.Returns a Request object.
 Parameters
f – The a
Function
to senddest – the rank to send to
tag – the tag of the message

recv
(f, source=2, tag=1)[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
tag – the tag of the message

send
(f, rank, 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
firedrake.exceptions module¶
firedrake.expression module¶

class
firedrake.expression.
Expression
(code=None, element=None, cell=None, degree=None, **kwargs)[source]¶ Bases:
ufl.coefficient.Coefficient
Python function that may be evaluated on a
FunctionSpace
. This provides a mechanism for settingFunction
values to userdetermined values.Expressions should very rarely be needed in Firedrake, since using the same mathematical expression in UFL is usually possible and will result in much faster code.
To use an Expression, we can either
interpolate()
it onto aFunction
, orproject()
it into aFunctionSpace
. Note that not allFunctionSpace
s support interpolation, but all do support projection.Expressions are specified by creating a subclass of
Expression
with a userdefined eval` method. For example, the following expression sets the outputFunction
to the square of the magnitude of the coordinate:class MyExpression(Expression): def eval(self, value, X): value[:] = numpy.dot(X, X)
Observe that the (single) entry of the
value
parameter is written to, not the parameter itself.This
Expression
could be interpolated onto theFunction
f
by executing:f.interpolate(MyExpression())
Note the brackets required to instantiate the
MyExpression
object.If a Python
Expression
is to set the value of a vectorvaluedFunction
then it is necessary to explicitly override thevalue_shape()
method of thatExpression
. For example:class MyExpression(Expression): def eval(self, value, X): value[:] = X def value_shape(self): return (2,)
C string expressions have now been removed from Firedrake, so passing
code
into this constructor will trigger an exception. :param kwargs: userdefined values that are accessible in theExpression code. These values maybe updated by accessing the property of the same name.

rank
()[source]¶ Return the rank of this
Expression

ufl_shape
¶ Return the associated UFL shape.

value_shape
()[source]¶ Return the shape of this
Expression
.This is the number of values the code snippet in the expression contains.

firedrake.extrusion_numbering module¶
Computation dof numberings for extruded meshes¶
On meshes with a constant number of cell layers (i.e. each column contains the same number of cells), it is possible to compute all the correct numberings by just lying to DMPlex about how many degrees of freedom there are on the base topological entities.
This ceases to be true as soon as we permit variable numbers of cells in each column, since now, although the number of degrees of freedom on a cell does not change from column to column, the number that are stacked up on each topological entity does change.
This module implements the necessary chicanery to deal with it.
Computation of topological layer extents¶
First, a picture.
Consider a onedimensional mesh:
x0x1x2x
Extruded to form the following twodimensional mesh:
xx
 
 
2  
 
xxxx
  
  
1   
  
xxx
 
 
0  
 
xx
This is constructed by providing the number of cells in each column as well as the starting cell layer:
[[0, 2],
[1, 1],
[2, 1]]
We need to promote this cell layering to layering for all topological entities. Our solution to “interior” facets that only have one side is to require that they are geometrically zero sized, and then guarantee that we never iterate over them. We therefore need to keep track of two bits of information, the layer extent for allocation purposes and also the layer extent for iteration purposes.
We compute both by iterating over the cells and transferring cell layers to points in the closure of each cell. Allocation bounds use minmax on the cell bounds, iteration bounds use maxmin.
To simplify some things, we require that the resulting mesh is not topologically disconnected anywhere. Offset cells must, at least, share a vertex with some other cell.
Computation of function space allocation size¶
With the layer extents computed, we need to compute the dof allocation. For this, we need the number of degrees of freedom on the base topological entity, and above it in each cell:
xx
 o 
o o o
o o o
 o 
ooo
This element has one degree of freedom on each base vertex and cell, two degrees of freedom “above” each vertex, and four above each cell. To compute the number of degrees of freedom on the column of topological entities we sum the number on the entity, multiplied by the number of layers with the number above, multiplied by the number of layers minus one (due to the fencepost error difference). This number of layers naturally changes from entity to entity, and so we can’t compute this up front, but must do it point by point, constructing the PETSc Section as we go.
Computation of function space maps¶
Now we need the maps from topological entities (cells and facets) to the function space nodes they can see. The allocation offsets that the numbering section gives us are wrong, because when we have a step in the column height, the offset will be wrong if we’re looking from the higher cell. Consider a vertex discretisation on the previous mesh, with a numbering:
810
 
 
 
 
2579
  
  
  
  
146
 
 
 
 
03
The cell node map we get by just looking at allocation offsets is:
[[0, 1, 3, 4],
[3, 4, 6, 7],
[6, 7, 9, 10]]
note how the second and third cells have the wrong value for their “left” vertices. Instead, we need to shift the numbering we obtain from the allocation offset by the number of entities we’re skipping over, to result in:
[[0, 1, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10]]
Now, when we iterate over cells, we ensure that we access the correct dofs. The same trick needs to be applied to facet maps too.
Computation of boundary nodes¶
For the top and bottom boundary nodes, we walk over the cells at, respectively, the top and bottom of the column and pull out those nodes whose entity height matches the appropriate cell height. As an example:
810
 
 
 
 
2579
  
  
  
  
146
 
 
 
 
03
The bottom boundary nodes are:
[0, 3, 4, 6, 7, 9]
whereas the top are:
[2, 5, 7, 8, 10]
For these strange “interior” facets, we first walk over the cells, picking up the dofs in the closure of the base (ceiling) of the cell, then we walk over facets, picking up all the dofs in the closure of facets that are exposed (there may be more than one of these in the cell column). We don’t have to worry about any lowerdimensional entities, because if a codim 2 or greater entity is exposed in a column, then the codim 1 entity in its star is also exposed.
For the side boundary nodes, we can make a simplification: we know that the facet heights are always the same as the cell column heights (because there is only one cell in the support of the facet). Hence we just walk over the boundary facets of the base mesh, extract out the nodes on that facet on the bottom cell and walk up the column. This is guaranteed to pick up all the nodes in the closure of the facet column.

firedrake.extrusion_numbering.
entity_layers
()¶ Compute the layers for a given entity type.
 Parameters
mesh – the extruded mesh to compute layers for.
height – the height of the entity to consider (in the DMPlex sense). e.g. 0 > cells, 1 > facets, etc…
label – optional label to select some subset of the points of the given height (may be None meaning select all points).
 Returns
a numpy array of shape (num_entities, 2) providing the layer extents for iteration on the requested entities.

firedrake.extrusion_numbering.
layer_extents
()¶ Compute the extents (start and stop layers) for an extruded mesh.
 Parameters
dm – The DMPlex.
cell_numbering – The cell numbering (plex points to Firedrake points).
cell_extents – The cell layers.
 Returns
a numpy array of shape (npoints, 4) where npoints is the number of mesh points in the base mesh.
npoints[p, 0:2]
gives the start and stop layers for allocation for mesh pointp
(in plex ordering), whilenpoints[p, 2:4]
gives the start and stop layers for iteration over mesh pointp
(in plex ordering).
Warning
The indexing of this array uses DMPlex point ordering, not Firedrake ordering. So you always need to iterate over plex points and translate to Firedrake numbers if necessary.

firedrake.extrusion_numbering.
node_classes
()¶ Compute the node classes for a given extruded mesh.
 Parameters
mesh – the extruded mesh.
nodes_per_entity – Number of nodes on, and on top of, each type of topological entity on the base mesh for a single cell layer. Multiplying up by the number of layers happens in this function.
 Returns
A numpy array of shape (3, ) giving the set entity sizes for the given nodes per entity.

firedrake.extrusion_numbering.
top_bottom_boundary_nodes
()¶ Extract top or bottom boundary nodes from an extruded function space.
 Parameters
mesh – The extruded mesh.
cell_node_list – The map from cells to nodes.
masks – masks for dofs in the closure of the facets of the cell. First the vertical facets, then the horizontal facets (bottom then top).
offsets – Offsets to apply walking up the column.
kind – Whether we should select the bottom, or the top, nodes.
 Returns
a numpy array of unique indices of nodes on the bottom or top of the mesh.
firedrake.extrusion_utils module¶

firedrake.extrusion_utils.
entity_closures
(cell)[source]¶ Map entities in a cell to points in the topological closure of the entity.
 Parameters
cell – a FIAT cell.

firedrake.extrusion_utils.
entity_indices
(cell)[source]¶ Return a dict mapping topological entities on a cell to their integer index.
This provides an iteration ordering for entities on extruded meshes.
 Parameters
cell – a FIAT cell.

firedrake.extrusion_utils.
entity_reordering
(cell)[source]¶ Return an array reordering extruded cell entities.
If we iterate over the base cell, it is natural to then go over all the entities induced by the product with an interval. This iteration order is not the same as the natural iteration order, so we need a reordering.
 Parameters
cell – a FIAT tensor product cell.

firedrake.extrusion_utils.
make_extruded_coords
(extruded_topology, base_coords, ext_coords, layer_height, extrusion_type='uniform', kernel=None)[source]¶ Given either a kernel or a (fixed) layer_height, compute an extruded coordinate field for an extruded mesh.
 Parameters
extruded_topology – an
ExtrudedMeshTopology
to extrude a coordinate field for.base_coords – a
Function
to read the base coordinates from.ext_coords – a
Function
to write the extruded coordinates into.layer_height – an equispaced height for each layer.
extrusion_type – the type of extrusion to use. Predefined options are either “uniform” (creating equispaced layers by extruding in the (n+1)dth direction), “radial” (creating equispaced layers by extruding in the outward direction from the origin) or “radial_hedgehog” (creating equispaced layers by extruding coordinates in the outward cellnormal direction, needs a P1dgxP1 coordinate field).
kernel – an optional kernel to carry out coordinate extrusion.
The kernel signature (if provided) is:
void kernel(double **base_coords, double **ext_coords, double *layer_height, int layer)
The kernel iterates over the cells of the mesh and receives as arguments the coordinates of the base cell (to read), the coordinates on the extruded cell (to write to), the fixed layer height, and the current cell layer.
firedrake.formmanipulation module¶

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

class
IndexInliner
[source]¶ Bases:
ufl.corealg.multifunction.MultiFunction
Inline fixed index of list tensors

expr
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.


expr
(o, *ops)¶ Reuse object if operands are the same objects.
Use in your own subclass by setting e.g.
expr = MultiFunction.reuse_if_untouched
as a default rule.

index_inliner
= <firedrake.formmanipulation.ExtractSubBlock.IndexInliner object>¶

split
(form, argument_indices)[source]¶ Split a form.
 Parameters
form – the form to split.
argument_indices – indices of test and trial spaces to extract. This should be 0, 1, or 2tuple (whose length is the same as the number of arguments as the
form
) whose entries are either an integer index, or else an iterable of indices.
Returns a new
ufl.classes.Form
on the selected subspace.

class

class
firedrake.formmanipulation.
SplitForm
(indices, form)¶ Bases:
tuple
Create new instance of SplitForm(indices, form)

form
¶ Alias for field number 1

indices
¶ Alias for field number 0


firedrake.formmanipulation.
split_form
(form)[source]¶ Split a form into a tuple of subforms defined on the component spaces.
Each entry is a
SplitForm
tuple of the indices into the component arguments and the form defined on that block.For example, consider the following code:
V = FunctionSpace(m, 'CG', 1) W = V*V*V u, v, w = TrialFunctions(W) p, q, r = TestFunctions(W) a = q*u*dx + p*w*dx
Then splitting the form returns a tuple of two forms.
((0, 2), w*p*dx), (1, 0), q*u*dx))
Due to the limited amount of simplification that UFL does, some of the returned forms may eventually evaluate to zero. The form compiler will remove these in its more complex simplification stages.
firedrake.function module¶

class
firedrake.function.
Function
(function_space, val=None, name=None, dtype=dtype('float64'))[source]¶ Bases:
ufl.coefficient.Coefficient
A
Function
represents a discretised field over the domain defined by the underlyingMesh()
. Functions are represented as sums of basis functions:\[\begin{split}f = \\sum_i f_i \phi_i(x)\end{split}\]The
Function
class provides storage for the coefficients \(f_i\) and associates them with aFunctionSpace
object which provides the basis functions \(\\phi_i(x)\).Note that the coefficients are always scalars: if the
Function
is vectorvalued then this is specified in theFunctionSpace
. Parameters
function_space – the
FunctionSpace
, orMixedFunctionSpace
on which to build thisFunction
. Alternatively, anotherFunction
may be passed here and its function space will be used to build thisFunction
. In this case, the function values are copied.val – NumPy arraylike (or
pyop2.Dat
) providing initial values (optional). If val is an existingFunction
, then the data will be shared.name – userdefined name for this
Function
(optional).dtype – optional data type for this
Function
(defaults toScalarType
).

assign
(expr, subset=None)[source]¶ Set the
Function
value to the pointwise value of expr. expr may only containFunction
s on the sameFunctionSpace
as theFunction
being assigned to.Similar functionality is available for the augmented assignment operators +=, =, *= and /=. For example, if f and g are both Functions on the same
FunctionSpace
then:f += 2 * g
will add twice g to f.
If present, subset must be an
pyop2.Subset
of thisFunction
’snode_set
. The expression will then only be assigned to the nodes on that subset.

at
(arg, *args, **kwargs)[source]¶ Evaluate function at points.
 Parameters
arg – The point to locate.
args – Additional points.
dont_raise – Do not raise an error if a point is not found.
tolerance – Tolerance to use when checking for points in cell.

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)[source]¶ Interpolate an expression onto this
Function
. Parameters
expression –
Expression
or a UFL expression to interpolate Returns
this
Function
object

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

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

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

topological
¶ The underlying coordinateless function.
firedrake.functionspace module¶
This module implements the uservisible API for constructing
FunctionSpace
and MixedFunctionSpace
objects. The
API is functional, rather than objectbased, to allow for simple
backwardscompatibility, argument checking, and dispatch.

firedrake.functionspace.
MixedFunctionSpace
(spaces, name=None, mesh=None)[source]¶ Create a
MixedFunctionSpace
. Parameters
spaces – An iterable of constituent spaces, or a
MixedElement
.name – An optional name for the mixed function space.
mesh – An optional mesh. Must be provided if spaces is a
MixedElement
, ignored otherwise.

firedrake.functionspace.
FunctionSpace
(mesh, family, degree=None, name=None, vfamily=None, vdegree=None)[source]¶ Create a
FunctionSpace
. Parameters
mesh – The mesh to determine the cell from.
family – The finite element family.
degree – The degree of the finite element.
name – An optional name for the function space.
vfamily – The finite element in the vertical dimension (extruded meshes only).
vdegree – The degree of the element in the vertical dimension (extruded meshes only).
The
family
argument may be an existingufl.FiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned.

firedrake.functionspace.
VectorFunctionSpace
(mesh, family, degree=None, dim=None, name=None, vfamily=None, vdegree=None)[source]¶ Create a rank1
FunctionSpace
. Parameters
mesh – The mesh to determine the cell from.
family – The finite element family.
degree – The degree of the finite element.
dim – An optional number of degrees of freedom per function space node (defaults to the geometric dimension of the mesh).
name – An optional name for the function space.
vfamily – The finite element in the vertical dimension (extruded meshes only).
vdegree – The degree of the element in the vertical dimension (extruded meshes only).
The
family
argument may be an existingufl.FiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned. In this case, the provided element must have an emptyufl.FiniteElementBase.value_shape()
.Note
The element that you provide need be a scalar element (with empty
value_shape
), however, it should not be an existingVectorElement
. If you already have an existingVectorElement
, you should pass it toFunctionSpace()
directly instead.

firedrake.functionspace.
TensorFunctionSpace
(mesh, family, degree=None, shape=None, symmetry=None, name=None, vfamily=None, vdegree=None)[source]¶ Create a rank2
FunctionSpace
. Parameters
mesh – The mesh to determine the cell from.
family – The finite element family.
degree – The degree of the finite element.
shape – An optional shape for the tensorvalued degrees of freedom at each function space node (defaults to a square tensor using the geometric dimension of the mesh).
symmetry – Optional symmetries in the tensor value.
name – An optional name for the function space.
vfamily – The finite element in the vertical dimension (extruded meshes only).
vdegree – The degree of the element in the vertical dimension (extruded meshes only).
The
family
argument may be an existingFiniteElementBase
, in which case all other arguments are ignored and the appropriateFunctionSpace
is returned. In this case, the provided element must have an emptyvalue_shape()
.Note
The element that you provide must be a scalar element (with empty
value_shape
). If you already have an existingTensorElement
, you should pass it toFunctionSpace()
directly instead.
firedrake.functionspacedata module¶
This module provides an object that encapsulates data that can be
shared between different FunctionSpace
objects.
The sharing is based on the idea of compatibility of function space
node layout. The shared data is stored on the Mesh()
the
function space is created on, since the created objects are
meshspecific. The sharing is done on an individual key basis. So,
for example, Sets can be shared between all function spaces with the
same number of nodes per topological entity. However, maps are
specific to the node ordering.
This means, for example, that function spaces with the same node ordering, but different numbers of dofs per node (e.g. FiniteElement vs VectorElement) can share the PyOP2 Set and Map data.
Return the
FunctionSpaceData
for the given element. Parameters
mesh – The mesh to build the function space data on.
finat_element – A FInAT element.
 Raises
ValueError – if mesh or finat_element are invalid.
 Returns
a
FunctionSpaceData
object with the shared data.
firedrake.functionspaceimpl module¶
This module provides the implementations of FunctionSpace
and MixedFunctionSpace
objects, along with some utility
classes for attaching extra information to instances of these.

firedrake.functionspaceimpl.
ComponentFunctionSpace
(parent, component)[source]¶ Build a new FunctionSpace that remembers it represents a particular component. Used for applying boundary conditions to components of a
VectorFunctionSpace()
orTensorFunctionSpace()
. Parameters
parent – The parent space (a FunctionSpace with a VectorElement or TensorElement).
component – The component to represent.
 Returns
A new
ProxyFunctionSpace
with the component set.

class
firedrake.functionspaceimpl.
FunctionSpace
(mesh, element, name=None, real_tensorproduct=False)[source]¶ Bases:
object
A representation of a function space.
A
FunctionSpace
associates degrees of freedom with topological mesh entities. The degree of freedom mapping is determined from the provided element. Parameters
mesh – The
Mesh()
to build the function space on.element – The
FiniteElementBase
describing the degrees of freedom.name – An optional name for this
FunctionSpace
, useful for later identification.
The element can be a essentially any
FiniteElementBase
, except for aMixedElement
, for which one should use theMixedFunctionSpace
constructor.To determine whether the space is scalar, vector or tensorvalued, one should inspect the
rank
of the resulting object. Note that function spaces created on intrinsically vectorvalued finite elements (such as the RaviartThomas space) haverank
0.Warning
Users should not build a
FunctionSpace
directly, instead they should use the utilityFunctionSpace()
function, which provides extra error checking and argument sanitising.
boundary_nodes
(sub_domain, method)[source]¶ Return the boundary nodes for this
FunctionSpace
. Parameters
sub_domain – the mesh marker selecting which subset of facets to consider.
method – the method for determining boundary nodes.
 Returns
A numpy array of the unique function space nodes on the selected portion of the boundary.
See also
DirichletBC
for details of the arguments.

component
= None¶ The component of this space in its parent VectorElement space, or
None
.

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

dof_count
[source]¶ The number of degrees of freedom (includes halo dofs) of this function space on this process. Cf.
node_count
.

dof_dset
= None¶ A
pyop2.DataSet
representing the function space degrees of freedom.

exterior_facet_node_map
()[source]¶ Return the
pyop2.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.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, uid=None)[source]¶ Return a newly allocated
pyop2.Dat
defined on thedof_dset
of thisFunction
.

name
= None¶ The (optional) descriptive name for this space.

node_count
[source]¶ The number of nodes (includes halo nodes) of this function space on this process. If the
FunctionSpace
hasrank
0, this is equal to thedof_count
, otherwise thedof_count
isdim
times thenode_count
.

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

rank
= None¶ The rank of this
FunctionSpace
. Spaces where the element is scalarvalued (or intrinsically vectorvalued) have rank zero. Spaces built onVectorElement
orTensorElement
instances have rank equivalent to the number of components of theirvalue_shape()
.

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

firedrake.functionspaceimpl.
IndexedFunctionSpace
(index, space, parent)[source]¶ Build a new FunctionSpace that remembers it is a particular subspace of a
MixedFunctionSpace
. Parameters
index – The index into the parent space.
space – The subspace to represent
parent – The parent mixed space.
 Returns
A new
ProxyFunctionSpace
with index and parent set.

class
firedrake.functionspaceimpl.
MixedFunctionSpace
(spaces, name=None)[source]¶ Bases:
object
A function space on a mixed finite element.
This is essentially just a bag of individual
FunctionSpace
objects. Parameters
spaces – The constituent spaces.
name – An optional name for the mixed space.
Warning
Users should not build a
MixedFunctionSpace
directly, but should instead use the functional interface provided byMixedFunctionSpace()
.
cell_node_map
()[source]¶ A
pyop2.MixedMap
from theMesh.cell_set
of the underlying mesh to thenode_set
of thisMixedFunctionSpace
. This is composed of theFunctionSpace.cell_node_map
s of the underlyingFunctionSpace
s of which thisMixedFunctionSpace
is composed.

component
= None¶

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

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

dof_dset
[source]¶ A
pyop2.MixedDataSet
containing the degrees of freedom of thisMixedFunctionSpace
. This is composed of theFunctionSpace.dof_dset
s of the underlyingFunctionSpace
s of which thisMixedFunctionSpace
is composed.

exterior_facet_node_map
()[source]¶ Return the
pyop2.Map
from exterior facets to function space nodes.

index
= None¶

interior_facet_node_map
()[source]¶ Return the
pyop2.MixedMap
from interior facets to function space nodes.

local_to_global_map
(bcs)[source]¶ Return a map from process local dof numbering to global dof numbering.
If BCs is provided, mask out those dofs which match the BC nodes.

make_dat
(val=None, valuetype=None, name=None, uid=None)[source]¶ Return a newly allocated
pyop2.MixedDat
defined on thedof_dset
of thisMixedFunctionSpace
.

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

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

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

parent
= None¶

rank
= 1¶

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

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

topological
¶ Function space on a mesh topology.

value_size
[source]¶ Return the sum of the
FunctionSpace.value_size
s of theFunctionSpace
s thisMixedFunctionSpace
is composed of.

class
firedrake.functionspaceimpl.
ProxyFunctionSpace
(mesh, element, name=None, real_tensorproduct=False)[source]¶ Bases:
firedrake.functionspaceimpl.FunctionSpace
A
FunctionSpace
that one can attach extra properties to. Parameters
mesh – The mesh to use.
element – The UFL element.
name – The name of the function space.
Warning
Users should not build a
ProxyFunctionSpace
directly, it is mostly used as an internal implementation detail.
identifier
= None¶ An optional identifier, for debugging purposes.

make_dat
(*args, **kwargs)[source]¶ Create a
pyop2.Dat
. Raises
ValueError – if
no_dats
isTrue
.

class
firedrake.functionspaceimpl.
RealFunctionSpace
(mesh, element, name)[source]¶ Bases:
firedrake.functionspaceimpl.FunctionSpace
FunctionSpace
based on elements of family “Real”. A :class`RealFunctionSpace` only has a single global value for the whole mesh.This class should not be directly instantiated by users. Instead, FunctionSpace objects will transform themselves into
RealFunctionSpace
objects as appropriate.
bottom_nodes
()[source]¶ RealFunctionSpace
objects have no bottom nodes.

cell_node_map
(bcs=None)[source]¶ RealFunctionSpace
objects have no cell node map.

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

exterior_facet_node_map
(bcs=None)[source]¶ RealFunctionSpace
objects have no exterior facet node map.

finat_element
= None¶

interior_facet_node_map
(bcs=None)[source]¶ RealFunctionSpace
objects have no interior facet node map.

local_to_global_map
(bcs, lgmap=None)[source]¶ Return a map from process local dof numbering to global dof numbering.
If BCs is provided, mask out those dofs which match the BC nodes.

make_dat
(val=None, valuetype=None, name=None, uid=None)[source]¶ Return a newly allocated
pyop2.Global
representing the data for aFunction
on this space.

rank
= 0¶

shape
= ()¶

top_nodes
()[source]¶ RealFunctionSpace
objects have no bottom nodes.

value_size
= 1¶


class
firedrake.functionspaceimpl.
WithGeometry
(function_space, mesh)[source]¶ Bases:
ufl.functionspace.FunctionSpace
Attach geometric information to a
FunctionSpace
.Function spaces on meshes with different geometry but the same topology can share data, except for their UFL cell. This class facilitates that.
Users should not instantiate a
WithGeometry
object explicitly except in a small number of cases. Parameters
function_space – The topological function space to attach geometry to.
mesh – The mesh with geometric information to use.

get_work_function
(zero=True)[source]¶ Get a temporary work
Function
on thisFunctionSpace
. Parameters
zero – Should the
Function
be guaranteed zero? Ifzero
isFalse
the returned function may or may not be zeroed, and the user is responsible for appropriate zeroing. Raises
ValueError – if
max_work_functions
are already checked out.
Note
This method is intended to be used for shortlived work functions, if you actually need a function for general usage use the
Function
constructor.When you are finished with the work function, you should restore it to the pool of available functions with
restore_work_function()
.

max_work_functions
¶ The maximum number of work functions this
FunctionSpace
supports.See
get_work_function()
for obtaining work functions.

mesh
()¶ Return ufl domain.

num_work_functions
¶ The number of checked out work functions.

restore_work_function
(function)[source]¶ Restore a work function obtained with
get_work_function()
. Parameters
function – The work function to restore
 Raises
ValueError – if the provided function was not obtained with
get_work_function()
or it has already been restored.
Warning
This does not invalidate the name in the calling scope, it is the user’s responsibility not to use a work function after restoring it.

ufl_function_space
()[source]¶ The
FunctionSpace
this object represents.
firedrake.halo module¶

class
firedrake.halo.
Halo
(dm, section)[source]¶ Bases:
pyop2.base.Halo
Build a Halo for a function space.
 Parameters
dm – The DMPlex describing the topology.
section – The data layout.
The halo is implemented using a PETSc SF (star forest) object and is usable as a PyOP2
pyop2.Halo
.
global_to_local_begin
(dat, insert_mode)[source]¶ Begin an exchange from global (assembled) to local (ghosted) representation.
 Parameters
dat – The
Dat
to exchange.insert_mode – The insertion mode.

global_to_local_end
(dat, insert_mode)[source]¶ Finish an exchange from global (assembled) to local (ghosted) representation.
 Parameters
dat – The
Dat
to exchange.insert_mode – The insertion mode.

local_to_global_begin
(dat, insert_mode)[source]¶ Begin an exchange from local (ghosted) to global (assembled) representation.
 Parameters
dat – The
Dat
to exchange.insert_mode – The insertion mode.
firedrake.hdf5interface module¶

firedrake.hdf5interface.
get_h5py_file
()¶ Attempt to convert PETSc viewer file handle to h5py File.
 Parameters
vwr – The PETSc Viewer (must have type HDF5).
Warning
For this to work, h5py and PETSc must both have been compiled against the same HDF5 library (otherwise the file handles are not interchangeable). This is the likeliest reason for failure when attempting the conversion.
firedrake.interpolation module¶

firedrake.interpolation.
interpolate
(expr, V, subset=None, access=Access('WRITE'))[source]¶ Interpolate an expression onto a new function in V.
 Parameters
expr – an
Expression
.V – the
FunctionSpace
to interpolate into (or else an existingFunction
).subset – An optional
pyop2.Subset
to apply the interpolation over.access – The access descriptor for combining updates to shared dofs.
Returns a new
Function
in the spaceV
(orV
if it was a Function).Note
If you find interpolating the same expression again and again (for example in a time loop) you may find you get better performance by using a
Interpolator
instead.

class
firedrake.interpolation.
Interpolator
(expr, V, subset=None, access=Access('WRITE'))[source]¶ Bases:
object
A reusable interpolation object.
 Parameters
expr – The expression to interpolate.
V – The
FunctionSpace
orFunction
to interpolate into.
This object can be used to carry out the same interpolation multiple times (for example in a timestepping loop).
Note
The
Interpolator
holds a reference to the provided arguments (such that they won’t be collected until theInterpolator
is also collected).
firedrake.linear_solver module¶

class
firedrake.linear_solver.
LinearSolver
(A, P=None, solver_parameters=None, nullspace=None, transpose_nullspace=None, near_nullspace=None, options_prefix=None)[source]¶ Bases:
firedrake.petsc.OptionsManager
A linear solver for assembled systems (Ax = b).
 Parameters
A – a
MatrixBase
(the operator).P – an optional
MatrixBase
to construct any preconditioner from; if none is suppliedA
is used to construct the preconditioner.parameters – (optional) dict of solver parameters.
nullspace – an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
spanning the null space of the operator.transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
near_nullspace – as for the nullspace, but used to set the near nullpace.
options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the
solver_parameters
dict.
Note
Any boundary conditions for this solve must have been applied when assembling the operator.
firedrake.logging module¶

firedrake.logging.
set_level
(level)¶ Set the log level for Firedrake components.
 Parameters
level – The level to use.
This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.

firedrake.logging.
set_log_level
(level)[source]¶ Set the log level for Firedrake components.
 Parameters
level – The level to use.
This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.

firedrake.logging.
set_log_handlers
(handlers=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Set handlers for the log messages of the different Firedrake components.
 Parameters
handlers – Optional dict of handlers keyed by the name of the logger. If not provided, a separate
logging.StreamHandler
will be created for each logger.comm – The communicator the handler should be collective over. If provided, only rank0 on that communicator will write to the handler, other ranks will use a
logging.NullHandler
. If set toNone
, all ranks will use the provided handler. This could be used, for example, if you want to log to one file per rank.

firedrake.logging.
info_red
(message, *args, **kwargs)[source]¶ Write info message in red.
 Parameters
message – the message to be printed.
firedrake.matrix module¶

class
firedrake.matrix.
ImplicitMatrix
(a, bcs, *args, **kwargs)[source]¶ Bases:
firedrake.matrix.MatrixBase
A representation of the action of bilinear form operating without explicitly assembling the associated matrix. This class wraps the relevant information for Python PETSc matrix.
 Parameters
Note
This object acts to the right on an assembled
Function
and to the left on an assembled cofunction (currently represented by aFunction
).
force_evaluation
()¶

class
firedrake.matrix.
Matrix
(a, bcs, mat_type, *args, **kwargs)[source]¶ Bases:
firedrake.matrix.MatrixBase
A representation of an assembled bilinear form.
 Parameters
A
pyop2.Mat
will be built from the remaining arguments, for valid values, seepyop2.Mat
.Note
This object acts to the right on an assembled
Function
and to the left on an assembled cofunction (currently represented by aFunction
).

class
firedrake.matrix.
MatrixBase
(a, bcs, mat_type)[source]¶ Bases:
object
A representation of the linear operator associated with a bilinear form and bcs. Explicitly assembled matrices and matrixfree matrix classes will derive from this
 Parameters
a – the bilinear form this
MatrixBase
represents.bcs – an iterable of boundary conditions to apply to this
MatrixBase
. May be None if there are no boundary conditions to apply.mat_type – matrix type of assembled matrix, or ‘matfree’ for matrixfree

a
¶ The bilinear form this
MatrixBase
was assembled from

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

force_evaluation
()[source]¶ Force any pending writes to this matrix.
Ensures that the matrix is assembled and populated with values, ready for sending to PETSc.

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

mat_type
= None¶ Matrix type.
Matrix type used in the assembly of the PETSc matrix: ‘aij’, ‘baij’, or ‘nest’, or ‘matfree’ for matrixfree.
firedrake.mesh module¶

firedrake.mesh.
Mesh
(meshfile, **kwargs)[source]¶ Construct a mesh object.
Meshes may either be created by reading from a mesh file, or by providing a PETSc DMPlex object defining the mesh topology.
 Parameters
meshfile – Mesh file name (or DMPlex object) defining mesh topology. See below for details on supported mesh formats.
dim – optional specification of the geometric dimension of the mesh (ignored if not reading from mesh file). If not supplied the geometric dimension is deduced from the topological dimension of entities in the mesh.
reorder – optional flag indicating whether to reorder meshes for better cache locality. If not supplied the default value in
parameters["reorder_meshes"]
is used.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 2tuple that specifies a partitioning of the cells (only really useful for debugging).
"overlap_type"
: a 2tuple indicating how to growthe mesh overlap. The first entry should be a
DistributedMeshOverlapType
instance, the second the number of levels of overlap.
comm – the communicator to use when creating the mesh. If not supplied, then the mesh will be created on COMM_WORLD. Ignored if
meshfile
is a DMPlex object (in which case the communicator will be taken from there).
When the mesh is read from a file the following mesh formats are supported (determined, case insensitively, from the filename extension):
GMSH: with extension .msh
Exodus: with extension .e, .exo
CGNS: with extension .cgns
Triangle: with extension .node
Note
When the mesh is created directly from a DMPlex object, the
dim
parameter is ignored (the DMPlex already knows its geometric and topological dimensions).

firedrake.mesh.
ExtrudedMesh
(mesh, layers, layer_height=None, extrusion_type='uniform', kernel=None, gdim=None)[source]¶ Build an extruded mesh from an input mesh
 Parameters
mesh – the unstructured base mesh
layers – number of extruded cell layers in the “vertical” direction. One may also pass an array of shape (cells, 2) to specify a variable number of layers. In this case, each entry is a pair
[a, b]
wherea
indicates the starting cell layer of the column andb
the number of cell layers in that column.layer_height – the layer height, assuming all layers are evenly spaced. If this is omitted, the value defaults to 1/layers (i.e. the extruded mesh has total height 1.0) unless a custom kernel is used. Must be provided if using a variable number of layers.
extrusion_type – the algorithm to employ to calculate the extruded coordinates. One of “uniform”, “radial”, “radial_hedgehog” or “custom”. See below.
kernel – a
pyop2.Kernel
to produce coordinates for the extruded mesh. Seemake_extruded_coords()
for more details.gdim – number of spatial dimensions of the resulting mesh (this is only used if a custom kernel is provided)
The various values of
extrusion_type
have the following meanings:"uniform"
the extruded mesh has an extra spatial dimension compared to the base mesh. The layers exist in this dimension only.
"radial"
the extruded mesh has the same number of spatial dimensions as the base mesh; the cells are radially extruded outwards from the origin. This requires the base mesh to have topological dimension strictly smaller than geometric dimension.
"radial_hedgehog"
similar to radial, but the cells are extruded in the direction of the outwardpointing cell normal (this produces a P1dgxP1 coordinate field). In this case, a radially extruded coordinate field (generated with
extrusion_type="radial"
) is available in theradial_coordinates
attribute."custom"
use a custom kernel to generate the extruded coordinates
For more details see the manual section on extruded meshes.

firedrake.mesh.
SubDomainData
(geometric_expr)[source]¶ Creates a subdomain data object from a booleanvalued UFL expression.
The result can be attached as the subdomain_data field of a
ufl.Measure
. For example:x = mesh.coordinates sd = SubDomainData(x[0] < 0.5) assemble(f*dx(subdomain_data=sd))

firedrake.mesh.
unmarked
= 1¶ A mesh marker that selects all entities that are not explicitly marked.
firedrake.norms module¶

firedrake.norms.
errornorm
(u, uh, norm_type='L2', degree_rise=None, mesh=None)[source]¶ Compute the error \(e = u  u_h\) in the specified norm.
 Parameters
u – a
Function
or UFL expression containing an “exact” 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.
VectorSpaceBasis
(vecs=None, constant=False)[source]¶ Bases:
object
Build a basis for a vector space.
You can use this basis to express the null space of a singular operator.
 Parameters
vecs – a list of
Vector
s orFunctions
spanning the space.constant – does the null space include the constant vector? If you pass
constant=True
you should not also include the constant vector in the list ofvecs
you supply.
Note
Before using this object in a solver, you must ensure that the basis is orthonormal. You can do this by calling
orthonormalize()
, this modifies the provided vectors in place.Warning
The vectors you pass in to this object are not copied. You should therefore not modify them after instantiation since the basis will then be incorrect.

check_orthogonality
(orthonormal=True)[source]¶ Check if the basis is orthogonal.
 Parameters
orthonormal – If True check that the basis is also orthonormal.
 Raises
ValueError – If the basis is not orthogonal/orthonormal.

nullspace
(comm=None)[source]¶ The PETSc NullSpace object for this
VectorSpaceBasis
. Parameters
comm – Communicator to create the nullspace on.

orthogonalize
(b)[source]¶ Orthogonalize
b
with respect to thisVectorSpaceBasis
. Parameters
b – a
Function
Note
Modifies
b
in place.

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)
firedrake.optimizer module¶
firedrake.output module¶

class
firedrake.output.
File
(filename, project_output=False, comm=None, mode='w')[source]¶ Bases:
object
Create an object for outputting data for visualisation.
This produces output in VTU format, suitable for visualisation with Paraview or other VTKcapable visualisation packages.
 Parameters
filename – The name of the output file (must end in
.pvd
).project_output – Should the output be projected to linears? Default is to use interpolation.
comm – The MPI communicator to use.
mode – “w” to overwrite any existing file, “a” to append to an existing file.
Note
Visualisation is only possible for linear fields (either continuous or discontinuous). All other fields are first either projected or interpolated to linear before storing for visualisation purposes.
firedrake.parameters module¶
The parameters dictionary contains global parameter settings.

firedrake.parameters.
parameters
= {'coffee': {'optlevel': 'Ov'}, 'default_matrix_type': 'nest', 'default_sub_matrix_type': 'baij', 'form_compiler': {'mode': 'spectral', 'precision': 15, 'quadrature_degree': 'auto', 'quadrature_rule': 'auto', 'scalar_type': 'double', 'unroll_indexsum': 3}, 'pyop2_options': {'block_sparsity': True, 'cache_dir': '/home/vtdb72/Documents/work/src/firedrake/.cache/pyop2', 'cflags': '', 'check_src_hashes': True, 'compiler': 'gcc', 'debug': False, 'lazy_evaluation': True, 'lazy_max_trace_length': 100, 'ldflags': '', 'log_level': 'WARNING', 'matnest': True, 'no_fork_available': False, 'node_local_compilation': True, 'opt_level': 'Ov', 'print_cache_size': False, 'print_summary': False, 'simd_width': 4, 'type_check': True}, 'reorder_meshes': True, 'type_check_safe_par_loops': False}¶ A nested dictionary of parameters used by Firedrake

firedrake.parameters.
disable_performance_optimisations
()[source]¶ Switches off performance optimisations in Firedrake.
This is mostly useful for debugging purposes.
This switches off all of COFFEE’s kernel compilation optimisations and enables PyOP2’s runtime checking of par_loop arguments in all cases (even those where they are claimed safe). Additionally, it switches to compiling generated code in debug mode.
Returns a function that can be called with no arguments, to restore the state of the parameters dict.
firedrake.parloops module¶
This module implements parallel loops reading and writing
Function
s. This provides a mechanism for implementing
nonfinite element operations such as slope limiters.

firedrake.parloops.
par_loop
(kernel, measure, args, kernel_kwargs=None, is_loopy_kernel=False, **kwargs)[source]¶ A
par_loop()
is a userdefined operation which reads and writesFunction
s by looping over the mesh cells or facets and accessing the degrees of freedom on adjacent entities. Parameters
kernel – a string containing the C code to be executed. Or a 2tuple of (domains, instructions) to create a loopy kernel (must also set
is_loopy_kernel=True
). If loopy syntax is used, the domains and instructions should be specified in loopy kernel syntax. See the loopy tutorial for details.measure – is a UFL
Measure
which determines the manner in which the iteration over the mesh is to occur. Alternatively, you can passdirect
to designate a direct loop.args – is a dictionary mapping variable names in the kernel to
Function
s or components of mixedFunction
s and indicates how theseFunction
s are to be accessed.kernel_kwargs – keyword arguments to be passed to the
Kernel
constructorkwargs – additional keyword arguments are passed to the underlying
par_loop
iterate –
Optionally specify which region of an
ExtrudedSet
to iterate over. Valid values are the following objects from pyop2:ON_BOTTOM
: iterate over the bottom layer of cells.ON_TOP
iterate over the top layer of cells.ALL
iterate over all cells (the default if unspecified)ON_INTERIOR_FACETS
iterate over all the layers except the top layer, accessing data two adjacent (in the extruded direction) cells at a time.
Example
Assume that A is a
Function
in CG1 and B is aFunction
in DG0. Then the following code sets each DoF in A to the maximum value that B attains in the cells adjacent to that DoF:A.assign(numpy.finfo(0.).min) par_loop('for (int i=0; i<A.dofs; i++) A[i] = fmax(A[i], B[0]);', dx, {'A' : (A, RW), 'B': (B, READ)})
The equivalent using loopy kernel syntax is:
domain = '{[i]: 0 <= i < A.dofs}' instructions = ''' for i A[i] = max(A[i], B[0]) end ''' par_loop((domain, instructions), dx, {'A' : (A, RW), 'B': (B, READ)}, is_loopy_kernel=True)
Argument definitions
Each item in the args dictionary maps a string to a tuple containing a
Function
orConstant
and an argument intent. The string is the c language variable name by which this function will be accessed in the kernel. The argument intent indicates how the kernel will access this variable: READ
The variable will be read but not written to.
 WRITE
The variable will be written to but not read. If multiple kernel invocations write to the same DoF, then the order of these writes is undefined.
 RW
The variable will be both read and written to. If multiple kernel invocations access the same DoF, then the order of these accesses is undefined, but it is guaranteed that no race will occur.
 INC
The variable will be added into using +=. As before, the order in which the kernel invocations increment the variable is undefined, but there is a guarantee that no races will occur.
Note
Only READ intents are valid for
Constant
coefficients, and an error will be raised in other cases.The measure
The measure determines the mesh entities over which the iteration will occur, and the size of the kernel stencil. The iteration will occur over the same mesh entities as if the measure had been used to define an integral, and the stencil will likewise be the same as the integral case. That is to say, if the measure is a volume measure, the kernel will be called once per cell and the DoFs accessible to the kernel will be those associated with the cell, its facets, edges and vertices. If the measure is a facet measure then the iteration will occur over the corresponding class of facets and the accessible DoFs will be those on the cell(s) adjacent to the facet, and on the facets, edges and vertices adjacent to those facets.
For volume measures the DoFs are guaranteed to be in the FInAT local DoFs order. For facet measures, the DoFs will be in sorted first by the cell to which they are adjacent. Within each cell, they will be in FInAT order. Note that if a continuous
Function
is accessed via an internal facet measure, the DoFs on the interface between the two facets will be accessible twice: once via each cell. The orientation of the cell(s) relative to the current facet is currently arbitrary.A direct loop over nodes without any indirections can be specified by passing
direct
as the measure. In this case, all of the arguments must beFunction
s in the sameFunctionSpace
.The kernel code
The kernel code is plain C in which the variables specified in the args dictionary are available to be read or written in according to the argument intent specified. Most basic C operations are permitted. However there are some restrictions:
Only functions from math.h may be called.
Pointer operations other than dereferencing arrays are prohibited.
Indirect free variables referencing
Function
s are all of type double*. For spaces with rank greater than zero (Vector or TensorElement), the data are laid out XYZ… XYZ… XYZ…. With the vector/tensor component moving fastest.In loopy syntax, these may be addressed using 2D indexing:
A[i, j]
Where
i
runs over nodes, andj
runs over components.In a direct
par_loop()
, the variables will all be of type double* with the single index being the vector component.Constant
s are always of type double*, both for indirect and directpar_loop()
calls.

firedrake.parloops.
direct
= direct¶ A singleton object which can be used in a
par_loop()
in place of the measure in order to indicate that the loop is a direct loop over degrees of freedom.
firedrake.petsc module¶

class
firedrake.petsc.
OptionsManager
(parameters, options_prefix)[source]¶ Bases:
object

commandline_options
= frozenset({'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 onceperPETScobject thing).So that the runtime monitors which look in the options database actually see options, you need to ensure that the options database is populated at the time of a
SNESSolve
orKSPSolve
call. Do that using theinserted_options()
context manager.with self.inserted_options(): self.snes.solve(...)
This ensures that the options database has the relevant entries for the duration of the
with
block, before removing them afterwards. This is a much more robust way of dealing with the fixedsize options database than trying to clear it out using destructors.This object can also be used only to manage insertion and deletion into the PETSc options database, by using the context manager.

inserted_options
()[source]¶ Context manager inside which the petsc options database contains the parameters from this object.

options_object
= <petsc4py.PETSc.Options object>¶

firedrake.plot module¶

firedrake.plot.
plot
(function_or_mesh, num_sample_points=10, axes=None, plot3d=False, **kwargs)[source]¶ Plot a Firedrake object.
 Parameters
function_or_mesh – The
Function
orMesh()
to plot. An iterable ofFunction
s may also be provided, in which case an animated plot will be available.num_sample_points – Number of Sample points per element, ignored if degree < 4 where an exact Bezier curve will be used instead of sampling at points. For 2D plots, the number of sampling points per element will not exactly this value. Instead, it is used as a guide to the number of subdivisions to use when triangulating the surface.
axes – Axes to be plotted on
plot3d – For 2D plotting, use matplotlib 3D functionality? (slow)
contour – For 2D plotting, True for a contour plot
bezier – For 1D plotting, interpolate using bezier curve instead of piecewise linear
auto_resample – For 1D plotting for functions with degree >= 4, resample automatically when zoomed
interactive – For 1D plotting for multiple functions, use an interactive inferface in Jupyter Notebook
colors – for meshes, the colour to use for the edges (passed to constructor of LineCollection)
kwargs – Additional keyword arguments passed to
matplotlib.plot
.
firedrake.pointeval_utils module¶
firedrake.pointquery_utils module¶
firedrake.projection module¶

firedrake.projection.
project
(v, V, bcs=None, solver_parameters=None, form_compiler_parameters=None, use_slate_for_inverse=True, name=None)[source]¶ Project an
Expression
orFunction
into aFunctionSpace
 Parameters
v – the
Expression
,ufl.Expr
orFunction
to projectV – the
FunctionSpace
orFunction
to project intobcs – boundary conditions to apply in the projection
solver_parameters – parameters to pass to the solver used when projecting.
form_compiler_parameters – parameters to the form compiler
use_slate_for_inverse – compute mass inverse cellwise using SLATE (ignored for nonDG function spaces).
name – name of the resulting
Function
If
V
is aFunction
thenv
is projected intoV
andV
is returned. If V is aFunctionSpace
thenv
is projected into a newFunction
and thatFunction
is returned.

firedrake.projection.
Projector
(v, v_out, bcs=None, solver_parameters=None, form_compiler_parameters=None, constant_jacobian=True, use_slate_for_inverse=False)[source]¶ A projector projects a UFL expression into a function space and places the result in a function from that function space, allowing the solver to be reused. Projection reverts to an assign operation if
v
is aFunction
and belongs to the same function space asv_out
. Parameters
v – the
ufl.Expr
orFunction
to projectV –
Function
(orFunctionSpace
) to put the result in.bcs – an optional set of
DirichletBC
objects to apply on the target function space.solver_parameters – parameters to pass to the solver used when projecting.
constant_jacobian – Is the projection matrix constant between calls? Say False if you have moving meshes.
use_slate_for_inverse – compute mass inverse cellwise using SLATE (only valid for DG function spaces).
firedrake.randomfunctiongen module¶

class
firedrake.randomfunctiongen.
RandomGenerator
¶ Bases:
randomgen.generator.RandomGenerator
Container for the Basic Random Number Generators.
Users can pass to many of the available distribution methods a
FunctionSpace
as the first argument to obtain a randomisedFunction
.Note
FunctionSpace, V, has to be passed as the first argument.
Example:
from firedrake import * mesh = UnitSquareMesh(2,2) V = FunctionSpace(mesh, 'CG', 1) pcg = PCG64(seed=123456789) rg = RandomGenerator(pcg) f_beta = rg.beta(V, 1.0, 2.0) print(f_beta.dat.data) # produces: # [0.56462514 0.11585311 0.01247943 0.398984 0.19097059 0.5446709 0.1078666 0.2178807 0.64848515]

beta
(*args, **kwargs)¶ beta (V, a, b)
Generate a
Function
f = Function(V), randomise it by calling the original method beta (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.beta.html, which is reproduced below with appropriate changes.
beta (a, b, size=None)
Draw samples from a Beta distribution.
The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution. It has the probability distribution function
\[f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha  1} (1  x)^{\beta  1},\]where the normalization, B, is the beta function,
\[B(\alpha, \beta) = \int_0^1 t^{\alpha  1} (1  t)^{\beta  1} dt.\]It is often seen in Bayesian inference and order statistics.
 Parameters
a – float or array_like of floats. Alpha, positive (>0).
b – float or array_like of floats. Beta, positive (>0).
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifa
andb
are both scalars. Otherwise,np.broadcast(a, b).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized beta distribution.

binomial
(*args, **kwargs)¶ binomial (V, n, p)
Generate a
Function
f = Function(V), randomise it by calling the original method binomial (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.binomial.html, which is reproduced below with appropriate changes.
binomial (n, p, size=None)
Draw samples from a binomial distribution.
Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use)
 Parameters
n – int or array_like of ints. Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.
p – float or array_like of floats. Parameter of the distribution, >= 0 and <=1.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifn
andp
are both scalars. Otherwise,np.broadcast(n, p).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.
See Also
scipy.stats.binom : probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the binomial distribution is
\[P(N) = \binom{n}{N}p^N(1p)^{nN},\]where \(n\) is the number of trials, \(p\) is the probability of success, and \(N\) is the number of successes.
When estimating the standard error of a proportion in a population by using a random sample, the normal distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial distribution should be used in this case.
References
 1
Dalgaard, Peter, “Introductory Statistics with R”,. SpringerVerlag, 2002.
 2
Glantz, Stanton A. “Primer of Biostatistics.”, McGrawHill,. Fifth Edition, 2002.
 3
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.
 4
Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A. Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html
 5
Wikipedia, “Binomial distribution”, https://en.wikipedia.org/wiki/Binomial_distribution
Examples
Draw samples from the distribution:
n, p = 10, .5 # number of trials, probability of each trial s = randomfunctiongen.generator.binomial(n, p, 1000) # result of flipping a coin 10 times, tested 1000 times.
A real world example. A company drills 9 wildcat oil exploration wells, each with an estimated probability of success of 0.1. All nine wells fail. What is the probability of that happening?
Let’s do 20,000 trials of the model, and count the number that generate zero positive results:
sum(randomfunctiongen.generator.binomial(9, 0.1, 20000) == 0)/20000. # answer = 0.38885, or 38%.

brng
(*args, **kwargs)¶ Gets the basic RNG instance used by the generator
 Parameters
basic_rng – Basic RNG. The basic RNG instance used by the generator

bytes
(length)¶ Return random bytes.
 Parameters
length – int. Number of random bytes.
 Returns
str. String of length length.
Examples:
randomfunctiongen.generator.bytes(10) # ' eh\x85\x022SZ\xbf\xa4' #random

chisquare
(*args, **kwargs)¶ chisquare (V, df)
Generate a
Function
f = Function(V), randomise it by calling the original method chisquare (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.chisquare.html, which is reproduced below with appropriate changes.
chisquare (df, size=None)
Draw samples from a chisquare distribution.
When df independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chisquare (see Notes). This distribution is often used in hypothesis testing.
 Parameters
df – float or array_like of floats. Number of degrees of freedom, must be > 0.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifdf
is a scalar. Otherwise,np.array(df).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized chisquare distribution.
 Raises
When df <= 0 or when an inappropriate size (e.g.
size=1
) is given.Notes
The variable obtained by summing the squares of df independent, standard normally distributed random variables:
\[Q = \sum_{i=0}^{\mathtt{df}} X^2_i\]is chisquare distributed, denoted
\[Q \sim \chi^2_k.\]The probability density function of the chisquared distribution is
\[p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)} x^{k/2  1} e^{x/2},\]where \(\Gamma\) is the gamma function,
\[\Gamma(x) = \int_0^{\infty} t^{x  1} e^{t} dt.\]References
 1
NIST “Engineering Statistics Handbook” https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.html
Examples:
randomfunctiongen.generator.chisquare(2,4) # array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272]) # random

choice
(*args, **kwargs)¶ choice (V, a, replace=True, p=None, axis=0):
Generate a
Function
f = Function(V), randomise it by calling the original method choice (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.choice.html, which is reproduced below with appropriate changes.
choice (a, size=None, replace=True, p=None, axis=0):
Generates a random sample from a given 1D array
New in version 1.7.0.
 Parameters
a – 1D arraylike or int. If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a)
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.replace – boolean, optional. Whether the sample is with or without replacement
p – 1D arraylike, optional. The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.
axis – int, optional. The axis along which the selection is performed. The default, 0, selects by row.
 Returns
single item or ndarray. The generated random samples
 Raises
If a is an int and less than zero, if p is not 1dimensional, if a is arraylike with a size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size.
See Also
randint, shuffle, permutation
Examples
Generate a uniform random sample from np.arange(5) of size 3:
randomfunctiongen.generator.choice(5, 3) # array([0, 3, 4]) # random #This is equivalent to randomfunctiongen.generator.randint(0,5,3)
Generate a nonuniform random sample from np.arange(5) of size 3:
randomfunctiongen.generator.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) # array([3, 3, 0]) # random
Generate a uniform random sample from np.arange(5) of size 3 without replacement:
randomfunctiongen.generator.choice(5, 3, replace=False) # array([3,1,0]) # random #This is equivalent to randomfunctiongen.generator.permutation(np.arange(5))[:3]
Generate a nonuniform random sample from np.arange(5) of size 3 without replacement:
randomfunctiongen.generator.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) # array([2, 3, 0]) # random
Any of the above can be repeated with an arbitrary arraylike instead of just integers. For instance:
aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] randomfunctiongen.generator.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) # array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random # dtype='<U11')

complex_normal
(*args, **kwargs)¶ complex_normal (V, loc=0.0, gamma=1.0, relation=0.0)
Generate a
Function
f = Function(V), randomise it by calling the original method complex_normal (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.complex_normal.html, which is reproduced below with appropriate changes.
complex_normal (loc=0.0, gamma=1.0, relation=0.0, size=None)
Draw random samples from a complex normal (Gaussian) distribution.
 Parameters
loc – complex or array_like of complex. Mean of the distribution.
gamma – float, complex or array_like of float or complex. Variance of the distribution
relation – float, complex or array_like of float or complex. Relation between the two component normals
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifloc
,gamma
andrelation
are all scalars. Otherwise,np.broadcast(loc, gamma, relation).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized complex normal distribution.
See Also
 Parameters
randomfunctiongen.generator.normal – random values from a realvalued normal distribution
Notes
EXPERIMENTAL Not part of official NumPy RandomState, may change until formal release on PyPi.
Complex normals are generated from a bivariate normal where the variance of the real component is 0.5 Re(gamma + relation), the variance of the imaginary component is 0.5 Re(gamma  relation), and the covariance between the two is 0.5 Im(relation). The implied covariance matrix must be positive semidefinite and so both variances must be zero and the covariance must be weakly smaller than the product of the two standard deviations.
References
 1
Wikipedia, “Complex normal distribution”, https://en.wikipedia.org/wiki/Complex_normal_distribution
 2
Leigh J. Halliwell, “Complex Random Variables” in “Casualty. Actuarial Society EForum”, Fall 2015.
Examples
Draw samples from the distribution:
s = randomfunctiongen.generator.complex_normal(size=1000)

dirichlet
(*args, **kwargs)¶ dirichlet (V, alpha)
Generate a
Function
f = Function(V), randomise it by calling the original method dirichlet (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.dirichlet.html, which is reproduced below with appropriate changes.
dirichlet (alpha, size=None)
Draw samples from the Dirichlet distribution.
Draw size samples of dimension k from a Dirichlet distribution. A Dirichletdistributed random variable can be seen as a multivariate generalization of a Beta distribution. The Dirichlet distribution is a conjugate prior of a multinomial distribution in Bayesian inference.
 Parameters
alpha – array. Parameter of the distribution (k dimension for sample of dimension k).
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.
 Returns
ndarray,. The drawn samples, of shape (size, alpha.ndim).
 Raises
If any value in alpha is less than or equal to zero
Notes
The Dirichlet distribution is a distribution over vectors \(x\) that fulfil the conditions \(x_i>0\) and \(\sum_{i=1}^k x_i = 1\).
The probability density function \(p\) of a Dirichletdistributed random vector \(X\) is proportional to
\[p(x) \propto \prod_{i=1}^{k}{x^{\alpha_i1}_i},\]where \(\alpha\) is a vector containing the positive concentration parameters.
The method uses the following property for computation: let \(Y\) be a random vector which has components that follow a standard gamma distribution, then \(X = \frac{1}{\sum_{i=1}^k{Y_i}} Y\) is Dirichletdistributed
References
 1
David McKay, “Information Theory, Inference and Learning. Algorithms,” chapter 23, http://www.inference.org.uk/mackay/itila/
 2
Wikipedia, “Dirichlet distribution”, https://en.wikipedia.org/wiki/Dirichlet_distribution
Examples
Taking an example cited in Wikipedia, this distribution can be used if one wanted to cut strings (each of initial length 1.0) into K pieces with different lengths, where each piece had, on average, a designated average length, but allowing some variation in the relative sizes of the pieces:
s = randomfunctiongen.generator.dirichlet((10, 5, 3), 20).transpose():: import matplotlib.pyplot as plt plt.barh(range(20), s[0]) plt.barh(range(20), s[1], left=s[0], color='g') plt.barh(range(20), s[2], left=s[0]+s[1], color='r') plt.title("Lengths of Strings")

exponential
(*args, **kwargs)¶ exponential (V, scale=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method exponential (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.exponential.html, which is reproduced below with appropriate changes.
exponential (scale=1.0, size=None)
Draw samples from an exponential distribution.
Its probability density function is
\[f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(\frac{x}{\beta}),\]for
x > 0
and 0 elsewhere. \(\beta\) is the scale parameter, which is the inverse of the rate parameter \(\lambda = 1/\beta\). The rate parameter is an alternative, widely used parameterization of the exponential distribution [3]_.The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms [1]_, or the time between page requests to Wikipedia [2]_.
 Parameters
scale – float or array_like of floats. The scale parameter, \(\beta = 1/\lambda\). Must be nonnegative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifscale
is a scalar. Otherwise,np.array(scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized exponential distribution.
References
 1
Peyton Z. Peebles Jr., “Probability, Random Variables and. Random Signal Principles”, 4th ed, 2001, p. 57.
 2
Wikipedia, “Poisson process”, https://en.wikipedia.org/wiki/Poisson_process
 3
Wikipedia, “Exponential distribution”, https://en.wikipedia.org/wiki/Exponential_distribution

f
(*args, **kwargs)¶ f (V, dfnum, dfden)
Generate a
Function
f = Function(V), randomise it by calling the original method f (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.f.html, which is reproduced below with appropriate changes.
f (dfnum, dfden, size=None)
Draw samples from an F distribution.
Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator) and dfden (degrees of freedom in denominator), where both parameters must be greater than zero.
The random variate of the F distribution (also known as the Fisher distribution) is a continuous probability distribution that arises in ANOVA tests, and is the ratio of two chisquare variates.
 Parameters
dfnum – float or array_like of floats. Degrees of freedom in numerator, must be > 0.
dfden – float or array_like of float. Degrees of freedom in denominator, must be > 0.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifdfnum
anddfden
are both scalars. Otherwise,np.broadcast(dfnum, dfden).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Fisher distribution.
See Also
scipy.stats.f : probability density function, distribution or cumulative density function, etc.
Notes
The F statistic is used to compare ingroup variances to betweengroup variances. Calculating the distribution depends on the sampling, and so it is a function of the respective degrees of freedom in the problem. The variable dfnum is the number of samples minus one, the betweengroups degrees of freedom, while dfden is the withingroups degrees of freedom, the sum of the number of samples in each group minus the number of groups.
References
 1
Glantz, Stanton A. “Primer of Biostatistics.”, McGrawHill,. Fifth Edition, 2002.
 2
Wikipedia, “Fdistribution”, https://en.wikipedia.org/wiki/Fdistribution
Examples
An example from Glantz[1], pp 4740:
Two groups, children of diabetics (25 people) and children from people without diabetes (25 controls). Fasting blood glucose was measured, case group had a mean value of 86.1, controls had a mean value of 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these data consistent with the null hypothesis that the parents diabetic status does not affect their children’s blood glucose levels? Calculating the F statistic from the data gives a value of 36.01.
Draw samples from the distribution:
dfnum = 1. # between group degrees of freedom dfden = 48. # within groups degrees of freedom s = randomfunctiongen.generator.f(dfnum, dfden, 1000)
The lower bound for the top 1% of the samples is
np.sort(s)[10] # 7.61988120985 # random
So there is about a 1% chance that the F statistic will exceed 7.62, the measured value is 36, so the null hypothesis is rejected at the 1% level.

gamma
(*args, **kwargs)¶ gamma (V, shape, scale=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method gamma (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.gamma.html, which is reproduced below with appropriate changes.
gamma (shape, scale=1.0, size=None)
Draw samples from a Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale (sometimes designated “theta”), where both parameters are > 0.
 Parameters
shape – float or array_like of floats. The shape of the gamma distribution. Must be nonnegative.
scale – float or array_like of floats, optional. The scale of the gamma distribution. Must be nonnegative. Default is equal to 1.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifshape
andscale
are both scalars. Otherwise,np.broadcast(shape, scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized gamma distribution.
See Also
scipy.stats.gamma : probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gamma distribution is
\[p(x) = x^{k1}\frac{e^{x/\theta}}{\theta^k\Gamma(k)},\]where \(k\) is the shape and \(\theta\) the scale, and \(\Gamma\) is the Gamma function.
The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant.
References
 1
Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A. Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html
 2
Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution
Examples
Draw samples from the distribution:
shape, scale = 2., 2. # mean=4, std=2*sqrt(2) s = randomfunctiongen.generator.gamma(shape, scale, 1000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt import scipy.special as sps # doctest: +SKIP count, bins, ignored = plt.hist(s, 50, density=True) y = bins**(shape1)*(np.exp(bins/scale) / # doctest: +SKIP (sps.gamma(shape)*scale**shape)) plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP plt.show()

geometric
(*args, **kwargs)¶ geometric (V, p)
Generate a
Function
f = Function(V), randomise it by calling the original method geometric (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.geometric.html, which is reproduced below with appropriate changes.
geometric (p, size=None)
Draw samples from the geometric distribution.
Bernoulli trials are experiments with one of two outcomes: success or failure (an example of such an experiment is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve success. It is therefore supported on the positive integers,
k = 1, 2, ...
.The probability mass function of the geometric distribution is
\[f(k) = (1  p)^{k  1} p\]where p is the probability of success of an individual trial.
 Parameters
p – float or array_like of floats. The probability of success of an individual trial.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifp
is a scalar. Otherwise,np.array(p).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized geometric distribution.
Examples
Draw ten thousand values from the geometric distribution, with the probability of an individual success equal to 0.35:
z = randomfunctiongen.generator.geometric(p=0.35, size=10000)
How many trials succeeded after a single run?:
(z == 1).sum() / 10000. # 0.34889999999999999 #random

gumbel
(*args, **kwargs)¶ gumbel (V, loc=0.0, scale=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method gumbel (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.gumbel.html, which is reproduced below with appropriate changes.
gumbel (loc=0.0, scale=1.0, size=None)
Draw samples from a Gumbel distribution.
Draw samples from a Gumbel distribution with specified location and scale. For more information on the Gumbel distribution, see Notes and References below.
 Parameters
loc – float or array_like of floats, optional. The location of the mode of the distribution. Default is 0.
scale – float or array_like of floats, optional. The scale parameter of the distribution. Default is 1. Must be non negative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifloc
andscale
are both scalars. Otherwise,np.broadcast(loc, scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Gumbel distribution.
See Also
scipy.stats.gumbel_l scipy.stats.gumbel_r scipy.stats.genextreme weibull
Notes
The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value Type I) distribution is one of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems. The Gumbel is a special case of the Extreme Value Type I distribution for maximums from distributions with “exponentiallike” tails.
The probability density for the Gumbel distribution is
\[p(x) = \frac{e^{(x  \mu)/ \beta}}{\beta} e^{ e^{(x  \mu)/ \beta}},\]where \(\mu\) is the mode, a location parameter, and \(\beta\) is the scale parameter.
The Gumbel (named for German mathematician Emil Julius Gumbel) was used very early in the hydrology literature, for modeling the occurrence of flood events. It is also used for modeling maximum wind speed and rainfall rates. It is a “fattailed” distribution  the probability of an event in the tail of the distribution is larger than if one used a Gaussian, hence the surprisingly frequent occurrence of 100year floods. Floods were initially modeled as a Gaussian process, which underestimated the frequency of extreme events.
It is one of a class of extreme value distributions, the Generalized Extreme Value (GEV) distributions, which also includes the Weibull and Frechet.
The function has a mean of \(\mu + 0.57721\beta\) and a variance of \(\frac{\pi^2}{6}\beta^2\).
References
 1
Gumbel, E. J., “Statistics of Extremes,”. New York: Columbia University Press, 1958.
 2
Reiss, R.D. and Thomas, M., “Statistical Analysis of Extreme. Values from Insurance, Finance, Hydrology and Other Fields,”. Basel: Birkhauser Verlag, 2001.
Examples
Draw samples from the distribution:
mu, beta = 0, 0.1 # location and scale s = randomfunctiongen.generator.gumbel(mu, beta, 1000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 30, density=True) plt.plot(bins, (1/beta)*np.exp((bins  mu)/beta) * np.exp( np.exp( (bins  mu) /beta) ), linewidth=2, color='r') plt.show()
Show how an extreme value distribution can arise from a Gaussian process and compare to a Gaussian:
means = [] maxima = [] for i in range(0,1000) : a = randomfunctiongen.generator.normal(mu, beta, 1000) means.append(a.mean()) maxima.append(a.max()) count, bins, ignored = plt.hist(maxima, 30, density=True) beta = np.std(maxima) * np.sqrt(6) / np.pi mu = np.mean(maxima)  0.57721*beta plt.plot(bins, (1/beta)*np.exp((bins  mu)/beta) * np.exp(np.exp((bins  mu)/beta)), linewidth=2, color='r') plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi)) * np.exp((bins  mu)**2 / (2 * beta**2)), linewidth=2, color='g') plt.show()

hypergeometric
(*args, **kwargs)¶ hypergeometric (V, ngood, nbad, nsample)
Generate a
Function
f = Function(V), randomise it by calling the original method hypergeometric (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.hypergeometric.html, which is reproduced below with appropriate changes.
hypergeometric (ngood, nbad, nsample, size=None)
Draw samples from a Hypergeometric distribution.
Samples are drawn from a hypergeometric distribution with specified parameters, ngood (ways to make a good selection), nbad (ways to make a bad selection), and nsample (number of items sampled, which is less than or equal to the sum
ngood + nbad
). Parameters
ngood – int or array_like of ints. Number of ways to make a good selection. Must be nonnegative.
nbad – int or array_like of ints. Number of ways to make a bad selection. Must be nonnegative.
nsample – int or array_like of ints. Number of items sampled. Must be nonnegative and less than
ngood + nbad
.size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned if ngood, nbad, and nsample are all scalars. Otherwise,np.broadcast(ngood, nbad, nsample).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized hypergeometric distribution. Each sample is the number of good items within a randomly selected subset of size nsample taken from a set of ngood good items and nbad bad items.
See Also
scipy.stats.hypergeom : probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Hypergeometric distribution is
\[P(x) = \frac{\binom{g}{x}\binom{b}{nx}}{\binom{g+b}{n}},\]where \(0 \le x \le n\) and \(nb \le x \le g\)
for P(x) the probability of
x
good results in the drawn sample, g = ngood, b = nbad, and n = nsample.Consider an urn with black and white marbles in it, ngood of them are black and nbad are white. If you draw nsample balls without replacement, then the hypergeometric distribution describes the distribution of black balls in the drawn sample.
Note that this distribution is very similar to the binomial distribution, except that in this case, samples are drawn without replacement, whereas in the Binomial case samples are drawn with replacement (or the sample space is infinite). As the sample space becomes large, this distribution approaches the binomial.
References
 1
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.
 2
Weisstein, Eric W. “Hypergeometric Distribution.” From. MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/HypergeometricDistribution.html
 3
Wikipedia, “Hypergeometric distribution”, https://en.wikipedia.org/wiki/Hypergeometric_distribution
Examples
Draw samples from the distribution:
ngood, nbad, nsamp = 100, 2, 10 # number of good, number of bad, and number of samples s = randomfunctiongen.generator.hypergeometric(ngood, nbad, nsamp, 1000) from matplotlib.pyplot import hist hist(s) # note that it is very unlikely to grab both bad items
Suppose you have an urn with 15 white and 15 black marbles. If you pull 15 marbles at random, how likely is it that 12 or more of them are one color?:
s = randomfunctiongen.generator.hypergeometric(15, 15, 15, 100000) sum(s>=12)/100000. + sum(s<=3)/100000. # answer = 0.003 >>> pretty unlikely!

laplace
(*args, **kwargs)¶ laplace (V, loc=0.0, scale=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method laplace (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.laplace.html, which is reproduced below with appropriate changes.
laplace (loc=0.0, scale=1.0, size=None)
Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
The Laplace distribution is similar to the Gaussian/normal distribution, but is sharper at the peak and has fatter tails. It represents the difference between two independent, identically distributed exponential random variables.
 Parameters
loc – float or array_like of floats, optional. The position, \(\mu\), of the distribution peak. Default is 0.
scale – float or array_like of floats, optional \(\lambda\), the exponential decay. Default is 1. Must be non negative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifloc
andscale
are both scalars. Otherwise,np.broadcast(loc, scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Laplace distribution.
Notes
It has the probability density function
\[f(x; \mu, \lambda) = \frac{1}{2\lambda} \exp\left(\frac{x  \mu}{\lambda}\right).\]The first law of Laplace, from 1774, states that the frequency of an error can be expressed as an exponential function of the absolute magnitude of the error, which leads to the Laplace distribution. For many problems in economics and health sciences, this distribution seems to model the data better than the standard Gaussian distribution.
References
 1
Abramowitz, M. and Stegun, I. A. (Eds.). “Handbook of. Mathematical Functions with Formulas, Graphs, and Mathematical. Tables, 9th printing,” New York: Dover, 1972.
 2
Kotz, Samuel, et. al. “The Laplace Distribution and. Generalizations, ” Birkhauser, 2001.
 3
Weisstein, Eric W. “Laplace Distribution.”. From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LaplaceDistribution.html
 4
Wikipedia, “Laplace distribution”, https://en.wikipedia.org/wiki/Laplace_distribution
Examples
Draw samples from the distribution:
loc, scale = 0., 1. s = randomfunctiongen.generator.laplace(loc, scale, 1000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 30, density=True) x = np.arange(8., 8., .01) pdf = np.exp(abs(xloc)/scale)/(2.*scale) plt.plot(x, pdf)
Plot Gaussian for comparison:
g = (1/(scale * np.sqrt(2 * np.pi)) * np.exp((x  loc)**2 / (2 * scale**2))) plt.plot(x,g)

logistic
(*args, **kwargs)¶ logistic (V, loc=0.0, scale=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method logistic (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.logistic.html, which is reproduced below with appropriate changes.
logistic (loc=0.0, scale=1.0, size=None)
Draw samples from a logistic distribution.
Samples are drawn from a logistic distribution with specified parameters, loc (location or mean, also median), and scale (>0).
 Parameters
loc – float or array_like of floats, optional. Parameter of the distribution. Default is 0.
scale – float or array_like of floats, optional. Parameter of the distribution. Must be nonnegative. Default is 1.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifloc
andscale
are both scalars. Otherwise,np.broadcast(loc, scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized logistic distribution.
See Also
scipy.stats.logistic : probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Logistic distribution is
\[P(x) = P(x) = \frac{e^{(x\mu)/s}}{s(1+e^{(x\mu)/s})^2},\]where \(\mu\) = location and \(s\) = scale.
The Logistic distribution is used in Extreme Value problems where it can act as a mixture of Gumbel distributions, in Epidemiology, and by the World Chess Federation (FIDE) where it is used in the Elo ranking system, assuming the performance of each player is a logistically distributed random variable.
References
 1
Reiss, R.D. and Thomas M. (2001), “Statistical Analysis of. Extreme Values, from Insurance, Finance, Hydrology and Other. Fields,” Birkhauser Verlag, Basel, pp 132133.
 2
Weisstein, Eric W. “Logistic Distribution.” From. MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LogisticDistribution.html
 3
Wikipedia, “Logisticdistribution”, https://en.wikipedia.org/wiki/Logistic_distribution
Examples
Draw samples from the distribution:
loc, scale = 10, 1 s = randomfunctiongen.generator.logistic(loc, scale, 10000) import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, bins=50):: # plot against distribution:: def logist(x, loc, scale): return np.exp((locx)/scale)/(scale*(1+np.exp((locx)/scale))**2) lgst_val = logist(bins, loc, scale) plt.plot(bins, lgst_val * count.max() / lgst_val.max()) plt.show()

lognormal
(*args, **kwargs)¶ lognormal (V, mean=0.0, sigma=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method lognormal (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.lognormal.html, which is reproduced below with appropriate changes.
lognormal (mean=0.0, sigma=1.0, size=None)
Draw samples from a lognormal distribution.
Draw samples from a lognormal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from.
 Parameters
mean – float or array_like of floats, optional. Mean value of the underlying normal distribution. Default is 0.
sigma – float or array_like of floats, optional. Standard deviation of the underlying normal distribution. Must be nonnegative. Default is 1.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifmean
andsigma
are both scalars. Otherwise,np.broadcast(mean, sigma).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized lognormal distribution.
See Also
scipy.stats.lognorm : probability density function, distribution, cumulative density function, etc.
Notes
A variable x has a lognormal distribution if log(x) is normally distributed. The probability density function for the lognormal distribution is:
\[p(x) = \frac{1}{\sigma x \sqrt{2\pi}} e^{(\frac{(ln(x)\mu)^2}{2\sigma^2})}\]where \(\mu\) is the mean and \(\sigma\) is the standard deviation of the normally distributed logarithm of the variable. A lognormal distribution results if a random variable is the product of a large number of independent, identicallydistributed variables in the same way that a normal distribution results if the variable is the sum of a large number of independent, identicallydistributed variables.
References
 1
Limpert, E., Stahel, W. A., and Abbt, M., “Lognormal. Distributions across the Sciences: Keys and Clues,”. BioScience, Vol. 51, No. 5, May, 2001. https://stat.ethz.ch/~stahel/lognormal/bioscience.pdf
 2
Reiss, R.D. and Thomas, M., “Statistical Analysis of Extreme. Values,” Basel: Birkhauser Verlag, 2001, pp. 3132.
Examples
Draw samples from the distribution:
mu, sigma = 3., 1. # mean and standard deviation s = randomfunctiongen.generator.lognormal(mu, sigma, 1000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 100, density=True, align='mid'):: x = np.linspace(min(bins), max(bins), 10000) pdf = (np.exp((np.log(x)  mu)**2 / (2 * sigma**2)) / (x * sigma * np.sqrt(2 * np.pi))):: plt.plot(x, pdf, linewidth=2, color='r') plt.axis('tight') plt.show()
Demonstrate that taking the products of random samples from a uniform distribution can be fit well by a lognormal probability density function:
# Generate a thousand samples: each is the product of 100 random # values, drawn from a normal distribution. b = [] for i in range(1000): a = 10. + randomfunctiongen.generator.standard_normal(100) b.append(np.product(a)):: b = np.array(b) / np.min(b) # scale values to be positive count, bins, ignored = plt.hist(b, 100, density=True, align='mid') sigma = np.std(np.log(b)) mu = np.mean(np.log(b)):: x = np.linspace(min(bins), max(bins), 10000) pdf = (np.exp((np.log(x)  mu)**2 / (2 * sigma**2)) / (x * sigma * np.sqrt(2 * np.pi))):: plt.plot(x, pdf, color='r', linewidth=2) plt.show()

logseries
(*args, **kwargs)¶ logseries (V, p)
Generate a
Function
f = Function(V), randomise it by calling the original method logseries (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.logseries.html, which is reproduced below with appropriate changes.
logseries (p, size=None)
Draw samples from a logarithmic series distribution.
Samples are drawn from a log series distribution with specified shape parameter, 0 <
p
< 1. Parameters
p – float or array_like of floats. Shape parameter for the distribution. Must be in the range (0, 1).
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifp
is a scalar. Otherwise,np.array(p).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized logarithmic series distribution.
See Also
scipy.stats.logser : probability density function, distribution or cumulative density function, etc.
Notes
The probability mass function for the Log Series distribution is
\[P(k) = \frac{p^k}{k \ln(1p)},\]where p = probability.
The log series distribution is frequently used to represent species richness and occurrence, first proposed by Fisher, Corbet, and Williams in 1943 [2]. It may also be used to model the numbers of occupants seen in cars [3].
References
 1
Buzas, Martin A.; Culver, Stephen J., Understanding regional species diversity through the log series distribution of occurrences: BIODIVERSITY RESEARCH Diversity & Distributions,. Volume 5, Number 5, September 1999 , pp. 187195(9).
 2
Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The relation between the number of species and the number of individuals in a random sample of an animal population. Journal of Animal Ecology, 12:4258.
 3
Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small. Data Sets, CRC Press, 1994.
 4
Wikipedia, “Logarithmic distribution”, https://en.wikipedia.org/wiki/Logarithmic_distribution
Examples
Draw samples from the distribution:
a = .6 s = randomfunctiongen.generator.logseries(a, 10000) import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s):: # plot against distribution:: def logseries(k, p): return p**k/(k*np.log(1p)) plt.plot(bins, logseries(bins, a) * count.max()/ logseries(bins, a).max(), 'r') plt.show()

multinomial
(*args, **kwargs)¶ multinomial (V, n, pvals)
Generate a
Function
f = Function(V), randomise it by calling the original method multinomial (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.multinomial.html, which is reproduced below with appropriate changes.
multinomial (n, pvals, size=None)
Draw samples from a multinomial distribution.
The multinomial distribution is a multivariate generalization of the binomial distribution. Take an experiment with one of
p
possible outcomes. An example of such an experiment is throwing a dice, where the outcome can be 1 through 6. Each sample drawn from the distribution represents n such experiments. Its values,X_i = [X_0, X_1, ..., X_p]
, represent the number of times the outcome wasi
. Parameters
n – int or arraylike of ints. Number of experiments.
pvals – sequence of floats, length p. Probabilities of each of the
p
different outcomes. These must sum to 1 (however, the last element is always assumed to account for the remaining probability, as long assum(pvals[:1]) <= 1)
.size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.
 Returns
ndarray. The drawn samples, of shape size, if that was provided. If not, the shape is
(N,)
.
In other words, each entry
out[i,j,...,:]
is an Ndimensional value drawn from the distribution.Examples
Throw a dice 20 times:
randomfunctiongen.generator.multinomial(20, [1/6.]*6, size=1) # array([[4, 1, 7, 5, 2, 1]]) # random
It landed 4 times on 1, once on 2, etc.
Now, throw the dice 20 times, and 20 times again:
randomfunctiongen.generator.multinomial(20, [1/6.]*6, size=2) # array([[3, 4, 3, 3, 4, 3], # [2, 4, 3, 4, 0, 7]]) # random
For the first run, we threw 3 times 1, 4 times 2, etc. For the second, we threw 2 times 1, 4 times 2, etc.
Now, do one experiment throwing the dice 10 time, and 10 times again, and another throwing the dice 20 times, and 20 times again:
randomfunctiongen.generator.multinomial([[10], [20]], [1/6.]*6, size=2) # array([[[2, 4, 0, 1, 2, 1], # [1, 3, 0, 3, 1, 2]], # [[1, 4, 4, 4, 4, 3], # [3, 3, 2, 5, 5, 2]]]) # random
The first array shows the outcomes of throwing the dice 10 times, and the second shows the outcomes from throwing the dice 20 times.
A loaded die is more likely to land on number 6:
randomfunctiongen.generator.multinomial(100, [1/7.]*5 + [2/7.]) # array([11, 16, 14, 17, 16, 26]) # random
The probability inputs should be normalized. As an implementation detail, the value of the last entry is ignored and assumed to take up any leftover probability mass, but this should not be relied on. A biased coin which has twice as much weight on one side as on the other should be sampled like so:
randomfunctiongen.generator.multinomial(100, [1.0 / 3, 2.0 / 3]) # RIGHT # array([38, 62]) # random
not like:
randomfunctiongen.generator.multinomial(100, [1.0, 2.0]) # WRONG # Traceback (most recent call last): # ValueError: pvals < 0, pvals > 1 or pvals contains NaNs

multivariate_normal
(*args, **kwargs)¶ multivariate_normal (V, mean, cov, check_valid=’warn’, tol=1e8)
Generate a
Function
f = Function(V), randomise it by calling the original method multivariate_normal (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.multivariate_normal.html, which is reproduced below with appropriate changes.
multivariate_normal (mean, cov, size=None, check_valid=’warn’, tol=1e8)
Draw random samples from a multivariate normal distribution.
The multivariate normal, multinormal or Gaussian distribution is a generalization of the onedimensional normal distribution to higher dimensions. Such a distribution is specified by its mean and covariance matrix. These parameters are analogous to the mean (average or “center”) and variance (standard deviation, or “width,” squared) of the onedimensional normal distribution.
 Parameters
mean – 1D array_like, of length N. Mean of the Ndimensional distribution.
cov – 2D array_like, of shape (N, N). Covariance matrix of the distribution. It must be symmetric and positivesemidefinite for proper sampling.
size – int or tuple of ints, optional. Given a shape of, for example,
(m,n,k)
,m*n*k
samples are generated, and packed in an mbynbyk arrangement. Because each sample is Ndimensional, the output shape is(m,n,k,N)
. If no shape is specified, a single (ND) sample is returned.check_valid – { ‘warn’, ‘raise’, ‘ignore’ }, optional. Behavior when the covariance matrix is not positive semidefinite.
tol – float, optional. Tolerance when checking the singular values in covariance matrix. cov is cast to double before the check.
 Returns
ndarray. The drawn samples, of shape size, if that was provided. If not, the shape is
(N,)
.
In other words, each entry
out[i,j,...,:]
is an Ndimensional value drawn from the distribution.Notes
The mean is a coordinate in Ndimensional space, which represents the location where samples are most likely to be generated. This is analogous to the peak of the bell curve for the onedimensional or univariate normal distribution.
Covariance indicates the level to which two variables vary together. From the multivariate normal distribution, we draw Ndimensional samples, \(X = [x_1, x_2, >>> x_N]\). The covariance matrix
# element \(C_{ij}\) is the covariance of \(x_i\) and \(x_j\). # The element \(C_{ii}\) is the variance of \(x_i\) (i.e. its # “spread”).
Instead of specifying the full covariance matrix, popular approximations include:
Spherical covariance (cov is a multiple of the identity matrix)
Diagonal covariance (cov has nonnegative elements, and only on
the diagonal)
This geometrical property can be seen in two dimensions by plotting generated datapoints:
mean = [0, 0] cov = [[1, 0], [0, 100]] # diagonal covariance
Diagonal covariance means that points are oriented along x or yaxis:
import matplotlib.pyplot as plt x, y = randomfunctiongen.generator.multivariate_normal(mean, cov, 5000).T plt.plot(x, y, 'x') plt.axis('equal') plt.show()
Note that the covariance matrix must be positive semidefinite (a.k.a. nonnegativedefinite). Otherwise, the behavior of this method is undefined and backwards compatibility is not guaranteed.
References
 1
Papoulis, A., “Probability, Random Variables, and Stochastic. Processes,” 3rd ed., New York: McGrawHill, 1991.
 2
Duda, R. O., Hart, P. E., and Stork, D. G., “Pattern. Classification,” 2nd ed., New York: Wiley, 2001.
Examples:
mean = (1, 2) cov = [[1, 0], [0, 1]] x = randomfunctiongen.generator.multivariate_normal(mean, cov, (3, 3)) x.shape # (3, 3, 2)
The following is probably true, given that 0.6 is roughly twice the standard deviation:
list((x[0,0,:]  mean) < 0.6) # [True, True] # random

negative_binomial
(*args, **kwargs)¶ negative_binomial (V, n, p)
Generate a
Function
f = Function(V), randomise it by calling the original method negative_binomial (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.negative_binomial.html, which is reproduced below with appropriate changes.
negative_binomial (n, p, size=None)
Draw samples from a negative binomial distribution.
Samples are drawn from a negative binomial distribution with specified parameters, n successes and p probability of success where n is > 0 and p is in the interval [0, 1].
 Parameters
n – float or array_like of floats. Parameter of the distribution, > 0.
p – float or array_like of floats. Parameter of the distribution, >= 0 and <=1.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifn
andp
are both scalars. Otherwise,np.broadcast(n, p).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized negative binomial distribution, where each sample is equal to N, the number of failures that occurred before a total of n successes was reached.
Notes
The probability mass function of the negative binomial distribution is
\[P(N;n,p) = \frac{\Gamma(N+n)}{N!\Gamma(n)}p^{n}(1p)^{N},\]where \(n\) is the number of successes, \(p\) is the probability of success, \(N+n\) is the number of trials, and \(\Gamma\) is the gamma function. When \(n\) is an integer, \(\frac{\Gamma(N+n)}{N!\Gamma(n)} = \binom{N+n1}{N}\), which is the more common form of this term in the the pmf. The negative binomial distribution gives the probability of N failures given n successes, with a success on the last trial.
If one throws a die repeatedly until the third time a “1” appears, then the probability distribution of the number of non“1”s that appear before the third “1” is a negative binomial distribution.
References
 1
Weisstein, Eric W. “Negative Binomial Distribution.” From. MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NegativeBinomialDistribution.html
 2
Wikipedia, “Negative binomial distribution”, https://en.wikipedia.org/wiki/Negative_binomial_distribution
Examples
Draw samples from the distribution:
A real world example. A company drills wildcat oil exploration wells, each with an estimated probability of success of 0.1. What is the probability of having one success for each successive well, that is what is the probability of a single success after drilling 5 wells, after 6 wells, etc.?:
s = randomfunctiongen.generator.negative_binomial(1, 0.1, 100000) for i in range(1, 11): # doctest: +SKIP probability = sum(s<i) / 100000. print(i, "wells drilled, probability of one success =", probability)

noncentral_chisquare
(*args, **kwargs)¶ noncentral_chisquare (V, df, nonc)
Generate a
Function
f = Function(V), randomise it by calling the original method noncentral_chisquare (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.noncentral_chisquare.html, which is reproduced below with appropriate changes.
noncentral_chisquare (df, nonc, size=None)
Draw samples from a noncentral chisquare distribution.
The noncentral \(\chi^2\) distribution is a generalization of the \(\chi^2\) distribution.
 Parameters
df – float or array_like of floats. Degrees of freedom, must be > 0.
Changed in version 1.10.0.
Earlier NumPy versions required dfnum > 1.
 Parameters
nonc – float or array_like of floats. Noncentrality, must be nonnegative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifdf
andnonc
are both scalars. Otherwise,np.broadcast(df, nonc).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized noncentral chisquare distribution.
Notes
The probability density function for the noncentral Chisquare distribution is
\[P(x;df,nonc) = \sum^{\infty}_{i=0} \frac{e^{nonc/2}(nonc/2)^{i}}{i!}. P_{Y_{df+2i}}(x),\]where \(Y_{q}\) is the Chisquare with q degrees of freedom.
References
 1
Wikipedia, “Noncentral chisquared distribution” https://en.wikipedia.org/wiki/Noncentral_chisquared_distribution
Examples
Draw values from the distribution and plot the histogram:
import matplotlib.pyplot as plt values = plt.hist(randomfunctiongen.generator.noncentral_chisquare(3, 20, 100000), bins=200, density=True) plt.show()
Draw values from a noncentral chisquare with very small noncentrality, and compare to a chisquare:
plt.figure() values = plt.hist(randomfunctiongen.generator.noncentral_chisquare(3, .0000001, 100000), bins=np.arange(0., 25, .1), density=True) values2 = plt.hist(randomfunctiongen.generator.chisquare(3, 100000), bins=np.arange(0., 25, .1), density=True) plt.plot(values[1][0:1], values[0]values2[0], 'ob') plt.show()
Demonstrate how large values of noncentrality lead to a more symmetric distribution:
plt.figure() values = plt.hist(randomfunctiongen.generator.noncentral_chisquare(3, 20, 100000), bins=200, density=True) plt.show()

noncentral_f
(*args, **kwargs)¶ noncentral_f (V, dfnum, dfden, nonc)
Generate a
Function
f = Function(V), randomise it by calling the original method noncentral_f (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.noncentral_f.html, which is reproduced below with appropriate changes.
noncentral_f (dfnum, dfden, nonc, size=None)
Draw samples from the noncentral F distribution.
Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator) and dfden (degrees of freedom in denominator), where both parameters > 1. nonc is the noncentrality parameter.
 Parameters
dfnum – float or array_like of floats. Numerator degrees of freedom, must be > 0.
Changed in version 1.14.0.
Earlier NumPy versions required dfnum > 1.
 Parameters
dfden – float or array_like of floats. Denominator degrees of freedom, must be > 0.
nonc – float or array_like of floats. Noncentrality parameter, the sum of the squares of the numerator means, must be >= 0.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifdfnum
,dfden
, andnonc
are all scalars. Otherwise,np.broadcast(dfnum, dfden, nonc).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized noncentral Fisher distribution.
Notes
When calculating the power of an experiment (power = probability of rejecting the null hypothesis when a specific alternative is true) the noncentral F statistic becomes important. When the null hypothesis is true, the F statistic follows a central F distribution. When the null hypothesis is not true, then it follows a noncentral F statistic.
References
 1
Weisstein, Eric W. “Noncentral FDistribution.”. From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NoncentralFDistribution.html
 2
Wikipedia, “Noncentral Fdistribution”, https://en.wikipedia.org/wiki/Noncentral_Fdistribution
Examples
In a study, testing for a specific alternative to the null hypothesis requires use of the Noncentral F distribution. We need to calculate the area in the tail of the distribution that exceeds the value of the F distribution for the null hypothesis. We’ll plot the two probability distributions for comparison:
dfnum = 3 # between group deg of freedom dfden = 20 # within groups degrees of freedom nonc = 3.0 nc_vals = randomfunctiongen.generator.noncentral_f(dfnum, dfden, nonc, 1000000) NF = np.histogram(nc_vals, bins=50, density=True) c_vals = randomfunctiongen.generator.f(dfnum, dfden, 1000000) F = np.histogram(c_vals, bins=50, density=True) import matplotlib.pyplot as plt plt.plot(F[1][1:], F[0]) plt.plot(NF[1][1:], NF[0]) plt.show()

normal
(*args, **kwargs)¶ normal (V, loc=0.0, scale=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method normal (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.normal.html, which is reproduced below with appropriate changes.
normal (loc=0.0, scale=1.0, size=None)
Draw random samples from a normal (Gaussian) distribution.
The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2]_, is often called the bell curve because of its characteristic shape (see the example below).
The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]_.
 Parameters
loc – float or array_like of floats. Mean (“centre”) of the distribution.
scale – float or array_like of floats. Standard deviation (spread or “width”) of the distribution. Must be nonnegative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifloc
andscale
are both scalars. Otherwise,np.broadcast(loc, scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized normal distribution.
See Also
scipy.stats.norm : probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gaussian distribution is
\[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{  \frac{ (x  \mu)^2 } {2 \sigma^2} },\]where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance.
The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x  \sigma\) [2]_). This implies that randomfunctiongen.generator.normal is more likely to return samples lying close to the mean, rather than those far away.
References
 1
Wikipedia, “Normal distribution”, https://en.wikipedia.org/wiki/Normal_distribution
 2
Peebles Jr., “Central Limit Theorem” in “Probability,. Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.
Examples
Draw samples from the distribution:
mu, sigma = 0, 0.1 # mean and standard deviation s = randomfunctiongen.generator.normal(mu, sigma, 1000)
Verify the mean and the variance:
abs(mu  np.mean(s)) # 0.0 # may vary:: abs(sigma  np.std(s, ddof=1)) # 0.1 # may vary
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 30, density=True) plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp(  (bins  mu)**2 / (2 * sigma**2) ), linewidth=2, color='r') plt.show()
Twobyfour array of samples from N(3, 6.25):
randomfunctiongen.generator.normal(3, 2.5, size=(2, 4)) # array([[4.49401501, 4.00950034, 1.81814867, 7.29718677], # random # [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random

pareto
(*args, **kwargs)¶ pareto (V, a)
Generate a
Function
f = Function(V), randomise it by calling the original method pareto (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.pareto.html, which is reproduced below with appropriate changes.
pareto (a, size=None)
Draw samples from a Pareto II or Lomax distribution with specified shape.
The Lomax or Pareto II distribution is a shifted Pareto distribution. The classical Pareto distribution can be obtained from the Lomax distribution by adding 1 and multiplying by the scale parameter
m
(see Notes). The smallest value of the Lomax distribution is zero while for the classical Pareto distribution it ismu
, where the standard Pareto distribution has locationmu = 1
. Lomax can also be considered as a simplified version of the Generalized Pareto distribution (available in SciPy), with the scale set to one and the location set to zero.The Pareto distribution must be greater than zero, and is unbounded above. It is also known as the “8020 rule”. In this distribution, 80 percent of the weights are in the lowest 20 percent of the range, while the other 20 percent fill the remaining 80 percent of the range.
 Parameters
a – float or array_like of floats. Shape of the distribution. Must be positive.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifa
is a scalar. Otherwise,np.array(a).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Pareto distribution.
See Also
scipy.stats.lomax : probability density function, distribution or cumulative density function, etc. scipy.stats.genpareto : probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Pareto distribution is
\[p(x) = \frac{am^a}{x^{a+1}}\]where \(a\) is the shape and \(m\) the scale.
The Pareto distribution, named after the Italian economist Vilfredo Pareto, is a power law probability distribution useful in many real world problems. Outside the field of economics it is generally referred to as the Bradford distribution. Pareto developed the distribution to describe the distribution of wealth in an economy. It has also found use in insurance, web page access statistics, oil field sizes, and many other problems, including the download frequency for projects in Sourceforge [1]_. It is one of the socalled “fattailed” distributions.
References
 1
Francis Hunt and Paul Johnson, On the Pareto Distribution of. Sourceforge projects.
 2
Pareto, V. (1896). Course of Political Economy. Lausanne.
 3
Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme. Values, Birkhauser Verlag, Basel, pp 2330.
 4
Wikipedia, “Pareto distribution”, https://en.wikipedia.org/wiki/Pareto_distribution
Examples
Draw samples from the distribution:
a, m = 3., 2. # shape and mode s = (randomfunctiongen.generator.pareto(a, 1000) + 1) * m
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt count, bins, _ = plt.hist(s, 100, density=True) fit = a*m**a / bins**(a+1) plt.plot(bins, max(count)*fit/max(fit), linewidth=2, color='r') plt.show()

permutation
(x)¶ Randomly permute a sequence, or return a permuted range.
If x is a multidimensional array, it is only shuffled along its first index.
 Parameters
x – int or array_like. If x is an integer, randomly permute
np.arange(x)
. If x is an array, make a copy and shuffle the elements randomly. Returns
ndarray. Permuted sequence or array range.
Examples:
randomfunctiongen.generator.permutation(10) # array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6]) # random:: randomfunctiongen.generator.permutation([1, 4, 9, 12, 15]) # array([15, 1, 9, 4, 12]) # random:: arr = np.arange(9).reshape((3, 3)) randomfunctiongen.generator.permutation(arr) # array([[6, 7, 8], # random # [0, 1, 2], # [3, 4, 5]])

poisson
(*args, **kwargs)¶ poisson (V, lam=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method poisson (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.poisson.html, which is reproduced below with appropriate changes.
poisson (lam=1.0, size=None)
Draw samples from a Poisson distribution.
The Poisson distribution is the limit of the binomial distribution for large N.
 Parameters
lam – float or array_like of floats. Expectation of interval, must be >= 0. A sequence of expectation intervals must be broadcastable over the requested size.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned iflam
is a scalar. Otherwise,np.array(lam).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Poisson distribution.
Notes
The Poisson distribution
\[f(k; \lambda)=\frac{\lambda^k e^{\lambda}}{k!}\]For events with an expected separation \(\lambda\) the Poisson distribution \(f(k; \lambda)\) describes the probability of \(k\) events occurring within the observed interval \(\lambda\).
Because the output is limited to the range of the C int64 type, a ValueError is raised when lam is within 10 sigma of the maximum representable value.
References
 1
Weisstein, Eric W. “Poisson Distribution.”. From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/PoissonDistribution.html
 2
Wikipedia, “Poisson distribution”, https://en.wikipedia.org/wiki/Poisson_distribution
Examples
Draw samples from the distribution:
import numpy as np s = randomfunctiongen.generator.poisson(5, 10000)
Display histogram of the sample:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 14, density=True) plt.show()
Draw each 100 values for lambda 100 and 500:
s = randomfunctiongen.generator.poisson(lam=(100., 500.), size=(100, 2))

power
(*args, **kwargs)¶ power (V, a)
Generate a
Function
f = Function(V), randomise it by calling the original method power (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.power.html, which is reproduced below with appropriate changes.
power (a, size=None)
Draws samples in [0, 1] from a power distribution with positive exponent a  1.
Also known as the power function distribution.
 Parameters
a – float or array_like of floats. Parameter of the distribution. Must be nonnegative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifa
is a scalar. Otherwise,np.array(a).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized power distribution.
 Raises
If a < 1.
Notes
The probability density function is
\[P(x; a) = ax^{a1}, 0 \le x \le 1, a>0.\]The power function distribution is just the inverse of the Pareto distribution. It may also be seen as a special case of the Beta distribution.
It is used, for example, in modeling the overreporting of insurance claims.
References
 1
Christian Kleiber, Samuel Kotz, “Statistical size distributions in economics and actuarial sciences”, Wiley, 2003.
 2
Heckert, N. A. and Filliben, James J. “NIST Handbook 148:. Dataplot Reference Manual, Volume 2: Let Subcommands and Library. Functions”, National Institute of Standards and Technology. Handbook Series, June 2003. https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf
Examples
Draw samples from the distribution:
a = 5. # shape samples = 1000 s = randomfunctiongen.generator.power(a, samples)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, bins=30) x = np.linspace(0, 1, 100) y = a*x**(a1.) normed_y = samples*np.diff(bins)[0]*y plt.plot(x, normed_y) plt.show()
Compare the power function distribution to the inverse of the Pareto:
from scipy import stats # doctest: +SKIP rvs = randomfunctiongen.generator.power(5, 1000000) rvsp = randomfunctiongen.generator.pareto(5, 1000000) xx = np.linspace(0,1,100) powpdf = stats.powerlaw.pdf(xx,5) # doctest: +SKIP:: plt.figure() plt.hist(rvs, bins=50, density=True) plt.plot(xx,powpdf,'r') # doctest: +SKIP plt.title('randomfunctiongen.generator.power(5)'):: plt.figure() plt.hist(1./(1.+rvsp), bins=50, density=True) plt.plot(xx,powpdf,'r') # doctest: +SKIP plt.title('inverse of 1 + randomfunctiongen.generator.pareto(5)'):: plt.figure() plt.hist(1./(1.+rvsp), bins=50, density=True) plt.plot(xx,powpdf,'r') # doctest: +SKIP plt.title('inverse of stats.pareto(5)')

rand
(*args, **kwargs)¶ rand (V, dtype=’d’)
Generate a function \(f\) = Function(V), internally call the original method rand with given arguments, and return \(f\).
 Parameters
V –
FunctionSpace
 Returns
rand (d0, d1, …, dn, dtype=’d’)
Random values in a given shape.
This is a convenience function for users porting code from Matlab, and wraps randomfunctiongen.generator.random_sample. That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones.
Create an array of the given shape and populate it with random samples from a uniform distribution over
[0, 1)
. Parameters
d1, .., dn (d0,) – int, optional. The dimensions of the returned array, must be nonnegative. If no argument is given a single Python float is returned.
dtype – {str, dtype}, optional. Desired dtype of the result, either ‘d’ (or ‘float64’) or ‘f’ (or ‘float32’). All dtypes are determined by their name. The default value is ‘d’.
 Returns
ndarray, shape
(d0, d1, ..., dn)
. Random values.
See Also
random
Examples:
randomfunctiongen.generator.rand(3,2) # array([[ 0.14022471, 0.96360618], #random # [ 0.37601032, 0.25528411], #random # [ 0.49313049, 0.94909878]]) #random

randint
(*args, **kwargs)¶ randint (V, low, high=None, dtype=’int64’, use_masked=True)
Generate a
Function
f = Function(V), randomise it by calling the original method randint (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.randint.html, which is reproduced below with appropriate changes.
randint (low, high=None, size=None, dtype=’int64’, use_masked=True)
Return random integers from low (inclusive) to high (exclusive).
Return random integers from the “discrete uniform” distribution of the specified dtype in the “halfopen” interval [low, high). If high is None (the default), then results are from [0, low).
 Parameters
low – int or arraylike of ints. Lowest (signed) integers to be drawn from the distribution (unless
high=None
, in which case this parameter is one above the highest such integer).high – int or arraylike of ints, optional. If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if
high=None
). If arraylike, must contain integer valuessize – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.dtype – {str, dtype}, optional. Desired dtype of the result. All dtypes are determined by their name, i.e., ‘int64’, ‘int’, etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is ‘np.int’.
New in version 1.11.0.
 Parameters
use_masked – bool. If True the generator uses rejection sampling with a bit mask to reject random numbers that are out of bounds. If False the generator will use Lemire’s rejection sampling algorithm.
New in version 1.15.1.
 Returns
int or ndarray of ints sizeshaped array of random integers from the appropriate distribution, or a single such random int if size not provided.
Notes
When using broadcasting with uint64 dtypes, the maximum value (2**64) cannot be represented as a standard integer type. The high array (or low if high is None) must have object dtype, e.g., array([2**64]).
See Also
 Parameters
random_integers – similar to randint, only for the closed interval [low, high], and 1 is the lowest value if high is omitted. In particular, this other one is the one to use to generate uniformly distributed discrete nonintegers.
Examples:
randomfunctiongen.generator.randint(2, size=10) # array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random randomfunctiongen.generator.randint(1, size=10) # array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Generate a 2 x 4 array of ints between 0 and 4, inclusive:
randomfunctiongen.generator.randint(5, size=(2, 4)) # array([[4, 0, 2, 1], # [3, 2, 2, 0]]) # random
Generate a 1 x 3 array with 3 different upper bounds:
randomfunctiongen.generator.randint(1, [3, 5, 10]) # array([2, 2, 9]) # random
Generate a 1 by 3 array with 3 different lower bounds:
randomfunctiongen.generator.randint([1, 5, 7], 10) # array([9, 8, 7]) # random
Generate a 2 by 4 array using broadcasting with dtype of uint8:
randomfunctiongen.generator.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8) # array([[ 8, 6, 9, 7], # [ 1, 16, 9, 12]], dtype=uint8) # random
References
 1
Daniel Lemire., “Fast Random Integer Generation in an Interval”,. CoRR, Aug. 13, 2018, http://arxiv.org/abs/1805.10941.

randn
(*args, **kwargs)¶ randn (V, dtype=’d’)
Generate a function \(f\) = Function(V), internally call the original method randn with given arguments, and return \(f\).
 Parameters
V –
FunctionSpace
 Returns
randn (d0, d1, …, dn, dtype=’d’)
Return a sample (or samples) from the “standard normal” distribution.
This is a convenience function for users porting code from Matlab, and wraps randomfunctiongen.generator.standard_normal. That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones.
If positive int_like arguments are provided, randn generates an array of shape
(d0, d1, ..., dn)
, filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1. A single float randomly sampled from the distribution is returned if no argument is provided. Parameters
d1, .., dn (d0,) – int, optional. The dimensions of the returned array, must be nonnegative. If no argument is given a single Python float is returned.
dtype – {str, dtype}, optional. Desired dtype of the result, either ‘d’ (or ‘float64’) or ‘f’ (or ‘float32’). All dtypes are determined by their name. The default value is ‘d’.
 Returns
ndarray or float. A
(d0, d1, ..., dn)
shaped array of floatingpoint samples from the standard normal distribution, or a single such float if no parameters were supplied.
See Also
standard_normal : Similar, but takes a tuple as its argument.
 Parameters
normal – Also accepts mu and sigma arguments.
Notes
For random samples from \(N(\mu, \sigma^2)\), use:
sigma * randomfunctiongen.generator.randn(...) + mu
Examples:
randomfunctiongen.generator.randn() # 2.1923875335537315 # random
Twobyfour array of samples from N(3, 6.25):
3 + 2.5 * randomfunctiongen.generator.randn(2, 4) # array([[4.49401501, 4.00950034, 1.81814867, 7.29718677], # random # [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random

random_integers
(*args, **kwargs)¶ random_integers (V, low, high=None)
Generate a
Function
f = Function(V), randomise it by calling the original method random_integers (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.random_integers.html, which is reproduced below with appropriate changes.
random_integers (low, high=None, size=None)
Random integers of type np.int between low and high, inclusive.
Return random integers of type np.int from the “discrete uniform” distribution in the closed interval [low, high]. If high is None (the default), then results are from [1, low]. The np.int type translates to the C long integer type and its precision is platform dependent.
This function has been deprecated. Use randint instead.
Deprecated since version 1.11.0.
 Parameters
low – int. Lowest (signed) integer to be drawn from the distribution (unless
high=None
, in which case this parameter is the highest such integer).high – int, optional. If provided, the largest (signed) integer to be drawn from the distribution (see above for behavior if
high=None
).size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.
 Returns
int or ndarray of ints sizeshaped array of random integers from the appropriate distribution, or a single such random int if size not provided.
See Also
 Parameters
randint – Similar to random_integers, only for the halfopen interval [low, high), and 0 is the lowest value if high is omitted.
Notes
To sample from N evenly spaced floatingpoint numbers between a and b, use:
a + (b  a) * (randomfunctiongen.generator.random_integers(N)  1) / (N  1.)
Examples:
randomfunctiongen.generator.random_integers(5) # 4 # random type(randomfunctiongen.generator.random_integers(5)) # <class 'numpy.int64'> randomfunctiongen.generator.random_integers(5, size=(3,2)) # array([[5, 4], # random # [3, 3], # [4, 5]])
Choose five random numbers from the set of five evenlyspaced numbers between 0 and 2.5, inclusive (i.e., from the set \({0, 5/8, 10/8, 15/8, 20/8}\)):
2.5 * (randomfunctiongen.generator.random_integers(5, size=(5,))  1) / 4. # array([ 0.625, 1.25 , 0.625, 0.625, 2.5 ]) # random
Roll two six sided dice 1000 times and sum the results:
d1 = randomfunctiongen.generator.random_integers(1, 6, 1000) d2 = randomfunctiongen.generator.random_integers(1, 6, 1000) dsums = d1 + d2
Display results as a histogram:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(dsums, 11, density=True) plt.show()

random_sample
(*args, **kwargs)¶ random_sample (V, dtype=’d’, out=None)
Generate a
Function
f = Function(V), randomise it by calling the original method random_sample (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.random_sample.html, which is reproduced below with appropriate changes.
random_sample (size=None, dtype=’d’, out=None)
Return random floats in the halfopen interval [0.0, 1.0).
Results are from the “continuous uniform” distribution over the stated interval. To sample \(Unif[a, b), b > a\) multiply the output of random_sample by (ba) and add a:
(b  a) * random_sample() + a
 Parameters
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.dtype – {str, dtype}, optional. Desired dtype of the result, either ‘d’ (or ‘float64’) or ‘f’ (or ‘float32’). All dtypes are determined by their name. The default value is ‘d’.
out – ndarray, optional. Alternative output array in which to place the result. If size is not None, it must have the same shape as the provided size and must match the type of the output values.
 Returns
float or ndarray of floats. Array of random floats of shape size (*args, **kwargs)
:returns: float or ndarray of floats. Array of random floats of shape `size` * (*V, unless ``size=None``, in which case a single float is returned).
Generate a
Function
f = Function(V), randomise it by calling the original method *:returns: float or ndarray of floats. Array of random floats of shape size * (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at <https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.:returns: float or ndarray of floats. Array of random floats of shape `size .html>`__, which is reproduced below with appropriate changes.
:returns: float or ndarray of floats. Array of random floats of shape `size` * (*unless ``size=None``, in which case a single float is returned).
Examples:
randomfunctiongen.generator.random_sample() # 0.47108547995356098 # random type(randomfunctiongen.generator.random_sample()) # <class 'float'> randomfunctiongen.generator.random_sample((5,)) # array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428]) # random
Threebytwo array of random numbers from [5, 0):
5 * randomfunctiongen.generator.random_sample((3, 2))  5 # array([[3.99149989, 0.52338984], # random # [2.99091858, 0.79479508], # [1.23204345, 1.75224494]])

rayleigh
(*args, **kwargs)¶ rayleigh (V, scale=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method rayleigh (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.rayleigh.html, which is reproduced below with appropriate changes.
rayleigh (scale=1.0, size=None)
Draw samples from a Rayleigh distribution.
The \(\chi\) and Weibull distributions are generalizations of the Rayleigh.
 Parameters
scale – float or array_like of floats, optional. Scale, also equals the mode. Must be nonnegative. Default is 1.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifscale
is a scalar. Otherwise,np.array(scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Rayleigh distribution.
Notes
The probability density function for the Rayleigh distribution is
\[P(x;scale) = \frac{x}{scale^2}e^{\frac{x^2}{2 \cdotp scale^2}}\]The Rayleigh distribution would arise, for example, if the East and North components of the wind velocity had identical zeromean Gaussian distributions. Then the wind speed would have a Rayleigh distribution.
References
 1
Brighton Webs Ltd., “Rayleigh Distribution,” https://web.archive.org/web/20090514091424/http://brightonwebs.co.uk:80/distributions/rayleigh.asp
 2
Wikipedia, “Rayleigh distribution” https://en.wikipedia.org/wiki/Rayleigh_distribution
Examples
Draw values from the distribution and plot the histogram:
from matplotlib.pyplot import hist values = hist(randomfunctiongen.generator.rayleigh(3, 100000), bins=200, density=True)
Wave heights tend to follow a Rayleigh distribution. If the mean wave height is 1 meter, what fraction of waves are likely to be larger than 3 meters?:
meanvalue = 1 modevalue = np.sqrt(2 / np.pi) * meanvalue s = randomfunctiongen.generator.rayleigh(modevalue, 1000000)
The percentage of waves larger than 3 meters is:
100.*sum(s>3)/1000000. # 0.087300000000000003 # random

seed
(*args, **kwargs)¶ Reseed the basic RNG.
Parameters depend on the basic RNG used.
Notes
Arguments are directly passed to the basic RNG. This is a convenience function.
The best method to access seed is to directly use a basic RNG instance. This example demonstrates this best practice:
brng = PCG64(1234567891011) rg = brng.generator brng.seed(1110987654321)
The method used to create the generator is not important:
brng = PCG64(1234567891011) rg = RandomGenerator(brng) brng.seed(1110987654321)
These best practice examples are equivalent to:
rg = RandomGenerator(PCG64(1234567891011)) rg.seed(1110987654321)

shuffle
(x)¶ Modify a sequence inplace by shuffling its contents.
This function only shuffles the array along the first axis of a multidimensional array. The order of subarrays is changed but their contents remains the same.
 Parameters
x – array_like. The array or list to be shuffled.
None
Examples:
arr = np.arange(10) randomfunctiongen.generator.shuffle(arr) arr # [1 7 5 2 9 4 3 6 0 8] # random
Multidimensional arrays are only shuffled along the first axis:
arr = np.arange(9).reshape((3, 3)) randomfunctiongen.generator.shuffle(arr) arr # array([[3, 4, 5], # random # [6, 7, 8], # [0, 1, 2]])

standard_cauchy
(*args, **kwargs)¶ standard_cauchy (V)
Generate a
Function
f = Function(V), randomise it by calling the original method standard_cauchy (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.standard_cauchy.html, which is reproduced below with appropriate changes.
standard_cauchy (size=None)
Draw samples from a standard Cauchy distribution with mode = 0.
Also known as the Lorentz distribution.
 Parameters
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned. Returns
ndarray or scalar. The drawn samples.
Notes
The probability density function for the full Cauchy distribution is
\[P(x; x_0, \gamma) = \frac{1}{\pi \gamma \bigl[ 1+ (\frac{xx_0}{\gamma})^2 \bigr] }\]and the Standard Cauchy distribution just sets \(x_0=0\) and \(\gamma=1\)
The Cauchy distribution arises in the solution to the driven harmonic oscillator problem, and also describes spectral line broadening. It also describes the distribution of values at which a line tilted at a random angle will cut the x axis.
When studying hypothesis tests that assume normality, seeing how the tests perform on data from a Cauchy distribution is a good indicator of their sensitivity to a heavytailed distribution, since the Cauchy looks very much like a Gaussian distribution, but with heavier tails.
References
 1
NIST/SEMATECH eHandbook of Statistical Methods, “Cauchy. Distribution”, https://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.html
 2
Weisstein, Eric W. “Cauchy Distribution.” From MathWorld–A. Wolfram Web Resource. http://mathworld.wolfram.com/CauchyDistribution.html
 3
Wikipedia, “Cauchy distribution” https://en.wikipedia.org/wiki/Cauchy_distribution
Examples
Draw samples and plot the distribution:
import matplotlib.pyplot as plt s = randomfunctiongen.generator.standard_cauchy(1000000) s = s[(s>25) & (s<25)] # truncate distribution so it plots well plt.hist(s, bins=100) plt.show()

standard_exponential
(*args, **kwargs)¶ standard_exponential (V, dtype=’d’, method=’zig’, out=None)
Generate a
Function
f = Function(V), randomise it by calling the original method standard_exponential (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.standard_exponential.html, which is reproduced below with appropriate changes.
standard_exponential (size=None, dtype=’d’, method=’zig’, out=None)
Draw samples from the standard exponential distribution.
standard_exponential is identical to the exponential distribution with a scale parameter of 1.
 Parameters
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.dtype – dtype, optional. Desired dtype of the result, either ‘d’ (or ‘float64’) or ‘f’ (or ‘float32’). All dtypes are determined by their name. The default value is ‘d’.
method – str, optional. Either ‘inv’ or ‘zig’. ‘inv’ uses the default inverse CDF method. ‘zig’ uses the much faster Ziggurat method of Marsaglia and Tsang.
out – ndarray, optional. Alternative output array in which to place the result. If size is not None, it must have the same shape as the provided size and must match the type of the output values.
 Returns
float or ndarray. Drawn samples.
Examples
Output a 3x8000 array:
n = randomfunctiongen.generator.standard_exponential((3, 8000))

standard_gamma
(*args, **kwargs)¶ standard_gamma (V, shape, dtype=’d’, out=None)
Generate a
Function
f = Function(V), randomise it by calling the original method standard_gamma (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.standard_gamma.html, which is reproduced below with appropriate changes.
standard_gamma (shape, size=None, dtype=’d’, out=None)
Draw samples from a standard Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale=1.
 Parameters
shape – float or array_like of floats. Parameter, must be nonnegative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifshape
is a scalar. Otherwise,np.array(shape).size
samples are drawn.dtype – {str, dtype}, optional. Desired dtype of the result, either ‘d’ (or ‘float64’) or ‘f’ (or ‘float32’). All dtypes are determined by their name. The default value is ‘d’.
out – ndarray, optional. Alternative output array in which to place the result. If size is not None, it must have the same shape as the provided size and must match the type of the output values.
 Returns
ndarray or scalar. Drawn samples from the parameterized standard gamma distribution.
See Also
scipy.stats.gamma : probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gamma distribution is
\[p(x) = x^{k1}\frac{e^{x/\theta}}{\theta^k\Gamma(k)},\]where \(k\) is the shape and \(\theta\) the scale, and \(\Gamma\) is the Gamma function.
The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant.
References
 1
Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A. Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html
 2
Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution
Examples
Draw samples from the distribution:
shape, scale = 2., 1. # mean and width s = randomfunctiongen.generator.standard_gamma(shape, 1000000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt import scipy.special as sps # doctest: +SKIP count, bins, ignored = plt.hist(s, 50, density=True) y = bins**(shape1) * ((np.exp(bins/scale))/ # doctest: +SKIP (sps.gamma(shape) * scale**shape)) plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP plt.show()

standard_normal
(*args, **kwargs)¶ standard_normal (V, dtype=’d’, out=None)
Generate a
Function
f = Function(V), randomise it by calling the original method standard_normal (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.standard_normal.html, which is reproduced below with appropriate changes.
standard_normal (size=None, dtype=’d’, out=None)
Draw samples from a standard Normal distribution (mean=0, stdev=1).
 Parameters
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.dtype – {str, dtype}, optional. Desired dtype of the result, either ‘d’ (or ‘float64’) or ‘f’ (or ‘float32’). All dtypes are determined by their name. The default value is ‘d’.
out – ndarray, optional. Alternative output array in which to place the result. If size is not None, it must have the same shape as the provided size and must match the type of the output values.
 Returns
float or ndarray. A floatingpoint array of shape
size
of drawn samples, or a single sample ifsize
was not specified.
Notes
For random samples from \(N(\mu, \sigma^2)\), use one of:
mu + sigma * randomfunctiongen.generator.standard_normal(size=…) randomfunctiongen.generator.normal(mu, sigma, size=…)
See Also
normal : Equivalent function with additional
loc
andscale
arguments for setting the mean and standard deviation.Examples:
randomfunctiongen.generator.standard_normal() # 2.1923875335537315 #random:: s = randomfunctiongen.generator.standard_normal(8000) s # array([ 0.6888893 , 0.78096262, 0.89086505, ..., 0.49876311, # random # 0.38672696, 0.4685006 ]) # random s.shape # (8000,) s = randomfunctiongen.generator.standard_normal(size=(3, 4, 2)) s.shape # (3, 4, 2)
Twobyfour array of samples from \(N(3, 6.25)\):
3 + 2.5 * randomfunctiongen.generator.standard_normal(size=(2, 4)) # array([[4.49401501, 4.00950034, 1.81814867, 7.29718677], # random # [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random

standard_t
(*args, **kwargs)¶ standard_t (V, df)
Generate a
Function
f = Function(V), randomise it by calling the original method standard_t (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.standard_t.html, which is reproduced below with appropriate changes.
standard_t (df, size=None)
Draw samples from a standard Student’s t distribution with df degrees of freedom.
A special case of the hyperbolic distribution. As df gets large, the result resembles that of the standard normal distribution (standard_normal).
 Parameters
df – float or array_like of floats. Degrees of freedom, must be > 0.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifdf
is a scalar. Otherwise,np.array(df).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized standard Student’s t distribution.
Notes
The probability density function for the t distribution is
\[P(x, df) = \frac{\Gamma(\frac{df+1}{2})}{\sqrt{\pi df} \Gamma(\frac{df}{2})}\Bigl( 1+\frac{x^2}{df} \Bigr)^{(df+1)/2}\]The t test is based on an assumption that the data come from a Normal distribution. The t test provides a way to test whether the sample mean (that is the mean calculated from the data) is a good estimate of the true mean.
The derivation of the tdistribution was first published in 1908 by William Gosset while working for the Guinness Brewery in Dublin. Due to proprietary issues, he had to publish under a pseudonym, and so he used the name Student.
References
 1
Dalgaard, Peter, “Introductory Statistics With R”,. Springer, 2002.
 2
Wikipedia, “Student’s tdistribution” https://en.wikipedia.org/wiki/Student’s_tdistribution
Examples
From Dalgaard page 83 [1]_, suppose the daily energy intake for 11 women in kilojoules (kJ) is:
intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \ 7515, 8230, 8770])
Does their energy intake deviate systematically from the recommended value of 7725 kJ?
We have 10 degrees of freedom, so is the sample mean within 95% of the recommended value?:
s = randomfunctiongen.generator.standard_t(10, size=100000) np.mean(intake) # 6753.636363636364 intake.std(ddof=1) # 1142.1232221373727
Calculate the t statistic, setting the ddof parameter to the unbiased value so the divisor in the standard deviation will be degrees of freedom, N1:
t = (np.mean(intake)7725)/(intake.std(ddof=1)/np.sqrt(len(intake))) import matplotlib.pyplot as plt h = plt.hist(s, bins=100, density=True)
For a onesided ttest, how far out in the distribution does the t statistic appear?:
np.sum(s<t) / float(len(s)) # 0.0090699999999999999 #random
So the pvalue is about 0.009, which says the null hypothesis has a probability of about 99% of being true.

tomaxint
(*args, **kwargs)¶ tomaxint (V)
Generate a
Function
f = Function(V), randomise it by calling the original method tomaxint (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.tomaxint.html, which is reproduced below with appropriate changes.
tomaxint (size=None)
Return a sample of uniformly distributed random integers in the interval [0,
np.iinfo(np.int).max
]. The np.int type translates to the C long integer type and its precision is platform dependent. Parameters
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned. Returns
ndarray. Drawn samples, with shape size.
See Also
 Parameters
randint – Uniform sampling over a given halfopen interval of integers.
random_integers – Uniform sampling over a given closed interval of integers.
Examples:
rg = randomfunctiongen.RandomGenerator() # need a RandomGenerator object rg.tomaxint((2,2,2)) # array([[[1170048599, 1600360186], # random # [ 739731006, 1947757578]], # [[1871712945, 752307660], # [1601631370, 1479324245]]]) rg.tomaxint((2,2,2)) < np.iinfo(np.int).max # array([[[ True, True], # [ True, True]], # [[ True, True], # [ True, True]]])

triangular
(*args, **kwargs)¶ triangular (V, left, mode, right)
Generate a
Function
f = Function(V), randomise it by calling the original method triangular (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.triangular.html, which is reproduced below with appropriate changes.
triangular (left, mode, right, size=None)
Draw samples from the triangular distribution over the interval
[left, right]
.The triangular distribution is a continuous probability distribution with lower limit left, peak at mode, and upper limit right. Unlike the other distributions, these parameters directly define the shape of the pdf.
 Parameters
left – float or array_like of floats. Lower limit.
mode – float or array_like of floats. The value where the peak of the distribution occurs. The value must fulfill the condition
left <= mode <= right
.right – float or array_like of floats. Upper limit, must be larger than left.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifleft
,mode
, andright
are all scalars. Otherwise,np.broadcast(left, mode, right).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized triangular distribution.
Notes
The probability density function for the triangular distribution is
\[\begin{split}P(x;l, m, r) = \begin{cases} \frac{2(xl)}{(rl)(ml)}& \text{for $l \leq x \leq m$},\\ \frac{2(rx)}{(rl)(rm)}& \text{for $m \leq x \leq r$},\\ 0& \text{otherwise}. \end{cases}\end{split}\]The triangular distribution is often used in illdefined problems where the underlying distribution is not known, but some knowledge of the limits and mode exists. Often it is used in simulations.
References
 1
Wikipedia, “Triangular distribution” https://en.wikipedia.org/wiki/Triangular_distribution
Examples
Draw values from the distribution and plot the histogram:
import matplotlib.pyplot as plt h = plt.hist(randomfunctiongen.generator.triangular(3, 0, 8, 100000), bins=200, density=True) plt.show()

uniform
(*args, **kwargs)¶ uniform (V, low=0.0, high=1.0)
Generate a
Function
f = Function(V), randomise it by calling the original method uniform (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.uniform.html, which is reproduced below with appropriate changes.
uniform (low=0.0, high=1.0, size=None)
Draw samples from a uniform distribution.
Samples are uniformly distributed over the halfopen interval
[low, high)
(includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform. Parameters
low – float or array_like of floats, optional. Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.
high – float or array_like of floats. Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned iflow
andhigh
are both scalars. Otherwise,np.broadcast(low, high).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized uniform distribution.
See Also
 Parameters
randint – Discrete uniform distribution, yielding integers.
random_integers – Discrete uniform distribution over the closed interval
[low, high]
.random_sample – Floats uniformly distributed over
[0, 1)
.random – Alias for random_sample.
rand – Convenience function that accepts dimensions as input, e.g.,
rand(2,2)
would generate a 2by2 array of floats, uniformly distributed over[0, 1)
.
Notes
The probability density function of the uniform distribution is
\[p(x) = \frac{1}{b  a}\]anywhere within the interval
[a, b)
, and zero elsewhere.When
high
==low
, values oflow
will be returned. Ifhigh
<low
, the results are officially undefined and may eventually raise an error, i.e. do not rely on this function to behave when passed arguments satisfying that inequality condition.Examples
Draw samples from the distribution:
s = randomfunctiongen.generator.uniform(1,0,1000)
All values are within the given interval:
np.all(s >= 1) # True np.all(s < 0) # True
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 15, density=True) plt.plot(bins, np.ones_like(bins), linewidth=2, color='r') plt.show()

vonmises
(*args, **kwargs)¶ vonmises (V, mu, kappa)
Generate a
Function
f = Function(V), randomise it by calling the original method vonmises (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.vonmises.html, which is reproduced below with appropriate changes.
vonmises (mu, kappa, size=None)
Draw samples from a von Mises distribution.
Samples are drawn from a von Mises distribution with specified mode (mu) and dispersion (kappa), on the interval [pi, pi].
The von Mises distribution (also known as the circular normal distribution) is a continuous probability distribution on the unit circle. It may be thought of as the circular analogue of the normal distribution.
 Parameters
mu – float or array_like of floats. Mode (“center”) of the distribution.
kappa – float or array_like of floats. Dispersion of the distribution, has to be >=0.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifmu
andkappa
are both scalars. Otherwise,np.broadcast(mu, kappa).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized von Mises distribution.
See Also
scipy.stats.vonmises : probability density function, distribution, or cumulative density function, etc.
Notes
The probability density for the von Mises distribution is
\[p(x) = \frac{e^{\kappa cos(x\mu)}}{2\pi I_0(\kappa)},\]where \(\mu\) is the mode and \(\kappa\) the dispersion, and \(I_0(\kappa)\) is the modified Bessel function of order 0.
The von Mises is named for Richard Edler von Mises, who was born in AustriaHungary, in what is now the Ukraine. He fled to the United States in 1939 and became a professor at Harvard. He worked in probability theory, aerodynamics, fluid mechanics, and philosophy of science.
References
 1
Abramowitz, M. and Stegun, I. A. (Eds.). “Handbook of. Mathematical Functions with Formulas, Graphs, and Mathematical. Tables, 9th printing,” New York: Dover, 1972.
 2
von Mises, R., “Mathematical Theory of Probability and Statistics”, New York: Academic Press, 1964.
Examples
Draw samples from the distribution:
mu, kappa = 0.0, 4.0 # mean and dispersion s = randomfunctiongen.generator.vonmises(mu, kappa, 1000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt from scipy.special import i0 # doctest: +SKIP plt.hist(s, 50, density=True) x = np.linspace(np.pi, np.pi, num=51) y = np.exp(kappa*np.cos(xmu))/(2*np.pi*i0(kappa)) # doctest: +SKIP plt.plot(x, y, linewidth=2, color='r') # doctest: +SKIP plt.show()

wald
(*args, **kwargs)¶ wald (V, mean, scale)
Generate a
Function
f = Function(V), randomise it by calling the original method wald (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.wald.html, which is reproduced below with appropriate changes.
wald (mean, scale, size=None)
Draw samples from a Wald, or inverse Gaussian, distribution.
As the scale approaches infinity, the distribution becomes more like a Gaussian. Some references claim that the Wald is an inverse Gaussian with mean equal to 1, but this is by no means universal.
The inverse Gaussian distribution was first studied in relationship to Brownian motion. In 1956 M.C.K. Tweedie used the name inverse Gaussian because there is an inverse relationship between the time to cover a unit distance and distance covered in unit time.
 Parameters
mean – float or array_like of floats. Distribution mean, must be > 0.
scale – float or array_like of floats. Scale parameter, must be > 0.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifmean
andscale
are both scalars. Otherwise,np.broadcast(mean, scale).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Wald distribution.
Notes
The probability density function for the Wald distribution is
\[P(x;mean,scale) = \sqrt{\frac{scale}{2\pi x^3}}e^ \frac{scale(xmean)^2}{2\cdotp mean^2x}\]As noted above the inverse Gaussian distribution first arise from attempts to model Brownian motion. It is also a competitor to the Weibull for use in reliability modeling and modeling stock returns and interest rate processes.
References
 1
Brighton Webs Ltd., Wald Distribution, https://web.archive.org/web/20090423014010/http://www.brightonwebs.co.uk:80/distributions/wald.asp
 2
Chhikara, Raj S., and Folks, J. Leroy, “The Inverse Gaussian. Distribution: Theory : Methodology, and Applications”, CRC Press, 1988.
 3
Wikipedia, “Inverse Gaussian distribution” https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
Examples
Draw values from the distribution and plot the histogram:
import matplotlib.pyplot as plt h = plt.hist(randomfunctiongen.generator.wald(3, 2, 100000), bins=200, density=True) plt.show()

weibull
(*args, **kwargs)¶ weibull (V, a)
Generate a
Function
f = Function(V), randomise it by calling the original method weibull (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.weibull.html, which is reproduced below with appropriate changes.
weibull (a, size=None)
Draw samples from a Weibull distribution.
Draw samples from a 1parameter Weibull distribution with the given shape parameter a.
\[X = (ln(U))^{1/a}\]Here, U is drawn from the uniform distribution over (0,1].
The more common 2parameter Weibull, including a scale parameter \(\lambda\) is just \(X = \lambda(ln(U))^{1/a}\).
 Parameters
a – float or array_like of floats. Shape parameter of the distribution. Must be nonnegative.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifa
is a scalar. Otherwise,np.array(a).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Weibull distribution.
See Also
scipy.stats.weibull_max scipy.stats.weibull_min scipy.stats.genextreme gumbel
Notes
The Weibull (or Type III asymptotic extreme value distribution for smallest values, SEV Type III, or RosinRammler distribution) is one of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems. This class includes the Gumbel and Frechet distributions.
The probability density for the Weibull distribution is
\[p(x) = \frac{a} {\lambda}(\frac{x}{\lambda})^{a1}e^{(x/\lambda)^a},\]where \(a\) is the shape and \(\lambda\) the scale.
The function has its peak (the mode) at \(\lambda(\frac{a1}{a})^{1/a}\).
When
a = 1
, the Weibull distribution reduces to the exponential distribution.References
 1
Waloddi Weibull, Royal Technical University, Stockholm, 1939 “A Statistical Theory Of The Strength Of Materials”,. Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939,. Generalstabens Litografiska Anstalts Forlag, Stockholm.
 2
Waloddi Weibull, “A Statistical Distribution Function of. Wide Applicability”, Journal Of Applied Mechanics ASME Paper 1951.
 3
Wikipedia, “Weibull distribution”, https://en.wikipedia.org/wiki/Weibull_distribution
Examples
Draw samples from the distribution:
a = 5. # shape s = randomfunctiongen.generator.weibull(a, 1000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt x = np.arange(1,100.)/50. def weib(x,n,a): return (a / n) * (x / n)**(a  1) * np.exp((x / n)**a):: count, bins, ignored = plt.hist(randomfunctiongen.generator.weibull(5.,1000)) x = np.arange(1,100.)/50. scale = count.max()/weib(x, 1., 5.).max() plt.plot(x, weib(x, 1., 5.)*scale) plt.show()

zipf
(*args, **kwargs)¶ zipf (V, a)
Generate a
Function
f = Function(V), randomise it by calling the original method zipf (…) with given arguments, and return f. Parameters
V –
FunctionSpace
 Returns
The original documentation is found at https://bashtage.github.io/randomgen/generated/randomgen.legacy.legacy.LegacyGenerator.zipf.html, which is reproduced below with appropriate changes.
zipf (a, size=None)
Draw samples from a Zipf distribution.
Samples are drawn from a Zipf distribution with specified parameter a > 1.
The Zipf distribution (also known as the zeta distribution) is a continuous probability distribution that satisfies Zipf’s law: the frequency of an item is inversely proportional to its rank in a frequency table.
 Parameters
a – float or array_like of floats. Distribution parameter. Must be greater than 1.
size – int or tuple of ints, optional. Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifa
is a scalar. Otherwise,np.array(a).size
samples are drawn.
 Returns
ndarray or scalar. Drawn samples from the parameterized Zipf distribution.
See Also
scipy.stats.zipf : probability density function, distribution, or cumulative density function, etc.
Notes
The probability density for the Zipf distribution is
\[p(x) = \frac{x^{a}}{\zeta(a)},\]where \(\zeta\) is the Riemann Zeta function.
It is named for the American linguist George Kingsley Zipf, who noted that the frequency of any word in a sample of a language is inversely proportional to its rank in the frequency table.
References
 1
Zipf, G. K., “Selected Studies of the Principle of Relative. Frequency in Language,” Cambridge, MA: Harvard Univ. Press, 1932.
Examples
Draw samples from the distribution:
a = 2. # parameter s = randomfunctiongen.generator.zipf(a, 1000)
Display the histogram of the samples, along with the probability density function:
import matplotlib.pyplot as plt from scipy import special # doctest: +SKIP
Truncate s values at 50 so plot is interesting:
count, bins, ignored = plt.hist(s[s<50], 50, density=True) x = np.arange(1., 50.) y = x**(a) / special.zetac(a) # doctest: +SKIP plt.plot(x, y/max(y), linewidth=2, color='r') # doctest: +SKIP plt.show()


class
firedrake.randomfunctiongen.
DSFMT
(seed=None)¶ Bases:
randomgen.dsfmt.DSFMT
Container for the SIMDbased Mersenne Twister pseudo RNG.
 Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**321], array of integers in [0, 2**321] or
None
(the default). If seed isNone
, thenDSFMT
will try to read entropy from/dev/urandom
(or the Windows analog) if available to produce a 32bit seed. If unavailable, a 32bit hash of the time and process. ID is used.
Notes
DSFMT
directly provides generators for doubles, and unsigned 32 and 64 bit integers [1]_ . These are not directly available and must be consumed via aRandomGenerator
object.The Python stdlib module “random” also contains a Mersenne Twister pseudorandom number generator.
Parallel Features
DSFMT
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{128}\) random numbers have been generated [2]_. This allows the original sequence to be split so that distinct segments can be used in each worker process. All generators should be initialized with the same seed to ensure that the segments come from the same sequence:from randomfunctiongen.entropy import random_entropy seed = random_entropy() rs = [RandomGenerator(DSFMT(seed)) for _ in range(10)] # Advance each DSFMT instance by i jumps for i in range(10): rs[i].brng.jump()
State and Seeding
The
DSFMT
state vector consists of a 384 element array of 64bit unsigned integers plus a single integer value between 0 and 382 indicating the current position within the main array. The implementation used here augments this with a 382 element array of doubles which are used to efficiently access the random numbers produced by the dSFMT generator.DSFMT
is seeded using either a single 32bit unsigned integer or a vector of 32bit unsigned integers. In either case, the input seed is used as an input (or inputs) for a hashing function, and the output of the hashing function is used as the initial state. Using a single 32bit value for the seed can only initialize a small range of the possible initial state values.Compatibility Guarantee
DSFMT
does makes a guarantee that a fixed seed and will always produce the same results.References
 1
Mutsuo Saito and Makoto Matsumoto, “SIMDoriented Fast Mersenne. Twister: a 128bit Pseudorandom Number Generator.” Monte Carlo and QuasiMonte Carlo Methods 2006, Springer, pp. 607–622, 2008.
 2
Hiroshi Haramoto, Makoto Matsumoto, and Pierre L’Ecuyer, “A Fast. Jump Ahead Algorithm for Linear Recurrences in a Polynomial Space”,. Sequences and Their Applications  SETA, 290–298, 2008.

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
MT19937
(seed=None)¶ Bases:
randomgen.mt19937.MT19937
Container for the Mersenne Twister pseudorandom number generator.
 Parameters
seed – {None, int, array_like}, optional. Random seed used to initialize the pseudorandom number generator. Can be any integer between 0 and 2**32  1 inclusive, an array (or other sequence) of such integers, or
None
(the default). If seed isNone
, then will attempt to read data from/dev/urandom
(or the Windows analog) if available or seed from the clock otherwise.
Notes
MT19937
directly provides generators for doubles, and unsigned 32 and 64 bit integers [1]_ . These are not directly available and must be consumed via aRandomGenerator
object.The Python stdlib module “random” also contains a Mersenne Twister pseudorandom number generator.
State and Seeding
The
MT19937
state vector consists of a 768 element array of 32bit unsigned integers plus a single integer value between 0 and 768 indicating the current position within the main array.MT19937
is seeded using either a single 32bit unsigned integer or a vector of 32bit unsigned integers. In either case, the input seed is used as an input (or inputs) for a hashing function, and the output of the hashing function is used as the initial state. Using a single 32bit value for the seed can only initialize a small range of the possible initial state values.Compatibility Guarantee
MT19937
make a compatibility guarantee. A fixed seed and a fixed series of calls toMT19937
methods will always produce the same results up to roundoff error except when the values were incorrect. Incorrect values will be fixed and the version in which the fix was made will be noted in the relevant docstring.Parallel Features
MT19937
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{128}\) random numbers have been generated ([1]_, [2]_). This allows the original sequence to be split so that distinct segments can be used in each worker process. All generators should be initialized with the same seed to ensure that the segments come from the same sequence:from randomfunctiongen.entropy import random_entropy seed = random_entropy() rs = [RandomGenerator(MT19937(seed)) for _ in range(10)] # Advance each MT19937 instance by i jumps for i in range(10): rs[i].brng.jump(i)
References
 1
Hiroshi Haramoto, Makoto Matsumoto, and Pierre L’Ecuyer, “A Fast. Jump Ahead Algorithm for Linear Recurrences in a Polynomial Space”,. Sequences and Their Applications  SETA, 290–298, 2008.
 2
Hiroshi Haramoto, Makoto Matsumoto, Takuji Nishimura, François. Panneton, Pierre L’Ecuyer, “Efficient Jump Ahead for F2Linear. Random Number Generators”, INFORMS JOURNAL ON COMPUTING, Vol. 20,. No. 3, Summer 2008, pp. 385390.

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
PCG64
(seed=None, inc=0)¶ Bases:
randomgen.pcg64.PCG64
Container for the PCG64 pseudorandom number generator.
PCG64 is a 128bit implementation of O’Neill’s permutation congruential generator ([1]_, [2]_). PCG64 has a period of \(2^{128}\) and supports advancing an arbitrary number of steps as well as \(2^{127}\) streams.
PCG64
exposes no userfacing API exceptgenerator
,``state``,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
PCG64
makes a guarantee that a fixed seed will always produce the same results. Parameters
seed – {None, long}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**128] or
None
(the default). If seed isNone
, thenPCG64
will try to read data from/dev/urandom
(or the Windows analog) if available. If unavailable, a 64bit hash of the time and process ID is used.inc – {None, int}, optional. Stream to return. Can be an integer in [0, 2**128] or
None
(the default). If inc isNone
, then 0 is used. Can be used with the same seed to produce multiple streams using other values of inc.
Notes
Supports the method advance to advance the RNG an arbitrary number of steps. The state of the PCG64 RNG is represented by 2 128bit unsigned integers.
See
PCG32
for a similar implementation with a smaller period.Parallel Features
PCG64
can be used in parallel applications in one of two ways. The preferable method is to use substreams, which are generated by using the same value ofseed
and incrementing the second value,inc
:rg = [RandomGenerator(PCG64(1234, i + 1)) for i in range(10)]
The alternative method is to call
advance
with a different value on each instance to produce nonoverlapping sequences:rg = [RandomGenerator(PCG64(1234, i + 1)) for i in range(10)] for i in range(10): rg[i].brng.advance(i * 2**64)
State and Seeding
The
PCG64
state vector consists of 2 unsigned 128bit values, which are represented externally as python longs (2.x) or ints (Python 3+).PCG64
is seeded using a single 128bit unsigned integer (Python long/int). In addition, a second 128bit unsigned integer is used to set the stream.References
 1
“PCG, A Family of Better Random Number Generators”, http://www.pcgrandom.org/
 2
O’Neill, Melissa E. “PCG: A Family of Simple Fast SpaceEfficient. Statistically Good Algorithms for Random Number Generation”

generator
¶

seed
(seed=None, inc=None)¶

class
firedrake.randomfunctiongen.
PCG32
(seed=None, inc=0)¶ Bases:
randomgen.pcg32.PCG32
Container for the PCG32 pseudorandom number generator.
PCG32 is a 64bit implementation of O’Neill’s permutation congruential generator ([1]_, [2]_). PCG32 has a period of \(2^{64}\) and supports advancing an arbitrary number of steps as well as \(2^{63}\) streams.
PCG32
exposes no userfacing API exceptgenerator
,``state``,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
PCG32
makes a guarantee that a fixed seed will always produce the same results. Parameters
seed – {None, long}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**64] or
None
(the default). If seed isNone
, thenPCG32
will try to read data from/dev/urandom
(or the Windows analog) if available. If unavailable, a 64bit hash of the time and process ID is used.inc – {None, int}, optional. Stream to return. Can be an integer in [0, 2**64] or
None
(the default). If inc isNone
, then 0 is used. Can be used with the same seed to produce multiple streams using other values of inc.
Notes
Supports the method advance to advance the PRNG an arbitrary number of steps. The state of the PCG32 PRNG is represented by 2 128bit unsigned integers.
See
PCG32
for a similar implementation with a smaller period.Parallel Features
PCG32
can be used in parallel applications in one of two ways. The preferable method is to use substreams, which are generated by using the same value ofseed
and incrementing the second value,inc
:rg = [RandomGenerator(PCG32(1234, i + 1)) for i in range(10)]
The alternative method is to call
advance
with a different value on each instance to produce nonoverlapping sequences:rg = [RandomGenerator(PCG32(1234, i + 1)) for i in range(10)] for i in range(10): rg[i].brng.advance(i * 2**32)
State and Seeding
The
PCG32
state vector consists of 2 unsigned 64bit values/PCG32
is seeded using a single 64bit unsigned integer. In addition, a second 64bit unsigned integer is used to set the stream.References
 1
“PCG, A Family of Better Random Number Generators”, http://www.pcgrandom.org/
 2
O’Neill, Melissa E. “PCG: A Family of Simple Fast SpaceEfficient. Statistically Good Algorithms for Random Number Generation”

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
Philox
(seed=None, counter=None, key=None)¶ Bases:
randomgen.philox.Philox
Container for the Philox (4x64) pseudorandom number generator.
 Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**641], array of integers in [0, 2**641] or
None
(the default). If seed isNone
, data will be read from/dev/urandom
(or the Windows analog) if available. If unavailable, a hash of the time and process ID is used.counter – {None, int, array_like}, optional. Counter to use in the Philox state. Can be either a Python int (long in 2.x) in [0, 2**256) or a 4element uint64 array. If not provided, the RNG is initialized at 0.
key – {None, int, array_like}, optional. Key to use in the Philox state. Unlike seed, which is run through another RNG before use, the value in key is directly set. Can be either a Python int (long in 2.x) in [0, 2**128) or a 2element uint64 array. key and seed cannot both be used.
Notes
Philox is a 64bit PRNG that uses a counterbased design based on weaker (and faster) versions of cryptographic functions [1]_. Instances using different values of the key produce independent sequences. Philox has a period of \(2^{256}  1\) and supports arbitrary advancing and jumping the sequence in increments of \(2^{128}\). These features allow multiple nonoverlapping sequences to be generated.
Philox
exposes no userfacing API exceptgenerator
,state
,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
Philox
guarantees that a fixed seed will always produce the same results.See
Philox
for a closely related PRNG implementation.Parallel Features
Philox
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{128}\) random numbers have been generated. Alternatively,advance
can be used to advance the counter for an abritrary number of positive steps in [0, 2**256). When usingjump
, all generators should be initialized with the same seed to ensure that the segments come from the same sequence. Alternatively,Philox
can be used in parallel applications by using a sequence of distinct keys where each instance uses different key:rg = [RandomGenerator(Philox(1234)) for _ in range(10)] # Advance each Philox instance by i jumps for i in range(10): rg[i].brng.jump(i)
Using distinct keys produces independent streams:
key = 2**96 + 2**32 + 2**65 + 2**33 + 2**17 + 2**9 rg = [RandomGenerator(Philox(key=key+i)) for i in range(10)]
State and Seeding
The
Philox
state vector consists of a 256bit counter encoded as a 4element uint64 array and a 128bit key encoded as a 2element uint64 array. The counter is incremented by 1 for every 4 64bit randoms produced. The key determines the sequence produced. Using different keys produces independent sequences.Philox
is seeded using either a single 64bit unsigned integer or a vector of 64bit unsigned integers. In either case, the input seed is used as an input (or inputs) for another simple random number generator, Splitmix64, and the output of this PRNG function is used as the initial state. Using a single 64bit value for the seed can only initialize a small range of the possible initial state values. When using an array, the SplitMix64 state for producing the ith component of the initial state is XORd with the ith value of the seed array until the seed array is exhausted. When using an array the initial state for the SplitMix64 state is 0 so that using a single element array and using the same value as a scalar will produce the same initial state.Examples:
rg = RandomGenerator(Philox(1234)) rg.standard_normal() # 0.123 # random
Identical method using only Philox:
rg = Philox(1234).generator rg.standard_normal() # 0.123 # random
References
 1
John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, “Parallel Random Numbers: As Easy as 1, 2, 3,” Proceedings of the International Conference for High Performance Computing,. Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011.

generator
¶

seed
(seed=None, counter=None, key=None)¶

class
firedrake.randomfunctiongen.
ThreeFry
(seed=None, counter=None, key=None)¶ Bases:
randomgen.threefry.ThreeFry
Container for the ThreeFry (4x64) pseudorandom number generator.
 Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**641], array of integers in [0, 2**641] or
None
(the default). If seed isNone
, data will be read from/dev/urandom
(or the Windows analog) if available. If unavailable, a hash of the time and process ID is used.counter – {None, int, array_like}, optional. Counter to use in the ThreeFry state. Can be either a Python int (long in 2.x) in [0, 2**256) or a 4element uint64 array. If not provided, the RNG is initialized at 0.
key – {None, int, array_like}, optional. Key to use in the ThreeFry state. Unlike seed, which is run through another RNG before use, the value in key is directly set. Can be either a Python int (long in 2.x) in [0, 2**256) or a 4element uint64 array. key and seed cannot both be used.
Notes
ThreeFry is a 64bit PRNG that uses a counterbased design based on weaker (and faster) versions of cryptographic functions [1]_. Instances using different values of the key produce independent sequences. ThreeFry has a period of \(2^{256}  1\) and supports arbitrary advancing and jumping the sequence in increments of \(2^{128}\). These features allow multiple nonoverlapping sequences to be generated.
ThreeFry
exposes no userfacing API exceptgenerator
,state
,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
ThreeFry
guarantees that a fixed seed will always produce the same results.See
Philox
for a closely related PRNG implementation.Parallel Features
ThreeFry
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{128}\) random numbers have been generated. Alternatively,advance
can be used to advance the counter for an any positive step in [0, 2**256). When usingjump
, all generators should be initialized with the same seed to ensure that the segments come from the same sequence. Alternatively,ThreeFry
can be used in parallel applications by using a sequence of distinct keys where each instance uses different key:rg = [RandomGenerator(ThreeFry(1234)) for _ in range(10)] # Advance each ThreeFry instance by i jumps for i in range(10): rg[i].brng.jump(i)
Using distinct keys produces independent streams:
key = 2**196 + 2**132 + 2**65 + 2**33 + 2**17 + 2**9 rg = [RandomGenerator(ThreeFry(key=key+i)) for i in range(10)]
State and Seeding
The
ThreeFry
state vector consists of a 2 256bit values encoded as 4element uint64 arrays. One is a counter which is incremented by 1 for every 4 64bit randoms produced. The second is a key which determined the sequence produced. Using different keys produces independent sequences.ThreeFry
is seeded using either a single 64bit unsigned integer or a vector of 64bit unsigned integers. In either case, the input seed is used as an input (or inputs) for another simple random number generator, Splitmix64, and the output of this PRNG function is used as the initial state. Using a single 64bit value for the seed can only initialize a small range of the possible initial state values. When using an array, the SplitMix64 state for producing the ith component of the initial state is XORd with the ith value of the seed array until the seed array is exhausted. When using an array the initial state for the SplitMix64 state is 0 so that using a single element array and using the same value as a scalar will produce the same initial state.Examples:
rg = RandomGenerator(ThreeFry(1234)) rg.standard_normal() # 0.123 # random
Identical method using only ThreeFry:
rg = ThreeFry(1234).generator rg.standard_normal() # 0.123 # random
References
 1
John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, “Parallel Random Numbers: As Easy as 1, 2, 3,” Proceedings of the International Conference for High Performance Computing,. Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011.

generator
¶

seed
(seed=None, counter=None, key=None)¶

class
firedrake.randomfunctiongen.
ThreeFry32
(seed=None, counter=None, key=None)¶ Bases:
randomgen.threefry32.ThreeFry32
Container for the ThreeFry (4x32) pseudorandom number generator.
 Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**641], array of integers in [0, 2**641] or
None
(the default). If seed isNone
, data will be read from/dev/urandom
(or the Windows analog) if available. If unavailable, a hash of the time and process ID is used.counter – {None, int, array_like}, optional. Counter to use in the ThreeFry32 state. Can be either a Python int (long in 2.x) in [0, 2**128) or a 4element uint32 array. If not provided, the RNG is initialized at 0.
key – {None, int, array_like}, optional. Key to use in the ThreeFry32 state. Unlike seed, which is run through another RNG before use, the value in key is directly set. Can be either a Python int (long in 2.x) in [0, 2**128) or a 4element uint32 array. key and seed cannot both be used.
Notes
ThreeFry32 is a 32bit PRNG that uses a counterbased design based on weaker (and faster) versions of cryptographic functions [1]_. Instances using different values of the key produce independent sequences. ThreeFry32 has a period of \(2^{128}  1\) and supports arbitrary advancing and jumping the sequence in increments of \(2^{64}\). These features allow multiple nonoverlapping sequences to be generated.
ThreeFry32
exposes no userfacing API exceptgenerator
,state
,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
ThreeFry32
guarantees that a fixed seed will always produce the same results.See
TheeFry
andPhilox
closely related PRNG implementations.Parallel Features
ThreeFry32
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{64}\) random numbers have been generated. Alternatively,advance
can be used to advance the counter for an arbitrary number of positive steps in [0, 2**128). When usingjump
, all generators should be initialized with the same seed to ensure that the segments come from the same sequence. Alternatively,ThreeFry32
can be used in parallel applications by using a sequence of distinct keys where each instance uses different key:rg = [RandomGenerator(ThreeFry32(1234)) for _ in range(10)] # Advance each ThreeFry32 instance by i jumps for i in range(10): rg[i].brng.jump(i)
Using distinct keys produces independent streams:
key = 2**65 + 2**33 + 2**17 + 2**9 rg = [RandomGenerator(ThreeFry32(key=key+i)) for i in range(10)]
State and Seeding
The
ThreeFry32
state vector consists of a 2 128bit values encoded as 4element uint32 arrays. One is a counter which is incremented by 1 for every 4 32bit randoms produced. The second is a key which determined the sequence produced. Using different keys produces independent sequences.ThreeFry32
is seeded using either a single 64bit unsigned integer or a vector of 64bit unsigned integers. In either case, the input seed is used as an input (or inputs) for another simple random number generator, Splitmix64, and the output of this PRNG function is used as the initial state. Using a single 64bit value for the seed can only initialize a small range of the possible initial state values. When using an array, the SplitMix64 state for producing the ith component of the initial state is XORd with the ith value of the seed array until the seed array is exhausted. When using an array the initial state for the SplitMix64 state is 0 so that using a single element array and using the same value as a scalar will produce the same initial state.Examples:
rg = RandomGenerator(ThreeFry32(1234)) rg.standard_normal() # 0.123 # random
Identical method using only ThreeFry32:
rg = ThreeFry32(1234).generator rg.standard_normal() # 0.123 # random
References
 1
John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, “Parallel Random Numbers: As Easy as 1, 2, 3,” Proceedings of the International Conference for High Performance Computing,. Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011.

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
Xoroshiro128
(seed=None)¶ Bases:
randomgen.xoroshiro128.Xoroshiro128
Container for the xoroshiro128+ pseudorandom number generator.
 Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**641], array of integers in [0, 2**641] or
None
(the default). If seed isNone
, thenXoroshiro128
will try to read data from/dev/urandom
(or the Windows analog) if available. If unavailable, a 64bit hash of the time and process ID is used.
Notes
xoroshiro128+ is the successor to xorshift128+ written by David Blackman and Sebastiano Vigna. It is a 64bit PRNG that uses a carefully handcrafted shift/rotatebased linear transformation. This change both improves speed and statistical quality of the PRNG [1]_. xoroshiro128+ has a period of \(2^{128}  1\) and supports jumping the sequence in increments of \(2^{64}\), which allows multiple nonoverlapping sequences to be generated.
Xoroshiro128
exposes no userfacing API exceptgenerator
,state
,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
Xoroshiro128
guarantees that a fixed seed will always produce the same results.See
Xorshift1024
for an related PRNG implementation with a larger period (\(2^{1024}  1\)) and jump size (\(2^{512}  1\)).Parallel Features
Xoroshiro128
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{64}\) random numbers have been generated. This allow the original sequence to be split so that distinct segments can be used in each worker process. All generators should be initialized with the same seed to ensure that the segments come from the same sequence:rg = [RandomGenerator(Xoroshiro128(1234)) for _ in range(10)] # Advance each Xoroshiro128 instance by i jumps for i in range(10): rg[i].brng.jump(i)
State and Seeding
The
Xoroshiro128
state vector consists of a 2 element array of 64bit unsigned integers.Xoroshiro128
is seeded using either a single 64bit unsigned integer or a vector of 64bit unsigned integers. In either case, the input seed is used as an input (or inputs) for another simple random number generator, Splitmix64, and the output of this PRNG function is used as the initial state. Using a single 64bit value for the seed can only initialize a small range of the possible initial state values. When using an array, the SplitMix64 state for producing the ith component of the initial state is XORd with the ith value of the seed array until the seed array is exhausted. When using an array the initial state for the SplitMix64 state is 0 so that using a single element array and using the same value as a scalar will produce the same initial state.Examples:
rg = RandomGenerator(Xoroshiro128(1234)) rg.standard_normal() # 0.123 # random
Identical method using only Xoroshiro128:
rg = Xoroshiro128(1234).generator rg.standard_normal() # 0.123 # random
References
 1
“xoroshiro+ / xorshift* / xorshift+ generators and the PRNG shootout”, http://xorshift.di.unimi.it/

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
Xorshift1024
(seed=None)¶ Bases:
randomgen.xorshift1024.Xorshift1024
Container for the xorshift1024*φ pseudorandom number generator.
xorshift1024*φ is a 64bit implementation of Saito and Matsumoto’s XSadd generator [1]_ (see also [2]_, [3]_, [4]_). xorshift1024*φ has a period of \(2^{1024}  1\) and supports jumping the sequence in increments of \(2^{512}\), which allows multiple nonoverlapping sequences to be generated.
Xorshift1024
exposes no userfacing API exceptgenerator
,state
,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
Xorshift1024
guarantees that a fixed seed will always produce the same results. Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**641], array of integers in [0, 2**641] or
None
(the default). If seed isNone
, thenXorshift1024
will try to read data from/dev/urandom
(or the Windows analog) if available. If unavailable, a 64bit hash of the time and process ID is used.
Notes
See
Xoroshiro128
for a faster implementation that has a smaller period.Parallel Features
Xorshift1024
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{512}\) random numbers have been generated. This allows the original sequence to be split so that distinct segments can be used in each worker process. All generators should be initialized with the same seed to ensure that the segments come from the same sequence:rg = [RandomGenerator(Xorshift1024(1234)) for _ in range(10)] # Advance each Xorshift1024 instance by i jumps for i in range(10): rg[i].brng.jump(i)
State and Seeding
The
Xorshift1024
state vector consists of a 16 element array of 64bit unsigned integers.Xorshift1024
is seeded using either a single 64bit unsigned integer or a vector of 64bit unsigned integers. In either case, the input seed is used as an input (or inputs) for another simple random number generator, Splitmix64, and the output of this PRNG function is used as the initial state. Using a single 64bit value for the seed can only initialize a small range of the possible initial state values. When using an array, the SplitMix64 state for producing the ith component of the initial state is XORd with the ith value of the seed array until the seed array is exhausted. When using an array the initial state for the SplitMix64 state is 0 so that using a single element array and using the same value as a scalar will produce the same initial state.Examples:
rg = RandomGenerator(Xorshift1024(1234)) rg.standard_normal() # 0.123 # random
Identical method using only Xoroshiro128:
rg = Xorshift1024(1234).generator rg.standard_normal() # 0.123 # random
References
 1
“xorshift*/xorshift+ generators and the PRNG shootout”, http://xorshift.di.unimi.it/
 2
Marsaglia, George. “Xorshift RNGs.” Journal of Statistical Software [Online], 8.14, pp. 1  6, .2003.
 3
Sebastiano Vigna. “An experimental exploration of Marsaglia’s xorshift generators, scrambled.” CoRR, abs/1402.6246, 2014.
 4
Sebastiano Vigna. “Further scramblings of Marsaglia’s xorshift generators.” CoRR, abs/1403.0930, 2014.

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
Xoshiro256StarStar
(seed=None)¶ Bases:
randomgen.xoshiro256starstar.Xoshiro256StarStar
Container for the xoshiro256** pseudorandom number generator.
 Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**641], array of integers in [0, 2**641] or
None
(the default). If seed isNone
, thenXoshiro256StarStar
will try to read data from/dev/urandom
(or the Windows analog) if available. If unavailable, a 64bit hash of the time and process ID is used.
Notes
xoshiro256** is written by David Blackman and Sebastiano Vigna. It is a 64bit PRNG that uses a carefully linear transformation. This produces a fast PRNG with excellent statistical quality [1]_. xoshiro256** has a period of \(2^{256}  1\) and supports jumping the sequence in increments of \(2^{128}\), which allows multiple nonoverlapping sequences to be generated.
Xoshiro256StarStar
exposes no userfacing API exceptgenerator
,state
,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
Xoshiro256StarStar
guarantees that a fixed seed will always produce the same results.See
Xorshift1024
for a related PRNG with different periods (\(2^{1024}  1\)) and jump size (\(2^{512}  1\)).Parallel Features
Xoshiro256StarStar
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{128}\) random numbers have been generated. This allow the original sequence to be split so that distinct segments can be used in each worker process. All generators should be initialized with the same seed to ensure that the segments come from the same sequence:rg = [RandomGenerator(Xoshiro256StarStar(1234)) for _ in range(10)] # Advance each Xoshiro256StarStar instance by i jumps for i in range(10): rg[i].brng.jump(i)
State and Seeding
The
Xoshiro256StarStar
state vector consists of a 4 element array of 64bit unsigned integers.Xoshiro256StarStar
is seeded using either a single 64bit unsigned integer or a vector of 64bit unsigned integers. In either case, the input seed is used as an input (or inputs) for another simple random number generator, Splitmix64, and the output of this PRNG function is used as the initial state. Using a single 64bit value for the seed can only initialize a small range of the possible initial state values. When using an array, the SplitMix64 state for producing the ith component of the initial state is XORd with the ith value of the seed array until the seed array is exhausted. When using an array the initial state for the SplitMix64 state is 0 so that using a single element array and using the same value as a scalar will produce the same initial state.Examples:
rg = RandomGenerator(Xoshiro256StarStar(1234)) rg.standard_normal() # 0.123 # random
Identical method using only Xoshiro256StarStar:
rg = Xoshiro256StarStar(1234).generator rg.standard_normal() # 0.123 # random
References
 1
“xoroshiro+ / xorshift* / xorshift+ generators and the PRNG shootout”, http://xorshift.di.unimi.it/

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
Xoshiro512StarStar
(seed=None)¶ Bases:
randomgen.xoshiro512starstar.Xoshiro512StarStar
Container for the xoshiro512** pseudorandom number generator.
 Parameters
seed – {None, int, array_like}, optional. Random seed initializing the pseudorandom number generator. Can be an integer in [0, 2**641], array of integers in [0, 2**641] or
None
(the default). If seed isNone
, thenXoshiro512StarStar
will try to read data from/dev/urandom
(or the Windows analog) if available. If unavailable, a 64bit hash of the time and process ID is used.
Notes
xoshiro512** is written by David Blackman and Sebastiano Vigna. It is a 64bit PRNG that uses a carefully linear transformation. This produces a fast PRNG with excellent statistical quality [1]_. xoshiro512** has a period of \(2^{512}  1\) and supports jumping the sequence in increments of \(2^{256}\), which allows multiple nonoverlapping sequences to be generated.
Xoshiro512StarStar
exposes no userfacing API exceptgenerator
,state
,cffi
andctypes
. Designed for use in aRandomGenerator
object.Compatibility Guarantee
Xoshiro512StarStar
guarantees that a fixed seed will always produce the same results.See
Xorshift1024
for a related PRNG with different periods (\(2^{1024}  1\)) and jump size (\(2^{512}  1\)).Parallel Features
Xoshiro512StarStar
can be used in parallel applications by calling the methodjump
which advances the state asif \(2^{128}\) random numbers have been generated. This allow the original sequence to be split so that distinct segments can be used in each worker process. All generators should be initialized with the same seed to ensure that the segments come from the same sequence:rg = [RandomGenerator(Xoshiro512StarStar(1234)) for _ in range(10)] # Advance each Xoshiro512StarStar instance by i jumps for i in range(10): rg[i].brng.jump(i)
State and Seeding
The
Xoshiro512StarStar
state vector consists of a 4 element array of 64bit unsigned integers.Xoshiro512StarStar
is seeded using either a single 64bit unsigned integer or a vector of 64bit unsigned integers. In either case, the input seed is used as an input (or inputs) for another simple random number generator, Splitmix64, and the output of this PRNG function is used as the initial state. Using a single 64bit value for the seed can only initialize a small range of the possible initial state values. When using an array, the SplitMix64 state for producing the ith component of the initial state is XORd with the ith value of the seed array until the seed array is exhausted. When using an array the initial state for the SplitMix64 state is 0 so that using a single element array and using the same value as a scalar will produce the same initial state.Examples:
rg = RandomGenerator(Xoshiro512StarStar(1234)) rg.standard_normal() # 0.123 # random
Identical method using only Xoshiro512StarStar:
rg = Xoshiro512StarStar(1234).generator rg.standard_normal() # 0.123 # random
References
 1
“xoroshiro+ / xorshift* / xorshift+ generators and the PRNG shootout”, http://xorshift.di.unimi.it/

generator
¶

seed
(*args, **kwargs)¶

class
firedrake.randomfunctiongen.
RandomState
(brng=None)¶ Bases:
randomgen.mtrand.RandomState
Container for the Mersenne Twister pseudorandom number generator.
RandomState exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distributionspecific arguments, each method takes a keyword argument size that defaults to
None
. If size isNone
, then a single value is generated and returned. If size is an integer, then a 1D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned.Compatibility Guarantee A fixed seed and a fixed series of calls to ‘RandomState’ methods using the same parameters will always produce the same results up to roundoff error except when the values were incorrect. Incorrect values will be fixed and the NumPy version in which the fix was made will be noted in the relevant docstring. Extension of existing parameter ranges and the addition of new parameters is allowed as long the previous behavior remains unchanged.
 Parameters
brng – {None, int, array_like, BasicRNG}, optional. Random seed used to initialize the pseudorandom number generator or an instantized BasicRNG. If an integer or array, used as a seed for the MT19937 BasicRNG. Values can be any integer between 0 and 2**32  1 inclusive, an array (or other sequence) of such integers, or
None
(the default). If seed isNone
, then the MT19937. BasicRNG is initialized by reading data from/dev/urandom
(or the Windows analogue) if available or seed from the clock otherwise.
Notes
The Python stdlib module “random” also contains a Mersenne Twister pseudorandom number generator with a number of methods that are similar to the ones available in RandomState. RandomState, besides being NumPyaware, has the advantage that it provides a much larger number of probability distributions to choose from.

generator
¶

seed
(*args, **kwargs)¶
firedrake.solving module¶

firedrake.solving.
solve
(*args, **kwargs)[source]¶ Solve linear system Ax = b or variational problem a == L or F == 0.
The Firedrake solve() function can be used to solve either linear systems or variational problems. The following list explains the various ways in which the solve() function can be used.
1. Solving linear systems
A linear system Ax = b may be solved by calling
solve(A, x, b, bcs=bcs, solver_parameters={...})
where A is a
Matrix
and x and b areFunction
s. If present, bcs should be a list ofDirichletBC
s andEquationBC
s specifying, respectively, the strong boundary conditions to apply and PDEs to solve on the boundaries. For the format of solver_parameters see below.2. Solving linear variational problems
A linear variational problem a(u, v) = L(v) for all v may be solved by calling solve(a == L, u, …), where a is a bilinear form, L is a linear form, u is a
Function
(the solution). Optional arguments may be supplied to specify boundary conditions or solver parameters. Some examples are given below:solve(a == L, u) solve(a == L, u, bcs=bc) solve(a == L, u, bcs=[bc1, bc2]) solve(a == L, u, bcs=bcs, solver_parameters={"ksp_type": "gmres"})
The linear solver uses PETSc under the hood and accepts all PETSc options as solver parameters. For example, to solve the system using direct factorisation use:
solve(a == L, u, bcs=bcs, solver_parameters={"ksp_type": "preonly", "pc_type": "lu"})
3. Solving nonlinear variational problems
A nonlinear variational problem F(u; v) = 0 for all v may be solved by calling solve(F == 0, u, …), where the residual F is a linear form (linear in the test function v but possibly nonlinear in the unknown u) and u is a
Function
(the solution). Optional arguments may be supplied to specify boundary conditions, the Jacobian form or solver parameters. If the Jacobian is not supplied, it will be computed by automatic differentiation of the residual form. Some examples are given below:The nonlinear solver uses a PETSc SNES object under the hood. To pass options to it, use the same options names as you would for pure PETSc code. See
NonlinearVariationalSolver
for more details.solve(F == 0, u) solve(F == 0, u, bcs=bc) solve(F == 0, u, bcs=[bc1, bc2]) solve(F == 0, u, bcs, J=J, # Use NewtonKrylov iterations to solve the nonlinear # system, using direct factorisation to solve the linear system. solver_parameters={"snes_type": "newtonls", "ksp_type" : "preonly", "pc_type" : "lu"})
In all three cases, if the operator is singular you can pass a
VectorSpaceBasis
(orMixedVectorSpaceBasis
) spanning the null space of the operator to the solve call using thenullspace
keyword argument.If you need to project the transpose nullspace out of the right hand side, you can do so by using the
transpose_nullspace
keyword argument.In the same fashion you can add the near nullspace using the
near_nullspace
keyword argument.
firedrake.spatialindex module¶

class
firedrake.spatialindex.
SpatialIndex
¶ Bases:
object
Python class for holding a native spatial index object.

ctypes
¶ Returns a ctypes pointer to the native spatial index.


firedrake.spatialindex.
bounding_boxes
()¶ Given a spatial index and a point, return the bounding boxes the point is in.
 Parameters
sidx – the SpatialIndex
x – the point
 Returns
a numpy array of candidate bounding boxes.

firedrake.spatialindex.
from_regions
()¶ Builds a spatial index from a set of maximum bounding regions (MBRs).
regions_lo and regions_hi must have the same size. regions_lo[i] and regions_hi[i] contain the coordinates of the diagonally opposite lower and higher corners of the ith MBR, respectively.
firedrake.supermeshimpl module¶

firedrake.supermeshimpl.
assemble_mixed_mass_matrix
()¶

firedrake.supermeshimpl.
intersection_finder
()¶
firedrake.supermeshing module¶

firedrake.supermeshing.
assemble_mixed_mass_matrix
(V_A, V_B)[source]¶ Construct the mixed mass matrix of two function spaces, using the TrialFunction from V_A and the TestFunction from V_B.

firedrake.supermeshing.
intersection_finder
()¶
firedrake.tsfc_interface module¶
Provides the interface to TSFC for compiling a form, and transforms the TSFC generated code in order to make it suitable for passing to the backends.

class
firedrake.tsfc_interface.
KernelInfo
(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_map, needs_cell_facets, pass_layer_arg, needs_cell_sizes)¶ Bases:
tuple
Create new instance of KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_map, needs_cell_facets, pass_layer_arg, needs_cell_sizes)

coefficient_map
¶ Alias for field number 5

domain_number
¶ Alias for field number 4

integral_type
¶ Alias for field number 1

kernel
¶ Alias for field number 0

needs_cell_facets
¶ Alias for field number 6

needs_cell_sizes
¶ Alias for field number 8

oriented
¶ Alias for field number 2

pass_layer_arg
¶ Alias for field number 7

subdomain_id
¶ Alias for field number 3


class
firedrake.tsfc_interface.
SplitKernel
(indices, kinfo)¶ Bases:
tuple
Create new instance of SplitKernel(indices, kinfo)

indices
¶ Alias for field number 0

kinfo
¶ Alias for field number 1


class
firedrake.tsfc_interface.
TSFCKernel
(form, name, parameters, number_map, interface, coffee=False)[source]¶ Bases:
pyop2.caching.Cached
A wrapper object for one or more TSFC kernels compiled from a given
Form
. Parameters
form – the
Form
from which to compile the kernels.name – a prefix to be applied to the compiled kernel names. This is primarily useful for debugging.
parameters – a dict of parameters to pass to the form compiler.
number_map – a map from local coefficient numbers to global ones (useful for split forms).
interface – the KernelBuilder interface for TSFC (may be None)

firedrake.tsfc_interface.
compile_form
(form, name, parameters=None, inverse=False, split=True, interface=None, coffee=False)[source]¶ Compile a form using TSFC.
 Parameters
form – the
Form
to compile.name – a prefix for the generated kernel functions.
parameters – optional dict of parameters to pass to the form compiler. If not provided, parameters are read from the
form_compiler
slot of the Firedrakeparameters
dictionary (which see).inverse – If True then assemble the inverse of the local tensor.
split – If
False
, then don’t split mixed forms.coffee – compile coffee kernel instead of loopy kernel
Returns a tuple of tuples of (index, integral type, subdomain id, coordinates, coefficients, needs_orientations,
Kernels
).needs_orientations
indicates whether the form requires cell orientation information (for correctly pulling back to reference elements on embedded manifolds).The coordinates are extracted from the domain of the integral (a
Mesh()
)
firedrake.ufl_expr module¶

class
firedrake.ufl_expr.
Argument
(function_space, number, part=None)[source]¶ Bases:
ufl.argument.Argument
Representation of the argument to a form.
 Parameters
function_space – the
FunctionSpace
the argument corresponds to.number – the number of the argument being constructed.
part – optional index (mostly ignored).
Note
an
Argument
with a number of0
is used as aTestFunction()
, with a number of1
it is used as aTrialFunction()
.

firedrake.ufl_expr.
TestFunction
(function_space, part=None)[source]¶ Build a test function on the specified function space.
 Parameters
function_space – the
FunctionSpace
to build the test function on.part – optional index (mostly ignored).

firedrake.ufl_expr.
TrialFunction
(function_space, part=None)[source]¶ Build a trial function on the specified function space.
 Parameters
function_space – the
FunctionSpace
to build the trial function on.part – optional index (mostly ignored).

firedrake.ufl_expr.
TestFunctions
(function_space)[source]¶ Return a tuple of test functions on the specified function space.
 Parameters
function_space – the
FunctionSpace
to build the test functions on.
This returns
len(function_space)
test functions, which, if the function space is aMixedFunctionSpace
, are indexed appropriately.

firedrake.ufl_expr.
TrialFunctions
(function_space)[source]¶ Return a tuple of trial functions on the specified function space.
 Parameters
function_space – the
FunctionSpace
to build the trial functions on.
This returns
len(function_space)
trial functions, which, if the function space is aMixedFunctionSpace
, are indexed appropriately.

firedrake.ufl_expr.
derivative
(form, u, du=None, coefficient_derivatives=None)[source]¶ Compute the derivative of a form.
Given a form, this computes its linearization with respect to the provided
Function
. The resulting form has one additionalArgument
in the same finite element space as the Function. Parameters
form – a
Form
to compute the derivative of.u – a
Function
to compute the derivative with respect to.du – an optional
Argument
to use as the replacement in the new form (constructed automatically if not provided).coefficient_derivatives – an optional
dict
to provide the derivative of a coefficient function.
 Raises
ValueError – If any of the coefficients in
form
were obtained fromu.split()
. UFL doesn’t notice that these are related tou
and so therefore the derivative is wrong (instead one should have writtensplit(u)
).
See also
ufl.derivative()
.

firedrake.ufl_expr.
adjoint
(form, reordered_arguments=None)[source]¶ Compute the adjoint of a form.
 Parameters
form – A UFL form, or a Slate tensor.
reordered_arguments – arguments to use when creating the adjoint. Ignored if form is a Slate tensor.
If the form is a slate tensor, this just returns its transpose. Otherwise, given a bilinear form, compute the adjoint form by changing the ordering (number) of the test and trial functions.
By default, new Argument objects will be created with opposite ordering. However, if the adjoint form is to be added to other forms later, their arguments must match. In that case, the user must provide a tuple reordered_arguments=(u2,v2).

firedrake.ufl_expr.
action
(form, coefficient)[source]¶ Compute the action of a form on a coefficient.
 Parameters
form – A UFL form, or a Slate tensor.
coefficient – The
Function
to act on.
 Returns
a symbolic expression for the action.
firedrake.utility_meshes module¶

firedrake.utility_meshes.
IntervalMesh
(ncells, length_or_left, right=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a uniform mesh of an interval.
 Parameters
ncells – The number of the cells over the interval.
length_or_left – The length of the interval (if
right
is not provided) or else the left hand boundary point.right – (optional) position of the right boundary point (in which case
length_or_left
should be the left boundary point).comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The left hand boundary point has boundary marker 1, while the right hand point has marker 2.

firedrake.utility_meshes.
UnitIntervalMesh
(ncells, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a uniform mesh of the interval [0,1].
 Parameters
ncells – The number of the cells over the interval.
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The left hand (\(x=0\)) boundary point has boundary marker 1, while the right hand (\(x=1\)) point has marker 2.

firedrake.utility_meshes.
PeriodicIntervalMesh
(ncells, length, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a periodic mesh of an interval.
 Parameters
ncells – The number of cells over the interval.
length – The length the interval.
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
PeriodicUnitIntervalMesh
(ncells, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a periodic mesh of the unit interval
 Parameters
ncells – The number of cells in the interval.
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
UnitTriangleMesh
(comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a mesh of the reference triangle
 Parameters
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
RectangleMesh
(nx, ny, Lx, Ly, quadrilateral=False, reorder=None, diagonal='left', distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a rectangular mesh
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
Lx – The extent in the x direction
Ly – The extent in the y direction
quadrilateral – (optional), creates quadrilateral mesh, defaults to False
reorder – (optional), should the mesh be reordered
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
diagonal – For triangular meshes, should the diagonal got from bottom left to top right (
"right"
), or top left to bottom right ("left"
), or put in both diagonals ("crossed"
).
The boundary edges in this mesh are numbered as follows:
1: plane x == 0
2: plane x == Lx
3: plane y == 0
4: plane y == Ly

firedrake.utility_meshes.
SquareMesh
(nx, ny, L, reorder=None, quadrilateral=False, diagonal='left', distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a square mesh
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
L – The extent in the x and y directions
quadrilateral – (optional), creates quadrilateral mesh, defaults to False
reorder – (optional), should the mesh be reordered
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The boundary edges in this mesh are numbered as follows:
1: plane x == 0
2: plane x == L
3: plane y == 0
4: plane y == L

firedrake.utility_meshes.
UnitSquareMesh
(nx, ny, reorder=None, diagonal='left', quadrilateral=False, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a unit square mesh
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
quadrilateral – (optional), creates quadrilateral mesh, defaults to False
reorder – (optional), should the mesh be reordered
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The boundary edges in this mesh are numbered as follows:
1: plane x == 0
2: plane x == 1
3: plane y == 0
4: plane y == 1

firedrake.utility_meshes.
PeriodicRectangleMesh
(nx, ny, Lx, Ly, direction='both', quadrilateral=False, reorder=None, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a periodic rectangular mesh
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
Lx – The extent in the x direction
Ly – The extent in the y direction
direction – The direction of the periodicity, one of
"both"
,"x"
or"y"
.quadrilateral – (optional), creates quadrilateral mesh, defaults to False
reorder – (optional), should the mesh be reordered
diagonal – (optional), one of
"crossed"
,"left"
,"right"
."left"
is the default. Not valid for quad meshes. Only used for direction"x"
or direction"y"
.comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
If direction == “x” the boundary edges in this mesh are numbered as follows:
1: plane y == 0
2: plane y == Ly
If direction == “y” the boundary edges are:
1: plane x == 0
2: plane x == Lx

firedrake.utility_meshes.
PeriodicSquareMesh
(nx, ny, L, direction='both', quadrilateral=False, reorder=None, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a periodic square mesh
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
L – The extent in the x and y directions
direction – The direction of the periodicity, one of
"both"
,"x"
or"y"
.quadrilateral – (optional), creates quadrilateral mesh, defaults to False
reorder – (optional), should the mesh be reordered
diagonal – (optional), one of
"crossed"
,"left"
,"right"
."left"
is the default. Not valid for quad meshes.comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
If direction == “x” the boundary edges in this mesh are numbered as follows:
1: plane y == 0
2: plane y == L
If direction == “y” the boundary edges are:
1: plane x == 0
2: plane x == L

firedrake.utility_meshes.
PeriodicUnitSquareMesh
(nx, ny, direction='both', reorder=None, quadrilateral=False, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a periodic unit square mesh
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
direction – The direction of the periodicity, one of
"both"
,"x"
or"y"
.quadrilateral – (optional), creates quadrilateral mesh, defaults to False
reorder – (optional), should the mesh be reordered
diagonal – (optional), one of
"crossed"
,"left"
,"right"
."left"
is the default. Not valid for quad meshes.comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
If direction == “x” the boundary edges in this mesh are numbered as follows:
1: plane y == 0
2: plane y == 1
If direction == “y” the boundary edges are:
1: plane x == 0
2: plane x == 1

firedrake.utility_meshes.
CircleManifoldMesh
(ncells, radius=1, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generated a 1D mesh of the circle, immersed in 2D.
 Parameters
ncells – number of cells the circle should be divided into (min 3)
radius – (optional) radius of the circle to approximate (defaults to 1).
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
UnitTetrahedronMesh
(comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a mesh of the reference tetrahedron.
 Parameters
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
BoxMesh
(nx, ny, nz, Lx, Ly, Lz, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a mesh of a 3D box.
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
nz – The number of cells in the z direction
Lx – The extent in the x direction
Ly – The extent in the y direction
Lz – The extent in the z direction
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The boundary surfaces are numbered as follows:
1: plane x == 0
2: plane x == Lx
3: plane y == 0
4: plane y == Ly
5: plane z == 0
6: plane z == Lz

firedrake.utility_meshes.
CubeMesh
(nx, ny, nz, L, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a mesh of a cube
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
nz – The number of cells in the z direction
L – The extent in the x, y and z directions
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The boundary surfaces are numbered as follows:
1: plane x == 0
2: plane x == L
3: plane y == 0
4: plane y == L
5: plane z == 0
6: plane z == L

firedrake.utility_meshes.
UnitCubeMesh
(nx, ny, nz, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a mesh of a unit cube
 Parameters
nx – The number of cells in the x direction
ny – The number of cells in the y direction
nz – The number of cells in the z direction
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The boundary surfaces are numbered as follows:
1: plane x == 0
2: plane x == 1
3: plane y == 0
4: plane y == 1
5: plane z == 0
6: plane z == 1

firedrake.utility_meshes.
IcosahedralSphereMesh
(radius, refinement_level=0, degree=1, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate an icosahedral approximation to the surface of the sphere.
 Parameters
radius –
The radius of the sphere to approximate. For a radius R the edge length of the underlying icosahedron will be.
\[a = \frac{R}{\sin(2 \pi / 5)}\]refinement_level – optional number of refinements (0 is an icosahedron).
degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
UnitIcosahedralSphereMesh
(refinement_level=0, degree=1, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate an icosahedral approximation to the unit sphere.
 Parameters
refinement_level – optional number of refinements (0 is an icosahedron).
degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
OctahedralSphereMesh
(radius, refinement_level=0, degree=1, hemisphere='both', z0=0.8, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate an octahedral approximation to the surface of the sphere.
 Parameters
radius – The radius of the sphere to approximate.
refinement_level – optional number of refinements (0 is an octahedron).
degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
hemisphere – One of “both” (default), “north”, or “south”
z0 – for abs(z/R)>z0, blend from a mesh where the higherorder nonvertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh. (defaults to z0=0.8).
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
UnitOctahedralSphereMesh
(refinement_level=0, degree=1, hemisphere='both', z0=0.8, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate an octahedral approximation to the unit sphere.
 Parameters
refinement_level – optional number of refinements (0 is an octahedron).
degree – polynomial degree of coordinate space (defaults to 1: flat triangles)
hemisphere – One of “both” (default), “north”, or “south”
z0 – for abs(z)>z0, blend from a mesh where the higherorder nonvertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh. (defaults to z0=0.8).
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
CubedSphereMesh
(radius, refinement_level=0, degree=1, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate an cubed approximation to the surface of the sphere.
 Parameters
radius – The radius of the sphere to approximate.
refinement_level – optional number of refinements (0 is a cube).
degree – polynomial degree of coordinate space (defaults to 1: bilinear quads)
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
UnitCubedSphereMesh
(refinement_level=0, degree=1, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a cubed approximation to the unit sphere.
 Parameters
refinement_level – optional number of refinements (0 is a cube).
degree – polynomial degree of coordinate space (defaults to 1: bilinear quads)
reorder – (optional), should the mesh be reordered?
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
TorusMesh
(nR, nr, R, r, quadrilateral=False, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generate a toroidal mesh
 Parameters
nR – The number of cells in the major direction (min 3)
nr – The number of cells in the minor direction (min 3)
R – The major radius
r – The minor radius
quadrilateral – (optional), creates quadrilateral mesh, defaults to False
reorder – (optional), should the mesh be reordered
comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).

firedrake.utility_meshes.
CylinderMesh
(nr, nl, radius=1, depth=1, longitudinal_direction='z', quadrilateral=False, reorder=None, distribution_parameters=None, diagonal=None, comm=<mpi4py.MPI.Intracomm object>)[source]¶ Generates a cylinder mesh.
 Parameters
nr – number of cells the cylinder circumference should be divided into (min 3)
nl – number of cells along the longitudinal axis of the cylinder
radius – (optional) radius of the cylinder to approximate (default 1).
depth – (optional) depth of the cylinder to approximate (default 1).
longitudinal_direction – (option) direction for the longitudinal axis of the cylinder.
quadrilateral – (optional), creates quadrilateral mesh, defaults to False
diagonal – (optional), one of
"crossed"
,"left"
,"right"
."left"
is the default. Not valid for quad meshes.comm – Optional communicator to build the mesh on (defaults to COMM_WORLD).
The boundary edges in this mesh are numbered as follows:
1: plane l == 0 (bottom)
2: plane l == depth (top)
firedrake.utils module¶
firedrake.variational_solver module¶

class
firedrake.variational_solver.
LinearVariationalProblem
(a, L, u, bcs=None, aP=None, form_compiler_parameters=None, constant_jacobian=True)[source]¶ Bases:
firedrake.variational_solver.NonlinearVariationalProblem
Linear variational problem a(u, v) = L(v).
 Parameters
a – the bilinear form
L – the linear form
u – the
Function
to solve forbcs – the boundary conditions (optional)
aP – an optional operator to assemble to precondition the system (if not provided a preconditioner may be computed from
a
)form_compiler_parameters (dict) – parameters to pass to the form compiler (optional)
constant_jacobian – (optional) flag indicating that the Jacobian is constant (i.e. does not depend on varying fields). If your Jacobian can change, set this flag to
False
.

class
firedrake.variational_solver.
LinearVariationalSolver
(*args, **kwargs)[source]¶ Bases:
firedrake.variational_solver.NonlinearVariationalSolver
Solves a
LinearVariationalProblem
. Parameters
problem – A
LinearVariationalProblem
to solve.solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.
nullspace – an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
) spanning the null space of the operator.transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the
solver_parameters
dict.appctx – A dictionary containing application context that is passed to the preconditioner if matrixfree.

class
firedrake.variational_solver.
NonlinearVariationalProblem
(F, u, bcs=None, J=None, Jp=None, form_compiler_parameters=None, is_linear=False)[source]¶ Bases:
object
Nonlinear variational problem F(u; v) = 0.
 Parameters
F – the nonlinear form
u – the
Function
to solve forbcs – the boundary conditions (optional)
J – the Jacobian J = dF/du (optional)
Jp – a form used for preconditioning the linear system, optional, if not supplied then the Jacobian itself will be used.
form_compiler_parameters (dict) – parameters to pass to the form compiler (optional)
 Is_linear
internally used to check if all domain/bc forms are given either in ‘A == b’ style or in ‘F == 0’ style.

class
firedrake.variational_solver.
NonlinearVariationalSolver
(problem, **kwargs)[source]¶ Bases:
firedrake.petsc.OptionsManager
Solves a
NonlinearVariationalProblem
. Parameters
problem – A
NonlinearVariationalProblem
to solve.nullspace – an optional
VectorSpaceBasis
(orMixedVectorSpaceBasis
) spanning the null space of the operator.transpose_nullspace – as for the nullspace, but used to make the right hand side consistent.
near_nullspace – as for the nullspace, but used to specify the near nullspace (for multigrid solvers).
solver_parameters – Solver parameters to pass to PETSc. This should be a dict mapping PETSc options to values.
appctx – A dictionary containing application context that is passed to the preconditioner if matrixfree.
options_prefix – an optional prefix used to distinguish PETSc options. If not provided a unique prefix will be created. Use this option if you want to pass options to the solver from the command line in addition to through the
solver_parameters
dict.pre_jacobian_callback – A userdefined function that will be called immediately before Jacobian assembly. This can be used, for example, to update a coefficient function that has a complicated dependence on the unknown solution.
pre_function_callback – As above, but called immediately before residual assembly
Example usage of the
solver_parameters
option: to set the nonlinear solver type to just use a linear solver, use{'snes_type': 'ksponly'}
PETSc flag options (where the presence of the option means something) should be specified with
None
. For example:{'snes_monitor': None}
To use the
pre_jacobian_callback
orpre_function_callback
functionality, the userdefined function must accept the current solution as a petsc4py Vec. Example usage is given below:def update_diffusivity(current_solution): with cursol.dat.vec_wo as v: current_solution.copy(v) solve(trial*test*dx == dot(grad(cursol), grad(test))*dx, diffusivity) solver = NonlinearVariationalSolver(problem, pre_jacobian_callback=update_diffusivity)

set_transfer_operators
(*contextmanagers)[source]¶ Set context managers which manages which grid transfer operators should be used.
 Parameters
contextmanagers – instances of
transfer_operators
. Raises
RuntimeError – if called after calling solve.
firedrake.vector module¶

class
firedrake.vector.
Vector
(x)[source]¶ Bases:
object
Build a Vector that wraps a
pyop2.Dat
for Dolfin compatibilty. Parameters
x – an
Function
to wrap or aVector
to copy. The former shares data, the latter copies data.

apply
(action)[source]¶ Finalise vector assembly. This is not actually required in Firedrake but is provided for Dolfin compatibility.

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

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

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