simudo.fem package

Submodules

simudo.fem.adaptive_stepper module

class simudo.fem.adaptive_stepper.AdaptiveStepper(**kwargs)[source]

Bases: simudo.fem.adaptive_stepper.BaseAdaptiveStepper

This implements a slightly more concrete class than BaseAdaptiveStepper.

Parameters

to_save_objects (dict) – Mapping of vector-like objects representing the current solution, whose values to save (and restore upon solver failure).

to_save_objects = None
user_apply_parameter_to_solution(solution, parameter)[source]
user_make_solver(solution)[source]
user_solution_add(solution, solution_scale, saved_solution, saved_scale)[source]

This procedure must update the current solution so that:

self.current_solution = (self.solution*solution_scale +
                         saved_solution*saved_scale)

where saved_solution is as returned by user_solution_save().

If solution_scale is equal to 0, then the current solution must be erased (careful with NaNs!).

user_solution_save(solution)[source]

This procedure must return a copy of the solution variables of solution in a format acceptable by user_solution_add. Typically a dict of ‘key’: vector pairs.

user_solver(solution, parameter)[source]

This user-defined method must re-solve solution using parameter value parameter.

Must return boolean indicating whether the solver succeeded.

class simudo.fem.adaptive_stepper.BaseAdaptiveStepper(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Adaptive solution base class.

This implements an adaptive solution method: progressively change an input parameter in small increments, re-solving the problem at each step.

If solutions are successful, gradually larger step sizes will be used. If a solution fails, the last successful solution is re-loaded and a smaller step size is chosen.

A series of specific parameter values to be attained can be given, for example to generate multiple points for a current-voltage curve.

Parameters
  • solution (object) – Solution object, whatever that means.

  • parameter_target_values (list) – List of values for parameter to attain. output_writer will be called as each target value is attained.

  • break_criteria_cb (callable, optional) – A function that will be evaluated after each target value. If it returns True, the adaptive stepper will stop.

parameter

Current value of the parameter.

Type

float

step_size

Current step size.

Type

float

update_parameter_success_factor

If the solver succeeds, multiply step_size by this factor.

Type

float

update_parameter_failure_factor

If the solver fails, multiply step_size by this factor.

Type

float

stepper_rel_tol

If step_size ` drops below :py:attr:`stepper_rel_tol`*max(:py:attr:`parameter, initial_step_size), the stepper will stop and raise a StepperError.

Type

float

Notes

This class implements the abstract algorithm, so it makes no assumptions as to what solution represents. Users of this class must implement the user_solver(), user_solution_add(), and user_solution_save() methods.

add_prior_solution(parameter_value, solver_succeeded, saved_solution)[source]
break_criteria_cb = None
cleanup_prior_solutions()[source]
do_iteration()[source]

Solve the problem at a single value of the solution parameter.

do_loop()[source]

This method must be called to actually perform the adaptive stepping procedure

get_last_successful(count)[source]
keep_saved_solutions_count = 2
output_writer = None
parameter
parameter_start_value = 0.0
parameter_target_values = [1.0]
prior_solutions

list of (parameter_value, solver_succeeded, saved_solution)

prior_solutions_idx_saved_solution
prior_solutions_idx_successful
reset_parameter_to_last_successful()[source]
solution = None
step_size = 0.01
stepper_rel_tol = 1e-05
update_parameter()[source]

This method is called to update parameter after each solver call (successful or not). It also restores a previous solution if the solver call failed.

update_parameter_failure_factor = 0.5
update_parameter_success_factor = 2.0
user_solution_add(solution, solution_scale, saved_solution, saved_scale)[source]

This procedure must update the current solution so that:

self.current_solution = (self.solution*solution_scale +
                         saved_solution*saved_scale)

where saved_solution is as returned by user_solution_save().

If solution_scale is equal to 0, then the current solution must be erased (careful with NaNs!).

user_solution_save(solution)[source]

This procedure must return a copy of the solution variables of solution in a format acceptable by user_solution_add. Typically a dict of ‘key’: vector pairs.

user_solver(solution, parameter)[source]

This user-defined method must re-solve solution using parameter value parameter.

Must return boolean indicating whether the solver succeeded.

class simudo.fem.adaptive_stepper.ConstantStepperMixin[source]

Bases: object

Parameters
  • constants (pint.Quantity wrapping dolfin.Constant) – On each iteration, the constant’s value will be assigned to be the current parameter value.

  • parameter_unit (pint.Quantity, optional) – Parameter unit.

get_mapped_parameter()[source]
parameter_unit = None
property unit_registry
user_apply_parameter_to_solution(solution, parameter_value)[source]
exception simudo.fem.adaptive_stepper.StepperError[source]

Bases: Exception

simudo.fem.assign module

simudo.fem.assign.opportunistic_assign(source, target, function_subspace_registry)[source]

Assign the value of source source to target target, where target may be a function or subfunction.

Use the fast assign() method if possible, otherwise py:func:dolfin.project.

simudo.fem.delayed_form module

class simudo.fem.delayed_form.DelayedForm(*terms)[source]

Bases: object

abs()[source]
delete_units()[source]
classmethod from_sum(iterable)[source]
map(func)[source]
to_ufl(units=None)[source]

simudo.fem.dolfin_parameters module

simudo.fem.dolfin_parameters.setup_dolfin_parameters()[source]

simudo.fem.expr module

class simudo.fem.expr.CellFunctionFunction(cell_function, DG0_space)[source]

Bases: object

make_cases(mapping, default=0.0)[source]
class simudo.fem.expr.CellMidpointExpression(mesh, **kwargs)[source]

Bases: dolfin.function.expression.UserExpression

eval_cell(values, x, cell)[source]
simudo.fem.expr.bbox_vecs(bbox)[source]

r[i,j,k] == (bbox[i,j] if i==k else 0)

example use:

(left, right), (bottom, top) = bbox_vecs(bbox) v = (bottom+top) / 2 + 1/3 * left + 2/3 * right

simudo.fem.expr.constantify_if_literal(value)[source]

If the argument is not a UFL expression, assume it is a floating point number or array, and pass it to dolfin.Constant(). This avoids re-compilation when the literal value changes.

simudo.fem.expr.dofs_coordinates(function_space)[source]
simudo.fem.expr.dolfin_interp1d(variable, X, Y, fill_value)[source]

Create 1D interpolator.

Parameters
  • variable – UFL “x” variable or expression that will be evaluated.

  • X – X values. Must be Python floats.

  • Y – Y values. Can be numerical constants or dolfin expressions.

  • fill_value – Like in scipy.interpolate.interp1d().

simudo.fem.expr.force_ufl(expr, zero=None)[source]

Certain functions, like dolfin.project(), expect the expression to be a UFL form, and crash if it’s a plain old float. This function converts such a constant value into a ufl expression.

simudo.fem.expr.is_ufl_like(expr)[source]
simudo.fem.expr.mesh_bbox(mesh)[source]

compute mesh bounding box

simudo.fem.expr.point_to_array(p)[source]
simudo.fem.expr.scalar_function_to_Expression(f)[source]
simudo.fem.expr.tuple_to_point(xs)[source]
simudo.fem.expr.vector_function_to_Expression(f)[source]

simudo.fem.extra_bindings module

simudo.fem.extra_bindings.Function_eval_many(arg0: object, arg1: int, arg2: int, arg3: numpy.ndarray[numpy.float64[m, 1], flags.writeable], arg4: numpy.ndarray[numpy.float64[m, 1]]) → None
simudo.fem.extra_bindings.LagrangeInterpolator_interpolate_Expression(arg0: dolfin.cpp.function.LagrangeInterpolator, arg1: dolfin.cpp.function.Function, arg2: dolfin.cpp.function.Expression) → None

simudo.fem.ffc_jit_lock module

class simudo.fem.ffc_jit_lock.LockFile(filename)[source]

Bases: object

acquire()[source]
release()[source]
simudo.fem.ffc_jit_lock.new_jit(ufl_object, parameters=None, indirect=False)[source]

simudo.fem.function_space module

class simudo.fem.function_space.MixedFunctionHelper(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Utility mixin for objects that hold a mixed function make up of many subfunctions that need to be gathered from different objects, for example poisson_drift_diffusion.PoissonDriftDiffusion.

Parameters
  • mesh_util (mesh_util.MeshUtil) – Instance of MeshUtil.

  • subspace_descriptors_for_solution_space (sequence of dict) – Sequence of subspace descriptor dicts. This property must contain the subspace descriptors that will be used to build the solution space. Typically one would gather these by calling WithSubfunctionsMixin.solution_subspace_descriptors on all the objects that contain subspace descriptors.

property function_space_cache
make_solution_mixed_function()[source]

intercept this to use your own Function instead of allocating a new one

make_tolerance_function()[source]

Collect “trial_tolerance” from each of the subspaces and assign it as a constant in each subspace. This function is generally used in the Newton solver to determine if the iterative updates are less than an absolute tolerance.

Returns

function – The function. Use the .function attribute to get the dolfin Function.

Return type

MixedFunction

property mesh
property solution_function

Dolfin Function.

solution_mixed_function_data
solution_mixed_space
property solution_test_function

Dolfin TestFunction.

class simudo.fem.function_space.MixedFunctionSpace(mesh, subspace_descriptors, function_space_cache)[source]

Bases: object

Convenience class for dealing with mixed function spaces.

class MixedFunction(mixed_function_space, function=None)

Bases: simudo.fem.function_space.MixedFunctionLikeMixin

class MixedTestFunction(mixed_function_space, function=None)

Bases: simudo.fem.function_space.MixedFunctionLikeMixin

element
function_space
function_subspaces
get_element()[source]

use element property instead

get_function_space()[source]

use function_space property instead

make_function(**kwargs)[source]
make_test_function(**kwargs)[source]
split(dolfin_function, kind=None)[source]

returns OrderedDict of (key: subfunction*unit)

subspace_descriptors_dict

Like subspace_descriptors, except it’s a dictionary where the keys are “trial_key” as well as “test_key”.

class simudo.fem.function_space.WithSubfunctionsMixin(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Utility mixin for objects that need subfunctions (poisson_drift_diffusion.MixedPoisson, poisson_drift_diffusion.MixedQflBand, etc).

Parameters
  • key (str) – Unique prefix to prevent clashes between trial/test function names across instances (for example, “CB” to distinguish between “CB/j” and “VB/j”).

  • subfunctions_info – Sequence of dicts with keys “{trial,test}_{name,units}” and “element”.

  • mixed_function_solution_object (MixedFunctionHelper) – Where to register subfunctions.

get_subfunction(name)[source]
property solution_subspace_descriptors

Creates properly namespaced subspace descriptors.

Returns

Returns properly namespaced subspace descriptors by prefixing the descriptors in subfunctions_info with self.key + "/".

subfunction_prefix(name)[source]

Apply prefix to this subfunction name.

simudo.fem.function_space_cache module

class simudo.fem.function_space_cache.FunctionSpaceCache[source]

Bases: object

FunctionSpace(mesh, element, constrained_domain=None)[source]

simudo.fem.function_subspace_registry module

exception simudo.fem.function_subspace_registry.AssignmentError[source]

Bases: simudo.fem.function_subspace_registry.FSRError

exception simudo.fem.function_subspace_registry.FSRError[source]

Bases: Exception

class simudo.fem.function_subspace_registry.FunctionSubspaceRegistry[source]

Bases: object

The FEniCS API does not provide any obvious way of retrieving the function space of the result of dolfin.split(mixed_function). This class keeps track of those function spaces.

Also, FunctionAssigner is broken, so we’re also taking over that functionality.

Function(space, *args, **kwargs)[source]
assign(target, source, coefficient=1.0, offset=0.0, ignore_incompatible=False)[source]
assign_scalar(target, scalar)[source]
clear()[source]
copy(subfunction)[source]
entity_dofs(function, dim, entities)[source]

entities must be uintp array

classmethod from_union(function_subspace_registries)[source]

This creates a registry that is the union of several other registries, and can therefore handle any spaces found within them.

get_full_function_functionspace(u)[source]
get_full_function_functionspace_indices(u, no_indices=False)[source]
get_function_space(subfunction, collapsed=False)[source]

Get function space for a (sub)function. Use collapsed=True to return a fresh independent/unattached copy.

get_vector_and_indices(function)[source]
get_vector_and_subspace_info(subfunction)[source]
new_independent_function(subfunction)[source]
register(function_space, _root_space=None, _subfunction=None)[source]
exception simudo.fem.function_subspace_registry.FunctionTypeError[source]

Bases: simudo.fem.function_subspace_registry.AssignmentError, TypeError

exception simudo.fem.function_subspace_registry.IncompatibleFunctionSpacesError[source]

Bases: simudo.fem.function_subspace_registry.AssignmentError

simudo.fem.ipython module

class simudo.fem.ipython.DisplayMixin[source]

Bases: object

display()[source]
class simudo.fem.ipython.LineCutPlot(functions, line_cutter=None)[source]

Bases: object

class RenderingPlot(ax, size=None, extent=None, render_callback=None, kw=None, simple_plot=None)

Bases: mpl_render.mpl_render.BaseRendering

The user_render() method is expected to return a tuple (Xs, Ys) where Xs and Ys are 1D arrays.

force_single_thread = True
plotobj = True
size = (2000, 2000)
close()[source]
create_plot(k, v, render)[source]
create_renderer(k, v)[source]
default_extract_params
extent
get_default_extract_params()[source]
get_renderer_extract_params(k, v)[source]
init_all()[source]
init_fig()[source]
init_plots()[source]
init_renderers()[source]
simudo.fem.ipython.downproject(expr, scalar_space, vector_space)[source]
simudo.fem.ipython.fchainmap(args)[source]

construct chainmap with empty dict as first argument, and discard None values from args

simudo.fem.mesh_data module

class simudo.fem.mesh_data.MeshData(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Holds mesh and topology data relating to a particular dolfin mesh.

mesh

The mesh itself.

Type

dolfin.Mesh

cell_function

Subdomain cell markers.

Type

dolfin.CellFunction

facet_function

Subdomain boundary facet markers.

Type

dolfin.FacetFunction

region_name_to_cvs

{region_name: set_of_cell_values}

Type

dict

facets_name_to_fvs

{facets_name: {(facet_value, sign), …}}

Type

dict

facets_manager

Relation information between cell and facet values.

Type

FacetsManager

material_to_region_map

Mapping from material to abstract CellRegion.

Type

dict

mesh_unit

Mesh length unit.

Type

pint.Quantity

cell_to_cells_adjacency_via_facet
evaluate_topology(region)[source]

Evaluate a topological region.

Parameters

region (topology.CellRegion or topology.FacetRegion) – Topological region.

Returns

geometrical_values – The return value depends on the type of the region argument.

  • If the region is a topology.CellRegion, return a set of cell values (values in cell_function).

  • If the region is a topology.FacetRegion, return a set of tuples (facet_value, sign) where facet_value is a facet value (value in facet_function), and sign is either +1 or -1 depending on whether the facet orientation matches the boundary orientation.

Return type

set

simudo.fem.mesh_util module

class simudo.fem.mesh_util.MeshUtil(**kwargs)[source]

Bases: simudo.fem.mesh_util1.MeshUtilPY, simudo.util.setattr_init_mixin.SetattrInitMixin

Holds a plethora of PDE definition utilities, some of which are (needlessly) mesh-specific.

Notes

Most of the methods and attributes are hidden away in the Pyaml file. FIXME: Need to fix imports so that sphinx can see the pyaml modules.

Parameters
mesh_data

Holds mesh and topology information.

Type

MeshData

function_space_cache

Used to avoid creating redundant function spaces. Created automatically only if _sloppy is True.

Type

FunctionSpaceCache

function_subspace_registry

Used for assignment and copying across subfunctions. Created automatically only if _sloppy is True.

Type

FunctionSubspaceRegistry

unit_registry

Pint unit registry.

Type

pint.UnitRegistry

\_sloppy

Create some of the above attributes automatically. If you want the function_subspace_registry to be shared, do not use this option.

Type

bool

property cell_function
cell_function_function
dless(x)[source]
element(name, *args, **kwargs)[source]
ensure_quantity(x)[source]
property facet_function
function_space_cache

create new one if not supplied

function_subspace_registry

create new one if not supplied

get_debug_probe(quantity, space)[source]
magnitude(x)[source]
property mesh
property mesh_unit
region_ds_and_dS(region)[source]

Return ds and dS (surface) measures corresponding to topological FacetRegion, for internal and external facets respectively.

Parameters

region (FacetRegion) – Facet region.

Returns

measures – Facet integration measures (ds, dS).

Return type

tuple of expr.DelayedForm

region_dx(region)[source]

Return dx (volume) measure corresponding to topological CellRegion.

Parameters

region (CellRegion) – Volume region.

Returns

measure – Volume integration measure.

Return type

expr.DelayedForm

region_oriented_dS(region, orient=True)[source]

Return the internal dS measures corresponding to topological FacetRegion, for “minus” and “plus” sides respectively.

Parameters
  • region (FacetRegion) – Facet region.

  • orient (bool, optional) – Actually orient the measures. If False, then all dS’s are added to dS_plus (second element of returned tuple).

Returns

measures – Facet integration measures (dS_minus, dS_plus).

Return type

tuple of expr.DelayedForm

property space
property ufl_cell
unit_registry

get unit from self.mesh_data.mesh_unit

units(x)[source]

simudo.fem.newton_solver module

exception simudo.fem.newton_solver.ExitOptimizerException[source]

Bases: Exception

class simudo.fem.newton_solver.NewtonSolution(solver, u_=None)[source]

Bases: object

A
b
b_norm
combined_du_norm
copy()[source]
copy_to(other)[source]
do_assemble_system(assemble_A=True, assemble_b=True)[source]
do_invalidate_cache(check=False)[source]
do_linear_solve()[source]
du_norm
has_nans
mumps_icntl = ()
q
rel_du_norm
size
str_error()[source]
class simudo.fem.newton_solver.NewtonSolver(F, u_, bcs, J=None, parameters=None)[source]

Bases: object

A general Newton solver.

Parameters
  • F (ufl.Form) – Nonlinear form to be solved (by setting equal to zero). That is, we are trying to solve F(u_) = 0 by varying u_.

  • u_ (dolfin.Function) – Function being varied (read: solved for).

  • bcs (list of dolfin.DirichletBC) – List of essential boundary conditions to be applied.

  • J (ufl.core.expr.Expr, optional) – Jacobian of the form with respect to u_’s coefficients. If this is not supplied, it is derived from F automatically.

  • parameters (dict) – Parameters controlling the Newton solution process.

iteration

Current iteration.

Type

int

Notes

The underscore in u_ is a subscript minus, and signifies that this is the “previous” value of the function is used to evalute the form in the iterative Newton process for nonlinear problems.

create_solution(*args, **kwargs)[source]
do_before_first_iteration_hook()[source]
do_init_assembler()[source]
do_init_parameters()[source]
do_init_solution(u_)[source]
do_iteration()[source]
do_post_iteration_hook()[source]
do_pre_iteration_hook()[source]
do_update_solution()[source]
du_mask_array = None
extra_iterations = None
classmethod from_nice_obj(obj)[source]
get_omega()[source]
has_converged()[source]
iteration = 0
log_print(string='', end='\n')[source]
logger
set_problem(F, u_, bcs, J=None)[source]
should_stop()[source]
should_stop_real()[source]
solution_class

alias of simudo.fem.newton_solver.NewtonSolution

solve()[source]
user_update_solution_vector(solution, du)[source]
class simudo.fem.newton_solver.NewtonSolverLogDamping(F, u_, bcs, J=None, parameters=None)[source]

Bases: simudo.fem.newton_solver.NewtonSolver

user_update_solution_vector(solution, du)[source]
class simudo.fem.newton_solver.NewtonSolverMaxDu(F, u_, bcs, J=None, parameters=None)[source]

Bases: simudo.fem.newton_solver.NewtonSolver

user_update_solution_vector(solution, du)[source]

simudo.fem.offset_partitioning module

class simudo.fem.offset_partitioning.PartitionOffsets(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Offset partitioner.

function

Input function. Must be DG0 function.

Type

dolfin.Function

out_function

Output function. If not set, use function. Must be DG0 function.

Type

dolfin.Function

thresholds

Thresholds, as list of tuples (absolute_threshold, relative_threshold).

Type

sequence

mesh_util

Mesh utilities and data.

Type

mesh_util.MeshUtil

bc_cells

Pair (cells, cellavgs), where both are equally sized arrays. The first array is the indices of BC-adjacent cells, and the second array are their values.

Notes

The algorithm is as follows:

  1. All cells are unmarked (have a marker value of nan), and unseen. The cell queue is empty.

  2. The cells adjacent to boundary conditions are placed in the cell queue. They are marked with the boundary condition value.

  3. While there exist unseen cells:

    1. If the cell queue is empty, pick one unseen cell and place it in the cell queue.

    2. Remove cell out of queue, and visit it:

      1. Consider the current cell as seen.

      2. If the cell is already marked, set this_marker to the marker value. Otherwise, set this_marker to the current cell value.

      3. For every unmarked and unseen neighbor: if its value is “close” to our marker value, mark it with this_marker, and consider it “seen”.

      4. Add newly-marked cells to the cell queue.

      5. If the current cell was unmarked and step 7 marked any cells, mark the current cell with this_marker.

bc_cells = ((), ())
debug_fill_with_zero_except_bc = False
out_function
thresholds = ((1e-08, 0.0),)
update()[source]

simudo.fem.plot module

class simudo.fem.plot.BaseDolfinFunctionRenderFrame(renderer, size, extent)[source]

Bases: object

V
compute_V()[source]
evaluate_function_at_coordinates(function, coordinates, default_value)[source]
extract(params)[source]

method to facilitate subclassing

extract_params
extracted_V
class simudo.fem.plot.DolfinFunctionLineCutRenderer(function, extract_params)[source]

Bases: simudo.fem.plot.DolfinFunctionRenderer

frame_class

alias of simudo.fem.plot.DolfinFunctionRenderLineCutFrame

class simudo.fem.plot.DolfinFunctionRenderFrame(renderer, size, extent)[source]

Bases: simudo.fem.plot.BaseDolfinFunctionRenderFrame

Xs
Ys
compute_V()[source]
coordinates
class simudo.fem.plot.DolfinFunctionRenderLineCutFrame(renderer, size, extent)[source]

Bases: simudo.fem.plot.BaseDolfinFunctionRenderFrame

Ts
coordinates
property extracted_T
class simudo.fem.plot.DolfinFunctionRenderer(function, extract_params)[source]

Bases: object

default_value = nan
frame_class

alias of simudo.fem.plot.DolfinFunctionRenderFrame

get_frame(size, extent)[source]
value_shape
class simudo.fem.plot.LineCutter(p0, p1)[source]

Bases: object

coordinates(Ts)[source]
t_bounds
simudo.fem.plot.evaluate_function_at_coordinates(function, coordinates, value_outside_mesh=nan)[source]

Evaluate Dolfin function on N arbitrary coordinates.

Parameters
  • function (dolfin.Function) – Dolfin function to evaluate.

  • coordinates (numpy.ndarray) – Array of N coordinates with shape (N, space_dimension) on which to evaluate function. For 1D, the shape (N,) is also accepted.

  • value_outside_mesh (value, optional) – For points that landed outside the function’s range (mesh), use this value instead.

Returns

values – Array of function values. First shape component is N, and remaining shape components are given by the shape of the function value (function.value_shape()).

Return type

numpy.ndarray

simudo.fem.spatial module

class simudo.fem.spatial.BoundaryCondition(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Boundary condition class, used both for essential and natural BCs.

Parameters
  • priority – Priority of this boundary condition. Lower values have higher priority.

  • region (topology.FacetRegion) – Facet region where this BC applies.

  • value (ufl.core.expr.Expr) – Value of the boundary condition.

  • require_natural (bool, optional) – Does this BC require natural (as opposed to inflexible essential) application? By default false.

  • internal (bool) – Apply this BC to internal facets? (default: False)

  • external (bool) – Apply this BC to external facets? (default: True)

  • should_extract (bool) – Whether to automatically apply extractor to this BC.

external = True
internal = False
require_natural = False
should_extract = True
class simudo.fem.spatial.CombinedBoundaryCondition(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Combination of multiple BoundaryCondition.

Parameters
  • bcs (SortedList) – Boundary conditions to combine.

  • value_extractor (callable, optional) – Applied to BoundaryCondition objects to obtain the boundary condition value. See map.

  • mesh_util (mesh_util.MeshUtil) – Used to evaluate abstract topology into actual facet values, and other things.

  • essential_var (dolfin.Function, optional) – Variable to apply BC on (used for essential BCs).

  • natural_ignore_sign (bool, optional) – Whether to ignore the facet sign when building a natural BC.

map

Mapping {(facet_value, sign): extracted_bc}.

Type

dict

reverse_map

Mapping {extracted_bc: {(facet_value, sign), ...}}.

Type

dict

fv_set

Set of referenced facet values. Useful to check that BCs don’t overlap.

Type

set

algo_fvs_to_cell_averages(mesh_util, bcdata, fv_adjacent_cells_function, target_unit=None)[source]

Algorithm for turning BC data into cell averages.

Parameters
  • mesh_util (mesh_util.MeshUtil) – Mesh utilities and data.

  • bcdata (dict) – Mapping {expr: {(facet_value, sign), …}}.

  • target_unit (optional) – Unit to expr to in the bcdict argument.

  • fv_adjacent_cells_function (dolfin.Function) – DG0 function containing ones and zeros; ones iff the cell is adjacent to a BC.

algo_get_fv_adjacent_cells(facet_function, fvs)[source]

Get list of cells adjacent to facets that are marked with a facet value in fvs inside facet_function.

fv_adjacent_cellavg

DG0 function representing the average of the boundary condition value in adjacent facets.

fv_adjacent_cells

Return list of cells that are adjacent to the facet values.

fv_adjacent_cells_function

Returns binary cellwise constant (DG0) function, where cell has value 1 iff cell is in fv_adjacent_cells.

fv_set
get_essential_bc(var=None, bc_reverse_map=None)[source]
get_fv_adjacent_cellavg()[source]
get_natural_bc(ignore_sign=None, bc_reverse_map=None, bc_type='external')[source]
map
property mesh_data
offset_partitioning_bc_cells
reverse_map
value_extractor = None
class simudo.fem.spatial.ExtractedBoundaryCondition(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Boundary condition for which the value has been “extracted” by CombinedBoundaryCondition.value_extractor.

Parameters
  • value – Extracted value.

  • bc – Original BoundaryCondition that this BC came from.

class simudo.fem.spatial.Spatial(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Contains spatially dependent quantities, such as material parameters, as well as boundary conditions.

Parameters
  • parent (object) – Attributes such as mesh_data are taken from here by default.

  • mesh_util (mesh_util.MeshUtil, optional) – Mesh-specific utilities. By default taken from parent.

  • material_to_region_map – Material to region map. By default taken from mesh_data.

value_rules

Rules for spatially dependent values. Must be dict of list of dicts.

Type

defaultdict(SortedList)

bcs

Boundary conditions.

Type

defaultdict(SortedList)

add_BC(key, region, value, priority=0, require_natural=False, internal=False, external=True, **kwargs)[source]
add_material_data(key, material_name, value, priority=0)[source]
add_rule(key, region, value, priority=0)[source]

Add a rule for a spatially-dependent value.

Parameters
  • key (str) – Name of the spatial property, e.g., "temperature" or "poisson/static_rho".

  • region (topology.CellRegion) – Cell region where this value applies.

  • value (ufl.core.expr.Expr) – Value.

  • priority – Priority of this rule. Lower values have higher priority.

add_value_rule(region, key, value, priority=0)[source]

Deprecated. Use add_rule().

bcs
get(key)[source]

Get spatially dependent quantity named key.

get_mixed_bc_pair(essential_key, essential_var, natural_key, natural_var, natural_ignore_sign=False, essential_extract=None, natural_extract=None)[source]

Get mixed BC pair, ensuring that the essential and natural BCs don’t overlap.

Parameters
  • essential_key (str) – Essential BC subfunction key.

  • natural_key (str) – Natural BC subfunction key.

  • natural_ignore_sign (bool, optional) – Whether to ignore facet sign/orientation in the natural BC. Default is false.

  • essential_extract (callable, optional) – Function that will be called to extract a BC value from a boundary condition object. Use this to implement any sort of transformation you want to apply to the boundary condition value.

  • natural_extract (callable, optional) – See essential_extract above.

Returns

  • essential_bcs (list) – List of dolfin.DirichletBC.

  • natural_bc_expr (UFL expr) – Natural BC expression.

get_single_essential_bc(key, var, extract=None)[source]

Get single essential BC.

Parameters
  • key (str) – Essential BC key.

  • var (str) – Essential BC variable.

  • extract (callable, optional) – See essential_extract under get_mixed_bc_pair().

Returns

essential_bcs – List of dolfin.DirichletBC.

Return type

list

get_vanilla_bc_pair(variable_key)[source]

not implemented because all our methods are mixed methods

make_combined_bc(key, value_extractor=None, **kwargs)[source]
property material_to_region_map
property mesh_data
property mesh_util
value_rules
class simudo.fem.spatial.ValueRule(**kwargs)[source]

Bases: simudo.util.setattr_init_mixin.SetattrInitMixin

Rule for spatially-dependent value.

Parameters
  • priority – Priority of this rule. Lower values have higher priority.

  • region (topology.CellRegion) – Cell region where this value applies.

  • value (ufl.core.expr.Expr) – Value.

simudo.fem.sympy_dolfin_printer module

class simudo.fem.sympy_dolfin_printer.DolfinConstant(*args)[source]

Bases: sympy.core.function.Function

default_assumptions = {}
nargs = FiniteSet(1)
classmethod release(expr)[source]
property value
class simudo.fem.sympy_dolfin_printer.DolfinPrinter(*args, **kwargs)[source]

Bases: sympy.printing.printer.Printer

Code printer for Theano computations

doprint(expr, **kwargs)[source]

Returns printer’s representation for expr (as a string)

emptyPrinter(expr)[source]
mapping = {<class 'sympy.core.power.Pow'>: <built-in function pow>, <class 'sympy.core.mul.Mul'>: <function <lambda>.<locals>.<lambda>>, <class 'sympy.core.add.Add'>: <function <lambda>.<locals>.<lambda>>, Abs: <function my_abs>, acos: <function acos>, asin: <function asin>, atan: <function atan>, cos: <function cos>, erf: <function erf>, exp: <function exp>, log: <function ln>, sin: <function sin>, tan: <function tan>, <function sqrt>: <function sqrt>}
printmethod: str = '_dolfin'
simudo.fem.sympy_dolfin_printer.sympy_to_ufl(R, mesh, expr, syms=None, **kwargs)[source]
simudo.fem.sympy_dolfin_printer.sympy_to_ufl_base(expr, syms, **kwargs)[source]

simudo.fem.ufl_extra module

class simudo.fem.ufl_extra.ExpM1(argument)[source]

Bases: ufl.mathfunctions.MathFunction

derivative()[source]
class simudo.fem.ufl_extra.Ln1P(argument)[source]

Bases: ufl.mathfunctions.MathFunction

derivative()[source]
simudo.fem.ufl_extra.expm1(x)[source]
simudo.fem.ufl_extra.ln1p(x)[source]

Module contents