# firedrake package¶

## firedrake.assemble module¶

firedrake.assemble.assemble(expr, tensor=None, bcs=None, form_compiler_parameters=None, mat_type=None, sub_mat_type=None, appctx={}, options_prefix=None, **kwargs)[source]

Evaluate expr.

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

• 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 the Measure in the form. For example, if a quadrature_degree of 4 is specified in this argument, but a degree of 3 is requested in the measure, the latter will be used.

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

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

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

• options_prefix – PETSc options prefix to apply to matrices.

If expr is a Form then this evaluates the corresponding integral(s) and returns a float for 0-forms, a Function for 1-forms and a Matrix or ImplicitMatrix for 2-forms. Similarly if it is a Slate tensor expression.

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

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

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

## firedrake.assemble_expressions module¶

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

Bases: object

Representation of a pointwise assignment expression.

Parameters

• rvalue – The pointwise expression.

property args

Tuple of par_loop arguments for the expression.

coefficients[source]

Tuple of coefficients involved in the assignment.

fast_key[source]

A fast lookup key for this expression.

iterset[source]
lvalue
par_loop_args[source]

Arguments for a parallel loop to evaluate this expression.

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

rcoefficients[source]

Coefficients appearing in the rvalue.

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

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

split[source]

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

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

Base class for augmented pointwise assignment.

Parameters

• rvalue – The pointwise expression.

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

• rvalue – The pointwise expression.

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

• rvalue – The pointwise expression.

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

• rvalue – The pointwise expression.

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

• rvalue – The pointwise expression.

lvalue
rvalue
symbol = '-='
class firedrake.assemble_expressions.IndexRelabeller[source]
expr(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched


as a default rule.

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

Bases: ufl.corealg.multifunction.MultiFunction, tsfc.ufl2gem.Mixin

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

Trigger error for types with missing handlers.

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

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

Parameters
• expr – The UFL expression.

• subset – Optional subset to apply the expression on.

Returns

A new function.

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

Compile a single pointwise expression to GEM.

Parameters
Returns

A (lvalue, rvalue) pair of preprocessed GEM.

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

Bases: object

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

Evaluate a pointwise expression.

Parameters
• expr – The expression to evaluate.

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

Returns

The lvalue in the provided expression.

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

Compile a kernel for pointwise expressions.

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

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

Returns

a PyOP2 kernel for evaluation of the expressions.

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

## firedrake.bcs module¶

class firedrake.bcs.DirichletBC(*args, **kwargs)[source]

Bases: firedrake.bcs.BCBase, firedrake.adjoint.dirichletbc.DirichletBCMixin

Implementation of a strong Dirichlet boundary condition.

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

• g – the boundary condition values. This can be a Function on V, a Constant, an Expression, an iterable of literal constants (converted to an Expression), or a literal constant which can be pointwise evaluated at the nodes of V. Expressions are projected onto V 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 and bottom strings are used to flag the bcs application on the top and bottom boundaries of the extruded mesh respectively.

• method – the method for determining boundary nodes. 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 no-slip conditions on HDiv spaces.

apply(r, u=None)[source]

Apply this boundary condition to r.

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

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

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

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

The value of this boundary condition.

homogenize()[source]

Convert this boundary condition into a homogeneous one.

Set the value to zero.

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

Restore the original value of this boundary condition.

This uses the value passed on instantiation of the object.

set_value(val)[source]

Set the value of this boundary condition.

Parameters

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

class firedrake.bcs.EquationBC(*args, bcs=None, J=None, Jp=None, 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 for

• sub_domain – see DirichletBC.

• bcs – a list of DirichletBCs and/or :class:.EquationBCs 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

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

Return EquationBCSplit associated with the given ‘form_type’.

Parameters

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

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

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

Parameters

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

## firedrake.checkpointing module¶

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

Bases: object

A very dumb checkpoint object.

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

Parameters

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

Note

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

close()[source]

Close the checkpoint file (flushing any pending writes)

get_timesteps()[source]

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

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

property h5file

An h5py File object pointing at the open file handle.

has_attribute(obj, name)[source]

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

Parameters
• obj – The path to the data object.

• name – The name of the attribute.

load(function, name=None)[source]

Store a function from the checkpoint file.

Parameters
• function – The function to load values into.

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

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

new_file(name=None)[source]

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

Parameters

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

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

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


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

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

Read an HDF5 attribute on a specified data object.

Parameters
• obj – The path to the data object.

• name – The name of the attribute.

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

set_timestep(t, idx=None)[source]

Set the timestep for output.

Parameters
• t – The timestep value.

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

store(function, name=None)[source]

Store a function in the checkpoint file.

Parameters
• function – The function to store.

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

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

property vwr

The PETSc Viewer used to store and load function data.

write_attribute(obj, name, val)[source]

Set an HDF5 attribute on a specified data object.

Parameters
• obj – The path to the data object.

• name – The name of the attribute.

• val – The attribute value.

Raises AttributeError if writing the attribute fails.

firedrake.checkpointing.FILE_CREATE = 1

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

firedrake.checkpointing.FILE_READ = 0

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

firedrake.checkpointing.FILE_UPDATE = 2

Open a checkpoint file for updating. Creates the file if it does not exist, providing both read and write access.

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

Bases: object

An object to facilitate checkpointing.

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

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

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

attributes(obj)[source]
Parameters

obj – The path to the group.

close()[source]

Close the checkpoint file (flushing any pending writes)

flush()[source]

Flush any pending writes.

get_timestamps()[source]

Get the timestamps this HDF5File knows about.

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

Store a function from the checkpoint file.

Parameters
• function – The function to load values into.

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

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

Store a function in the checkpoint file.

Parameters
• function – The function to store.

• path – the path to store the function under.

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

## firedrake.constant module¶

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

A “constant” coefficient

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

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

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

Note

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

assign(value)[source]

Set the value of this constant.

Parameters

value – A value of the appropriate shape

cell_node_map(bcs=None)[source]

Return a null cell to node map.

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

Return the evaluation of this Constant.

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

• mapping – A mapping (ignored).

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

• index_values – ignored.

exterior_facet_node_map(bcs=None)[source]

Return a null exterior facet to node map.

function_space()[source]

Return a null function space.

interior_facet_node_map(bcs=None)[source]

Return a null interior facet to node map.

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

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

## firedrake.dmhooks module¶

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

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

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

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

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

class firedrake.dmhooks.SetupHooks[source]

Bases: object

Hooks run for setup and teardown of DMs inside solvers.

Used for transferring problem-specific data onto subproblems.

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

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

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

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

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

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

• call_setup – Should the setup function be called now?

• call_teardown – Should the teardown function be called now?

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

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

Bases: object

Context manager for adding subproblem setup hooks to a DM.

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

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

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

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

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

# In setup
pc = ...
pc.setDM(dm)
pc.setFromOptions()

...

# in apply
dm = pc.getDM()
pc.apply(...)

firedrake.dmhooks.attach_hooks(dm, level=None, sf=None, section=None)[source]

Attach callback hooks to a DM.

Parameters
• DM – The DM to attach callbacks to.

• level – Optional refinement level.

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

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

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

Callback to coarsen a DM.

Parameters
• DM – The DM to coarsen.

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

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

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

Callback to decompose a DM.

Parameters

DM – The DM.

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

firedrake.dmhooks.create_matrix(dm)[source]

Callback to create a matrix from this DM.

Parameters

DM – The DM.

Note

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

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

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

Parameters
• DM – The DM.

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

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

Bases: object

firedrake.dmhooks.get_appctx(dm, default=None)
firedrake.dmhooks.get_attr(attr, dm, default=None)[source]
firedrake.dmhooks.get_ctx_coarsener(dm)[source]
firedrake.dmhooks.get_function_space(dm)[source]

Get the FunctionSpace attached to this DM.

Parameters

dm – The DM to get the function space from.

Raises

RuntimeError – if no function space was found.

firedrake.dmhooks.get_parent(dm)[source]
firedrake.dmhooks.get_transfer_manager(dm)[source]
firedrake.dmhooks.pop_appctx(dm, match=None)
firedrake.dmhooks.pop_attr(attr, dm, match=None)[source]
firedrake.dmhooks.pop_ctx_coarsener(dm, match=None)
firedrake.dmhooks.pop_parent(dm, match=None)
firedrake.dmhooks.push_appctx(dm, obj)
firedrake.dmhooks.push_attr(attr, dm, obj)[source]
firedrake.dmhooks.push_ctx_coarsener(dm, obj)
firedrake.dmhooks.push_parent(dm, obj)
firedrake.dmhooks.refine(dm, comm)[source]

Callback to refine a DM.

Parameters
• DM – The DM to refine.

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

firedrake.dmhooks.set_function_space(dm, V)[source]

Set the FunctionSpace on this DM.

Parameters
• dm – The DM

• V – The function space.

Note

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

## firedrake.ensemble module¶

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

Bases: object

Create a set of space and ensemble subcommunicators.

Parameters
• comm – The communicator to split.

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

Raises

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

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

Allreduce a function f into f_reduced over ensemble_comm.

Parameters
• f – The a Function to allreduce.

• f_reduced – the result of the reduction.

• op – MPI reduction operator.

Raises

ValueError – if communicators mismatch, or function sizes mismatch.

comm

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

ensemble_comm

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

global_comm

The global communicator.

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

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

Returns a Request object.

Parameters
• f – The a Function to receive into

• source – the rank to receive from

• tag – the tag of the message

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

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

Returns a Request object.

Parameters
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 into

• source – 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

## firedrake.exceptions module¶

exception firedrake.exceptions.ConvergenceError[source]

Bases: Exception

Error raised when a solver fails to converge

## firedrake.expression module¶

class firedrake.expression.Expression(code=None, element=None, cell=None, degree=None, **kwargs)[source]

Python function that may be evaluated on a FunctionSpace. This provides a mechanism for setting Function values to user-determined 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 a Function, or project() it into a FunctionSpace. Note that not all FunctionSpaces support interpolation, but all do support projection.

Expressions are specified by creating a subclass of Expression with a user-defined eval method. For example, the following expression sets the output Function 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 the Function 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 vector-valued Function then it is necessary to explicitly override the value_shape() method of that Expression. 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: user-defined values that are accessible in the

Expression code. These values maybe updated by accessing the property of the same name.

rank()[source]

Return the rank of this Expression

property 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_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.flat_entity_dofs(entity_dofs)[source]
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 equi-spaced height for each layer.

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

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

The kernel signature (if provided) is:

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


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

## firedrake.formmanipulation module¶

class firedrake.formmanipulation.ExtractSubBlock[source]

Extract a sub-block from a form.

class IndexInliner[source]

Inline fixed index of list tensors

expr(o, *ops)

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched


as a default rule.

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

Reuse object if operands are the same objects.

Use in your own subclass by setting e.g.

expr = MultiFunction.reuse_if_untouched


as a default rule.

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

Split a form.

Parameters
• form – the form to split.

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

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

class firedrake.formmanipulation.SplitForm(indices, form)

Bases: tuple

Create new instance of SplitForm(indices, form)

form

Alias for field number 1

indices

Alias for field number 0

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

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

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

For example, consider the following code:

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


Then splitting the form returns a tuple of two forms.

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


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

## firedrake.function module¶

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

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

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

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

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

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

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

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

f += 2 * g


will add twice g to f.

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

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

Evaluate function at points.

Parameters
• arg – The point to locate.

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

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

copy(deepcopy=False)[source]

Return a copy of this Function.

Parameters

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

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

Get self from mapping and return the component asked for.

function_space()[source]

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

interpolate(expression, subset=None)[source]

Interpolate an expression onto this Function.

Parameters

expressionExpression or a UFL expression to interpolate

Returns

this Function object

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

Project b onto self. b must be a Function or an Expression.

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

split()[source]

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

sub(i)[source]

Extract the ith sub Function of this Function.

Parameters

i – the index to extract

See also split().

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

property topological

The underlying coordinateless function.

vector()[source]

Return a Vector wrapping the data in this Function

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

Bases: Exception

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

Attributes: domain, point

## firedrake.functionspace module¶

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

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

Create a FunctionSpace.

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

• family – The finite element family.

• degree – The degree of the finite element.

• name – An optional name for the function space.

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

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

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

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

Create a MixedFunctionSpace.

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

Create a rank-2 FunctionSpace.

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

• family – The finite element family.

• degree – The degree of the finite element.

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

• symmetry – Optional symmetries in the tensor value.

• name – An optional name for the function space.

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

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

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

Note

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

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

Create a rank-1 FunctionSpace.

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

• family – The finite element family.

• degree – The degree of the finite element.

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

• name – An optional name for the function space.

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

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

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

Note

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

## firedrake.functionspacedata module¶

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

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

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

firedrake.functionspacedata.get_shared_data(mesh, finat_element, real_tensorproduct=False)[source]

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

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

• component – The component to represent.

Returns

A new ProxyFunctionSpace with the component set.

class firedrake.functionspaceimpl.FunctionSpace(mesh, element, name=None, 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

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

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

Warning

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

boundary_nodes(sub_domain, 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.

cell_node_list[source]

A numpy array mapping mesh cells to function space nodes.

cell_node_map()[source]

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

collapse()[source]
component = None

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

dim()[source]

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

See also dof_count and node_count.

dm[source]

A PETSc DM describing the data layout for this FunctionSpace.

dof_count[source]

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

dof_dset

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

exterior_facet_node_map()[source]

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

index = None

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

interior_facet_node_map()[source]

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

local_to_global_map(bcs, lgmap=None)[source]

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

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

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

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

mesh()[source]
name

The (optional) descriptive name for this space.

node_count[source]

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

node_set

A pyop2.Set representing the function space nodes.

parent = None

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

rank

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

split()[source]

Split into a tuple of constituent spaces.

sub(i)[source]

Return a view into the ith component.

topological[source]

Function space on a mesh topology.

ufl_element()[source]

The FiniteElementBase associated with this space.

ufl_function_space()[source]

The FunctionSpace associated with this space.

value_size

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

firedrake.functionspaceimpl.IndexedFunctionSpace(index, space, parent)[source]

Build a new FunctionSpace that remembers it is a particular subspace of a MixedFunctionSpace.

Parameters
• index – The index into the parent space.

• space – The subspace to represent

• parent – The parent mixed space.

Returns

A new ProxyFunctionSpace with index and parent set.

class firedrake.functionspaceimpl.MixedFunctionSpace(spaces, name=None)[source]

Bases: object

A function space on a mixed finite element.

This is essentially just a bag of individual FunctionSpace objects.

Parameters
• spaces – The constituent spaces.

• name – An optional name for the mixed space.

Warning

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

cell_node_map()[source]

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

component = None
dim()[source]

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

See also dof_count and node_count.

dm[source]

A PETSc DM describing the data layout for fieldsplit solvers.

dof_count[source]

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

dof_dset[source]

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

exterior_facet_node_map()[source]

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

index = None
interior_facet_node_map()[source]

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

local_to_global_map(bcs)[source]

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

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

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

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

mesh()[source]
node_count[source]

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

node_set[source]

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

num_sub_spaces()[source]

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

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

The list of FunctionSpaces of which this MixedFunctionSpace is composed.

sub(i)[source]

Return the ith :class:FunctionSpace in this MixedFunctionSpace.

property topological

Function space on a mesh topology.

ufl_element()[source]

The MixedElement associated with this space.

ufl_function_space()[source]

The FunctionSpace associated with this space.

value_size[source]

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

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

A FunctionSpace that one can attach extra properties to.

Parameters
• mesh – The mesh to use.

• element – The UFL element.

• name – The name of the function space.

Warning

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

identifier = None

An optional identifier, for debugging purposes.

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

Create a pyop2.Dat.

Raises

ValueError – if no_dats is True.

no_dats = False

Can this proxy make pyop2.Dat objects

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

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

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

bottom_nodes()[source]

RealFunctionSpace objects have no bottom nodes.

cell_node_map(bcs=None)[source]

RealFunctionSpace objects have no cell node map.

dim()[source]

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

See also dof_count and node_count.

exterior_facet_node_map(bcs=None)[source]

RealFunctionSpace objects have no exterior facet node map.

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

RealFunctionSpace objects have no interior facet node map.

local_to_global_map(bcs, lgmap=None)[source]

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

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

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

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

rank = 0
shape = ()
top_nodes()[source]

RealFunctionSpace objects have no bottom nodes.

value_size = 1
class firedrake.functionspaceimpl.WithGeometry(function_space, mesh)[source]

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.

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

Get a temporary work Function on this FunctionSpace.

Parameters

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

Raises

ValueError – if max_work_functions are already checked out.

Note

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

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

property max_work_functions

The maximum number of work functions this FunctionSpace supports.

See get_work_function() for obtaining work functions.

mesh()

Return ufl domain.

property num_work_functions

The number of checked out work functions.

restore_work_function(function)[source]

Restore a work function obtained with get_work_function().

Parameters

function – The work function to restore

Raises

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

Warning

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

split()[source]

Split into a tuple of constituent spaces.

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

The Cell this FunctionSpace is defined on.

ufl_function_space()[source]

The FunctionSpace this object represents.

## firedrake.halo module¶

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

Build a Halo for a function space.

Parameters
• dm – The DM describing the topology.

• section – The data layout.

The halo is implemented using a PETSc SF (star forest) object and is usable as a PyOP2 pyop2.Halo.

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

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

Parameters
• dat – The Dat to exchange.

• insert_mode – The insertion mode.

global_to_local_end(dat, insert_mode)[source]

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

Parameters
• dat – The Dat to exchange.

• insert_mode – The insertion mode.

local_to_global_begin(dat, insert_mode)[source]

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

Parameters
• dat – The Dat to exchange.

• insert_mode – The insertion mode.

local_to_global_end(dat, insert_mode)[source]

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

Parameters
• dat – The Dat to exchange.

• insert_mode – The insertion mode.

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

## firedrake.interpolation module¶

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

Bases: object

A reusable interpolation object. :arg expr: The expression to interpolate. :arg V: The FunctionSpace or Function to

interpolate into.

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

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

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

Note

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

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

Compute the interpolation. :arg function: If the expression being interpolated contains an

ufl.Argument, then the Function value to interpolate.

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

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

Returns

The resulting interpolated Function.

firedrake.interpolation.interpolate(expr, V, subset=None, access=<Access.WRITE: 2>)[source]

Interpolate an expression onto a new function in V. :arg expr: an Expression. :arg V: the FunctionSpace to interpolate into (or else

an existing Function).

Parameters
• 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 space V (or V if it was a Function).

Note

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

Note

If you find interpolating the same expression again and again (for example in a time loop) you may find you get better performance by using an Interpolator instead.

## firedrake.linear_solver module¶

class firedrake.linear_solver.LinearSolver(A, P=None, solver_parameters=None, nullspace=None, transpose_nullspace=None, near_nullspace=None, options_prefix=None)[source]

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

Parameters
• A – a MatrixBase (the operator).

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

• parameters – (optional) dict of solver parameters.

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

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

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

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

Note

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

solve(x, b)[source]
test_space[source]
trial_space[source]

## firedrake.logging module¶

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Write info message in blue.

Parameters

message – the message to be printed.

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

Write info message in green.

Parameters

message – the message to be printed.

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

Write info message in red.

Parameters

message – the message to be printed.

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

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

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

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

firedrake.logging.set_level(level)

Set the log level for Firedrake components.

Parameters

level – The level to use.

This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.

firedrake.logging.set_log_handlers(handlers=None, comm=<mpi4py.MPI.Intracomm object>)[source]

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

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

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

firedrake.logging.set_log_level(level)[source]

Set the log level for Firedrake components.

Parameters

level – The level to use.

This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.

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

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

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

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

## firedrake.matrix module¶

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

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

Parameters
• a – the bilinear form this Matrix represents.

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

Note

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

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

A representation of an assembled bilinear form.

Parameters
• a – the bilinear form this Matrix represents.

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

• mat_type – matrix type of assembled matrix.

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

Note

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

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

Bases: object

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

Parameters
• a – the bilinear form this MatrixBase represents.

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

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

property bcs

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

property has_bcs

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

mat_type

Matrix type.

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

## firedrake.mesh module¶

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

Bases: enum.Enum

How should the mesh overlap be grown for distributed meshes?

Possible options are:

Defaults to FACET.

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

Build an extruded mesh from an input mesh

Parameters
• mesh – the unstructured base mesh

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

• layer_height – the layer height, 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. See make_extruded_coords() for more details.

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

The various values of extrusion_type have the following meanings:

"uniform"

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

"radial"

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

"radial_hedgehog"

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

"custom"

use a custom kernel to generate the extruded coordinates

For more details see the manual section on extruded meshes.

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

Construct a mesh object.

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

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

• dim – optional specification of the geometric dimension of the mesh (ignored if not reading from mesh file). If not supplied the geometric dimension is deduced from the topological dimension of entities in the mesh.

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

• distribution_parameters

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

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

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

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

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

• 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.SubDomainData(geometric_expr)[source]

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

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

x = mesh.coordinates sd = SubDomainData(x[0] < 0.5) assemble(f*dx(subdomain_data=sd))

firedrake.mesh.VertexOnlyMesh(mesh, vertexcoords)[source]

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

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

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

Note

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

Note

Meshes created from a coordinates firedrake.Function and immersed manifold meshes are not yet supported.

firedrake.mesh.unmarked = -1

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

## firedrake.norms module¶

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

Compute the error $$e = u - u_h$$ in the specified norm.

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

• uh – a Function containing the approximate solution

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

• degree_rise – ignored.

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

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

Compute the norm of v.

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

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

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

Available norm types are:

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

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

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

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

## firedrake.nullspace module¶

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

Bases: object

A basis for a mixed vector space

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

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

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

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

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

W = V*Q

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

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


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

nullspace = MixedVectorSpaceBasis(W, [W[0], VectorSpaceBasis(constant=True)])
solve(a == ..., nullspace=nullspace)

class firedrake.nullspace.VectorSpaceBasis(vecs=None, constant=False)[source]

Bases: object

Build a basis for a vector space.

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

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

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

Note

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

Warning

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

check_orthogonality(orthonormal=True)[source]

Check if the basis is orthogonal.

Parameters

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

Raises

ValueError – If the basis is not orthogonal/orthonormal.

is_orthogonal()[source]

Is this vector space basis orthogonal?

is_orthonormal()[source]

Is this vector space basis orthonormal?

nullspace(comm=None)[source]

The PETSc NullSpace object for this VectorSpaceBasis.

Parameters

comm – Communicator to create the nullspace on.

orthogonalize(b)[source]

Orthogonalize b with respect to this VectorSpaceBasis.

Parameters

Note

Modifies b in place.

orthonormalize()[source]

Orthonormalize the basis.

Warning

This modifies the basis in place.

## firedrake.optimizer module¶

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

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

• Mesh coordinates

• All available maps binding sets of mesh components

## firedrake.output module¶

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

Bases: object

Create an object for outputting data for visualisation.

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

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

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

• comm – The MPI communicator to use.

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

• target_degree – override the degree of the output space.

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

Note

Visualisation is only possible for Lagrange fields (either continuous or discontinuous). All other fields are first either projected or interpolated to Lagrange elements before storing for visualisation purposes.

write(*functions, **kwargs)[source]

Write functions to this File.

Parameters
• functions – list of functions to write.

• time – optional timestep value.

You may save more than one function to the same file. However, all calls to write() must use the same set of functions.

## firedrake.parameters module¶

The parameters dictionary contains global parameter settings.

class firedrake.parameters.Parameters(name=None, **kwargs)[source]

Bases: dict

add(key, value=None)[source]
name()[source]
rename(name)[source]
set_update_function(callable)[source]

Set a function to be called whenever a dictionary entry is changed.

Parameters

callable – the function.

The function receives two arguments, the key-value pair of updated entries.

firedrake.parameters.disable_performance_optimisations()[source]

Switches off performance optimisations in Firedrake.

This is mostly useful for debugging purposes.

This switches off all of COFFEE’s kernel compilation optimisations and enables PyOP2’s runtime checking of par_loop arguments in all cases (even those where they are claimed safe). Additionally, it switches to compiling generated code in debug mode.

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

firedrake.parameters.parameters = {'coffee': {'optlevel': 'Ov'}, 'default_matrix_type': 'nest', 'default_sub_matrix_type': 'baij', 'form_compiler': {'mode': 'spectral', 'quadrature_degree': 'auto', 'quadrature_rule': 'auto', 'scalar_type': dtype('float64'), 'scalar_type_c': 'double', 'unroll_indexsum': 3}, 'pyop2_options': {'block_sparsity': True, 'cache_dir': '/Users/dham/src/firedrake/.cache/pyop2', 'cflags': '', 'check_src_hashes': True, 'compiler': 'gcc', 'compute_kernel_flops': False, 'debug': False, 'dump_gencode': False, '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, 'use_safe_cflags': True}, 'reorder_meshes': True, 'type_check_safe_par_loops': False}

A nested dictionary of parameters used by Firedrake

## firedrake.paraview_reordering module¶

firedrake.paraview_reordering.bary_to_cart(bar)[source]
firedrake.paraview_reordering.firedrake_local_to_cart(element)[source]

Gets the list of nodes for an element (provided they exist.) :arg element: a ufl element. :returns: a list of arrays of floats where each array is a node.

firedrake.paraview_reordering.invert(list1, list2)[source]

Given two maps (lists) from [0..N] to nodes, finds a permutations between them. :arg list1: a list of nodes. :arg list2: a second list of nodes. :returns: a list of integers, l, such that list1[x] = list2[l[x]]

firedrake.paraview_reordering.tet_barycentric_index(tet, index, order)[source]

Wrapper for vtkLagrangeTetra::BarycentricIndex.

firedrake.paraview_reordering.vtk_hex_local_to_cart(orders)[source]

Produces a list of nodes for VTK’s lagrange hex basis. :arg order: the three orders of the hex basis. :return a list of arrays of floats.

firedrake.paraview_reordering.vtk_interval_local_coord(i, order)[source]

See vtkLagrangeCurve::PointIndexFromIJK.

firedrake.paraview_reordering.vtk_lagrange_hex_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_interval_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_quad_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_tet_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_triangle_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_lagrange_wedge_reorder(ufl_element)[source]
firedrake.paraview_reordering.vtk_quad_local_to_cart(orders)[source]

Produces a list of nodes for VTK’s lagrange quad basis. :arg order: the order of the quad basis. :return a list of arrays of floats.

firedrake.paraview_reordering.vtk_tet_local_to_cart(order)[source]

Produces a list of nodes for VTK’s lagrange tet basis. :arg order: the order of the tet :return a list of arrays of floats

firedrake.paraview_reordering.vtk_triangle_index_cart(tri, index, order)[source]

Wrapper for vtkLagrangeTriangle::BarycentricIndex

firedrake.paraview_reordering.vtk_triangle_local_to_cart(order)[source]
firedrake.paraview_reordering.vtk_wedge_local_to_cart(ordersp)[source]

Produces a list of nodes for VTK’s lagrange wedge basis. :arg order: the orders of the wedge (triangle, interval) :return a list of arrays of floats

## firedrake.parloops module¶

This module implements parallel loops reading and writing Functions. This provides a mechanism for implementing non-finite element operations such as slope limiters.

firedrake.parloops.direct = direct

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

firedrake.parloops.par_loop(kernel, measure, args, kernel_kwargs=None, is_loopy_kernel=False, **kwargs)[source]

A par_loop() is a user-defined operation which reads and writes Functions by looping over the mesh cells or facets and accessing the degrees of freedom on adjacent entities.

Parameters
• kernel – a string containing the C code to be executed. Or a 2-tuple of (domains, instructions) to create a loopy kernel (must also set is_loopy_kernel=True). If loopy syntax is used, the domains and instructions should be specified in loopy kernel syntax. See the loopy tutorial for details.

• measure – is a UFL Measure which determines the manner in which the iteration over the mesh is to occur. Alternatively, you can pass direct to designate a direct loop.

• args – is a dictionary mapping variable names in the kernel to Functions or components of mixed Functions and indicates how these Functions are to be accessed.

• kernel_kwargs – keyword arguments to be passed to the Kernel constructor

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

• iterate

Optionally specify which region of an ExtrudedSet to iterate over. Valid values are the following objects from pyop2:

• ON_BOTTOM: iterate over the bottom layer of cells.

• ON_TOP iterate over the top layer of cells.

• ALL iterate over all cells (the default if unspecified)

• ON_INTERIOR_FACETS iterate over all the layers except the top layer, accessing data two adjacent (in the extruded direction) cells at a time.

Example

Assume that A is a Function in CG1 and B is a Function in DG0. Then the following code sets each DoF in A to the maximum value that B attains in the cells adjacent to that DoF:

A.assign(numpy.finfo(0.).min)
par_loop('for (int i=0; i<A.dofs; i++) A[i] = fmax(A[i], B[0]);', dx,
{'A' : (A, RW), 'B': (B, READ)})


The equivalent using loopy kernel syntax is:

domain = '{[i]: 0 <= i < A.dofs}'
instructions = '''
for i
A[i] = max(A[i], B[0])
end
'''
par_loop((domain, instructions), dx, {'A' : (A, RW), 'B': (B, READ)}, is_loopy_kernel=True)


Argument definitions

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

The variable will be read but not written to.

WRITE

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

RW

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

INC

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

Note

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

The measure

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

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

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

The kernel code

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

• Only functions from math.h may be called.

• Pointer operations other than dereferencing arrays are prohibited.

Indirect free variables referencing Functions are all of type double*. For spaces with rank greater than zero (Vector or TensorElement), the data are laid out XYZ… XYZ… XYZ…. With the vector/tensor component moving fastest.

In loopy syntax, these may be addressed using 2D indexing:

A[i, j]


Where i runs over nodes, and j runs over components.

In a direct par_loop(), the variables will all be of type double* with the single index being the vector component.

Constants are always of type double*, both for indirect and direct par_loop() calls.

## firedrake.petsc module¶

class firedrake.petsc.OptionsManager(parameters, options_prefix)[source]

Bases: object

commandline_options = frozenset({'b', 'd'})
count = count(0)

Mixin class that helps with managing setting petsc options.

Parameters
• parameters – The dictionary of parameters to use.

• options_prefix – The prefix to look up items in the global options database (may be None, in which case only entries from parameters will be considered. If no trailing underscore is provided, one is appended. Hence foo_ and foo are treated equivalently. As an exception, if the prefix is the empty string, no underscore is appended.

To use this, you must call its constructor to with the parameters you want in the options database.

You then call set_from_options(), passing the PETSc object you’d like to call setFromOptions on. Note that this will actually only call setFromOptions the first time (so really this parameters object is a once-per-PETSc-object thing).

So that the runtime monitors which look in the options database actually see options, you need to ensure that the options database is populated at the time of a SNESSolve or KSPSolve call. Do that using the inserted_options() context manager.

with self.inserted_options():
self.snes.solve(...)


This ensures that the options database has the relevant entries for the duration of the with block, before removing them afterwards. This is a much more robust way of dealing with the fixed-size options database than trying to clear it out using destructors.

This object can also be used only to manage insertion and deletion into the PETSc options database, by using the context manager.

inserted_options()[source]

Context manager inside which the petsc options database contains the parameters from this object.

options_object = <petsc4py.PETSc.Options object>
set_default_parameter(key, val)[source]

Set a default parameter value.

Parameters
• key – The parameter name

• val – The parameter value.

Ensures that the right thing happens cleaning up the options database.

set_from_options(petsc_obj)[source]

Set up petsc_obj from the options database.

Parameters

petsc_obj – The PETSc object to call setFromOptions on.

Matt says: “Only ever call setFromOptions once”. This function ensures we do so.

## firedrake.plot module¶

firedrake.plot.plot(function, *args, num_sample_points=10, **kwargs)[source]

Plot a 1D Firedrake Function

Parameters
• function – The Function to plot

• args – same as for matplotlib plot

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

• kwargs – same as for matplotlib

Returns

list of matplotlib Line2D

firedrake.plot.quiver(function, **kwargs)[source]

Make a quiver plot of a 2D vector Firedrake Function

Parameters
Returns

matplotlib Quiver object

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

Create a streamline plot of a vector field

Similar to matplotlib streamplot

Parameters
• function – the Firedrake Function to plot

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

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

• max_time – maximum time to integrate a streamline

• start_width – line width at beginning of streamline

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

• tolerance – dimensionless tolerance for adaptive ODE integration

• loc_tolerance – point location tolerance for at()

• kwargs – same as for matplotlib LineCollection

firedrake.plot.tricontour(function, *args, **kwargs)[source]

Create a contour plot of a 2D Firedrake Function

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

Parameters
Returns

matplotlib ContourSet object

firedrake.plot.tricontourf(function, *args, **kwargs)[source]

Create a filled contour plot of a 2D Firedrake Function

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

Parameters
Returns

matplotlib ContourSet object

firedrake.plot.tripcolor(function, *args, **kwargs)[source]

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

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

Parameters
• function – the function to plot

• args – same as for matplotlib tripcolor

• kwargs – same as for matplotlib

Returns

matplotlib PolyCollection object

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

Plot a mesh with a different color for each boundary segment

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

Parameters
• mesh – mesh to be plotted

• axes – matplotlib Axes object on which to plot mesh

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

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

Returns

list of matplotlib Collection objects

firedrake.plot.trisurf(function, *args, **kwargs)[source]

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

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

Parameters
Returns

matplotlib Poly3DCollection object

## firedrake.pointeval_utils module¶

firedrake.pointeval_utils.compile_element(expression, coordinates, parameters=None)[source]

Generates C code for point evaluations.

Parameters
• expression – UFL expression

• coordinates – coordinate field

• parameters – form compiler parameters

Returns

C code as string

## firedrake.pointquery_utils module¶

firedrake.pointquery_utils.X_isub_dX(topological_dimension)[source]
firedrake.pointquery_utils.compile_coordinate_element(ufl_coordinate_element, contains_eps, parameters=None)[source]

Generates C code for changing to reference coordinates.

Parameters

ufl_coordinate_element – UFL element of the coordinates

Returns

C code as string

firedrake.pointquery_utils.compute_celldist(fiat_cell, X='X', celldist='celldist')[source]
firedrake.pointquery_utils.dX_norm_square(topological_dimension)[source]
firedrake.pointquery_utils.init_X(fiat_cell, parameters)[source]
firedrake.pointquery_utils.inside_check(fiat_cell, eps, X='X')[source]
firedrake.pointquery_utils.is_affine(ufl_element)[source]
firedrake.pointquery_utils.make_args(function)[source]
firedrake.pointquery_utils.make_wrapper(function, **kwargs)[source]
firedrake.pointquery_utils.src_locate_cell(mesh, tolerance=None)[source]
firedrake.pointquery_utils.to_reference_coordinates(ufl_coordinate_element, parameters)[source]

## firedrake.projection module¶

firedrake.projection.Projector(v, v_out, bcs=None, solver_parameters=None, form_compiler_parameters=None, constant_jacobian=True, use_slate_for_inverse=False)[source]

A projector projects a UFL expression into a function space and places the result in a function from that function space, allowing the solver to be reused. Projection reverts to an assign operation if v is a Function and belongs to the same function space as v_out.

Parameters
• v – the ufl.Expr or Function to project

• VFunction (or FunctionSpace) to put the result in.

• bcs – an optional set of DirichletBC objects to apply on the target function space.

• solver_parameters – parameters to pass to the solver used when projecting.

• constant_jacobian – Is the projection matrix constant between calls? Say False if you have moving meshes.

• use_slate_for_inverse – compute mass inverse cell-wise using SLATE (only valid for DG function spaces).

firedrake.projection.project(v, V, bcs=None, solver_parameters=None, form_compiler_parameters=None, use_slate_for_inverse=True, name=None)[source]

Project an Expression or Function into a FunctionSpace

Parameters

If V is a Function then v is projected into V and V is returned. If V is a FunctionSpace then v is projected into a new Function and that Function is returned.

## firedrake.randomfunctiongen module¶

This module wraps randomgen and enables users to generate a randomised Function from a FunctionSpace. This module inherits all attributes from randomgen.

class firedrake.randomfunctiongen.DSFMT(seed=None)

Bases: randomgen.dsfmt.DSFMT

Container for the SIMD-based Mersenne Twister pseudo RNG.

Parameters

seed – {None, int, array_like}, optional. Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**32-1], array of integers in [0, 2**32-1] or None (the default). If seed is None, then DSFMT will try to read entropy from /dev/urandom (or the Windows analog) if available to produce a 32-bit seed. If unavailable, a 32-bit 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 a RandomGenerator object.

The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator.

Parallel Features

DSFMT can be used in parallel applications by calling the method jump which advances the state as-if $$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 64-bit 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 32-bit unsigned integer or a vector of 32-bit 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 32-bit 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, “SIMD-oriented Fast Mersenne. Twister: a 128-bit Pseudorandom Number Generator.” Monte Carlo and Quasi-Monte 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.

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the basic RNG

seed(seed=None)

Seed the generator.

seed{None, int, array_like}, optional

Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**32-1], array of integers in [0, 2**32-1] or None (the default). If seed is None, then DSFMT will try to read entropy from /dev/urandom (or the Windows analog) if available to produce a 32-bit seed. If unavailable, a 32-bit hash of the time and process ID is used.

ValueError

If seed values are out of range for the PRNG.

class firedrake.randomfunctiongen.MT19937(seed=None)

Bases: randomgen.mt19937.MT19937

Container for the Mersenne Twister pseudo-random number generator.

Parameters

seed – {None, int, array_like}, optional. Random seed used to initialize the pseudo-random 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 is None, 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 a RandomGenerator object.

The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator.

State and Seeding

The MT19937 state vector consists of a 768 element array of 32-bit 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 32-bit unsigned integer or a vector of 32-bit 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 32-bit 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 to MT19937 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 method jump which advances the state as-if $$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 F2-Linear. Random Number Generators”, INFORMS JOURNAL ON COMPUTING, Vol. 20,. No. 3, Summer 2008, pp. 385-390.

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the core PRNG

seed(seed=None)

Seed the generator.

seed{None, int, array_like}, optional

Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**32-1], array of integers in [0, 2**32-1] or None (the default). If seed is None, then MT19937 will try to read entropy from /dev/urandom (or the Windows analog) if available to produce a 32-bit seed. If unavailable, a 32-bit hash of the time and process ID is used.

ValueError

If seed values are out of range for the PRNG.

class firedrake.randomfunctiongen.PCG32(seed=None, inc=0)

Bases: randomgen.pcg32.PCG32

Container for the PCG-32 pseudo-random number generator.

PCG-32 is a 64-bit implementation of O’Neill’s permutation congruential generator ([1]_, [2]_). PCG-32 has a period of $$2^{64}$$ and supports advancing an arbitrary number of steps as well as $$2^{63}$$ streams.

PCG32 exposes no user-facing API except generator,state, cffi and ctypes. Designed for use in a RandomGenerator 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 pseudo-random number generator. Can be an integer in [0, 2**64] or None (the default). If seed is None, then PCG32 will try to read data from /dev/urandom (or the Windows analog) if available. If unavailable, a 64-bit 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 is None, 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 PCG-32 PRNG is represented by 2 128-bit 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 sub-streams, which are generated by using the same value of seed 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 non-overlapping sequences:

rg = [RandomGenerator(PCG32(1234, i + 1)) for i in range(10)]
for i in range(10):


State and Seeding

The PCG32 state vector consists of 2 unsigned 64-bit values/ PCG32 is seeded using a single 64-bit unsigned integer. In addition, a second 64-bit unsigned integer is used to set the stream.

References

1

“PCG, A Family of Better Random Number Generators”, http://www.pcg-random.org/

2

O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient. Statistically Good Algorithms for Random Number Generation”

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the core PRNG

seed(seed=None, inc=0)

Seed the generator.

This method is called when PCG32 is initialized. It can be called again to re-seed the generator. For details, see PCG32.

seedint, optional

Seed for PCG32.

incint, optional

Increment to use for PCG stream

ValueError

If seed values are out of range for the PRNG.

class firedrake.randomfunctiongen.PCG64(seed=None, inc=0)

Bases: randomgen.pcg64.PCG64

Container for the PCG-64 pseudo-random number generator.

PCG-64 is a 128-bit implementation of O’Neill’s permutation congruential generator ([1]_, [2]_). PCG-64 has a period of $$2^{128}$$ and supports advancing an arbitrary number of steps as well as $$2^{127}$$ streams.

PCG64 exposes no user-facing API except generator,state, cffi and ctypes. Designed for use in a RandomGenerator 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 pseudo-random number generator. Can be an integer in [0, 2**128] or None (the default). If seed is None, then PCG64 will try to read data from /dev/urandom (or the Windows analog) if available. If unavailable, a 64-bit 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 is None, 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 PCG-64 RNG is represented by 2 128-bit 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 sub-streams, which are generated by using the same value of seed 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 non-overlapping sequences:

rg = [RandomGenerator(PCG64(1234, i + 1)) for i in range(10)]
for i in range(10):


State and Seeding

The PCG64 state vector consists of 2 unsigned 128-bit values, which are represented externally as python longs (2.x) or ints (Python 3+). PCG64 is seeded using a single 128-bit unsigned integer (Python long/int). In addition, a second 128-bit unsigned integer is used to set the stream.

References

1

“PCG, A Family of Better Random Number Generators”, http://www.pcg-random.org/

2

O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient. Statistically Good Algorithms for Random Number Generation”

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator using this instance as the core RNG

seed(seed=None, inc=0)

Seed the generator.

This method is called when PCG64 is initialized. It can be called again to re-seed the generator. For details, see PCG64.

seedint, optional

Seed for PCG64.

incint, optional

Increment to use for PCG stream

ValueError

If seed values are out of range for the RNG.

class firedrake.randomfunctiongen.Philox(seed=None, counter=None, key=None)

Bases: randomgen.philox.Philox

Container for the Philox (4x64) pseudo-random number generator.

Parameters
• seed – {None, int, array_like}, optional. Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**64-1], array of integers in [0, 2**64-1] or None (the default). If seed is None, 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 4-element 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 2-element uint64 array. key and seed cannot both be used.

Notes

Philox is a 64-bit PRNG that uses a counter-based 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 non-overlapping sequences to be generated.

Philox exposes no user-facing API except generator, state, cffi and ctypes. Designed for use in a RandomGenerator 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 method jump which advances the state as-if $$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 using jump, 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 256-bit counter encoded as a 4-element uint64 array and a 128-bit key encoded as a 2-element uint64 array. The counter is incremented by 1 for every 4 64-bit randoms produced. The key determines the sequence produced. Using different keys produces independent sequences.

Philox is seeded using either a single 64-bit unsigned integer or a vector of 64-bit 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 64-bit 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.

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the core PRNG

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

Seed the generator.

This method is called when Philox is initialized. It can be called again to re-seed the generator. For details, see Philox.

seedint, optional

Seed for Philox.

counter{int array}, optional

Positive integer less than 2**256 containing the counter position or a 4 element array of uint64 containing the counter

key{int, array}, options

Positive integer less than 2**128 containing the key or a 2 element array of uint64 containing the key

ValueError

If values are out of range for the PRNG.

The two representation of the counter and key are related through array[i] = (value // 2**(64*i)) % 2**64.

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

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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if a and b 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p 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.

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(1-p)^{n-N},$

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”,. Springer-Verlag, 2002.

2

Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill,. 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 wild-cat 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
Returns

Function

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 chi-square distribution.

When df independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chi-square (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), then m * n * k samples are drawn. If size is None (default), a single value is returned if df is a scalar. Otherwise, np.array(df).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized chi-square 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 chi-square distributed, denoted

$Q \sim \chi^2_k.$

The probability density function of the chi-squared 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
Returns

Function

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 1-D array

New in version 1.7.0.

Parameters
• a – 1-D array-like 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), then m * 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 – 1-D array-like, 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 1-dimensional, if a is array-like 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.

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 non-uniform 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 non-uniform 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 array-like 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc, gamma and relation 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.

Parameters

randomfunctiongen.generator.normal – random values from a real-valued 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 semi-definite 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 E-Forum”, 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
Returns

Function

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 Dirichlet-distributed 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), then m * 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 Dirichlet-distributed random vector $$X$$ is proportional to

$p(x) \propto \prod_{i=1}^{k}{x^{\alpha_i-1}_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 Dirichlet-distributed

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
Returns

Function

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

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if scale 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
Returns

Function

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 chi-square 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), then m * n * k samples are drawn. If size is None (default), a single value is returned if dfnum and dfden are both scalars. Otherwise, np.broadcast(dfnum, dfden).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized Fisher distribution.

scipy.stats.f : probability density function, distribution or cumulative density function, etc.

Notes

The F statistic is used to compare in-group variances to between-group 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 between-groups degrees of freedom, while dfden is the within-groups 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.”, McGraw-Hill,. Fifth Edition, 2002.

2

Wikipedia, “F-distribution”, https://en.wikipedia.org/wiki/F-distribution

Examples

An example from Glantz[1], pp 47-40:

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
Returns

Function

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

• scale – float or array_like of floats, optional. The scale of the gamma distribution. Must be non-negative. Default is equal to 1.

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if shape and scale are both scalars. Otherwise, np.broadcast(shape, scale).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized gamma distribution.

scipy.stats.gamma : probability density function, distribution or cumulative density function, etc.

Notes

The probability density for the Gamma distribution is

$p(x) = x^{k-1}\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**(shape-1)*(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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if p 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized Gumbel distribution.

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 “exponential-like” 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 “fat-tailed” 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 100-year 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)

Generate a Function f = Function(V), randomise it by calling the original method hypergeometric (…) with given arguments, and return f.

Parameters
Returns

Function

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.

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), then m * n * k samples are drawn. If size is None (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.

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}{n-x}}{\binom{g+b}{n}},$

where $$0 \le x \le n$$ and $$n-b \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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale 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(x-loc)/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
Returns

Function

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 non-negative. Default is 1.

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized logistic distribution.

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

2

Weisstein, Eric W. “Logistic Distribution.” From. MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LogisticDistribution.html

3

Wikipedia, “Logistic-distribution”, 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((loc-x)/scale)/(scale*(1+np.exp((loc-x)/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
Returns

Function

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 log-normal distribution.

Draw samples from a log-normal 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 non-negative. Default is 1.

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if mean and sigma are both scalars. Otherwise, np.broadcast(mean, sigma).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized log-normal distribution.

scipy.stats.lognorm : probability density function, distribution, cumulative density function, etc.

Notes

A variable x has a log-normal distribution if log(x) is normally distributed. The probability density function for the log-normal 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 log-normal distribution results if a random variable is the product of a large number of independent, identically-distributed variables in the same way that a normal distribution results if the variable is the sum of a large number of independent, identically-distributed variables.

References

1

Limpert, E., Stahel, W. A., and Abbt, M., “Log-normal. 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. 31-32.

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 log-normal 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if p is a scalar. Otherwise, np.array(p).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized logarithmic series distribution.

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(1-p)},$

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. 187-195(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:42-58.

3
1. 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(1-p))
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
Returns

Function

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

Parameters
• n – int or array-like 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 as sum(pvals[:-1]) <= 1).

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * 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 N-dimensional 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=1e-8)

Generate a Function f = Function(V), randomise it by calling the original method multivariate_normal (…) with given arguments, and return f.

Parameters
Returns

Function

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=1e-8)

Draw random samples from a multivariate normal distribution.

The multivariate normal, multinormal or Gaussian distribution is a generalization of the one-dimensional 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 one-dimensional normal distribution.

Parameters
• mean – 1-D array_like, of length N. Mean of the N-dimensional distribution.

• cov – 2-D array_like, of shape (N, N). Covariance matrix of the distribution. It must be symmetric and positive-semidefinite 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 m-by-n-by-k arrangement. Because each sample is N-dimensional, the output shape is (m,n,k,N). If no shape is specified, a single (N-D) 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 N-dimensional value drawn from the distribution.

Notes

The mean is a coordinate in N-dimensional 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 one-dimensional or univariate normal distribution.

Covariance indicates the level to which two variables vary together. From the multivariate normal distribution, we draw N-dimensional 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 non-negative elements, and only on

the diagonal)

This geometrical property can be seen in two dimensions by plotting generated data-points:

mean = [0, 0]
cov = [[1, 0], [0, 100]]  # diagonal covariance


Diagonal covariance means that points are oriented along x or y-axis:

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. nonnegative-definite). 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: McGraw-Hill, 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p 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}(1-p)^{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+n-1}{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 wild-cat 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
Returns

Function

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 chi-square 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. Non-centrality, must be non-negative.

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if df and nonc are both scalars. Otherwise, np.broadcast(df, nonc).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized noncentral chi-square distribution.

Notes

The probability density function for the noncentral Chi-square 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 Chi-square with q degrees of freedom.

References

1

Wikipedia, “Noncentral chi-squared distribution” https://en.wikipedia.org/wiki/Noncentral_chi-squared_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 non-centrality 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
Returns

Function

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 non-centrality 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. Non-centrality 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), then m * n * k samples are drawn. If size is None (default), a single value is returned if dfnum, dfden, and nonc 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 non-central 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 non-central F statistic.

References

1

Weisstein, Eric W. “Noncentral F-Distribution.”. From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NoncentralF-Distribution.html

2

Wikipedia, “Noncentral F-distribution”, https://en.wikipedia.org/wiki/Noncentral_F-distribution

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
Returns

Function

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

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized normal distribution.

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


Two-by-four 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
Returns

Function

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 is mu, where the standard Pareto distribution has location mu = 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 “80-20 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), then m * n * k samples are drawn. If size is None (default), a single value is returned if a is a scalar. Otherwise, np.array(a).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized Pareto distribution.

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 so-called “fat-tailed” 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 23-30.

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 multi-dimensional 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if lam 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
Returns

Function

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

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if a 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^{a-1}, 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 over-reporting 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**(a-1.)
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
Returns

Function

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

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
Returns

Function

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 “half-open” interval [low, high). If high is None (the default), then results are from [0, low).

Parameters
• low – int or array-like 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 array-like 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 array-like, must contain integer values

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * 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 size-shaped 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]).

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

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
Returns

Function

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 non-negative. 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 floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied.

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


Two-by-four 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
Returns

Function

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), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns

int or ndarray of ints size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.

Parameters

randint – Similar to random_integers, only for the half-open interval [low, high), and 0 is the lowest value if high is omitted.

Notes

To sample from N evenly spaced floating-point 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 evenly-spaced 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
Returns

Function

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 half-open 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 (b-a) 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), then m * 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
Returns

Function

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


Three-by-two 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
Returns

Function

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 non-negative. Default is 1.

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if scale 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 zero-mean 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://brighton-webs.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 in-place by shuffling its contents.

This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays 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


Multi-dimensional 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
Returns

Function

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), then m * 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{x-x_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 heavy-tailed distribution, since the Cauchy looks very much like a Gaussian distribution, but with heavier tails.

References

1

NIST/SEMATECH e-Handbook 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
Returns

Function

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), then m * 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
Returns

Function

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

• size – int or tuple of ints, optional. Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if shape 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.

scipy.stats.gamma : probability density function, distribution or cumulative density function, etc.

Notes

The probability density for the Gamma distribution is

$p(x) = x^{k-1}\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**(shape-1) * ((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
Returns

Function

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), then m * 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 floating-point array of shape size of drawn samples, or a single sample if size 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=…)

normal : Equivalent function with additional loc and scale 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)


Two-by-four 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if df 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 t-distribution 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 t-distribution” https://en.wikipedia.org/wiki/Student’s_t-distribution

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, N-1:

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 one-sided t-test, how far out in the distribution does the t statistic appear?:

np.sum(s<t) / float(len(s))
#        0.0090699999999999999  #random


So the p-value 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
Returns

Function

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), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns

ndarray. Drawn samples, with shape size.

Parameters
• randint – Uniform sampling over a given half-open 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if left, mode, and right 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(x-l)}{(r-l)(m-l)}& \text{for l \leq x \leq m},\\ \frac{2(r-x)}{(r-l)(r-m)}& \text{for m \leq x \leq r},\\ 0& \text{otherwise}. \end{cases}\end{split}$

The triangular distribution is often used in ill-defined 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
Returns

Function

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 half-open 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), then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars. Otherwise, np.broadcast(low, high).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized uniform distribution.

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 2-by-2 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 of low will be returned. If high < 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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if mu and kappa are both scalars. Otherwise, np.broadcast(mu, kappa).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized von Mises distribution.

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 Austria-Hungary, 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(x-mu))/(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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if mean and scale 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(x-mean)^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.brighton-webs.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
Returns

Function

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 1-parameter 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 2-parameter 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), then m * n * k samples are drawn. If size is None (default), a single value is returned if a is a scalar. Otherwise, np.array(a).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized Weibull distribution.

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 Rosin-Rammler 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})^{a-1}e^{-(x/\lambda)^a},$

where $$a$$ is the shape and $$\lambda$$ the scale.

The function has its peak (the mode) at $$\lambda(\frac{a-1}{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
Returns

Function

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), then m * n * k samples are drawn. If size is None (default), a single value is returned if a is a scalar. Otherwise, np.array(a).size samples are drawn.

Returns

ndarray or scalar. Drawn samples from the parameterized Zipf distribution.

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.RandomState(brng=None)

Bases: randomgen.mtrand.RandomState

Container for the Mersenne Twister pseudo-random number generator.

RandomState exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D 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 pseudo-random 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 is None, 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 pseudo-random number generator with a number of methods that are similar to the ones available in RandomState. RandomState, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.

property generator
seed(self, *args, **kwargs)

Reseed the basic RNG.

Parameters depend on the basic RNG used.

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.

>>> from numpy.random import MT19937
>>> from numpy.random import RandomState
>>> brng = MT19937(123456789)
>>> rs = RandomState(brng)
>>> brng.seed(987654321)


These best practice examples are equivalent to

>>> rs = RandomState(MT19937())
>>> rs.seed(987654321)

class firedrake.randomfunctiongen.ThreeFry(seed=None, counter=None, key=None)

Bases: randomgen.threefry.ThreeFry

Container for the ThreeFry (4x64) pseudo-random number generator.

Parameters
• seed – {None, int, array_like}, optional. Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**64-1], array of integers in [0, 2**64-1] or None (the default). If seed is None, 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 4-element 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 4-element uint64 array. key and seed cannot both be used.

Notes

ThreeFry is a 64-bit PRNG that uses a counter-based 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 non-overlapping sequences to be generated.

ThreeFry exposes no user-facing API except generator, state, cffi and ctypes. Designed for use in a RandomGenerator 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 method jump which advances the state as-if $$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 using jump, 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 256-bit values encoded as 4-element uint64 arrays. One is a counter which is incremented by 1 for every 4 64-bit 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 64-bit unsigned integer or a vector of 64-bit 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 64-bit 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.

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the core PRNG

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

Seed the generator.

This method is called when ThreeFry is initialized. It can be called again to re-seed the generator. For details, see ThreeFry.

seedint, optional

Seed for ThreeFry.

counter{None, int array}, optional

Positive integer less than 2**256 containing the counter position or a 4 element array of uint64 containing the counter

key{None, int, array}, optional

Positive integer less than 2**256 containing the key or a 4 element array of uint64 containing the key. key and seed cannot be simultaneously used.

ValueError

If values are out of range for the PRNG.

The two representation of the counter and key are related through array[i] = (value // 2**(64*i)) % 2**64.

class firedrake.randomfunctiongen.ThreeFry32(seed=None, counter=None, key=None)

Bases: randomgen.threefry32.ThreeFry32

Container for the ThreeFry (4x32) pseudo-random number generator.

Parameters
• seed – {None, int, array_like}, optional. Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**64-1], array of integers in [0, 2**64-1] or None (the default). If seed is None, 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 4-element 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 4-element uint32 array. key and seed cannot both be used.

Notes

ThreeFry32 is a 32-bit PRNG that uses a counter-based 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 non-overlapping sequences to be generated.

ThreeFry32 exposes no user-facing API except generator, state, cffi and ctypes. Designed for use in a RandomGenerator object.

Compatibility Guarantee

ThreeFry32 guarantees that a fixed seed will always produce the same results.

See TheeFry and Philox closely related PRNG implementations.

Parallel Features

ThreeFry32 can be used in parallel applications by calling the method jump which advances the state as-if $$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 using jump, 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 128-bit values encoded as 4-element uint32 arrays. One is a counter which is incremented by 1 for every 4 32-bit 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 64-bit unsigned integer or a vector of 64-bit 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 64-bit 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.

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the core PRNG

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

Seed the generator.

This method is called when ThreeFry32 is initialized. It can be called again to re-seed the generator. For details, see ThreeFry32.

seedint, optional

Seed for ThreeFry32.

counter{int array}, optional

Positive integer less than 2**128 containing the counter position or a 4 element array of uint32 containing the counter

key{int, array}, options

Positive integer less than 2**128 containing the key or a 4 element array of uint32 containing the key

ValueError

If values are out of range for the PRNG.

The two representation of the counter and key are related through array[i] = (value // 2**(32*i)) % 2**32.

class firedrake.randomfunctiongen.Xoroshiro128(seed=None)

Bases: randomgen.xoroshiro128.Xoroshiro128

Container for the xoroshiro128+ pseudo-random number generator.

Parameters

seed – {None, int, array_like}, optional. Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**64-1], array of integers in [0, 2**64-1] or None (the default). If seed is None, then Xoroshiro128 will try to read data from /dev/urandom (or the Windows analog) if available. If unavailable, a 64-bit 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 64-bit PRNG that uses a carefully handcrafted shift/rotate-based 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 non-overlapping sequences to be generated.

Xoroshiro128 exposes no user-facing API except generator, state, cffi and ctypes. Designed for use in a RandomGenerator 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 method jump which advances the state as-if $$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 64-bit unsigned integers.

Xoroshiro128 is seeded using either a single 64-bit unsigned integer or a vector of 64-bit 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 64-bit 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/

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the basic RNG

seed(seed=None)

Seed the generator.

This method is called at initialized. It can be called again to re-seed the generator.

seed{int, ndarray}, optional

Seed for PRNG. Can be a single 64 biy unsigned integer or an array of 64 bit unsigned integers.

ValueError

If seed values are out of range for the PRNG.

class firedrake.randomfunctiongen.Xorshift1024(seed=None)

Bases: randomgen.xorshift1024.Xorshift1024

Container for the xorshift1024*φ pseudo-random number generator.

xorshift1024*φ is a 64-bit 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 non-overlapping sequences to be generated.

Xorshift1024 exposes no user-facing API except generator, state, cffi and ctypes. Designed for use in a RandomGenerator 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 pseudo-random number generator. Can be an integer in [0, 2**64-1], array of integers in [0, 2**64-1] or None (the default). If seed is None, then Xorshift1024 will try to read data from /dev/urandom (or the Windows analog) if available. If unavailable, a 64-bit 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 method jump which advances the state as-if $$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 64-bit unsigned integers.

Xorshift1024 is seeded using either a single 64-bit unsigned integer or a vector of 64-bit 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 64-bit 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.

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the core PRNG

seed(seed=None, stream=None)

Seed the generator.

This method is called when Xorshift1024 is initialized. It can be called again to re-seed the generator. For details, see Xorshift1024.

seedint, optional

Seed for Xorshift1024.

ValueError

If seed values are out of range for the PRNG.

class firedrake.randomfunctiongen.Xoshiro256StarStar(seed=None)

Bases: randomgen.xoshiro256starstar.Xoshiro256StarStar

Container for the xoshiro256** pseudo-random number generator.

Parameters

seed – {None, int, array_like}, optional. Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**64-1], array of integers in [0, 2**64-1] or None (the default). If seed is None, then Xoshiro256StarStar will try to read data from /dev/urandom (or the Windows analog) if available. If unavailable, a 64-bit hash of the time and process ID is used.

Notes

xoshiro256** is written by David Blackman and Sebastiano Vigna. It is a 64-bit 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 non-overlapping sequences to be generated.

Xoshiro256StarStar exposes no user-facing API except generator, state, cffi and ctypes. Designed for use in a RandomGenerator 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 method jump which advances the state as-if $$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 64-bit unsigned integers.

Xoshiro256StarStar is seeded using either a single 64-bit unsigned integer or a vector of 64-bit 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 64-bit 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/

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the basic RNG

seed(seed=None)

Seed the generator.

This method is called at initialized. It can be called again to re-seed the generator.

seed{int, ndarray}, optional

Seed for PRNG. Can be a single 64 bit unsigned integer or an array of 64 bit unsigned integers.

ValueError

If seed values are out of range for the PRNG.

class firedrake.randomfunctiongen.Xoshiro512StarStar(seed=None)

Bases: randomgen.xoshiro512starstar.Xoshiro512StarStar

Container for the xoshiro512** pseudo-random number generator.

Parameters

seed – {None, int, array_like}, optional. Random seed initializing the pseudo-random number generator. Can be an integer in [0, 2**64-1], array of integers in [0, 2**64-1] or None (the default). If seed is None, then Xoshiro512StarStar will try to read data from /dev/urandom (or the Windows analog) if available. If unavailable, a 64-bit hash of the time and process ID is used.

Notes

xoshiro512** is written by David Blackman and Sebastiano Vigna. It is a 64-bit 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 non-overlapping sequences to be generated.

Xoshiro512StarStar exposes no user-facing API except generator, state, cffi and ctypes. Designed for use in a RandomGenerator 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 method jump which advances the state as-if $$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 64-bit unsigned integers.

Xoshiro512StarStar is seeded using either a single 64-bit unsigned integer or a vector of 64-bit 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 64-bit 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/

property generator

Return a RandomGenerator object

genrandomgen.generator.RandomGenerator

Random generator used this instance as the basic RNG

seed(seed=None)

Seed the generator.

This method is called at initialized. It can be called again to re-seed the generator.

seed{int, ndarray}, optional

Seed for PRNG. Can be a single 64 bit unsigned integer or an array of 64 bit unsigned integers.

ValueError

If seed values are out of range for the PRNG.

## firedrake.solving module¶

firedrake.solving.solve(*args, **kwargs)[source]

Solve linear system Ax = b or variational problem a == L or F == 0.

The Firedrake solve() function can be used to solve either linear systems or variational problems. The following list explains the various ways in which the solve() function can be used.

1. Solving linear systems

A linear system Ax = b may be solved by calling

solve(A, x, b, bcs=bcs, solver_parameters={...})


where A is a Matrix and x and b are Functions. If present, bcs should be a list of DirichletBCs and EquationBCs specifying, respectively, the strong boundary conditions to apply and PDEs to solve on the boundaries. For the format of solver_parameters see below.

2. Solving linear variational problems

A linear variational problem a(u, v) = L(v) for all v may be solved by calling solve(a == L, u, …), where a is a bilinear form, L is a linear form, u is a Function (the solution). Optional arguments may be supplied to specify boundary conditions or solver parameters. Some examples are given below:

solve(a == L, u)
solve(a == L, u, bcs=bc)
solve(a == L, u, bcs=[bc1, bc2])

solve(a == L, u, bcs=bcs,
solver_parameters={"ksp_type": "gmres"})


The linear solver uses PETSc under the hood and accepts all PETSc options as solver parameters. For example, to solve the system using direct factorisation use:

solve(a == L, u, bcs=bcs,
solver_parameters={"ksp_type": "preonly", "pc_type": "lu"})


3. Solving nonlinear variational problems

A nonlinear variational problem F(u; v) = 0 for all v may be solved by calling solve(F == 0, u, …), where the residual F is a linear form (linear in the test function v but possibly nonlinear in the unknown u) and u is a Function (the solution). Optional arguments may be supplied to specify boundary conditions, the Jacobian form or solver parameters. If the Jacobian is not supplied, it will be computed by automatic differentiation of the residual form. Some examples are given below:

The nonlinear solver uses a PETSc SNES object under the hood. To pass options to it, use the same options names as you would for pure PETSc code. See NonlinearVariationalSolver for more details.

solve(F == 0, u)
solve(F == 0, u, bcs=bc)
solve(F == 0, u, bcs=[bc1, bc2])

solve(F == 0, u, bcs, J=J,
# Use Newton-Krylov iterations to solve the nonlinear
# system, using direct factorisation to solve the linear system.
solver_parameters={"snes_type": "newtonls",
"ksp_type" : "preonly",
"pc_type" : "lu"})


In all three cases, if the operator is singular you can pass a VectorSpaceBasis (or MixedVectorSpaceBasis) spanning the null space of the operator to the solve call using the nullspace keyword argument.

If you need to project the transpose nullspace out of the right hand side, you can do so by using the transpose_nullspace keyword argument.

In the same fashion you can add the near nullspace using the near_nullspace keyword argument.

## firedrake.solving_utils module¶

firedrake.solving_utils.check_snes_convergence(snes)[source]

## firedrake.supermeshing module¶

firedrake.supermeshing.assemble_mixed_mass_matrix(V_A, V_B)[source]

Construct the mixed mass matrix of two function spaces, using the TrialFunction from V_A and the TestFunction from V_B.

firedrake.supermeshing.intersection_finder()

## firedrake.tsfc_interface module¶

Provides the interface to TSFC for compiling a form, and transforms the TSFC-generated code to make it suitable for passing to the backends.

class firedrake.tsfc_interface.KernelInfo(kernel, integral_type, oriented, subdomain_id, domain_number, coefficient_map, needs_cell_facets, pass_layer_arg, needs_cell_sizes)

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(*args, **kwargs)[source]

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.clear_cache(comm=None)[source]

Clear the Firedrake TSFC kernel cache.

firedrake.tsfc_interface.compile_form(form, name, parameters=None, split=True, interface=None, coffee=False, diagonal=False)[source]

Compile a form using TSFC.

Parameters
• form – the Form to compile.

• name – a prefix for the generated kernel functions.

• parameters – optional dict of parameters to pass to the form compiler. If not provided, parameters are read from the form_compiler slot of the Firedrake parameters dictionary (which see).

• split – If False, then don’t split mixed forms.

• coffee – compile coffee kernel instead of loopy kernel

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

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

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

## firedrake.ufl_expr module¶

class firedrake.ufl_expr.Argument(function_space, number, part=None)[source]

Representation of the argument to a form.

Parameters
• function_space – the FunctionSpace the argument corresponds to.

• number – the number of the argument being constructed.

• part – optional index (mostly ignored).

Note

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

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

A symbolic representation of the cell size of a mesh.

Parameters

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

firedrake.ufl_expr.FacetNormal(mesh)[source]

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

Parameters

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

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

Build a test function on the specified function space.

Parameters
firedrake.ufl_expr.TestFunctions(function_space)[source]

Return a tuple of test functions on the specified function space.

Parameters

function_space – the FunctionSpace to build the test functions on.

This returns len(function_space) test functions, which, if the function space is a MixedFunctionSpace, are indexed appropriately.

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

Build a trial function on the specified function space.

Parameters
firedrake.ufl_expr.TrialFunctions(function_space)[source]

Return a tuple of trial functions on the specified function space.

Parameters

function_space – the FunctionSpace to build the trial functions on.

This returns len(function_space) trial functions, which, if the function space is a MixedFunctionSpace, are indexed appropriately.

firedrake.ufl_expr.action(form, coefficient)[source]

Compute the action of a form on a coefficient.

Parameters
Returns

a symbolic expression for the action.

firedrake.ufl_expr.adjoint(form, reordered_arguments=None)[source]

Compute the adjoint of a form.

Parameters
• form – A UFL form, or a Slate tensor.

• reordered_arguments – arguments to use when creating the adjoint. Ignored if form is a Slate tensor.

If the form is a slate tensor, this just returns its transpose. Otherwise, given a bilinear form, compute the adjoint form by changing the ordering (number) of the test and trial functions.

By default, new Argument objects will be created with opposite ordering. However, if the adjoint form is to be added to other forms later, their arguments must match. In that case, the user must provide a tuple reordered_arguments=(u2,v2).

firedrake.ufl_expr.derivative(form, u, du=None, coefficient_derivatives=None)[source]

Compute the derivative of a form.

Given a form, this computes its linearization with respect to the provided Function. The resulting form has one additional Argument in the same finite element space as the Function.

Parameters
Raises

ValueError – If any of the coefficients in form were obtained from u.split(). UFL doesn’t notice that these are related to u and so therefore the derivative is wrong (instead one should have written split(u)).

See also ufl.derivative().

## firedrake.utility_meshes module¶

firedrake.utility_meshes.BoxMesh(nx, ny, nz, Lx, Ly, Lz, reorder=None, distribution_parameters=None, diagonal='default', comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a mesh of a 3D box.

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

• ny – The number of cells in the y direction

• nz – The number of cells in the z direction

• Lx – The extent in the x direction

• Ly – The extent in the y direction

• Lz – The extent in the z direction

• diagonal – Two ways of cutting hexadra, should be cut into 6 tetrahedra ("default"), or 5 tetrahedra thus less biased ("crossed")

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

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

The boundary surfaces are numbered as follows:

• 1: plane x == 0

• 2: plane x == Lx

• 3: plane y == 0

• 4: plane y == Ly

• 5: plane z == 0

• 6: plane z == Lz

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

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

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

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

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

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

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

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

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

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

firedrake.utility_meshes.PeriodicBoxMesh(nx, ny, nz, Lx, Ly, Lz, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a periodic mesh of a 3D box.

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

• ny – The number of cells in the y direction

• nz – The number of cells in the z direction

• Lx – The extent in the x direction

• Ly – The extent in the y direction

• Lz – The extent in the z direction

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

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

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

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

• 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.PeriodicUnitCubeMesh(nx, ny, nz, reorder=None, distribution_parameters=None, comm=<mpi4py.MPI.Intracomm object>)[source]

Generate a periodic mesh of a unit cube

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

• ny – The number of cells in the y direction

• nz – The number of cells in the z direction

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

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

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

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

• 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

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

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

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

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

Generate a mesh of the unit disk in 2D

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

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

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

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.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.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 higher-order non-vertex nodes are on lines of latitude to a mesh where these nodes are just pushed out radially from the equivalent P1 mesh. (defaults to z0=0.8).

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

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

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

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

firedrake.utils.known_pyop2_safe(f)[source]

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

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

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

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

## firedrake.variational_solver module¶

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

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

Parameters
• a – the bilinear form

• L – the linear form

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

• bcs – the boundary conditions (optional)

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

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

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

class firedrake.variational_solver.LinearVariationalSolver(*args, **kwargs)[source]

Solves a LinearVariationalProblem.

Parameters
• problem – A LinearVariationalProblem to solve.

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

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

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

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

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

invalidate_jacobian`()[source]