simudo.fem package¶
Submodules¶
simudo.fem.adaptive_stepper module¶
- class simudo.fem.adaptive_stepper.AdaptiveStepper(**kwargs)[source]¶
Bases:
BaseAdaptiveStepperConcrete subclass of
BaseAdaptiveStepperwith solution save/restore support.Subclasses must implement
user_make_solver()(returns aNewtonSolver) anduser_apply_parameter_to_solution().- Parameters:
to_save_objects (dict) – Mapping of vector-like objects representing the current
solution, whose values to save (and restore upon solver failure).
See also
NonequilibriumCoupledStepperPDD subclass.
VoltageSteppervoltage-sweep specialisation.
OpticalIntensityAdaptiveStepperoptical-ramp specialisation.
- check_bcs_resolve_to_facets()[source]¶
Fail loudly if no boundary condition matches any exterior facet.
A mesh that was read back from a file does not have its facet-to-cell connectivity built, and
boundary_mesh_entities()identifies exterior facets withlen(f.entities(D)) == 1. Without that connectivity it yields nothing, somark_boundary_facetsmarks nothing, the right/top/left/bottom classes are never assigned, and every facet region namingexterior(or anything built on it, such as the contacts) evaluates to the empty set. Every boundary condition then applies to zero facets, with no error raised anywhere.Nothing can be repaired at this point: the boundary marking happens in
compute_facets(), during problem construction, long before any checkpoint is read. The connectivity has to exist before then. So this only reports, and points at the fix.This problem occurs when a mesh is loaded from a file, which is what a restart requires whenever meshing is not reproducible.
- find_unconverged_parameters()[source]¶
Run after a failed step to see which variables failed to meet their tolerance
- load_xdmf_checkpoint()[source]¶
Load in a saved checkpoint file. Must have been made with the same problemdata used to make this AdaptiveStepper instance.
- 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_solutionis as returned byuser_solution_save().If
solution_scaleis 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.
- class simudo.fem.adaptive_stepper.BaseAdaptiveStepper(**kwargs)[source]¶
Bases:
SetattrInitMixinAdaptive 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
parameterto attain.output_writerwill 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.
- Variables:
parameter (float) – Current value of the parameter.
step_size (float) – Current step size.
update_parameter_success_factor (float) – If the solver succeeds, multiply
step_sizeby this factor.update_parameter_failure_factor (float) – If the solver fails, multiply
step_sizeby this factor.stepper_rel_tol (float) – If
step_size ` drops below :py:attr:`stepper_rel_tol`*max(:py:attr:`parameter, initial_step_size), the stepper will stop and raise aStepperError.
Notes
This class implements the abstract algorithm, so it makes no assumptions as to what
solutionrepresents. Users of this class must implement theuser_solver(),user_solution_add(), anduser_solution_save()methods.See also
AdaptiveStepperconcrete subclass with save/restore support.
NonequilibriumCoupledStepperPDD-specific subclass.
- break_criteria_cb = None¶
- checkpoint_reload_yaml = None¶
- checkpoint_write_filename = None¶
- checkpoint_write_values = ()¶
- debug_find_unconverged_parameters = False¶
- keep_saved_solutions_count = 2¶
- log_print_new_parameter()[source]¶
As the stepper updates the parameter, call this method to output to the log
- output_writer = None¶
- parameter¶
- parameter_name = ''¶
- 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¶
- stepper_rel_tol = 1e-05¶
- update_parameter()[source]¶
This method is called to update
parameterafter 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_solutionis as returned byuser_solution_save().If
solution_scaleis 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.Quantitywrappingdolfin.Constant) – On each step, the constant’s value will be assigned to be the current parameter value.parameter_unit (
pint.Quantity, optional) – Parameter unit.
- parameter_unit = None¶
- property unit_registry¶
simudo.fem.assign module¶
simudo.fem.delayed_form module¶
simudo.fem.dolfin_parameters module¶
simudo.fem.expr module¶
- 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.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.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¶
simudo.fem.function_space module¶
- class simudo.fem.function_space.MixedFunctionHelper(**kwargs)[source]¶
Bases:
SetattrInitMixinUtility mixin for objects that hold a mixed function made 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 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_descriptorson 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
.functionattribute to get the dolfin Function.- Return type:
- 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:
objectConvenience class for dealing with mixed function spaces.
- class MixedFunction(mixed_function_space, function=None)¶
Bases:
MixedFunctionLikeMixin
- class MixedTestFunction(mixed_function_space, function=None)¶
Bases:
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 simudo.fem.function_space.WithSubfunctionsMixin(**kwargs)[source]¶
Bases:
SetattrInitMixinUtility 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.
- property solution_subspace_descriptors¶
Creates properly namespaced subspace descriptors.
- Returns:
Returns properly namespaced subspace descriptors by prefixing the descriptors in
subfunctions_infowithself.key + "/".
simudo.fem.function_space_cache module¶
simudo.fem.function_subspace_registry module¶
- class simudo.fem.function_subspace_registry.FunctionSubspaceRegistry[source]¶
Bases:
objectThe 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.
- get_function_space(subfunction, collapsed=False)[source]¶
Get function space of a (sub)function. Use collapsed=True to return a fresh independent/unattached copy.
- exception simudo.fem.function_subspace_registry.FunctionTypeError[source]¶
Bases:
AssignmentError,TypeError
- exception simudo.fem.function_subspace_registry.IncompatibleFunctionSpacesError[source]¶
Bases:
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:
BaseRenderingThe 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¶
simudo.fem.mesh_data module¶
- class simudo.fem.mesh_data.MeshData(**kwargs)[source]¶
Bases:
SetattrInitMixinHolds mesh and topology data relating to a particular dolfin mesh.
- Variables:
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.CellRegionortopology.FacetRegion) – Topological region.- Returns:
geometrical_values – The return value depends on the type of the
regionargument.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_valueis a facet value (value infacet_function), andsignis either+1or-1depending 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:
MeshUtilPY,SetattrInitMixinHolds 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.
- Variables:
mesh_data (
MeshData) – Holds mesh and topology information.function_space_cache (
FunctionSpaceCache) – Used to avoid creating redundant function spaces. Created automatically only if_sloppyisTrue.function_subspace_registry (
FunctionSubspaceRegistry) – Used for assignment and copying across subfunctions. Created automatically only if_sloppyisTrue.unit_registry (
pint.UnitRegistry) – Pint unit registry._sloppy (bool) – Create some of the above attributes automatically. If you want the
function_subspace_registryto be shared, do not use this option.
- property cell_function¶
- cell_function_function¶
- property facet_function¶
- function_space_cache¶
create new one if not supplied
- function_subspace_registry¶
create new one if not supplied
- 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 todS_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
simudo.fem.newton_solver module¶
- class simudo.fem.newton_solver.NewtonSolution(solver, u_=None)[source]¶
Bases:
object- A¶
- b¶
- b_norm¶
- combined_b_norm¶
Like combined_du_norm but for b instead of du
- combined_du_norm¶
- du_norm¶
- has_nans¶
- mumps_icntl = ()¶
- q¶
- rel_du_norm¶
- release_linear_solver()[source]¶
Drop the cached LU/MUMPS solver at the end of a Newton solve.
_lu_solveris deliberately kept for the whole solve (seedo_linear_solve()) so that MUMPS can reuse its symbolic analysis across Newton iterations, and it is therefore not listed in_cached_property_attrs– clearing it per iteration would throw away exactly the saving it exists for.It must still be released once the solve is over. This object and its
NewtonSolverhold each other (NewtonSolution.__init__()setsself.solver,NewtonSolver.do_init_solution()setsself.solution), so the pair is a reference cycle: dropping the solver does not reclaim it by refcounting, only a generational garbage collection does. CPython triggers collection from counts of Python allocations, so a handful of Python objects holding a large MUMPS factorisation is nearly invisible to that heuristic and collection can be arbitrarily late. Releasing here frees the factorisation deterministically instead.Measured on a 2-D drift-diffusion voltage sweep: without this, RSS grew ~13 MB per Newton iteration (reaching tens of GB on production meshes, with OOM kills); with it, ~1.7 MB per iteration. Computed terminal currents were unchanged to ~5e-4 relative, i.e. within the Newton convergence tolerance.
- size¶
- class simudo.fem.newton_solver.NewtonSolver(F, u_, bcs, J=None, parameters=None, pdd=None)[source]¶
Bases:
objectA 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_) = 0by 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 fromFautomatically.parameters (dict) – Parameters controlling the Newton solution process.
- Variables:
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.- default_parameters = {'absolute_tolerance': 1e-05, 'absolute_tolerance_vector': 1.0, 'convergence_criterion': 'du', 'extra_iterations': 3, 'form_compiler_parameters': {'eliminate_zeros': True, 'optimize': True, 'precompute_basis_const': False, 'precompute_ip_const': False, 'simplify_expressions': False}, 'maximum_iterations': 25, 'minimum_iterations': -1, 'mumps_icntl': (), 'relative_tolerance': 1e-06, 'relaxation_parameter': 1.0}¶
- du_mask_array = None¶
- extra_iterations = None¶
- iteration = 0¶
- logger¶
- solution_class¶
alias of
NewtonSolution
- class simudo.fem.newton_solver.NewtonSolverLogDamping(F, u_, bcs, J=None, parameters=None, pdd=None)[source]¶
Bases:
NewtonSolverVariant of
NewtonSolverthat applies log-damping to the Newton updatedubefore each solution step, following Gaury 2018. The damping strength is controlled byparameters['logdamping_alpha'](default 1.72); larger values give stronger damping.Used by
OpticalIntensityLogDampStepper.
- class simudo.fem.newton_solver.NewtonSolverMaxDu(F, u_, bcs, J=None, parameters=None, pdd=None)[source]¶
Bases:
NewtonSolverVariant of
NewtonSolverthat clips the Newton updateduto[-maximum_du, +maximum_du]component-wise before applying it. Setparameters['maximum_du']to enable the clipping.
simudo.fem.offset_partitioning module¶
- class simudo.fem.offset_partitioning.PartitionOffsets(**kwargs)[source]¶
Bases:
SetattrInitMixinOffset partitioner.
- Variables:
function (
dolfin.Function) – Input function. Must be DG0 function.out_function (
dolfin.Function) – Output function. If not set, usefunction. 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_markerto the marker value. Otherwise, setthis_markerto 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¶
- class simudo.fem.plot.BaseDolfinFunctionRenderFrame(renderer, size, extent)[source]¶
Bases:
object- V¶
- extract_params¶
- extracted_V¶
- class simudo.fem.plot.DolfinFunctionLineCutRenderer(function, extract_params)[source]¶
Bases:
DolfinFunctionRenderer- frame_class¶
alias of
DolfinFunctionRenderLineCutFrame
- class simudo.fem.plot.DolfinFunctionRenderFrame(renderer, size, extent)[source]¶
Bases:
BaseDolfinFunctionRenderFrame- Xs¶
- Ys¶
- coordinates¶
- class simudo.fem.plot.DolfinFunctionRenderLineCutFrame(renderer, size, extent)[source]¶
Bases:
BaseDolfinFunctionRenderFrame- Ts¶
- coordinates¶
- property extracted_T¶
- class simudo.fem.plot.DolfinFunctionRenderer(function, extract_params)[source]¶
Bases:
object- default_value = nan¶
- frame_class¶
alias of
DolfinFunctionRenderFrame
- value_shape¶
- 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:
SetattrInitMixinBoundary 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.CallableValueRule(**kwargs)[source]¶
Bases:
SetattrInitMixin- Rule for a spatially-dependent value defined by a callable
e.g., of photon energy.
- Parameters:
priority – Priority of this rule. Lower values have higher priority.
region (
topology.CellRegion) – Cell region where this callable applies.func (callable) – Callable with signature
f(E: pint.Quantity) -> pint.Quantity. Returns a scalar pint Quantity (possibly wrapping a dolfin.Constant or live UFL expression for state-dependent quantities).
- class simudo.fem.spatial.CombinedBoundaryCondition(**kwargs)[source]¶
Bases:
SetattrInitMixinCombination of multiple
BoundaryCondition.- Parameters:
bcs (SortedList) – Boundary conditions to combine.
value_extractor (callable, optional) – Applied to
BoundaryConditionobjects 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.
- Variables:
map (dict) – Mapping
{(facet_value, sign): extracted_bc}.reverse_map (dict) – Mapping
{extracted_bc: {(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
exprto in thebcdictargument.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
fvsinsidefacet_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¶
- property mesh_data¶
- offset_partitioning_bc_cells¶
- reverse_map¶
- value_extractor = None¶
- class simudo.fem.spatial.ExtractedBoundaryCondition(**kwargs)[source]¶
Bases:
SetattrInitMixinBoundary condition for which the value has been “extracted” by
CombinedBoundaryCondition.value_extractor.- Parameters:
value – Extracted value.
bc – Original
BoundaryConditionthat this BC came from.
- simudo.fem.spatial.KEY_ALIASES = {'v_th': 'vth'}¶
Legacy spatial-key spellings mapped onto their canonical form.
Thermal velocity was historically written
v_thwhen supplied as a trap process parameter (nr_top/v_th) andvthwhen supplied as a band property (CB/vth). It is a band property, sovthis canonical.Aliases are applied to the final path component only, so
nr_top/v_thnormalises tonr_top/vthwhile a region or process whose name happens to bev_this left alone.
- class simudo.fem.spatial.Spatial(**kwargs)[source]¶
Bases:
SetattrInitMixinContains 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.
- Variables:
value_rules (defaultdict(SortedList)) – Rules for spatially dependent values. Must be dict of list of dicts.
bcs (defaultdict(SortedList)) – Boundary conditions.
- add_BC(key, region, value, priority=0, require_natural=False, internal=False, external=True, **kwargs)[source]¶
- add_callable_rule(key, region, func, priority=0)[source]¶
Add a callable rule for a (usually energy)-dependent spatially-varying quantity.
- Parameters:
key (str) – Spatial key, e.g.
'opt_cv/alpha_function'.region (
topology.CellRegion) – Cell region where this callable applies.func (callable) – Callable with signature
f(E: pint.Quantity) -> pint.Quantity. Called at assembly time with a fixed value of e.g., photon energy; returns a scalar pint Quantity (may wrap a dolfin.Constant or a live UFL expression for state-dependent quantities such as intermediate-band fill factors).priority (int, optional) – Lower values have higher priority. Default 0.
- add_material_callable_data(key, material_name, func, priority=0)[source]¶
Register a callable rule for the cells where material_name is applied. Mirror of
add_material_data()for callables.
- 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¶
- callable_value_rules¶
- get_callable(key, E)[source]¶
Evaluate callable rules for
keyat photon energyE.Iterates over
callable_value_rules[key]in priority order, callsfunc(E)for each registered region, and assembles a piecewise UFL expression using the cell-marker mechanism (same asget()).Cell markers not covered by any rule default to zero.
- Parameters:
key (str) – Spatial key, e.g.
'opt_cv/alpha_function'.E (pint.Quantity) – (e.g.) Photon energy. Treated as a fixed Python-side scalar at each call
- Returns:
Piecewise expression assembled from the per-region callables.
- Return type:
pint.Quantity wrapping a UFL expression
- Raises:
AssertionError – If no callable rules are registered for
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_extractunderget_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
- property material_to_region_map¶
- property mesh_data¶
- property mesh_util¶
- value_rules¶
- class simudo.fem.spatial.ValueRule(**kwargs)[source]¶
Bases:
SetattrInitMixinRule 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.spatial.canonicalize_key(key)[source]¶
Map a deprecated spatial key onto its canonical spelling.
Applied by every
Spatialmethod that takes a key, so material files, YAML input and hand-writtenadd_rulecalls are all normalised on the way in and on the way out. Unrecognised keys are returned unchanged.- Parameters:
key (str) – Spatial key, e.g.
"nr_top/v_th"or"temperature".- Returns:
The canonical spelling of key.
- Return type:
str
simudo.fem.sympy_dolfin_printer module¶
- class simudo.fem.sympy_dolfin_printer.DolfinConstant(*args)[source]¶
Bases:
Function- default_assumptions = {}¶
- nargs = {1}¶
- property value¶
- class simudo.fem.sympy_dolfin_printer.DolfinPrinter(*args, **kwargs)[source]¶
Bases:
PrinterCode printer for Theano computations
- mapping = {<class 'sympy.core.add.Add'>: <function <lambda>.<locals>.<lambda>>, <class 'sympy.core.mul.Mul'>: <function <lambda>.<locals>.<lambda>>, <class 'sympy.core.power.Pow'>: <built-in function pow>, <function sqrt>: <function sqrt>, 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>}¶
- printmethod: str = '_dolfin'¶