algorithms Package

algorithms Package

This module collects algorithms and utility functions operating on UFL objects.

ad Module

Front-end for AD routines.

ufl.algorithms.ad.expand_derivatives(form, dim=None, apply_expand_compounds_before=True, apply_expand_compounds_after=False, use_alternative_wrapper_algorithm=False)

Expand all derivatives of expr.

In the returned expression g which is mathematically equivalent to expr, there are no VariableDerivative or CoefficientDerivative objects left, and Grad objects have been propagated to Terminal nodes.

analysis Module

Utility algorithms for inspection of and information extraction from UFL objects in various ways.

class ufl.algorithms.analysis.IntegralData(domain_type, domain_id, integrals, metadata)

Bases: object

Utility class with the members
(domain_type, domain_id, integrals, metadata)

where metadata is an empty dictionary that may be used for associating metadata with each object.

domain_id
domain_type
integrals
metadata
ufl.algorithms.analysis.build_argument_replace_map(arguments, coefficients, element_mapping=None)

Create new Argument and Coefficient objects with count starting at 0. Return mapping from old to new objects, and lists of the new objects.

ufl.algorithms.analysis.count_nodes(expr, ids=None)

Count the number of unique Expr instances in expression.

ufl.algorithms.analysis.estimate_quadrature_degree(integral)

Estimate the necessary quadrature order for integral using the sum of argument degrees.

ufl.algorithms.analysis.extract_arguments(a)

Build a sorted list of all arguments in a, which can be a Form, Integral or Expr.

ufl.algorithms.analysis.extract_arguments_and_coefficients(a)

Build two sorted lists of all arguments and coefficients in a, which can be a Form, Integral or Expr.

ufl.algorithms.analysis.extract_classes(a)

Build a set of all unique Expr subclasses used in a. The argument a can be a Form, Integral or Expr.

ufl.algorithms.analysis.extract_coefficients(a)

Build a sorted list of all coefficients in a, which can be a Form, Integral or Expr.

ufl.algorithms.analysis.extract_domain_data(form)

Extract the domain_data attached to integrals of each domain type in form.

ufl.algorithms.analysis.extract_duplications(expression)

Build a set of all repeated expressions in expression.

ufl.algorithms.analysis.extract_element_map(elements)

Build map from elements to element index in ordered tuple.

ufl.algorithms.analysis.extract_elements(form)

Build sorted tuple of all elements used in form.

ufl.algorithms.analysis.extract_indices(expression)

Build a set of all Index objects used in expression.

ufl.algorithms.analysis.extract_max_quadrature_element_degree(integral)

Extract quadrature integration order from quadrature elements in integral. Returns None if not found.

ufl.algorithms.analysis.extract_num_sub_domains(form)

Extract the upper limit of sub domain ids for each domain type.

ufl.algorithms.analysis.extract_sub_elements(elements)

Build sorted tuple of all sub elements (including parent element).

ufl.algorithms.analysis.extract_terminals(a)

Build a set of all Terminal objects in a.

ufl.algorithms.analysis.extract_type(a, ufl_type)

Build a set of all objects of class ufl_type found in a. The argument a can be a Form, Integral or Expr.

ufl.algorithms.analysis.extract_unique_elements(form)

Build sorted tuple of all unique elements used in form.

ufl.algorithms.analysis.extract_unique_sub_elements(elements)

Build sorted tuple of all unique sub elements (including parent element).

ufl.algorithms.analysis.extract_variables(a)

Build a list of all Variable objects in a, which can be a Form, Integral or Expr. The ordering in the list obeys dependency order.

ufl.algorithms.analysis.has_type(a, ufl_types)

Check if any class from ufl_types is found in a. The argument a can be a Form, Integral or Expr.

ufl.algorithms.analysis.sort_elements(elements)

Sort elements so that any sub elements appear before the corresponding mixed elements. This is useful when sub elements need to be defined before the corresponding mixed elements.

The ordering is based on sorting a directed acyclic graph.

ufl.algorithms.analysis.unique_tuple(objects)

Return sorted tuple of unique objects.

argument_dependencies Module

Algorithms for analysing argument dependencies in expressions.

class ufl.algorithms.argument_dependencies.ArgumentDependencyExtracter

Bases: ufl.algorithms.transformer.Transformer

argument(o)
cell_avg(o, a)

Nonterminals that are linear with a single argument.

component_tensor(o, f, i)
conditional(o, cond, t, f)

Considering EQ, NE, LE, GE, LT, GT nonlinear in this context.

cross(o, *opdeps)
curl(o, a)

Nonterminals that are linear with a single argument.

div(o, a)

Nonterminals that are linear with a single argument.

division(o, a, b)

Arguments cannot be in the denominator.

dot(o, *opdeps)
expr(o, *opdeps)

Default for nonterminals: nonlinear in all operands.

facet_avg(o, a)

Nonterminals that are linear with a single argument.

grad(o, a)

Nonterminals that are linear with a single argument.

index_sum(o, f, i)

Index sums inherit the dependencies of their summand.

indexed(o, f, i)
inner(o, *opdeps)
linear(o, a)

Nonterminals that are linear with a single argument.

list_tensor(o, *opdeps)

Require same dependencies for all listtensor entries.

negative_restricted(o, a)

Nonterminals that are linear with a single argument.

outer(o, *opdeps)
positive_restricted(o, a)

Nonterminals that are linear with a single argument.

product(o, *opdeps)
skew(o, a)

Nonterminals that are linear with a single argument.

spatial_derivative(o, a, b)
sum(o, *opdeps)

Sums can contain both linear and bilinear terms (we could change this to require that all operands have the same dependencies).

terminal(o)

Default for terminals: no dependency on Arguments.

trace(o, a)

Nonterminals that are linear with a single argument.

transposed(o, a)

Nonterminals that are linear with a single argument.

variable(o)
variable_derivative(o, a, b)
exception ufl.algorithms.argument_dependencies.NotMultiLinearException(*args, **kwargs)

Bases: exceptions.Exception

ufl.algorithms.argument_dependencies.extract_argument_dependencies(e)

Extract a set of sets of Arguments.

checks Module

Functions to check the validity of forms.

ufl.algorithms.checks.validate_form(form)

Performs all implemented validations on a form. Raises exception if something fails.

deprecated Module

Stuff in this file will probably be removed.

class ufl.algorithms.deprecated.DuplicationMarker(duplications)

Bases: ufl.algorithms.transformer.ReuseTransformer

argument(o)
coefficient(o)
constant(o)
expr(o, *ops)
facet_normal(o)
variable(o)
wrap_terminal(o)
class ufl.algorithms.deprecated.DuplicationPurger

Bases: ufl.algorithms.transformer.ReuseTransformer

Replace all duplicated nodes from an UFL Expr.

expr(x, *ops)
terminal(x)
class ufl.algorithms.deprecated.TreeFlattener

Bases: ufl.algorithms.transformer.ReuseTransformer

product(o, *ops)
sum(o, *ops)
sum_or_product(o, *ops)
ufl.algorithms.deprecated.flatten(e)

Convert an UFL expression to a new UFL expression, with sums and products flattened from binary tree nodes to n-ary tree nodes.

ufl.algorithms.deprecated.mark_duplications(e)

Wrap subexpressions that are equal (completely equal, not mathematically equivalent) in Variable objects to facilitate subexpression reuse.

ufl.algorithms.deprecated.purge_duplications(e)

Replace any subexpressions in expression that occur more than once with a single instance.

domain_analysis Module

Algorithm sketch to build canonical data structure for integrals over subdomains.

class ufl.algorithms.domain_analysis.ExprTupleKey(x)

Bases: object

x
ufl.algorithms.domain_analysis.build_sub_integral_list(itgs)
ufl.algorithms.domain_analysis.canonicalize_sub_integral_data(sub_integrals)
ufl.algorithms.domain_analysis.convert_sub_integral_data_to_integral_data(sub_integral_data)
ufl.algorithms.domain_analysis.expr_tuple_key(expr)
ufl.algorithms.domain_analysis.extract_domain_data_from_integral_dict(integrals)
ufl.algorithms.domain_analysis.extract_domain_data_from_integral_list(integrals)
ufl.algorithms.domain_analysis.extract_integral_data_from_integral_dict(integrals)
ufl.algorithms.domain_analysis.integral_dict_to_sub_integral_data(integrals)
ufl.algorithms.domain_analysis.integral_domain_ids(integral)
ufl.algorithms.domain_analysis.print_sub_integral_data(sub_integral_data)
ufl.algorithms.domain_analysis.reconstruct_form_from_sub_integral_data(sub_integral_data, domain_data=None)

elementtransformations Module

ufl.algorithms.elementtransformations.change_regularity(element, family)

For a given finite element, return the corresponding space specified by ‘family’.

ufl.algorithms.elementtransformations.increase_order(element)

Return element of same family, but a polynomial degree higher.

ufl.algorithms.elementtransformations.tear(V)

For a finite element, return the corresponding discontinuous element.

estimate_degrees Module

Algorithms for estimating polynomial degrees of expressions.

class ufl.algorithms.estimate_degrees.SumDegreeEstimator(default_degree, element_replace_map)

Bases: ufl.algorithms.transformer.Transformer

This algorithm is exact for a few operators and heuristic for many.

abs(v, a)

This is a heuristic, correct if there is no

atan_2(v, a, b)

Using the heuristic degree(atan2(const,const)) == 0 degree(atan2(a,b)) == max(degree(a),degree(b))+2 which can be wildly inaccurate but at least gives a somewhat high integration degree.

bessel_function(v, nu, x)

Using the heuristic degree(bessel_*(const)) == 0 degree(bessel_*(x)) == degree(x)+2 which can be wildly inaccurate but at least gives a somewhat high integration degree.

cell_avg(v, a)

Cell average of a function is always cellwise constant.

cofactor(v, *args)
component_tensor(v, A, ii)
compound_derivative(v, *args)
compound_tensor_operator(v, *args)
condition(v, *args)
conditional(v, c, t, f)

Degree of condition does not influence degree of values which conditional takes. So heuristicaly taking max of true degree and false degree. This will be exact in cells where condition takes single value. For improving accuracy of quadrature near condition transition surface quadrature order must be adjusted manually.

constant_value(v)

Constant values are constant. Duh.

cross(v, *ops)
curl(v, f)
derivative(v, *args)
determinant(v, *args)
deviatoric(v, *args)
div(v, f)
division(v, *ops)

Using the sum here is a heuristic. Consider e.g. (x+1)/(x-1).

dot(v, *ops)
expr(v, *ops)

For most operators we take the max degree of its operands.

facet_avg(v, a)

Facet average of a function is always cellwise constant.

form_argument(v)

A form argument provides a degree depending on the element, or the default degree if the element has no degree.

geometric_quantity(v)

Most geometric quantities are cellwise constant.

grad(v, f)
index_sum(v, A, ii)
indexed(v, A, ii)
inner(v, *ops)
inverse(v, *args)
label(v)
list_tensor(v, *ops)
local_coordinate(v)

A coordinate provides one additional degree.

math_function(v, a)

Using the heuristic degree(sin(const)) == 0 degree(sin(a)) == degree(a)+2 which can be wildly inaccurate but at least gives a somewhat high integration degree.

multi_index(v)
nabla_div(v, f)
nabla_grad(v, f)
negative_restricted(v, a)
outer(v, *ops)
positive_restricted(v, a)
power(v, a, b)

If b is an integer: degree(a**b) == degree(a)*b otherwise use the heuristic degree(a**b) == degree(a)*2

product(v, *ops)
skew(v, *args)
spatial_coordinate(v)

A coordinate provides one additional degree.

sum(v, *ops)
sym(v, *args)
trace(v, *args)
transposed(v, A)
variable(v, e, l)
variable_derivative(v, *args)
ufl.algorithms.estimate_degrees.estimate_total_polynomial_degree(e, default_degree=1, element_replace_map={})

Estimate total polynomial degree of integrand.

NB! Although some compound types are supported here, some derivatives and compounds must be preprocessed prior to degree estimation. In generic code, this algorithm should only be applied after preprocessing.

For coefficients defined on an element with unspecified degree (None), the degree is set to the given default degree.

expand_compounds Module

Algorithm for expanding compound expressions into equivalent representations using basic operators.

class ufl.algorithms.expand_compounds.CompoundExpander(geometric_dimension)

Bases: ufl.algorithms.transformer.ReuseTransformer

Expands compound expressions to equivalent representations using basic operators.

cofactor(o, A)
cross(o, a, b)
curl(o, a)
determinant(o, A)
deviatoric(o, A)
div(o, a)
dot(o, a, b)
grad(o, a)
inner(o, a, b)
inverse(o, A)
nabla_div(o, a)
nabla_grad(o, a)
outer(o, a, b)
skew(o, A)
sym(o, A)
trace(o, A)
transposed(o, A)
class ufl.algorithms.expand_compounds.CompoundExpanderPostDiff(dim)

Bases: ufl.algorithms.expand_compounds.CompoundExpander

curl(o, a, i)
div(o, a, i)
nabla_div(o, a, i)
nabla_grad(o, a, i)
class ufl.algorithms.expand_compounds.CompoundExpanderPreDiff(dim)

Bases: ufl.algorithms.expand_compounds.CompoundExpander

curl(o, a)
div(o, a)
grad(o, a)
nabla_div(o, a)
nabla_grad(o, a)
ufl.algorithms.expand_compounds.expand_compounds(e, dim=None)

Expand compound objects into basic operators. Requires e to have a well defined geometric dimension.

ufl.algorithms.expand_compounds.expand_compounds1(e, dim=None)

Expand compound objects into basic operators. Requires e to have a well defined geometric dimension.

ufl.algorithms.expand_compounds.expand_compounds2(e, dim=None)

Expand compound objects into basic operators. Requires e to have a well defined geometric dimension.

ufl.algorithms.expand_compounds.expand_compounds_postdiff(e, dim=None)

Expand compound objects into basic operators. Requires e to have a well defined geometric dimension.

ufl.algorithms.expand_compounds.expand_compounds_prediff(e, dim=None)

Expand compound objects into basic operators. Requires e to have a well defined geometric dimension.

expand_indices Module

This module defines expression transformation utilities, for expanding free indices in expressions to explicit fixed indices only.

class ufl.algorithms.expand_indices.IndexExpander

Bases: ufl.algorithms.transformer.ReuseTransformer

...

component()

Return current component tuple.

component_tensor(x)
division(x)
form_argument(x)
grad(x)
index_sum(x)
indexed(x)
list_tensor(x)
multi_index(x)
scalar_value(x)
terminal(x)
zero(x)
ufl.algorithms.expand_indices.expand_indices(e)
ufl.algorithms.expand_indices.purge_list_tensors(e)

Get rid of all ListTensor instances by expanding expressions to use their components directly. Will usually increase the size of the expression.

formdata Module

FormData class easy for collecting of various data about a form.

class ufl.algorithms.formdata.ExprData

Bases: object

Class collecting various information extracted from a Expr by calling preprocess.

Create empty expr data for given expr.

class ufl.algorithms.formdata.FormData

Bases: object

Class collecting various information extracted from a Form by calling preprocess.

Create empty form data for given form.

validate(object_names=None, common_cell=None, element_mapping=None)

Validate that the form data was built from the same inputs.

formfiles Module

A collection of utility algorithms for handling UFL files.

class ufl.algorithms.formfiles.FileData

Bases: object

ufl.algorithms.formfiles.execute_ufl_code(uflcode, filename)
ufl.algorithms.formfiles.interpret_ufl_namespace(namespace)

Takes a namespace dict from an executed ufl file and converts it to a FileData object.

ufl.algorithms.formfiles.load_forms(filename)

Return a list of all forms in a file.

ufl.algorithms.formfiles.load_ufl_file(filename)

Load a .ufl file with elements, coefficients and forms.

ufl.algorithms.formfiles.read_ufl_file(filename)

Read a .ufl file, handling file extension, file existance, and #include replacement.

ufl.algorithms.formfiles.replace_include_statements(code)

Replace ‘#include foo.ufl’ statements with contents of foo.ufl.

formtransformations Module

This module defines utilities for transforming complete Forms into new related Forms.

class ufl.algorithms.formtransformations.PartExtracter(arguments)

Bases: ufl.algorithms.transformer.Transformer

PartExtracter extracts those parts of a form that contain the given argument(s).

argument(x)

Return itself unless itself provides too much.

cell_avg(x, arg)

A linear operator with a single operand accepting arity > 0, providing whatever Argument its operand does.

component_tensor(x)

Return parts of expression belonging to this indexed expression.

division(x)

Return parts_of_numerator/denominator.

dot(x, *ops)

Note: Product is a visit-children-first handler. ops are the visited factors.

expr(x)

The default is a nonlinear operator not accepting any Arguments among its children.

facet_avg(x, arg)

A linear operator with a single operand accepting arity > 0, providing whatever Argument its operand does.

grad(x, arg)

A linear operator with a single operand accepting arity > 0, providing whatever Argument its operand does.

index_sum(x)

Return parts of expression belonging to this indexed expression.

indexed(x)

Return parts of expression belonging to this indexed expression.

inner(x, *ops)

Note: Product is a visit-children-first handler. ops are the visited factors.

linear_indexed_type(x)

Return parts of expression belonging to this indexed expression.

linear_operator(x, arg)

A linear operator with a single operand accepting arity > 0, providing whatever Argument its operand does.

list_tensor(x, *ops)
negative_restricted(x, arg)

A linear operator with a single operand accepting arity > 0, providing whatever Argument its operand does.

outer(x, *ops)

Note: Product is a visit-children-first handler. ops are the visited factors.

positive_restricted(x, arg)

A linear operator with a single operand accepting arity > 0, providing whatever Argument its operand does.

product(x, *ops)

Note: Product is a visit-children-first handler. ops are the visited factors.

spatial_derivative(x)

Return parts of expression belonging to this indexed expression.

sum(x)

Return the terms that might eventually yield the correct parts(!)

The logic required for sums is a bit elaborate:

A sum may contain terms providing different arguments. We should return (a sum of) a suitable subset of these terms. Those should all provide the same arguments.

For each term in a sum, there are 2 simple possibilities:

1a) The relevant part of the term is zero -> skip. 1b) The term provides more arguments than we want -> skip

2) If all terms fall into the above category, we can just return zero.

Any remaining terms may provide exactly the arguments we want, or fewer. This is where things start getting interesting.

3) Bottom-line: if there are terms with providing different arguments – provide terms that contain the most arguments. If there are terms providing different sets of same size -> throw error (e.g. Argument(-1) + Argument(-2))

terminal(x)

The default is a nonlinear operator not accepting any Arguments among its children.

variable(x)

Return relevant parts of this variable.

ufl.algorithms.formtransformations.compute_energy_norm(form, coefficient)

Compute the a-norm of a Coefficient given a form a.

This works simply by replacing the two Arguments with a Coefficient on the same function space (element). The Form returned will thus be a functional with no Arguments, and one additional Coefficient at the end if no coefficient has been provided.

ufl.algorithms.formtransformations.compute_form_action(form, coefficient)

Compute the action of a form on a Coefficient.

This works simply by replacing the last Argument with a Coefficient on the same function space (element). The form returned will thus have one Argument less and one additional Coefficient at the end if no Coefficient has been provided.

ufl.algorithms.formtransformations.compute_form_adjoint(form, reordered_arguments=None)

Compute the adjoint of a bilinear form.

This works simply by changing the ordering (count) of the two arguments.

ufl.algorithms.formtransformations.compute_form_arities(form)

Return set of arities of terms present in form.

ufl.algorithms.formtransformations.compute_form_functional(form)

Compute the functional part of a form, that is the terms independent of Arguments.

(Used for testing, not sure if it’s useful for anything?)

ufl.algorithms.formtransformations.compute_form_lhs(form)

Compute the left hand side of a form.

Example:

a = u*v*dx + f*v*dx a = lhs(a) -> u*v*dx
ufl.algorithms.formtransformations.compute_form_rhs(form)

Compute the right hand side of a form.

Example:

a = u*v*dx + f*v*dx L = rhs(a) -> -f*v*dx
ufl.algorithms.formtransformations.compute_form_with_arity(form, arity, arguments=None)

Compute parts of form of given arity.

ufl.algorithms.formtransformations.zero(e)

forward_ad Module

Forward mode AD implementation.

class ufl.algorithms.forward_ad.CoefficientAD(spatial_dim, coefficients, arguments, coefficient_derivatives, cache=None)

Bases: ufl.algorithms.forward_ad.ForwardAD

Apply AFD (Automatic Functional Differentiation) to expression.

coefficient(o)
grad(g)
variable(o)
class ufl.algorithms.forward_ad.ForwardAD(spatial_dim, var_shape, var_free_indices, var_index_dimensions, cache=None)

Bases: ufl.algorithms.transformer.Transformer

abs(o, a)
acos(o, a)
asin(o, a)
atan(o, a)
atan_2(o, a, b)
bessel_i(o, nu, x)
bessel_j(o, nu, x)
bessel_k(o, nu, x)
bessel_y(o, nu, x)
binary_condition(o, l, r)
cell_avg(o, a)
component_tensor(o)
conditional(o, c, t, f)
cos(o, a)
cosh(o, a)
derivative(o)
division(o, a, b)
erf(o, a)
exp(o, a)
expr(o)
facet_avg(o, a)
grad(o)
index_sum(o)
indexed(o)
list_tensor(o, *ops)
ln(o, a)
math_function(o, a)
multi_index(o)
not_condition(o, c)
power(o, a, b)
product(o, *ops)
restricted(o, a)
sin(o, a)
sinh(o, a)
sqrt(o, a)
sum(o, *ops)
tan(o, a)
tanh(o, a)
terminal(o)

Terminal objects are assumed independent of the differentiation variable by default, and simply ‘lifted’ to the pair (o, 0). Depending on the context, override this with custom rules for non-zero derivatives.

variable(o)

Variable objects are just ‘labels’, so by default the derivative of a variable is the derivative of its referenced expression.

xspatial_derivative(o)
class ufl.algorithms.forward_ad.GradAD(spatial_dim, cache=None)

Bases: ufl.algorithms.forward_ad.ForwardAD

constant(o)

Terminal objects are assumed independent of the differentiation variable by default, and simply ‘lifted’ to the pair (o, 0). Depending on the context, override this with custom rules for non-zero derivatives.

facet_normal(o)

Terminal objects are assumed independent of the differentiation variable by default, and simply ‘lifted’ to the pair (o, 0). Depending on the context, override this with custom rules for non-zero derivatives.

form_argument(o)

Represent grad(f) as Grad(f).

grad(o)

Represent grad(grad(f)) as Grad(Grad(f)).

spatial_coordinate(o)

Gradient of x w.r.t. x is Id.

class ufl.algorithms.forward_ad.UnimplementedADRules

Bases: object

cofactor(o, a)
cross(o, a, b)
determinant(o, a)
inverse(o, a)

Derivation: 0 = d/dx [Ainv*A] = Ainv’ * A + Ainv * A’ Ainv’ * A = - Ainv * A’ Ainv’ = - Ainv * A’ * Ainv

class ufl.algorithms.forward_ad.UnusedADRules

Bases: object

commute(o, a)

This should work for all single argument operators that commute with d/dw with w scalar.

curl(o, a)

This should work for all single argument operators that commute with d/dw with w scalar.

deviatoric(o, a)

This should work for all single argument operators that commute with d/dw with w scalar.

div(o, a)

This should work for all single argument operators that commute with d/dw with w scalar.

dot(o, a, b)
grad(o, a)
inner(o, a, b)
outer(o, a, b)
trace(o, a)

This should work for all single argument operators that commute with d/dw with w scalar.

transposed(o, a)

This should work for all single argument operators that commute with d/dw with w scalar.

class ufl.algorithms.forward_ad.VariableAD(spatial_dim, var, cache=None)

Bases: ufl.algorithms.forward_ad.ForwardAD

grad(o)
variable(o)
ufl.algorithms.forward_ad.apply_nested_forward_ad(expr, dim)
ufl.algorithms.forward_ad.compute_coefficient_forward_ad(f, w, v, cd, dim)
ufl.algorithms.forward_ad.compute_grad_forward_ad(f, dim)
ufl.algorithms.forward_ad.compute_variable_forward_ad(f, v, dim)

graph Module

Algorithms for working with linearized computational graphs.

class ufl.algorithms.graph.Graph(expression)

Graph class which computes connectivity on demand.

E()
Ein()
Eout()
V()
Vin()
Vout()
class ufl.algorithms.graph.HeapItem(incoming, outgoing, i)

Bases: object

class ufl.algorithms.graph.StringDependencyDefiner(argument_deps=None, coefficient_deps=None)

Bases: ufl.algorithms.multifunction.MultiFunction

Given an expr, returns a frozenset of its dependencies.

Possible dependency values are:
“c” - depends on runtime information like the cell, local<->global coordinate mappings, facet normals, or coefficients “x” - depends on local coordinates “v%d” % i - depends on argument i, for i in [0,rank)
argument(x)
coefficient(x)
constant(x)
expr(o)
facet_normal(o)
geometric_quantity(x)
spatial_derivative(o)
ufl.algorithms.graph.all_is(seq1, seq2)
ufl.algorithms.graph.build_graph(expr)

Build a linearized graph from an UFL Expr.

Returns G = (V, E), with V being a list of graph nodes (Expr objects) in post traversal ordering and E being a list of edges. Each edge is represented as a (i, j) tuple where i and j are vertex indices into V.

ufl.algorithms.graph.depth_first_ordering(G)
ufl.algorithms.graph.extract_edges(G)

Build lists of incoming and outgoing edges to and from each vertex in a linearized graph.

Returns lists Ein and Eout.

ufl.algorithms.graph.extract_incoming_edges(G)

Build lists of incoming edges to each vertex in a linearized graph.

ufl.algorithms.graph.extract_incoming_vertex_connections(G)

Build lists of vertices in incoming and outgoing edges to and from each vertex in a linearized graph.

Returns lists Vin and Vout.

ufl.algorithms.graph.extract_outgoing_edges(G)

Build list of outgoing edges from each vertex in a linearized graph.

ufl.algorithms.graph.extract_outgoing_vertex_connections(G)

Build lists of vertices in incoming and outgoing edges to and from each vertex in a linearized graph.

Returns lists Vin and Vout.

ufl.algorithms.graph.extract_vertex_connections(G)

Build lists of vertices in incoming and outgoing edges to and from each vertex in a linearized graph.

Returns lists Vin and Vout.

ufl.algorithms.graph.find_dependencies(G, targets)

Find the set of vertices in a computational graph that a set of target vertices depend on.

ufl.algorithms.graph.format_graph(G)
ufl.algorithms.graph.join_lines(sequence)
ufl.algorithms.graph.len_items(sequence)
ufl.algorithms.graph.lists(n)
ufl.algorithms.graph.partition(G, criteria=<function string_set_criteria>)
ufl.algorithms.graph.rebuild_tree(G)

Rebuild expression tree from linearized graph.

Does not touch the input graph. Assumes the graph is directed, acyclic, and connected, such that there is only one root node.

ufl.algorithms.graph.reorder(sequence, ordering)

Rearrange the items in a sequence.

ufl.algorithms.graph.string_set_criteria(v, keys)
ufl.algorithms.graph.test_expr()

latextools Module

This module defines basic utilities for stitching together LaTeX documents.

ufl.algorithms.latextools.align(lines)
ufl.algorithms.latextools.document(title, sections)
ufl.algorithms.latextools.itemize(items)
ufl.algorithms.latextools.section(s)
ufl.algorithms.latextools.subsection(s)
ufl.algorithms.latextools.subsubsection(s)
ufl.algorithms.latextools.testdocument()
ufl.algorithms.latextools.verbatim(string)

multifunction Module

Multifunctions.

class ufl.algorithms.multifunction.MultiFunction

Bases: object

Base class for collections of nonrecursive expression node handlers.

expr(o)

Trigger error.

undefined(o)

Trigger error.

pdiffs Module

This module defines partial differentiation rules for all relevant operands for use with reverse mode AD.

class ufl.algorithms.pdiffs.PartialDerivativeComputer

Bases: ufl.algorithms.multifunction.MultiFunction

NB! The main reason for keeping this out of the Expr hierarchy is to avoid user mistakes in the form of mixups with total derivatives, and to allow both reverse and forward mode AD.

abs(f)
\[\begin{split}\\frac{d}{dx} f(x) = \\frac{d}{dx} abs(x) = sign(x)\end{split}\]
acos(f)
\[\begin{split}\\frac{d}{dx} f(x) = \frac{d}{dx} \arccos(x) = \frac{-1}{\sqrt{1 - x^2}}\end{split}\]
asin(f)

d/dx asin x = 1/sqrt(1 - x^2)

atan(f)

d/dx atan x = 1/(1 + x^2)

atan_2(f)

f = atan2(x,y) d/dx atan2(x,y) = y / (x**2 + y**2 ) d/dy atan2(x,y) = -x / (x**2 + y**2)

bessel_function(nu, x)
cell_avg(f)
coefficient_derivative(f)
component_tensor(f)
condition(f)
conditional(f)
cos(f)

d/dx cos x = -sin(x)

cosh(f)

d/dx cosh x = sinh(x)

division(f)

f = x/y d/dx x/y = 1/y d/dy x/y = -x/y**2 = -f/y

erf(f)

d/dx erf x = 2/sqrt(pi)*exp(-x^2)

exp(f)

d/dx exp(x) = exp(x)

expr(o)
facet_avg(f)
index_sum(f)

d/dx sum_j x = TODO

indexed(f)

d/dx x_i = (1)_i = 1

list_tensor(f)

d/dx_i [x_0, ..., x_n-1] = e_i (unit vector)

ln(f)

d/dx ln x = 1 / x

negative_restricted(f)
positive_restricted(f)
power(f)

f = x**y d/dx x**y = y*x**(y-1) = y*f/x d/dy x**y = ln(x)*x**y = ln(x)*f

product(f)
sin(f)

d/dx sin x = cos(x)

sinh(f)

d/dx sinh x = cosh(x)

spatial_derivative(f)
sqrt(f)

d/dx sqrt(x) = 1 / (2*sqrt(x))

sum(f)

d/dx_i sum_j x_j = 1

tan(f)

d/dx tan x = (sec(x))^2 = 2/(cos(2x) + 1)

tanh(f)

d/dx tanh x = (sech(x))^2 = (2 cosh(x) / (cosh(2x) + 1))^2

variable_derivative(f)
ufl.algorithms.pdiffs.pdiffs(exprs)

predicates Module

Functions to check properties of forms and integrals.

ufl.algorithms.predicates.is_multilinear(form)

Check if form is multilinear in arguments.

preprocess Module

This module provides the preprocess function which form compilers will typically call prior to code generation to preprocess/simplify a raw input form given by a user.

class ufl.algorithms.preprocess.Timer(name)
end()
ufl.algorithms.preprocess.build_element_mapping(element_mapping, common_cell, arguments, coefficients)

Complete an element mapping for all elements used by arguments and coefficients, using a well defined common cell.

ufl.algorithms.preprocess.extract_common_cell(form, common_cell=None)

Extract common cell for form or expression.

ufl.algorithms.preprocess.preprocess(form, object_names=None, common_cell=None, element_mapping=None)

Preprocess raw input form to obtain form metadata, including a modified (preprocessed) form more easily manipulated by form compilers. The original form is left untouched. Currently, the following transformations are made to the preprocessed form:

expand_compounds (side effect of calling expand_derivatives) expand_derivatives renumber arguments and coefficients and apply evt. element mapping
ufl.algorithms.preprocess.preprocess_expression(expr, object_names=None, common_cell=None, element_mapping=None)

Preprocess raw input expression to obtain expression metadata, including a modified (preprocessed) expression more easily manipulated by expression compilers. The original expression is left untouched. Currently, the following transformations are made to the preprocessed form:

expand_compounds (side effect of calling expand_derivatives) expand_derivatives renumber arguments and coefficients and apply evt. element mapping

printing Module

A collection of utility algorithms for printing of UFL objects, mostly intended for debugging purposes.

ufl.algorithms.printing.form_info(form)
ufl.algorithms.printing.integral_info(integral)
ufl.algorithms.printing.tree_format(expression, indentation=0, parentheses=True)

propagate_restrictions Module

Algorithms related to restrictions.

class ufl.algorithms.propagate_restrictions.RestrictionChecker(require_restriction)

Bases: ufl.algorithms.transformer.Transformer

expr(o)
facet_normal(o)
form_argument(o)
restricted(o)
class ufl.algorithms.propagate_restrictions.RestrictionPropagator

Bases: ufl.algorithms.transformer.ReuseTransformer

cell_surface_area(o)
cell_volume(o)
circumradius(o)
facet_normal(o)
form_argument(o)
restricted(o)
variable(o)
ufl.algorithms.propagate_restrictions.check_restrictions(expression, require_restriction)
ufl.algorithms.propagate_restrictions.propagate_restrictions(expression)

Propagate restriction nodes to wrap terminal objects directly.

renumbering Module

Algorithms for renumbering of counted objects, currently variables and indices.

class ufl.algorithms.renumbering.IndexRenumberingTransformer

Bases: ufl.algorithms.renumbering.VariableRenumberingTransformer

index(o)
index_annotated(o)
multi_index(o)
scalar_value(o)
zero(o)
class ufl.algorithms.renumbering.IndexRenumberingTransformer2

Bases: ufl.algorithms.renumbering.VariableRenumberingTransformer

component_tensor(o)

Maps component to indices.

define_indices(ii, values)
define_new_indices(ii)
expr(o, *ops)
index(o)
index_annotated(o)
index_sum(o)

Defines a new index.

indexed(f)

Binds indices to component, ending their scope as free indices. If indices with the same count occur later in a subexpression, they represent new indices in a different scope.

multi_index(o)
new_index()

Create a new index using our contiguous numbering.

revert_indices(ii)
scalar_value(o)
terminal(o)
zero(o)
class ufl.algorithms.renumbering.VariableRenumberingTransformer

Bases: ufl.algorithms.transformer.ReuseTransformer

variable(o)
ufl.algorithms.renumbering.renumber_indices(expr)
ufl.algorithms.renumbering.renumber_indices1(expr)
ufl.algorithms.renumbering.renumber_indices2(expr)
ufl.algorithms.renumbering.renumber_variables(expr)

replace Module

Algorithm for replacing terminals in an expression.

class ufl.algorithms.replace.Replacer(mapping)

Bases: ufl.algorithms.transformer.ReuseTransformer

coefficient_derivative(o)
terminal(o)
ufl.algorithms.replace.replace(e, mapping)

Replace terminal objects in expression.

@param e:
An Expr or Form.
@param mapping:
A dict with from:to replacements to perform.

signature Module

Signature computation for forms.

ufl.algorithms.signature.compute_expression_hashdata(expression, terminal_hashdata)
ufl.algorithms.signature.compute_expression_signature(expr, function_replace_map=None)
ufl.algorithms.signature.compute_form_signature(form, function_replace_map=None)
ufl.algorithms.signature.compute_multiindex_hashdata(expr, index_numbering)
ufl.algorithms.signature.compute_terminal_hashdata(expressions, function_replace_map=None)

transformations Module

This module defines expression transformation utilities, either converting UFL expressions to new UFL expressions or converting UFL expressions to other representations.

transformer Module

This module defines the Transformer base class and some basic specializations to further base other algorithms upon, as well as some utilities for easier application of such algorithms.

class ufl.algorithms.transformer.CopyTransformer(variable_cache=None)

Bases: ufl.algorithms.transformer.Transformer

expr(o, *operands)

Always reconstruct expr.

terminal(o)

Always reuse Expr (ignore children)

variable(o)
class ufl.algorithms.transformer.ReuseTransformer(variable_cache=None)

Bases: ufl.algorithms.transformer.Transformer

expr(o, *operands)

Reuse Expr if possible, otherwise reconstruct from given operands.

terminal(o)

Always reuse Expr (ignore children)

variable(o)
class ufl.algorithms.transformer.Transformer(variable_cache=None)

Bases: object

Base class for a visitor-like algorithm design pattern used to transform expression trees from one representation to another.

always_reconstruct(o, *operands)

Always reconstruct expr.

expr(o)

Trigger error.

print_visit_stack()
reconstruct_variable(o)
reuse(o)

Always reuse Expr (ignore children)

reuse_if_possible(o, *operands)

Reuse Expr if possible, otherwise reconstruct from given operands.

reuse_variable(o)
terminal(o)

Always reuse Expr (ignore children)

undefined(o)

Trigger error.

visit(o)
class ufl.algorithms.transformer.VariableStripper

Bases: ufl.algorithms.transformer.ReuseTransformer

variable(o)
ufl.algorithms.transformer.apply_transformer(e, transformer, domain_type=None)

Apply transformer.visit(expression) to each integrand expression in form, or to form if it is an Expr.

ufl.algorithms.transformer.is_post_handler(function)

Is this a handler that expects transformed children as input?

ufl.algorithms.transformer.strip_variables(e)

Replace all Variable instances with the expression they represent.

ufl.algorithms.transformer.transform(expression, handlers)

Convert a UFLExpression according to rules defined by the mapping handlers = dict: class -> conversion function.

ufl.algorithms.transformer.transform_integrands(form, transform, domain_type=None)

Apply transform(expression) to each integrand expression in form, or to form if it is an Expr.

ufl.algorithms.transformer.ufl2ufl(e)

Convert an UFL expression to a new UFL expression, with no changes. This is used for testing that objects in the expression behave as expected.

ufl.algorithms.transformer.ufl2uflcopy(e)

Convert an UFL expression to a new UFL expression. All nonterminal object instances are replaced with identical copies, while terminal objects are kept. This is used for testing that objects in the expression behave as expected.

traversal Module

This module contains algorithms for traversing expression trees in different ways.

ufl.algorithms.traversal.iter_expressions(a)

Utility function to handle Form, Integral and any Expr the same way when inspecting expressions. Returns an iterable over Expr instances: - a is an Expr: (a,) - a is an Integral: the integrand expression of a - a is a Form: all integrand expressions of all integrals

ufl.algorithms.traversal.post_traversal(expr, stack=None)

Yields o for each tree node o in expr, parent after child. If a list is provided, the stack is updated while iterating.

ufl.algorithms.traversal.post_walk(a, func)

Call func on each expression tree node in a, parent after child. The argument a can be a Form, Integral or Expr.

ufl.algorithms.traversal.pre_traversal(expr, stack=None)

Yields o for each tree node o in expr, parent before child. If a list is provided, the stack is updated while iterating.

ufl.algorithms.traversal.pre_walk(a, func)

Call func on each expression tree node in a, parent before child. The argument a can be a Form, Integral or Expr.

ufl.algorithms.traversal.traverse_operands(expr)
ufl.algorithms.traversal.traverse_terminals(expr)
ufl.algorithms.traversal.traverse_terminals2(expr, visited=None)
ufl.algorithms.traversal.walk(a, pre_func, post_func, stack=None)

Call pre_func and post_func on each expression tree node in a.

The functions are called on a node before and after its children are visited respectively.

The argument a can be a Form, Integral or Expr.

tuplenotation Module

Deprecated file.

ufl.algorithms.tuplenotation.as_form(form)

Convert to form if not a form, otherwise return form.

ufl2dot Module

A collection of utility algorithms for printing of UFL objects in the DOT graph visualization language, mostly intended for debugging purposers.

class ufl.algorithms.ufl2dot.CompactLabeller(function_mapping=None)

Bases: ufl.algorithms.ufl2dot.ReprLabeller

cell_avg(e)
cell_surface_area(e)
cell_volume(e)
circumradius(e)
component_tensor(e)
curl(e)
determinant(e)
dev(e)
diff(e)
div(e)
division(e)
dot(e)
facet_area(e)
facet_avg(e)
facet_diameter(e)
facet_normal(e)
form_argument(e)
grad(e)
identity(e)
index_sum(e)
indexed(e)
inner(e)
math_function(e)
max_facet_edge_length(e)
multi_index(e)
nabla_div(e)
nabla_grad(e)
negative_restricted(e)
outer(e)
positive_restricted(e)
power(e)
product(e)
scalar_value(e)
skew(e)
spatial_coordinate(e)
sum(e)
trace(e)
transposed(e)
zero(e)
class ufl.algorithms.ufl2dot.FancyLabeller(function_mapping=None)

Bases: ufl.algorithms.ufl2dot.CompactLabeller

class ufl.algorithms.ufl2dot.ReprLabeller

Bases: ufl.algorithms.multifunction.MultiFunction

operator(e)
terminal(e)
ufl.algorithms.ufl2dot.build_entities(e, nodes, edges, nodeoffset, prefix='', labeller=None)
ufl.algorithms.ufl2dot.format_entities(nodes, edges)
ufl.algorithms.ufl2dot.ufl2dot(expression, formname='a', nodeoffset=0, begin=True, end=True, labeling='repr', object_names=None)

ufl2latex Module

This module defines expression transformation utilities, either converting UFL expressions to new UFL expressions or converting UFL expressions to other representations.

class ufl.algorithms.ufl2latex.Expression2LatexHandler(argument_names=None, coefficient_names=None)

Bases: ufl.algorithms.transformer.Transformer

abs(o, a)
acos(o, f)
and_condition(o, a, b)
argument(o)
asin(o, f)
atan(o, f)
atan2(o, f1, f2)
bessel_K(o, nu, f)
bessel_i(o, nu, f)
bessel_j(o, nu, f)
bessel_y(o, nu, f)
cell_avg(o, f)
coefficient(o)
coefficient_derivative(o, f, w, v)
cofactor(o, A)
component_tensor(o, *ops)
conditional(o, c, t, f)
constant(o)
cos(o, f)
cosh(o, f)
cross(o, a, b)
curl(o, f)
determinant(o, A)
deviatoric(o, A)
div(o, f)
division(o, a, b)
dot(o, a, b)
eq(o, a, b)
erf(o, f)
exp(o, f)
expr(o)
facet_normal(o)
ge(o, a, b)
grad(o, f)
gt(o, a, b)
identity(o)
index_sum(o, f, i)
indexed(o, a, b)
inner(o, a, b)
inverse(o, A)
le(o, a, b)
list_tensor(o)
ln(o, f)
lt(o, a, b)
multi_index(o)
nabla_div(o, f)
nabla_grad(o, f)
ne(o, a, b)
negative_restricted(o, f)
not_condition(o, a)
or_condition(o, a, b)
outer(o, a, b)
permutation_symbol(o)
positive_restricted(o, f)
power(o, a, b)
product(o, *ops)
scalar_value(o)
sin(o, f)
sinh(o, f)
skew(o, A)
sqrt(o, f)
sum(o, *ops)
sym(o, A)
tan(o, f)
tanh(o, f)
trace(o, A)
transposed(o, a)
variable(o)
variable_derivative(o, f, v)
zero(o)
ufl.algorithms.ufl2latex.bfname(i)
ufl.algorithms.ufl2latex.build_precedence_map()
ufl.algorithms.ufl2latex.cfname(i)
ufl.algorithms.ufl2latex.code2latex(G, partitions, formdata)

TODO: Document me

ufl.algorithms.ufl2latex.dependency_sorting(deplist, rank)
ufl.algorithms.ufl2latex.deps2latex(deps)
ufl.algorithms.ufl2latex.element2latex(element)
ufl.algorithms.ufl2latex.expression2latex(expression, argument_names=None, coefficient_names=None)
ufl.algorithms.ufl2latex.form2code2latex(formdata)
ufl.algorithms.ufl2latex.form2latex(form, formdata)
ufl.algorithms.ufl2latex.format_index(ii)
ufl.algorithms.ufl2latex.format_multi_index(ii, formatstring='%s')
ufl.algorithms.ufl2latex.formdata2latex(formdata)
ufl.algorithms.ufl2latex.forms2latexdocument(forms, uflfilename, compile=False)

Render forms from a .ufl file as a LaTeX document.

ufl.algorithms.ufl2latex.integrand2code(integrand, formdata)
ufl.algorithms.ufl2latex.par(s, condition=True)
ufl.algorithms.ufl2latex.tex2pdf(latexfilename, pdffilename)

Compile a .pdf file from a .tex file.

ufl.algorithms.ufl2latex.ufl2latex(expression)

Generate LaTeX code for a UFL expression or form (wrapper for form2latex and expression2latex).

ufl.algorithms.ufl2latex.ufl2pdf(uflfilename, latexfilename, pdffilename, compile=False)

Compile a .pdf file from a .ufl file.

ufl.algorithms.ufl2latex.ufl2tex(uflfilename, latexfilename, compile=False)

Compile a .tex file from a .ufl file.