simudo.fem package¶
Submodules¶
simudo.fem.adaptive_stepper module¶
-
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
¶ float – Current value of the parameter.
-
step_size
¶ float – Current step size.
Notes
This class implements the abstract algorithm, so it makes no assumptions as to what
solution
represents. Users of this class must implement theuser_solver()
,user_solution_add()
, anduser_solution_save()
methods.-
break_criteria_cb
= None¶
-
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
¶
-
solution
= None¶
-
step_size
= 0.01
-
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 byuser_solution_save()
.If
solution_scale
is equal to 0, then the current solution must be erased (careful with NaNs!).
-
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_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 byuser_solution_save()
.If
solution_scale
is equal to 0, then the current solution must be erased (careful with NaNs!).
-
-
class
simudo.fem.adaptive_stepper.
ConstantStepperMixin
[source]¶ Bases:
object
Parameters: - constants (
pint.Quantity
wrappingdolfin.Constant
) – On each iteration, the constant’s value will be assigned to be the current parameter value. - parameter_unit (
pint.Quantity
, optional) – Parameter unit.
-
parameter_unit
= None¶
-
unit_registry
¶
- constants (
simudo.fem.assign module¶
simudo.fem.delayed_form module¶
simudo.fem.dolfin_parameters module¶
simudo.fem.expr module¶
-
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.
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.
-
class
simudo.fem.expr.
CellMidpointExpression
(mesh, **kwargs)[source]¶ Bases:
dolfin.function.expression.UserExpression
simudo.fem.extra_bindings module¶
-
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.extra_bindings.
Function_eval_many
(arg0: object, arg1: int, arg2: int, arg3: numpy.ndarray[float64[m, 1], flags.writeable], arg4: numpy.ndarray[float64[m, 1]]) → None¶
simudo.fem.ffc_jit_lock module¶
simudo.fem.function_space module¶
-
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
¶
-
subspace_descriptors_dict
¶ Like subspace_descriptors, except it’s a dictionary where the keys are “trial_key” as well as “test_key”.
-
class
-
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.
-
function_space_cache
¶
-
make_solution_mixed_function
()[source]¶ intercept this to use your own Function instead of allocating a new one
-
mesh
¶
-
solution_function
¶ Dolfin Function.
-
solution_mixed_function_data
¶
-
solution_mixed_space
¶
-
solution_test_function
¶ Dolfin TestFunction.
- mesh_util (
-
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.
-
solution_subspace_descriptors
¶ Creates properly namespaced subspace descriptors.
Returns: Returns properly namespaced subspace descriptors by prefixing the descriptors in subfunctions_info
withself.key + "/"
.
simudo.fem.function_space_cache module¶
simudo.fem.function_subspace_registry module¶
-
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.
-
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.
-
classmethod
-
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.
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)¶
-
-
default_extract_params
¶
-
extent
¶
-
class
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
¶ dolfin.Mesh – The mesh itself.
-
cell_function
¶ dolfin.CellFunction – Subdomain cell markers.
-
facet_function
¶ dolfin.FacetFunction – Subdomain boundary facet markers.
-
region_name_to_cvs
¶ dict – {region_name: set_of_cell_values}
-
facets_name_to_fvs
¶ dict – {facets_name: {(facet_value, sign), …}}
-
facets_manager
¶ FacetsManager – Relation information between cell and facet values.
-
material_to_region_map
¶ dict – Mapping from material to abstract CellRegion.
-
mesh_unit
¶ pint.Quantity – Mesh length unit.
-
cell_to_cells_adjacency_via_facet
¶
-
evaluate_topology
(region)[source]¶ Evaluate a topological region.
Parameters: region ( topology.CellRegion
ortopology.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 incell_function
). - If the region is a
topology.FacetRegion
, return a set of tuples(facet_value, sign)
wherefacet_value
is a facet value (value infacet_function
), andsign
is either+1
or-1
depending on whether the facet orientation matches the boundary orientation.
Return type: set - If the region is a
-
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 – See
mesh_data
. - function_space_cache – See
function_space_cache
. - function_subspace_registry – See
function_subspace_registry
. - unit_registry (optional) – See
unit_registry
. - _sloppy – See
_sloppy
.
-
function_space_cache
¶ FunctionSpaceCache
– Used to avoid creating redundant function spaces. Created automatically only if_sloppy
isTrue
.
-
function_subspace_registry
¶ FunctionSubspaceRegistry
– Used for assignment and copying across subfunctions. Created automatically only if_sloppy
isTrue
.
-
unit_registry
¶ pint.UnitRegistry
– Pint unit registry.
-
_sloppy
¶ bool – Create some of the above attributes automatically. If you want the
function_subspace_registry
to be shared, do not use this option.
-
cell_function
¶
-
cell_function_function
¶
-
facet_function
¶
-
function_space_cache
create new one if not supplied
-
function_subspace_registry
create new one if not supplied
-
mesh
¶
-
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
-
space
¶
-
ufl_cell
¶
-
unit_registry
get unit from
self.mesh_data.mesh_unit
- mesh_data – See
simudo.fem.newton_solver module¶
-
class
simudo.fem.newton_solver.
NewtonSolution
(solver, u_=None)[source]¶ Bases:
object
-
A
¶
-
b
¶
-
b_norm
¶
-
du_norm
¶
-
has_nans
¶
-
q
¶
-
rel_du_norm
¶
-
size
¶
-
-
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 solveF(u_) = 0
by varyingu_
. - 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 tou_
’s coefficients. If this is not supplied, it is derived fromF
automatically. - parameters (dict) – Parameters controlling the Newton solution process.
-
iteration
¶ int – Current iteration.
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.-
du_mask_array
= None¶
-
extra_iterations
= None¶
-
iteration
= 0
-
logger
¶
-
solution_class
¶ alias of
NewtonSolution
- F (
simudo.fem.offset_partitioning module¶
-
class
simudo.fem.offset_partitioning.
PartitionOffsets
(**kwargs)[source]¶ Bases:
simudo.util.setattr_init_mixin.SetattrInitMixin
Offset partitioner.
-
function
¶ dolfin.Function
– Input function. Must be DG0 function.
-
thresholds
¶ sequence – Thresholds, as list of tuples
(absolute_threshold, relative_threshold)
.
-
mesh_util
¶ mesh_util.MeshUtil
– Mesh utilities and data.
-
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:
- All cells are unmarked (have a marker value of nan), and unseen. The cell queue is empty.
- The cells adjacent to boundary conditions are placed in the cell queue. They are marked with the boundary condition value.
- While there exist unseen cells:
- If the cell queue is empty, pick one unseen cell and place it in the cell queue.
- Remove cell out of queue, and visit it:
- Consider the current cell as seen.
- If the cell is already marked, set
this_marker
to the marker value. Otherwise, setthis_marker
to the current cell value. - For every unmarked and unseen neighbor: if its value is
“close” to our marker value, mark it with
this_marker
, and consider it “seen”. - Add newly-marked cells to the cell queue.
- 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),)
-
simudo.fem.plot module¶
-
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
- function (
-
class
simudo.fem.plot.
BaseDolfinFunctionRenderFrame
(renderer, size, extent)[source]¶ Bases:
object
-
V
¶
-
extract_params
¶
-
extracted_V
¶
-
-
class
simudo.fem.plot.
DolfinFunctionRenderFrame
(renderer, size, extent)[source]¶ Bases:
simudo.fem.plot.BaseDolfinFunctionRenderFrame
-
Xs
¶
-
Ys
¶
-
coordinates
¶
-
-
class
simudo.fem.plot.
DolfinFunctionRenderLineCutFrame
(renderer, size, extent)[source]¶ Bases:
simudo.fem.plot.BaseDolfinFunctionRenderFrame
-
Ts
¶
-
coordinates
¶
-
extracted_T
¶
-
-
class
simudo.fem.plot.
DolfinFunctionRenderer
(function, extract_params)[source]¶ Bases:
object
-
default_value
= nan¶
-
frame_class
¶ alias of
DolfinFunctionRenderFrame
-
value_shape
¶
-
-
class
simudo.fem.plot.
DolfinFunctionLineCutRenderer
(function, extract_params)[source]¶ Bases:
simudo.fem.plot.DolfinFunctionRenderer
-
frame_class
¶ alias of
DolfinFunctionRenderLineCutFrame
-
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.
-
require_natural
= False¶
-
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. Seemap
. - 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
¶ dict – Mapping
{(facet_value, sign): value_extractor(bc)}
.
-
reverse_map
¶ dict – Mapping
{bc_value: {(facet_value, sign), ...}}
.
-
fv_set
¶ set – Set of referenced facet values. Useful to check that BCs don’t overlap.
-
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 thebcdict
argument. - fv_adjacent_cells_function (
dolfin.Function
) – DG0 function containing ones and zeros; ones iff the cell is adjacent to a BC.
- mesh_util (
-
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
insidefacet_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
-
map
-
mesh_data
¶
-
offset_partitioning_bc_cells
¶
-
reverse_map
-
value_extractor
= None¶
-
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
¶ defaultdict(SortedList) – Rules for spatially dependent values. Must be dict of list of dicts.
-
bcs
¶ defaultdict(SortedList) – Boundary conditions.
-
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.
- key (str) – Name of the spatial property, e.g.,
-
add_value_rule
(region, key, value, priority=0)[source]¶ Deprecated. Use
add_rule()
.
-
bcs
-
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
underget_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
-
material_to_region_map
¶
-
mesh_data
¶
-
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
[source]¶ Bases:
sympy.core.function.Function
-
default_assumptions
= {}¶
-
nargs
= {1}¶
-
value
¶
-
-
class
simudo.fem.sympy_dolfin_printer.
DolfinPrinter
(*args, **kwargs)[source]¶ Bases:
sympy.printing.printer.Printer
Code printer for Theano computations
-
emptyPrinter
(expr)[source]¶ str(object=’‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
-
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
= '_dolfin'¶
-