API reference#

class DirichletBCBase(subdomain: SurfaceSubdomain, value: ndarray | Constant | int | float | Callable)[source]#

Bases: object

Dirichlet boundary condition class u = value.

Parameters:
  • subdomain – The surface subdomain where the boundary condition is applied

  • value – The value of the boundary condition

Variables:
  • subdomain (festim.subdomain.surface_subdomain.SurfaceSubdomain) – The surface subdomain where the boundary condition is applied

  • value (numpy.ndarray | dolfinx.fem.function.Constant | int | float | collections.abc.Callable[[numpy.ndarray], numpy.ndarray] | collections.abc.Callable[[numpy.ndarray, float], numpy.ndarray] | collections.abc.Callable[[float], float]) – The value of the boundary condition

  • value_fenics (None | dolfinx.fem.function.Function | dolfinx.fem.function.Constant | numpy.ndarray | float) – The value of the boundary condition in fenics format

  • bc_expr (dolfinx.fem.function.Expression) – The expression of the boundary condition that is used to update the value_fenics

define_surface_subdomain_dofs(facet_meshtags: MeshTags, function_space: FunctionSpace | tuple[FunctionSpace, FunctionSpace]) ndarray[Any, dtype[int32]] | tuple[ndarray[Any, dtype[int32]], ndarray[Any, dtype[int32]]][source]#

Defines the facets and the degrees of freedom of the boundary condition.

Given the input meshtags, find all facets matching the boundary condition subdomain ID, and locate all DOFs associated with the input function space(s).

Note

For sub-spaces, a tuple of sub-spaces are expected as input, and a tuple of arrays associated to each of the function spaces are returned.

Parameters:
  • facet_meshtags – MeshTags describing some facets in the domain

  • mesh

  • function_space – The function space or a tuple of function spaces:

  • (sub

  • collapsed)

property time_dependent: bool#

Returns true if the value of the boundary condition is time dependent.

update(t: float)[source]#

Updates the boundary condition value.

Parameters:

t – the time

class FixedConcentrationBC(subdomain: SurfaceSubdomain, value: ndarray | Constant | int | float | Callable, species: Species)[source]#

Bases: DirichletBCBase

Parameters:
  • subdomain (festim.Subdomain) – the surface subdomain where the boundary condition is applied

  • value – The value of the boundary condition. It can be a function of

  • time (space and/or)

  • species – The name of the species

Variables:
  • temperature_dependent (bool) – True if the value of the bc is

  • dependent (temperature)

Examples

FixedConcentrationBC(subdomain=my_subdomain, value=1, species="H")
FixedConcentrationBC(subdomain=my_subdomain,
                     value=lambda x: 1 + x[0], species="H")
FixedConcentrationBC(subdomain=my_subdomain,
                     value=lambda t: 1 + t, species="H")
FixedConcentrationBC(subdomain=my_subdomain,
                     value=lambda T: 1 + T, species="H")
FixedConcentrationBC(subdomain=my_subdomain,
                     value=lambda x, t: 1 + x[0] + t, species="H")
create_value(function_space: FunctionSpace, temperature: float | Constant, t: float | Constant, K_S: Function = None)[source]#

Creates the value of the boundary condition as a fenics object and sets it to self.value_fenics. If the value is a constant, it is converted to a dolfinx.fem.Constant. If the value is a function of t, it is converted to dolfinx.fem.Constant. Otherwise, it is converted to a dolfinx.fem.Function.Function and the expression of the function is stored in bc_expr.

Parameters:
  • function_space – the function space

  • temperature – The temperature

  • t – the time

  • K_S – The solubility of the species. If provided, the value of the

  • condition (boundary) – is divided by K_S (change of variable method).

class FixedTemperatureBC(subdomain: SurfaceSubdomain, value: ndarray | Constant | int | float | Callable)[source]#

Bases: DirichletBCBase

create_value(function_space: FunctionSpace, t: Constant)[source]#

Creates the value of the boundary condition as a fenics object and sets it to self.value_fenics. If the value is a constant, it is converted to a dolfinx.fem.Constant. If the value is a function of t, it is converted to a dolfinx.fem.Constant. Otherwise, it is converted to a` dolfinx.fem.Function` and the expression of the function is stored in bc_expr.

Parameters:
  • function_space – the function space

  • t – the time

class FluxBCBase(subdomain: SurfaceSubdomain, value)[source]#

Bases: object

Flux boundary condition class.

Ensuring the gradient of the solution u at a boundary:

\[-A \nabla u \cdot \mathbf{n} = f\]

where \(A\) is some material property (diffusivity for particle flux and thermal conductivity for heat flux), \(\mathbf{n}\) is the outwards normal vector of the boundary, \(f\) is a function of space and time.

Parameters:
  • subdomain (festim.SurfaceSubdomain) – the surface subdomain where the boundary condition is applied

  • value (float, fem.Constant, callable) – the value of the boundary condition

Variables:
  • subdomain (festim.SurfaceSubdomain) – the surface subdomain where the boundary condition is applied

  • value (float, fem.Constant, callable) – the value of the boundary condition

  • value_fenics (fem.Function or fem.Constant) – the value of the boundary

  • in (condition) – fenics format

  • bc_expr (fem.Expression) – the expression of the boundary condition that

  • to (is used) – update the value_fenics

create_value_fenics(mesh, temperature, t: Constant)[source]#

Creates the value of the boundary condition as a fenics object and sets it to self.value_fenics. If the value is a constant, it is converted to a fenics.Constant. If the value is a function of t, it is converted to a fenics.Constant. Otherwise, it is converted to a ufl Expression.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – the mesh

  • temperature (float) – the temperature

  • t (dolfinx.fem.Constant) – the time

update(t)[source]#

Updates the flux bc value.

Parameters:

t (float) – the time

class HeatFluxBC(subdomain, value)[source]#

Bases: FluxBCBase

Heat flux boundary condition class.

Ensuring the gradient of the solution T at a boundary: -lambda * grad(T) * n = f where lambda is the thermal conductivity , n is the outwards normal vector of the boundary, f is a function of space and time.

Parameters:
  • subdomain (festim.SurfaceSubdomain) – the surface subdomain where the heat flux is applied

  • value (float, callable, fem.Constant) – the value of the heat flux

Variables:
  • subdomain (festim.SurfaceSubdomain) – the surface subdomain where the heat flux is applied

  • value (float, callable, fem.Constant) – the value of the heat flux

  • value_fenics (fem.Function or fem.Constant) – the value of the heat flux in fenics format

  • bc_expr (fem.Expression) – the expression of the heat flux that is used to update the value_fenics

Examples

HeatFluxBC(subdomain=my_subdomain, value=1)
HeatFluxBC(subdomain=my_subdomain, value=lambda x: 1 + x[0])
HeatFluxBC(subdomain=my_subdomain, value=lambda t: 1 + t)
HeatFluxBC(subdomain=my_subdomain, value=lambda x, t: 1 + x[0] + t)
class HenrysBC(subdomain, H_0, E_H, pressure, species)[source]#

Bases: FixedConcentrationBC

Henrys boundary condition class.

c = H * pressure H = H_0 * exp(-E_H / k_B / T)

Parameters:
  • subdomain (festim.Subdomain) – the subdomain where the boundary condition is applied

  • species (str) – the name of the species

  • H_0 (float or fem.Constant) – the Henrys constant pre-exponential factor

  • (H/m3/Pa)

  • E_H (float or fem.Constant) – the Henrys constant activation energy (eV)

  • pressure (float or callable) – the pressure at the boundary (Pa)

Variables:
  • subdomain (festim.Subdomain) – the subdomain where the boundary condition is applied

  • value (float or fem.Constant) – the value of the boundary condition

  • species (festim.Species or str) – the name of the species

  • H_0 (float or fem.Constant) – the Henrys constant pre-exponential factor

  • (H/m3/Pa)

  • E_H (float or fem.Constant) – the Henrys constant activation energy (eV)

  • pressure (float or callable) – the pressure at the boundary (Pa)

Examples

HenrysBC(subdomain=my_subdomain, H_0=1e-6, E_H=0.2, pressure=1e5,
species="H")
HenrysBC(subdomain=my_subdomain, H_0=1e-6, E_H=0.2, pressure=lambda
x: 1e5 + x[0], species="H")
HenrysBC(subdomain=my_subdomain, H_0=1e-6, E_H=0.2, pressure=lambda
t: 1e5 + t, species="H")
HenrysBC(subdomain=my_subdomain, H_0=1e-6, E_H=0.2, pressure=lambda
T: 1e5 + T, species="H")
HenrysBC(subdomain=my_subdomain, H_0=1e-6, E_H=0.2, pressure=lambda
x, t: 1e5 + x[0] + t, species="H")
create_new_value_function()[source]#

Creates a new value function based on the pressure attribute.

Raises:

ValueError – if the pressure function is not supported

Returns:

the value function

Return type:

callable

class ParticleFluxBC(subdomain, value, species, species_dependent_value={})[source]#

Bases: FluxBCBase

Particle flux boundary condition class.

Ensuring the gradient of the solution c at a boundary: -D * grad(c) * n = f where D is the material diffusivity, n is the outwards normal vector of the boundary, f is a function of space and time.

Parameters:
  • subdomain (festim.SurfaceSubdomain) – the surface subdomain where the

  • flux (particle) – is applied

  • value (float, fem.Constant, callable) – the value of the particle flux

  • species (festim.Species) – the species to which the flux is applied

  • species_dependent_value (dict) – a dictionary containing the species

  • Example (that the value.) – {β€œname”: species} where β€œname” is the variable name in the callable value and species is a festim.Species object.

Variables:
  • subdomain (festim.SurfaceSubdomain) – the surface subdomain where the

  • flux (particle) – is applied

  • value (float or fem.Constant) – the value of the particle flux

  • species (festim.Species) – the species to which the flux is applied

  • value_fenics (fem.Function or fem.Constant) – the value of the particle flux in fenics format

  • bc_expr (fem.Expression) – the expression of the particle flux that is used to update the value_fenics

  • species_dependent_value (dict) – a dictionary containing the species

  • Example (that the value.) – {β€œname”: species} where β€œname” is the variable name in the callable value and species is a festim.Species object.

Examples

ParticleFluxBC(subdomain=my_subdomain, value=1, species="H")
ParticleFluxBC(subdomain=my_subdomain, value=lambda x: 1 + x[0],
species="H")
ParticleFluxBC(subdomain=my_subdomain, value=lambda t: 1 + t, species="H")
ParticleFluxBC(subdomain=my_subdomain, value=lambda T: 1 + T, species="H")
ParticleFluxBC(subdomain=my_subdomain, value=lambda x, t: 1 + x[0]
+ t, species="H")
ParticleFluxBC(subdomain=my_subdomain, value=lambda c1: 2 * c1**2,
species="H", species_dependent_value={"c1": species1})
create_value_fenics(mesh, temperature, t: Constant)[source]#

Creates the value of the boundary condition as a fenics object and sets it to self.value_fenics. If the value is a constant, it is converted to a fenics.Constant. If the value is a function of t, it is converted to a fenics.Constant. Otherwise, it is converted to a ufl Expression.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – the mesh

  • temperature (float) – the temperature

  • t (dolfinx.fem.Constant) – the time

class SievertsBC(subdomain, S_0, E_S, pressure, species)[source]#

Bases: FixedConcentrationBC

Sieverts boundary condition class.

c = S * sqrt(pressure) S = S_0 * exp(-E_S / k_B / T)

Parameters:
  • subdomain (festim.Subdomain) – the subdomain where the boundary condition is applied

  • species (str) – the name of the species

  • S_0 (float or fem.Constant) – the Sieverts constant pre-exponential

  • factor (H/m3/Pa0.5)

  • E_S (float or fem.Constant) – the Sieverts constant activation energy (eV)

  • pressure (float or callable) – the pressure at the boundary (Pa)

Variables:
  • subdomain (festim.Subdomain) – the subdomain where the boundary condition is applied

  • value (float or fem.Constant) – the value of the boundary condition

  • species (festim.Species or str) – the name of the species

  • S_0 (float or fem.Constant) – the Sieverts constant pre-exponential

  • factor (H/m3/Pa0.5)

  • E_S (float or fem.Constant) – the Sieverts constant activation energy (eV)

  • pressure (float or callable) – the pressure at the boundary (Pa)

Examples

SievertsBC(subdomain=my_subdomain, S_0=1e-6, E_S=0.2, pressure=1e5,
species="H")
SievertsBC(subdomain=my_subdomain, S_0=1e-6, E_S=0.2,
pressure=lambda x: 1e5 + x[0], species="H")
SievertsBC(subdomain=my_subdomain, S_0=1e-6, E_S=0.2,
pressure=lambda t: 1e5 + t, species="H")
SievertsBC(subdomain=my_subdomain, S_0=1e-6, E_S=0.2,
pressure=lambda T: 1e5 + T, species="H")
SievertsBC(subdomain=my_subdomain, S_0=1e-6, E_S=0.2,
pressure=lambda x, t: 1e5 + x[0] + t, species="H")
create_new_value_function()[source]#

Creates a new value function based on the pressure attribute.

Raises:

ValueError – if the pressure function is not supported

Returns:

the value function

Return type:

callable

class SurfaceReactionBC(reactant, gas_pressure, k_r0, E_kr, k_d0, E_kd, subdomain)[source]#

Bases: object

Boundary condition representing a surface reaction A + B <-> C.

where A, B are the reactants and C is the product the forward reaction rate is K_r = k_r0 * exp(-E_kr / (k_B * T)) and the backward reaction rate is K_d = k_d0 * exp(-E_kd / (k_B * T)) The reaction rate is: K = K_r * C_A * C_B - K_d * P_C with C_A, C_B the concentration of species A and B, P_C the partial pressure of species C at the surface.

The flux of species A entering the surface is K. In the special case where A=B, then the flux of particle entering the surface is 2*K

Parameters:
  • reactant (list) – list of F.Species objects representing the reactants

  • gas_pressure (float, callable) – the partial pressure of the product species

  • k_r0 (float) – the pre-exponential factor of the forward reaction rate

  • E_kr (float) – the activation energy of the forward reaction rate (eV)

  • k_d0 (float) – the pre-exponential factor of the backward reaction rate

  • E_kd (float) – the activation energy of the backward reaction rate (eV)

  • subdomain (F.SurfaceSubdomain) – the surface subdomain where the reaction occurs

class SurfaceReactionBCpartial(reactant, gas_pressure, k_r0, E_kr, k_d0, E_kd, subdomain, species)[source]#

Bases: ParticleFluxBC

Boundary condition representing a surface reaction A + B <-> C.

where A, B are the reactants and C is the product the forward reaction rate is K_r = k_r0 * exp(-E_kr / (k_B * T)) and the backward reaction rate is K_d = k_d0 * exp(-E_kd / (k_B * T)) The reaction rate is: K = K_r * C_A * C_B - K_d * P_C with C_A, C_B the concentration of species A and B, P_C the partial pressure of species C at the surface.

This class is used to create the flux of a single species entering the surface Example: The flux of species A entering the surface is K.

Parameters:
  • reactant (list) – list of F.Species objects representing the reactants

  • gas_pressure (float, callable) – the partial pressure of the product species

  • k_r0 (float) – the pre-exponential factor of the forward reaction rate

  • E_kr (float) – the activation energy of the forward reaction rate (eV)

  • k_d0 (float) – the pre-exponential factor of the backward reaction rate

  • E_kd (float) – the activation energy of the backward reaction rate (eV)

  • subdomain (F.SurfaceSubdomain) – the surface subdomain where the reaction occurs

  • species (F.Species) – the species to which the flux is applied

create_value_fenics(mesh, temperature, t: Constant)[source]#

Creates the value of the boundary condition as a fenics object and sets it to self.value_fenics. If the value is a constant, it is converted to a fenics.Constant. If the value is a function of t, it is converted to a fenics.Constant. Otherwise, it is converted to a ufl Expression.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – the mesh

  • temperature (float) – the temperature

  • t (dolfinx.fem.Constant) – the time

class AverageSurface(field: Species | str, surface: SurfaceSubdomain | int, filename: str | None = None)[source]#

Bases: SurfaceQuantity

Computes the average value of a field on a given surface.

Parameters:
  • field (festim.Species) – species for which the average surface is computed

  • surface (festim.SurfaceSubdomain) – surface subdomain

  • filename (str, optional) – name of the file to which the average surface is exported

Variables:

festim.SurfaceQuantity (see)

compute(u: Function | Indexed, ds: Measure, entity_maps=None)[source]#

Computes the average value of the field on the defined surface subdomain, and appends it to the data list.

Parameters:
  • u – field for which the average value is computed

  • ds – surface measure of the model

  • entity_maps – entity maps relating parent mesh and submesh

class AverageVolume(field: Species | str, volume: VolumeSubdomain | int, filename: str | None = None)[source]#

Bases: VolumeQuantity

Computes the average value of a field in a given volume.

Parameters:
  • field (festim.Species) – species for which the average volume is computed

  • volume (festim.VolumeSubdomain) – volume subdomain

  • filename (str, optional) – name of the file to which the average volume

  • exported (is)

Variables:

festim.VolumeQuantity (see)

compute(u, dx, entity_maps=None)[source]#

Computes the average value of solution function within the defined volume subdomain, and appends it to the data list.

class CustomFieldExport(filename: str | Path, expression: Callable, species_dependent_value: dict[str, Species] | None = None, times: list[float] | list[int] | None = None, subdomain: VolumeSubdomain = None, checkpoint: bool = False)[source]#

Bases: ExportBaseClass

Export a custom field to a VTX file

Parameters:
  • filename – The name of the output file

  • expression – A function evaluating the custom field. Positional arguments of the function can be β€œt” (time), β€œx” (spatial coordinate), β€œT” (temperature), or any key from the species_dependent_value dictionary.

  • species_dependent_value – A dictionary mapping argument names in expression to Species objects. Defaults to None.

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

  • subdomain – The volume subdomain on which the custom field is evaluated. Defaults to None.

  • checkpoint – If True, the export will be a checkpoint file using adios4dolfinx and won’t be readable by ParaView. Default is False.

Variables:
  • filename – The name of the output file

  • expression (collections.abc.Callable) – A function evaluating the custom field.

  • species_dependent_value (dict[str, festim.species.Species]) – A dictionary mapping argument names to Species objects.

  • subdomain (festim.subdomain.volume_subdomain.VolumeSubdomain) – The volume subdomain on which the custom field is evaluated.

  • checkpoint (bool) – If True, the export will be a checkpoint file.

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps.

  • function (dolfinx.fem.function.Function) – the function containing the custom field values

  • writer (dolfinx.io.utils.VTXWriter) – The VTXWriter object used to write the file

  • dolfinx_expression (dolfinx.fem.function.Expression) – the dolfinx expression used to evaluate the function

check_valid_inputs(kwargs: dict)[source]#

Check if we are in the mixed domain/discontinuous case and if the user-provided expression is valid in this case. dolfinx.fem.Expression does not support co-dim 0 submeshes and time is defined on the parent mesh, so we cannot have time-dependent custom fields in the mixed domain/discontinuous case.

When FEniCS/dolfinx#3207 is resolved we should be able to support this

property mixed_domain: bool#

Check if we are in a mixed domain/discontinuous case. This is the case if at least one of the species in species_dependent_value is defined on a subdomain or if the custom field is defined on a subdomain.

Returns:

True if we are in a mixed domain/discontinuous case, False otherwise.

set_dolfinx_expression(temperature: Constant | Function, time: Constant)[source]#

Set the dolfinx expression used to evaluate the custom field. This is done by evaluating the user-provided expression with the appropriate arguments and using the result to create a dolfinx expression.

Parameters:
  • temperature – The temperature field to use in the expression

  • time – The time to use in the expression

class CustomQuantity(expr: Callable, subdomain: SurfaceSubdomain | VolumeSubdomain, title: str = 'Custom Quantity', filename: str | None = None)[source]#

Bases: DerivedQuantity

Export CustomQuantity.

Parameters:
  • expr – function that returns a UFL expression

  • subdomain – subdomain on which the quantity is evaluated

  • title – title of the exported quantity

  • filename – name of the file to which the quantity is exported

Variables:
  • expr – function that returns a UFL expression

  • subdomain – subdomain on which the quantity is evaluated

  • title – title of the exported quantity

  • filename (str | None) – name of the file to which the quantity is exported

  • t (list[float]) – list of time values

  • data (list[float]) – list of values of the quantity

Usage:

import numpy as np
import festim as F

material = F.Material(D_0=1, E_D=0)
volume = F.VolumeSubdomain(id=1, material=material)
surface = F.SurfaceSubdomain(id=1, locator=lambda x: np.isclose(x[1], 1))

def total_concentration(**kwargs):
    return kwargs["A"] + kwargs["B"]

quantity = F.CustomQuantity(
    expr=total_concentration,
    subdomain=volume,
    title="Total quantity",
)

surface_quantity = F.CustomQuantity(
    expr=lambda **kwargs: -kwargs["D_A"] * ufl.dot(
        ufl.grad(kwargs["A"]), kwargs["n"]
    ),
    subdomain=surface,
    title="Surface flux",
)

The callable passed to expr receives keyword arguments assembled by the problem class. Common entries are:

A, B, …

Concentrations of the species present in the problem (here A and B).

n

The facet normal on the selected surface subdomain.

T

The temperature field.

D_A, D_B, …

Species-specific diffusion coefficients.

D

The diffusion coefficient data, either a single field for one species or a dictionary keyed by species name when several species are present.

x

The spatial coordinate (x[0], x[1], x[2]).

For a surface quantity, the returned UFL expression can represent a flux such as

\[q = -D\,\nabla c \cdot n\]

and FESTIM will assemble

\[Q = \int_{\Gamma} q\,\mathrm{d}\Gamma\]

over the selected surface subdomain.

The expression returned by expr is treated as an integrand and assembled over the chosen subdomain.

\[Q = \int_{\Omega} q\,\mathrm{d}\Omega\]

where q is the UFL expression returned by expr and \Omega is either a surface or a volume subdomain.

compute(measure: Measure, entity_maps: dict | None = None)[source]#

Computes the value of the custom quantity and appends it to the data list.

Parameters:
  • measure – volume or surface measure of the model

  • entity_maps – entity maps relating parent mesh and submesh

class DerivedQuantity(filename: str | None = None)[source]#

Bases: ABC

Base class for all derived quantities.

Variables:
  • filename (str | None) – name of the file to which the quantity is exported

  • t (list[float]) – list of time values

  • data (list[float]) – list of values of the quantity

write(t)[source]#

If the filename doesnt exist yet, create it and write the header, then append the time and value to the file.

class ExportBaseClass(filename: str | Path, ext: str, times: list[float] | list[int] | None = None)[source]#

Bases: object

Export functions to VTX file.

Parameters:
  • filename – The name of the output file

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

Variables:
  • filename – The name of the output file

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

class MaximumSurface(field: Species | str, surface: SurfaceSubdomain | int, filename: str | None = None)[source]#

Bases: SurfaceQuantity

Computes the maximum value of a field on a given surface.

Parameters:
  • field (festim.Species) – species for which the maximum surface is computed

  • surface (festim.SurfaceSubdomain) – surface subdomain

  • filename (str, optional) – name of the file to which the maximum surface

  • exported (is)

Variables:

festim.SurfaceQuantity (see)

compute()[source]#

Computes the maximum value of the field on the defined surface subdomain, and appends it to the data list.

class MaximumVolume(field: Species | str, volume: VolumeSubdomain | int, filename: str | None = None)[source]#

Bases: VolumeQuantity

Computes the maximum value of a field in a given volume.

Parameters:
  • field (festim.Species) – species for which the maximum volume is computed

  • volume (festim.VolumeSubdomain) – volume subdomain

  • filename (str, optional) – name of the file to which the maximum volume

  • exported (is)

Variables:

festim.VolumeQuantity (see)

compute()[source]#

Computes the maximum value of solution function within the defined volume subdomain, and appends it to the data list.

class MinimumSurface(field: Species | str, surface: SurfaceSubdomain | int, filename: str | None = None)[source]#

Bases: SurfaceQuantity

Computes the minimum value of a field on a given surface.

Parameters:
  • field (festim.Species) – species for which the minimum surface is computed

  • surface (festim.SurfaceSubdomain) – surface subdomain

  • filename (str, optional) – name of the file to which the minimum surface

  • exported (is)

Variables:

festim.SurfaceQuantity (see)

compute()[source]#

Computes the minimum value of the field on the defined surface subdomain, and appends it to the data list.

class MinimumVolume(field: Species | str, volume: VolumeSubdomain | int, filename: str | None = None)[source]#

Bases: VolumeQuantity

Computes the minimum value of a field in a given volume.

Parameters:
  • field (festim.Species) – species for which the minimum volume is computed

  • volume (festim.VolumeSubdomain) – volume subdomain

  • filename (str, optional) – name of the file to which the minimum volume

  • exported (is)

Variables:

festim.VolumeQuantity (see)

compute()[source]#

Computes the minimum value of solution function within the defined volume subdomain, and appends it to the data list.

class Profile1DExport(field: Species, subdomain: VolumeSubdomain = None, times: list[float] | None = None)[source]#

Bases: object

Class to export 1D profiles of a field in a simulation.

Parameters:
  • field – the species for which the profile is computed.

  • subdomain – the volume subdomain to compute the profile on. If None, the profile is computed over the entire domain.

  • times – if provided, the profile will be exported at these timesteps. Otherwise, exports at all timesteps. Defaults to None.

Variables:
  • field (festim.species.Species) – the species for which the profile is computed.

  • subdomain (festim.subdomain.volume_subdomain.VolumeSubdomain | None) – the volume subdomain to compute the profile on. If None, the profile is computed over the entire domain.

  • times (list[float] | None) – if provided, the profile will be exported at these timesteps. Otherwise, exports at all timesteps.

  • x (numpy.ndarray) – the coordinates along which the profile is computed.

  • data (list) – the computed profile data.

  • t (list[float]) – the list of time values at which the profile is computed.

class ReactionRateExport(reaction: Reaction, filename: str | Path, direction: str = 'both', times: list[float] | None = None, subdomain: VolumeSubdomain | None = None, checkpoint: bool = False)[source]#

Bases: CustomFieldExport

Export a reaction rate to a VTX file

Parameters:
  • reaction – The reaction to export the rate of.

  • filename – The name of the output file.

  • direction – The direction of the reaction to export. Can be β€œforward”, β€œbackward” or β€œboth”. Defaults to β€œboth”.

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

  • subdomain – The volume subdomain on which the reaction rate is evaluated. Defaults to None.

  • checkpoint – If True, the export will be a checkpoint file using adios4dolfinx and won’t be readable by ParaView. Default is False.

override_signature(expression: Callable, reactant_names: list[str], product_names: list[str])[source]#

Override the signature of the expression function. This is needed to ensure that the expression has the correct arguments for set_dolfinx_expression().

Parameters:

expression – The user-provided expression for the reaction rate. The arguments of the expression must be T (temperature) and the names of the reactants and products.

class SurfaceFlux(field: Species, surface: SurfaceSubdomain, filename: str | None = None)[source]#

Bases: SurfaceQuantity

Computes the flux of a field on a given surface.

Parameters:
  • field – species for which the surface flux is computed

  • surface – surface subdomain

  • filename – name of the file to which the surface flux is exported

Variables:

festim.SurfaceQuantity (see)

compute(u: Function | Indexed, ds: Measure, entity_maps=None)[source]#

Computes the value of the flux at the surface.

Parameters:
  • u – field for which the flux is computed

  • ds – surface measure of the model

  • entity_maps – entity maps relating parent mesh and submesh

class SurfaceQuantity(field: Species | str, surface: SurfaceSubdomain | int, filename: str | None = None)[source]#

Bases: DerivedQuantity

Export SurfaceQuantity.

Parameters:
  • field – species for which the surface flux is computed

  • surface – surface subdomain

  • filename – name of the file to which the surface flux is exported

Variables:
  • field (festim.species.Species) – species for which the surface flux is computed

  • surface (festim.subdomain.surface_subdomain.SurfaceSubdomain) – surface subdomain

  • filename (str | None) – name of the file to which the surface flux is exported

  • t (list[float]) – list of time values

  • data (list[float]) – list of values of the surface quantity

class TotalSurface(field: Species | str, surface: SurfaceSubdomain | int, filename: str | None = None)[source]#

Bases: SurfaceQuantity

Computes the total value of a field on a given surface.

Parameters:
  • field (festim.Species) – species for which the total volume is computed

  • surface (festim.SurfaceSubdomain) – surface subdomain

  • filename (str, optional) – name of the file to which the total volume is exported

Variables:

festim.SurfaceQuantity (see)

compute(u: Function | Indexed, ds: Measure, entity_maps=None)[source]#

Computes the total value of the field on the defined surface subdomain, and appends it to the data list.

Parameters:
  • u – field for which the total value is computed

  • ds – surface measure of the model

  • entity_maps – entity maps relating parent mesh and submesh

class TotalVolume(field: Species | str, volume: VolumeSubdomain | int, filename: str | None = None)[source]#

Bases: VolumeQuantity

Computes the total value of a field in a given volume.

Parameters:
  • field (festim.Species) – species for which the total volume is computed

  • volume (festim.VolumeSubdomain) – volume subdomain

  • filename (str, optional) – name of the file to which the total volume is exported

Variables:

festim.VolumeQuantity (see)

compute(u, dx: Measure, entity_maps=None)[source]#

Computes the value of the total volume of the field in the volume subdomain and appends it to the data list.

Parameters:
  • u – field for which the total volume is computed

  • dx – volume measure of the model

  • entity_maps – entity maps relating parent mesh and submesh

class VTXSpeciesExport(filename: str | Path, field: Species | list[Species], subdomain: VolumeSubdomain = None, checkpoint: bool = False, times: list[float] | list[int] | None = None)[source]#

Bases: ExportBaseClass

Export species field functions to VTX file.

Parameters:
  • filename – The name of the output file

  • field – Set of species to export

  • subdomain – A field can be defined on multiple domains. This arguments specifies what subdomains we export on. If None we export on all domains.

  • checkpoint – If True, the export will be a checkpoint file using adios4dolfinx and won’t be readable by ParaView. Default is False.

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

Variables:
  • filename – The name of the output file

  • field – Set of species to export

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

  • writer (dolfinx.io.utils.VTXWriter) – The VTXWriter object used to write the file

get_functions() list[Function][source]#

Returns list of species for a given subdomain.

If using legacy mode, return the whole species.

class VTXTemperatureExport(filename: str | Path, times: list[float] | list[int] | None = None)[source]#

Bases: ExportBaseClass

Export temperature field functions to VTX file.

Parameters:
  • filename – The name of the output file

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

Variables:
  • filename – The name of the output file

  • times – if provided, the field will be exported at these timesteps. Otherwise exports at all timesteps. Defaults to None.

  • writer (dolfinx.io.utils.VTXWriter) – The VTXWriter object used to write the file

class VolumeQuantity(field: Species | str, volume: VolumeSubdomain | int, filename: str | None = None)[source]#

Bases: DerivedQuantity

Export VolumeQuantity.

Parameters:
  • field – species for which the volume quantity is computed

  • volume – volume subdomain

  • filename – name of the file to which the volume quantity is exported

Variables:
  • field (festim.species.Species) – species for which the volume quantity is computed

  • volume (festim.subdomain.volume_subdomain.VolumeSubdomain) – volume subdomain

  • filename (str | None) – name of the file to which the volume quantity is exported

  • t (list[float]) – list of time values

  • data (list[float]) – list of values of the volume quantity

class XDMFExport(filename: str | Path, field: list[Species] | Species)[source]#

Bases: ExportBaseClass

Export functions to XDMFfile.

Parameters:
  • filename – The name of the output file

  • field – The field(s) to export

Variables:
  • _writer (dolfinx.io.XDMFFile) – the XDMF writer

  • _field (festim.Species, list of festim.Species) – the field index to export

define_writer(comm: Intracomm) None[source]#

Define the writer.

Parameters:

comm (mpi4py.MPI.Intracomm) – the MPI communicator

write(t: float)[source]#

Write functions to VTX file.

Parameters:

t (float) – the time of export

class CoordinateSystem(value)[source]#

Bases: Enum

classmethod from_string(s: str)[source]#

Can be removed with Python 3.11+.

class Mesh(mesh: Mesh | None = None, coordinate_system: str | CoordinateSystem = CoordinateSystem.CARTESIAN)[source]#

Bases: object

Mesh class.

Parameters:
  • mesh – The mesh. Defaults to None.

  • coordinate_system – the coordinate system of the mesh (β€œcartesian”, β€œcylindrical”, β€œspherical”). Defaults to β€œcartesian”.

Variables:
  • mesh (mesh The)

  • vdim (int) – the dimension of the mesh cells

  • fdim (int) – the dimension of the mesh facets

  • n (ufl.geometry.FacetNormal) – Symbolic representation of the vector normal to the facets of the mesh.

check_mesh_dim_coords()[source]#

Checks if the used coordinates can be applied for geometry with the specified dimensions.

define_meshtags(surface_subdomains, volume_subdomains, interfaces=None)[source]#

Defines the facet and volume meshtags of the mesh.

Parameters:
  • surface_subdomains (list of festim.SufaceSubdomains) – the surface

  • model (subdomains of the)

  • volume_subdomains (list of festim.VolumeSubdomains) – the volume

  • model

  • interfaces (dict, optional) – the interfaces between volume subdomains {int: [VolumeSubdomain, VolumeSubdomain]}. Defaults to None.

Returns:

the facet meshtags dolfinx.mesh.MeshTags: the volume meshtags

Return type:

dolfinx.mesh.MeshTags

class Mesh1D(vertices, **kwargs)[source]#

Bases: Mesh

1D Mesh.

Parameters:

vertices (list or np.ndarray) – the mesh x-coordinates (m)

Variables:

vertices (np.ndarray) – the mesh x-coordinates (m)

check_borders(volume_subdomains)[source]#

Checks that the borders of the subdomain are within the domain.

Parameters:

volume_subdomains (list of festim.VolumeSubdomain1D) – the volume subdomains

Raises:

Value error – if borders outside the domain

define_meshtags(surface_subdomains, volume_subdomains, interfaces=None)[source]#

Defines the facet and volume meshtags of the mesh.

Parameters:
  • surface_subdomains (list of festim.SufaceSubdomains) – the surface

  • model (subdomains of the)

  • volume_subdomains (list of festim.VolumeSubdomains) – the volume

  • model

  • interfaces (dict, optional) – the interfaces between volume subdomains {int: [VolumeSubdomain, VolumeSubdomain]}. Defaults to None.

Returns:

the facet meshtags dolfinx.mesh.MeshTags: the volume meshtags

Return type:

dolfinx.mesh.MeshTags

generate_mesh()[source]#

Generates a 1D mesh.

class MeshFromXDMF(volume_file, facet_file, mesh_name='Grid', surface_meshtags_name='Grid', volume_meshtags_name='Grid')[source]#

Bases: Mesh

Mesh read from the XDMF files.

Parameters:
  • volume_file (str) – path to the volume file

  • facet_file (str) – path to the facet file

  • mesh_name (str, optional) – name of the mesh in the volume XDMF file. Defaults to β€œGrid”.

  • surface_meshtags_name (str, optional) – name of the surface meshtags in the facet XDMF file. Defaults to β€œGrid”.

  • volume_meshtags_name (str, optional) – name of the volume meshtags in the volume XDMF file. Defaults to β€œGrid”.

Variables:
  • volume_file (str) – path to the volume file

  • facet_file (str) – path to the facet file

  • mesh_name (str) – name of the mesh in the volume XDMF file.

  • surface_meshtags_name (str) – name of the surface meshtags in the facet

  • file. (XDMF)

  • volume_meshtags_name (str) – name of the volume meshtags in the volume XDMF file

  • mesh (fenics.mesh.Mesh) – the fenics mesh

define_surface_meshtags()[source]#

Creates the facet meshtags.

Returns:

the facet meshtags

Return type:

dolfinx.MeshTags

define_volume_meshtags()[source]#

Creates the volume meshtags.

Returns:

the volume meshtags

Return type:

dolfinx.MeshTags

class Interface(id: int, subdomains: list[VolumeSubdomain], penalty_term: float = 10.0, method: InterfaceMethod = InterfaceMethod.penalty)[source]#

Bases: InterfaceBase

Represents an interface between two subdomains with discontinuous solutions.

This class handles the coupling of solutions across an interface between two volume subdomains using either penalty or Nitsche methods. It manages the exchange of boundary conditions and enforces continuity across the interface.

Variables:
  • id (int) – Tag of the interface subdomain in the parent mesh tags.

  • subdomains (tuple[festim.subdomain.volume_subdomain.VolumeSubdomain, festim.subdomain.volume_subdomain.VolumeSubdomain]) – The two subdomains sharing this interface.

  • parent_mesh (dolfinx.mesh.Mesh) – The parent mesh containing the interface.

  • mt (dolfinx.mesh.MeshTags) – Mesh tags for the parent mesh.

  • restriction (list[str, str]) – FEniCS restriction operators for each side of the interface, defaults to (β€œ+”, β€œ-β€œ).

  • padded (bool) – Whether the parent-to-submesh maps have been padded.

  • method (festim.subdomain.interface.InterfaceMethod) – The method used to enforce interface conditions (penalty or Nitsche).

  • penalty_term – Penalty parameter for the interface formulation.

Ks(species: Species, temperature)[source]#

Get solubility coefficients for both sides of the interface.

Computes the solubility coefficient at the interface temperature for each subdomain’s material.

Parameters:
  • species – The species for which to compute solubility.

  • temperature – A function that returns temperature at given restrictions.

Returns:

Solubility coefficients (K_0, K_1) for subdomains 0 and 1.

get_formulation(dS: Measure, species: list[Species], temperature) tuple[Form, Form][source]#

Generate the interface formulation for all species.

Parameters:
  • dS – Integration measure for the interface, with correct integration data.

  • species – Species for which interface conditions should be applied. Must be defined in both subdomains of the interface.

  • temperature – Temperature field/function for temperature-dependent laws.

Returns:

Variational forms to be added to each subdomain.

Raises:

AssertionError – If the interface method is unknown or species is not defined in both subdomains.

property method: InterfaceMethod#

Get the interface coupling method.

Returns:

The current interface method (penalty or Nitsche).

Return type:

InterfaceMethod

nitsche_method(dS, species, temperature)[source]#

Generate interface formulation using the Nitsche method.

The Nitsche method is a stabilized discontinuous Galerkin approach that enforces interface continuity through a combination of: - Average gradient terms - Jump-based penalty stabilization

This method is more stable for certain problems compared to pure penalty.

Parameters:
  • dS – Integration measure for the interface.

  • species – The species for which to compute the interface form.

  • temperature – A function returning temperature at given restrictions.

Returns:

Variational forms for subdomains 0 and 1.

penalty_method(dS, species, temperature)[source]#

Generate interface formulation using the penalty method.

The penalty method enforces interface continuity through a penalty term: penalty_term * (u_1/K_1 - u_0/K_0) applied symmetrically to both sides. Handles different solubility laws (Henry vs Sievert) on each side.

Parameters:
  • dS – Integration measure for the interface.

  • species – The species for which to compute the interface form.

  • temperature – A function returning temperature at given restrictions.

Returns:

Variational forms for subdomains 0 and 1.

class SurfaceSubdomain(id: int, locator: Callable | None = None)[source]#

Bases: object

Surface subdomain class.

Parameters:
  • id – the id of the surface subdomain

  • locator – a callable function that locates the boundary facets of the subdomain

Examples

SurfaceSubdomain(id=1, locator=lambda x: np.isclose(x[0], 1.0))
SurfaceSubdomain(id=1, locator=lambda x:
np.logical_or(np.isclose(x[1], 0.0), np.isclose(x[1], 1.0)))
SurfaceSubdomain(id=1, locator=lambda x:
np.logical_and(np.isclose(x[0], 0.0), np.isclose(x[1], 1.0)))
SurfaceSubdomain(id=1, locator=lambda x:
np.logical_and(np.isclose(x[0], 0.0), x[1] <= 0.5))
locate_boundary_facet_indices(mesh: Mesh) ndarray[source]#

Locate boundary facets of the subdomain in the mesh.

Parameters:

mesh – a dolfinx mesh object

Raises:

ValueError – if no locator function is provided

Returns:

the list of entities (facets) that belong to the subdomain

class SurfaceSubdomain1D(id: int, x: float)[source]#

Bases: SurfaceSubdomain

Surface subdomain class for 1D cases.

Parameters:
  • id – the id of the surface subdomain

  • x – the x coordinate of the surface subdomain

Variables:
  • id (int) – the id of the surface subdomain

  • x (float) – the x coordinate of the surface subdomain

Examples

SurfaceSubdomain1D(id=1, x=1)
class VolumeSubdomain(id, material, locator: Callable | None = None, name: str | None = None)[source]#

Bases: object

Volume subdomain class.

Parameters:
  • id – the id of the volume subdomain (> 0)

  • submesh – the submesh of the volume subdomain

  • cell_map – the cell map of the volume subdomain

  • parent_mesh – the parent mesh of the volume subdomain

  • parent_to_submesh – the parent to submesh map of the volume subdomain

  • v_map – the vertex map of the volume subdomain

  • n_map – the normal map of the volume subdomain

  • facet_to_parent – the facet to parent map of the volume subdomain

  • ft – the facet meshtags of the volume subdomain

  • padded – whether the subdomain is padded (for 0.9 compatibility)

  • u – the solution function of the subdomain

  • u_n – the previous solution function of the subdomain

  • material – the material assigned to the subdomain

  • sub_T – the sub temperature field in the subdomain

create_subdomain(mesh: Mesh, marker: MeshTags)[source]#

Creates the following attributes: .parent_mesh, .submesh, .cell_map, .v_map, padded, and the entity map parent_to_submesh.

Only used in festim.HydrogenTransportProblemDiscontinuous

Parameters:
  • mesh (dolfinx.mesh.Mesh) – the parent mesh

  • marker (dolfinx.mesh.MeshTags) – the parent volume markers

locate_subdomain_entities(mesh: Mesh) ndarray[Any, dtype[int32]][source]#

Locates all cells in subdomain borders within domain.

Parameters:

mesh – the mesh of the model

Returns:

the entities of the subdomain

Return type:

entities

class VolumeSubdomain1D(id, borders, material)[source]#

Bases: VolumeSubdomain

Volume subdomain class for 1D cases.

Parameters:
  • id (int) – the id of the volume subdomain

  • borders (list of float) – the borders of the volume subdomain

  • material (festim.Material) – the material of the volume subdomain

Variables:
  • id (int) – the id of the volume subdomain

  • borders (list of float) – the borders of the volume subdomain

  • material (festim.Material) – the material of the volume subdomain

Examples

VolumeSubdomain1D(id=1, borders=[0, 1], material=my_mat)
map_surface_to_volume_subdomains(ft: MeshTags, ct: MeshTags, facet_to_cell: AdjacencyList_int32, volume_subdomains: list[VolumeSubdomain], surface_subdomains: list[SurfaceSubdomain], comm=None) dict[SurfaceSubdomain, VolumeSubdomain][source]#

Maps surface subdomains to volume subdomains based on the facet and cell meshtags and the facet to cell connectivity.

Raises:

AssertionError – if a surface subdomain is connected to multiple volume subdomains

Parameters:
  • ft – the facet meshtags of the parent mesh

  • ct – the cell meshtags of the parent mesh

  • facet_to_cell – the facet to cell connectivity of the parent mesh

  • volume_subdomains – the list of volume subdomains

  • surface_subdomains – the list of surface subdomains

  • comm – MPI communicator (required for parallel runs)

Returns:

a dictionary mapping surface subdomains

to volume subdomains

Return type:

dict[SurfaceSubdomain, VolumeSubdomain]

class AdvectionTerm(velocity: Function, subdomain: VolumeSubdomain, species: Species)[source]#

Bases: object

Advection term class.

Parameters:
  • velocity – the velocity field or function

  • subdomain – the volume subdomain where the velocity is to be applied

  • species – the species to which the velocity field is acting on

Variables:
class VelocityField(input_value)[source]#

Bases: Value

A class to handle input values of velocity fields from users and convert them to a relevent fenics object.

Parameters:

input_value – The value of the user input

Variables:
  • input_value (dolfinx.fem.function.Function | collections.abc.Callable) – The value of the user input

  • fenics_interpolation_expression (dolfinx.fem.function.Expression) – The expression of the user input that is used to update the fenics_object

  • fenics_object (dolfinx.fem.function.Function) – The value of the user input in fenics format

  • explicit_time_dependent (bool) – True if the user input value is explicitly time dependent

  • temperature_dependent (bool) – True if the user input value is temperature dependent

  • vector_function_space (dolfinx.fem.function.FunctionSpace) – the vector function space of the fenics object

convert_input_value(function_space: FunctionSpace, t: Constant | None = None)[source]#

Converts a user given value to a relevent fenics object.

Parameters:
  • function_space – the function space of the fenics object

  • t – the time, optional

update(t: Constant)[source]#

Updates the velocity field.

Parameters:

t – the time

class CoupledTransientHeatTransferHydrogenTransport(heat_problem: HeatTransferProblem, hydrogen_problem: HydrogenTransportProblem)[source]#

Bases: object

Coupled heat transfer and hydrogen transport transient problem.

Parameters:
  • heat_problem – the heat transfer problem

  • hydrogen_problem – the hydrogen transport problem

Variables:

Examples

import festim as F

my_heat_transfer_model = F.HeatTransferProblem(...)

my_h_transport_model = F.HydrogenTransportProblem(...)

coupled_problem = F.CoupledTransientHeatTransferHydrogenTransport(
    heat_problem=my_heat_transfer_model,
    hydrogen_problem=my_h_transport_model,
)
class HeatTransferProblem(mesh=None, subdomains=None, initial_condition=None, boundary_conditions=None, sources=None, exports=None, settings=None)[source]#

Bases: ProblemBase

create_dirichletbc_form(bc)[source]#

Creates a dirichlet boundary condition form.

Parameters:

bc (festim.FixedTemperatureBC) – the boundary condition

Returns:

A representation of

the boundary condition for modifying linear systems.

Return type:

dolfinx.fem.bcs.DirichletBC

create_flux_values_fenics()[source]#

For each heat flux create the value_fenics.

create_formulation()[source]#

Creates the formulation of the model.

create_initial_conditions()[source]#

For each initial condition, create the value_fenics and assign it to the previous solution of the condition’s species.

create_source_values_fenics()[source]#

For each source create the value_fenics.

define_function_space()[source]#

Creates the function space of the model, creates a mixed element if model is multispecies.

Creates the main solution and previous solution function u and u_n. Create global DG function spaces of degree 0 and 1 for the global diffusion coefficient

initialise_exports()[source]#

Defines the export writers of the model, if field is given as a string, find species object in self.species.

post_processing()[source]#

Post processes the model.

class Value(input_value)[source]#

Bases: object

A class to handle input values from users and convert them to a relevent fenics object.

Parameters:

input_value – The value of the user input

Variables:
  • input_value (float | int | dolfinx.fem.function.Constant | numpy.ndarray | dolfinx.fem.function.Expression | ufl.core.expr.Expr | dolfinx.fem.function.Function) – The value of the user input

  • fenics_interpolation_expression (dolfinx.fem.function.Expression) – The expression of the user input that is used to update the fenics_object

  • fenics_object (dolfinx.fem.function.Function | dolfinx.fem.function.Constant | ufl.core.expr.Expr) – The value of the user input in fenics format

  • explicit_time_dependent (bool) – True if the user input value is explicitly time dependent

  • temperature_dependent (bool) – True if the user input value is temperature dependent

convert_input_value(function_space: FunctionSpace | None = None, t: Constant | None = None, temperature: Function | Constant | Expr | None = None, up_to_ufl_expr: bool | None = False)[source]#

Converts a user given value to a relevent fenics object depending on the type of the value provided.

Parameters:
  • function_space – the function space of the fenics object, optional

  • t – the time, optional

  • temperature – the temperature, optional

  • up_to_ufl_expr – if True, the value is only mapped to a function if the input is callable, not interpolated or converted to a function, optional

property explicit_time_dependent: bool#

Returns true if the value given is time dependent.

property temperature_dependent: bool#

Returns true if the value given is temperature dependent.

update(t: float)[source]#

Updates the value.

Parameters:

t – the time

as_fenics_constant(value: float | int | Constant, mesh: Mesh) Constant[source]#

Converts a value to a dolfinx.Constant.

Parameters:
  • value – the value to convert

  • mesh – the mesh of the domiain

Returns:

The converted value

Raises:

TypeError – if the value is not a float, an int or a dolfinx.Constant

as_fenics_interp_expr_and_function(value: Callable, function_space: FunctionSpace, t: Constant | None = None, temperature: Function | Constant | Expr | None = None) tuple[Expression, Function][source]#

Takes a user given callable function, maps the function to the mesh, time or temperature within festim as needed. Then creates the fenics interpolation expression and function objects.

Parameters:
  • value – the callable to convert

  • function_space – The function space to interpolate function over

  • t – the time, optional

  • temperature – the temperature, optional

Returns:

fenics interpolation expression, fenics function

as_mapped_function(value: Callable, function_space: FunctionSpace | None = None, t: Constant | None = None, temperature: Function | Constant | Expr | None = None) Expr[source]#

Maps a user given callable function to the mesh, time or temperature within festim as needed.

Parameters:
  • value – the callable to convert

  • function_space – the function space of the domain, optional

  • t – the time, optional

  • temperature – the temperature, optional

Returns:

The mapped function

is_it_time_to_export(times: list | None, current_time: float, atol=0, rtol=1e-05) bool[source]#

Checks if the exported field should be written to a file or not based on the current time and the times in export.times

After a successful match, the corresponding time is removed from the list to prevent multiple exports for the same target time.

Parameters:
  • current_time – the current simulation time

  • atol – absolute tolerance for time comparison

  • rtol – relative tolerance for time comparison

  • times – the times at which the field should be exported, if None, returns True

Returns:

True if the exported field should be written to a file, else False

Return type:

bool

nmm_interpolate(f_out: Function, f_in: Function, cells: MeshTags | None = None, padding: float | None = 1e-11)[source]#

Non Matching Mesh Interpolate: interpolate one function (f_in) from one mesh into another function (f_out) with a mismatching mesh

Parameters:
  • f_out – function to interpolate into

  • f_in – function to interpolate from

notes: https://fenicsproject.discourse.group/t/gjk-error-in-interpolation-between-non-matching-second-ordered-3d-meshes/16086/6

class HydrogenTransportProblem(mesh: Mesh | None = None, subdomains: list[VolumeSubdomain | SurfaceSubdomain] | None = None, species: list[Species] | None = None, reactions: list[Reaction] | None = None, temperature: float | int | Constant | Function | Callable[[ndarray[Any, dtype[float64]]], ndarray[Any, dtype[float64]]] | Callable[[ndarray[Any, dtype[float64]], Constant], ndarray[Any, dtype[float64]]] | None = None, sources=None, initial_conditions=None, boundary_conditions=None, settings=None, exports=None, traps=None, advection_terms=None, petsc_options=None, element_immobile: str = 'CG')[source]#

Bases: ProblemBase

Hydrogen Transport Problem.

Parameters:
  • mesh – The mesh

  • subdomains – list containing the subdomains

  • species – list containing the species

  • reactions – list containing the reactions

  • temperature – The temperature or a function describing the temperature as a model of either space or space and time. Unit (K)

  • sources – The hydrogen sources

  • initial_conditions – The initial conditions

  • boundary_conditions – The boundary conditions

  • exports (list of festim.Export) – the exports of the model

  • traps (list of F.Trap) – the traps of the model

  • advection_terms – the advection terms of the model

Variables:
  • mesh (festim.mesh.mesh.Mesh) – The mesh

  • subdomains (list[festim.subdomain.volume_subdomain.VolumeSubdomain]) – The subdomains

  • species – The species

  • reactions – the reaction

  • temperature – The temperature in unit K

  • sources (list[festim.source.SourceBase]) – The hydrogen sources

  • initial_conditions – The initial conditions

  • boundary_conditions – list of Dirichlet boundary conditions

  • exports (list of festim.Export) – the export

  • traps (list of F.Trap) – the traps of the model

  • advection_terms – the advection terms of the model

  • dx (dolfinx.fem.dx) – the volume measure of the model

  • ds (dolfinx.fem.ds) – the surface measure of the model

  • function_space (dolfinx.fem.FunctionSpaceBase) – the function space of the model

  • facet_meshtags (dolfinx.mesh.MeshTags) – the facet meshtags of the model

  • volume_meshtags (dolfinx.mesh.MeshTags) – the volume meshtags of the model

  • formulation (ufl.form.Form) – the formulation of the model

  • solver (dolfinx.nls.newton.NewtonSolver) – the solver of the model

  • temperature_fenics (fem.Constant or fem.Function) – the temperature of the model as a fenics object (fem.Constant or fem.Function).

  • temperature_expr (fem.Expression) – the expression of the temperature that is used to update the temperature_fenics

  • temperature_time_dependent (bool) – True if the temperature is time dependent

  • V_DG_0 (dolfinx.fem.FunctionSpaceBase) – A DG function space of degree 0 over domain

  • V_DG_1 (dolfinx.fem.FunctionSpaceBase) – A DG function space of degree 1 over domain

  • volume_subdomains (list of festim.VolumeSubdomain) – the volume subdomains of the model

  • surface_subdomains (list of festim.SurfaceSubdomain) – the surface subdomains of the model

Examples

Can be used as either

import festim as F
my_model = F.HydrogenTransportProblem()
my_model.mesh = F.Mesh(...)
my_model.subdomains = [F.Subdomain(...)]
my_model.species = [F.Species(name="H"), F.Species(name="Trap")]
my_model.temperature = 500
my_model.sources = [F.ParticleSource(...)]
my_model.boundary_conditions = [F.BoundaryCondition(...)]
my_model.initialise()

or

my_model = F.HydrogenTransportProblem(
    mesh=F.Mesh(...),
    subdomains=[F.Subdomain(...)],
    species=[F.Species(name="H"), F.Species(name="Trap")],
)
my_model.initialise()
assign_functions_to_species()[source]#

Creates the solution, prev solution, test function and post-processing solution for each species, as well as a collapsed function space for each species.

convert_advection_term_to_fenics_objects()[source]#

For each advection term convert the input value.

convert_source_input_values_to_fenics_objects()[source]#

For each source create the value_fenics.

create_dirichletbc_form(bc)[source]#

Creates a dirichlet boundary condition form.

Parameters:

bc (festim.DirichletBC) – the boundary condition

Returns:

A representation of

the boundary condition for modifying linear systems.

Return type:

dolfinx.fem.bcs.DirichletBC

create_flux_values_fenics()[source]#

For each particle flux create the value_fenics.

create_formulation()[source]#

Creates the formulation of the model.

create_implicit_species_value_fenics()[source]#

For each implicit species, create the value_fenics.

create_initial_conditions()[source]#

For each initial condition, create the value_fenics and assign it to the previous solution of the condition’s species.

create_species_from_traps()[source]#

Generate a species and reaction per trap defined in self.traps.

define_D_global(species)[source]#

Defines the global diffusion coefficient for a given species.

Parameters:

species (F.Species) – the species

Returns:

the global diffusion

coefficient and the expression of the global diffusion coefficient for a given species

Return type:

dolfinx.fem.Function, dolfinx.fem.Expression

define_boundary_conditions()[source]#

Defines the boundary conditions of the model.

define_function_spaces(element_degree: int = 1)[source]#

Creates the function space of the modelw with a mixed element. Creates the main solution and previous solution function u and u_n. Create global DG function spaces of degree 0 and 1 for the global diffusion coefficient.

Parameters:

element_degree – Degree order for finite element. Defaults to 1.

define_temperature()[source]#

Sets the value of temperature_fenics_value.

The type depends on self.temperature. If self.temperature is a function on t only, create a fem.Constant. Else, create an dolfinx.fem.Expression (stored in self.temperature_expr) to be updated, a dolfinx.fem.Function object is created from the Expression (stored in self.temperature_fenics_value). Raise a ValueError if temperature is None.

initialise_exports()[source]#

Defines the export writers of the model, if field is given as a string, find species object in self.species.

post_processing()[source]#

Post processes the model.

update_post_processing_solutions()[source]#

Updates the post-processing solutions of each species.

class HydrogenTransportProblemDiscontinuous(mesh=None, subdomains=None, species=None, reactions=None, temperature=None, sources=None, initial_conditions=None, boundary_conditions=None, settings=None, exports=None, traps=None, interfaces: list[Interface] | None = None, petsc_options: dict | None = None)[source]#

Bases: HydrogenTransportProblem

convert_advection_term_to_fenics_objects()[source]#

For each advection term convert the input value.

convert_source_input_values_to_fenics_objects()[source]#

For each source create the value_fenics.

create_dirichletbc_form(bc: FixedConcentrationBC)[source]#

Creates the value_fenics attribute for a given festim.FixedConcentrationBC and returns the appropriate dolfinx.fem.DirichletBC object.

Parameters:

bc (festim.FixedConcentrationBC) – the dirichlet BC

Returns:

the appropriate dolfinx representation

generated from dolfinx.fem.dirichletbc()

Return type:

dolfinx.fem.DirichletBC

create_flux_values_fenics()[source]#

For each particle flux create the value_fenics attribute.

create_formulation()[source]#

Takes all the formulations for each subdomain and adds the interface conditions.

Finally compute the jacobian matrix and store it in the J attribute, adds the entity_maps to the forms and store them in the forms attribute

create_initial_conditions()[source]#

For each intial condition, create the value_fenics and assign it to the previous solution of the condition’s species.

create_solver()[source]#

Creates the solver of the model.

create_subdomain_formulation(subdomain: VolumeSubdomain)[source]#

Creates the variational formulation for each subdomain and stores it in subdomain.F

Parameters:

subdomain (F.VolumeSubdomain) – a subdomain of the geometry

define_boundary_conditions()[source]#

Defines the boundary conditions of the model.

define_function_spaces(subdomain: VolumeSubdomain, element_degree=1)[source]#

Creates appropriate function space and functions for a given subdomain (submesh) based on the number of species existing in this subdomain. Then stores the functionspace, the current solution (u) and the previous solution (u_n) functions. It also populates the correspondance dicts attributes of the species (eg. species.subdomain_to_solution, species.subdomain_to_test_function, etc) for easy access to the right subfunctions, sub-testfunctions etc.

Parameters:
  • subdomain (F.VolumeSubdomain) – a subdomain of the geometry

  • element_degree (int, optional) – Degree order for finite element. Defaults to 1.

define_temperature()[source]#

Sets the value of temperature_fenics_value.

The type depends on self.temperature. If self.temperature is a function on t only, create a fem.Constant. Else, create an dolfinx.fem.Expression (stored in self.temperature_expr) to be updated, a dolfinx.fem.Function object is created from the Expression (stored in self.temperature_fenics_value). Raise a ValueError if temperature is None.

initialise_exports()[source]#

Defines the export writers of the model, if field is given as a string, find species object in self.species.

iterate()[source]#

Iterates the model for a given time step.

post_processing()[source]#

Post processes the model.

run()[source]#

Runs the model.

class InitialConcentration(value, volume, species: Species)[source]#

Bases: InitialConditionBase

Initial concentration class.

Parameters:
  • value – the value of the initial concentration of a given species.

  • species – the species to which the condition is applied

  • volume – the volume subdomain where the initial condition is applied

Variables:
  • value (float | int | dolfinx.fem.function.Constant | numpy.ndarray | dolfinx.fem.function.Expression | ufl.core.expr.Expr | dolfinx.fem.function.Function) – the value of the initial concentration of a given species.

  • species (festim.species.Species) – the species to which the condition is applied

  • volume (festim.subdomain.volume_subdomain.VolumeSubdomain) – the volume subdomain where the initial condition is applied

  • expr_fenics (collections.abc.Callable | dolfinx.fem.function.Expression) – the value of the initial condition in fenics expr format

Examples

InitialConcentration(value=1, species=my_species, volume=my_vol)
InitialConcentration(
    value=lambda x: 1 + x[0],
    species=my_species,
    volume=my_vol
)
InitialConcentration(
    value=lambda T: 1 + T,
    species=my_species,
    volume=my_vol
)
InitialConcentration(
    value=lambda x, T: 1 + x[0] + T,
    species=my_species,
    volume=my_vol
)
create_expr_fenics(mesh: Mesh, temperature: Function | Constant, function_space: functionspace)[source]#

Creates the expr_fenics of the initial condition.

If the value is a float or int, a function is created with an array with the shape of the mesh and all set to the value. Otherwise, it is converted to a fem.Expression.

Parameters:
  • mesh – the mesh

  • temperature – the temperature

  • function_space – the function space of the species

class InitialConditionBase(value: float | int | Constant | ndarray | Expression | Expr | Function, volume: VolumeSubdomain)[source]#

Bases: object

Base initial condition class.

Parameters:
  • value – the value of the initial condition.

  • volume – the volume subdomain where the initial condition is applied

Variables:
  • value (float | int | dolfinx.fem.function.Constant | numpy.ndarray | dolfinx.fem.function.Expression | ufl.core.expr.Expr | dolfinx.fem.function.Function) – the value of the initial condition.

  • volume (festim.subdomain.volume_subdomain.VolumeSubdomain) – the volume subdomain where the initial condition is applied

class InitialTemperature(value, volume)[source]#

Bases: InitialConditionBase

Initial temperature class.

Parameters:
  • value – the value of the initial temperature

  • volume – the volume subdomain where the initial condition is applied

Variables:
  • value (float | int | dolfinx.fem.function.Constant | numpy.ndarray | dolfinx.fem.function.Expression | ufl.core.expr.Expr | dolfinx.fem.function.Function) – the value of the initial temperature

  • volume (festim.subdomain.volume_subdomain.VolumeSubdomain) – the volume subdomain where the initial condition is applied

  • expr_fenics – the value of the initial condition in fenics expr format

Examples

InitialTemperature(value=1, volume=my_vol)
InitialTemperature(value=lambda x: 1 + x[0], volume=my_vol)
InitialTemperature(value=lambda x, t: 1 + x[0] + t, volume=my_vol)
create_expr_fenics(mesh: Mesh, function_space: functionspace)[source]#

Creates the expr_fenics of the initial condition.

If the value is a float or int, a function is created with an array with the shape of the mesh and all set to the value. Otherwise, it is converted to a fem.Expression.

Parameters:
  • mesh – the mesh

  • function_space – the function space of the species

read_function_from_file(filename: str, name: str, timestamp: int | float, family='P', order: int = 1, mesh: Mesh | None = None) Function[source]#

Read a function from a file.

note::

The function is read from a file using adios4dolfinx. For more information see the [adios4dolfinx documentation](https://jsdokken.com/adios4dolfinx/README.html).

Parameters:
  • filename – the filename

  • name – the name of the function

  • timestamp – the timestamp of the function

  • family – the family of the function space

  • order – the order of the function space

  • mesh – Mesh to create input space on.

Returns:

the function

class Material(D_0: float | int | Function | dict[float, int] | None = None, E_D: float | int | Function | dict[float, int] | None = None, K_S_0: float | int | dict[float, int] | None = None, E_K_S: float | int | dict[float, int] | None = None, thermal_conductivity: float | None = None, density: float | None = None, heat_capacity: float | None = None, name: str | None = None, solubility_law: SolubilityLaw | str = SolubilityLaw.NONE, D: Function | None = None)[source]#

Bases: object

Material class.

Parameters:
  • D_0 – the pre-exponential factor of the diffusion coefficient (m2/s)

  • E_D – the activation energy of the diffusion coeficient (eV)

  • K_S_0 – the pre-exponential factor of the solubility coefficient (H/m3/Pa0.5)

  • E_K_S – the activation energy of the solubility coeficient (eV)

  • name – the name of the material

  • thermal_conductivity – the thermal conductivity of the material (W/m/K)

  • density – the density of the material (kg/m3)

  • heat_capacity – the heat capacity of the material (J/kg/K)

  • solubility_law – the solubility law of the material (SIEVERT, HENRY or NONE). For single material problems one can use NONE. This does not work for multi-material problems

  • D – the diffusion coefficient of the material (m2/s)

Variables:
  • D_0 – the pre-exponential factor of the diffusion coefficient (m2/s)

  • E_D – the activation energy of the diffusion coeficient (eV)

  • K_S_0 – the pre-exponential factor of the solubility coefficient (H/m3/Pa0.5)

  • E_K_S – the activation energy of the solubility coeficient (eV)

  • name – the name of the material

  • thermal_conductivity – the thermal conductivity of the material (W/m/K)

  • density – the density of the material (kg/m3)

  • heat_capacity – the heat capacity of the material (J/kg/K)

  • solubility_law – the solubility law of the material (SIEVERT, HENRY or NONE). For single material problems one can use NONE. This does not work for multi-material problems

Examples

# if only one species:
Material(D_0=1.9e-7, E_D=0.2, name="my_mat")

# if several species:
Material(
    D_0={"Species_1": 1.9e-7, "Species_2": 2.0e-7},
    E_D={"Species_1": 0.2, "Species_2": 0.3},
    name="my_mat"
)
get_D_0(species=None)[source]#

Returns the pre-exponential factor of the diffusion coefficient.

Parameters:

species (festim.Species or str, optional) – the species we want the pre-exponential factor of the diffusion coefficient of. Only needed if D_0 is a dict.

Returns:

the pre-exponential factor of the diffusion coefficient

Return type:

float

get_E_D(species=None)[source]#

Returns the activation energy of the diffusion coefficient.

Parameters:

species (festim.Species or str, optional) – the species we want the activation energy of the diffusion coefficient of. Only needed if E_D is a dict.

Returns:

the activation energy of the diffusion coefficient

Return type:

float

get_E_K_S(species=None) float[source]#

Returns the activation energy of the solubility coefficient.

Parameters:

species – the species we want the activation energy of the solubility coefficient of. Only needed if E_K_S is a dict.

Returns:

the activation energy of the solubility coefficient

get_K_S_0(species=None) float[source]#

Returns the pre-exponential factor of the solubility coefficient.

Parameters:

species – the species we want the pre-exponential factor of the solubility coefficient of. Only needed if K_S_0 is a dict.

Returns:

the pre-exponential factor of the solubility coefficient

get_diffusion_coefficient(mesh=None, temperature=None, species=None)[source]#

Defines the diffusion coefficient.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – the domain mesh

  • temperature (dolfinx.fem.Constant) – the temperature

  • species (festim.Species, optional) – the species we want the diffusion coefficient of. Only needed if D_0 and E_D are dicts.

Returns:

the diffusion coefficient

Return type:

ufl.algebra.Product

get_solubility_coefficient(mesh, temperature, species=None)[source]#

Defines the solubility coefficient.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – the domain mesh

  • temperature (dolfinx.fem.Constant) – the temperature

  • species (festim.Species, optional) – the species we want the solubility coefficient of. Only needed if K_S_0 and E_K_S are dicts.

Returns:

the solubility coefficient

Return type:

ufl.algebra.Product

class SolubilityLaw(value)[source]#

Bases: Enum

classmethod from_string(s: str)[source]#

Can be removed with Python 3.11+.

class ProblemBase(mesh: Mesh = None, sources=None, exports=None, subdomains=None, boundary_conditions=None, settings=None, petsc_options=None)[source]#

Bases: object

Base class for HeatTransferProblem and HydrogenTransportProblem.

Variables:
  • show_progress_bar (bool) – If True a progress bar is displayed during the simulation

  • progress_bar (None | tqdm.asyncio.tqdm_asyncio) – the progress bar

create_solver()[source]#

Creates the solver of the model.

define_boundary_conditions()[source]#

Defines the dirichlet boundary conditions of the model.

define_meshtags_and_measures()[source]#

Defines the facet and volume meshtags of the model which are used to define the measures fo the model, dx and ds.

get_petsc_options() dict[str, Any][source]#

Gets the PETSc options to pass to the NewtonProblem solver. Default options are updated with user-provided options, if any.

Returns:

the petsc options to pass to the NewtonProblem solver.

iterate()[source]#

Iterates the model for a given time step.

run()[source]#

Runs the model.

class Reaction(reactant: Species | ImplicitSpecies | list[Species | ImplicitSpecies], k_0: float, E_k: float, volume: VolumeSubdomain1D, product: Species | list[Species] | None = [], p_0: float | None = None, E_p: float | None = None)[source]#

Bases: object

A reaction between two species, with a forward and backward rate.

Parameters:
  • (Union[F.Species (reactant)

  • F.ImplicitSpecies]

  • List[Union[F.Species

:param : :param F.ImplicitSpecies]]): The reactant. :param product: The product. :type product: Optional[Union[F.Species, List[F.Species]]] :param k_0: The forward rate constant pre-exponential factor. :type k_0: float :param E_k: The forward rate constant activation energy. :type E_k: float :param p_0: The backward rate constant pre-exponential factor. :type p_0: float :param E_p: The backward rate constant activation energy. :type E_p: float :param volume: The volume subdomain where the reaction :type volume: F.VolumeSubdomain1D :param takes place.:

Variables:
  • List[Union[F.Species, (reactant (Union[F.Species, F.ImplicitSpecies],)

  • F.ImplicitSpecies]]) – The reactant.

  • product (Optional[Union[F.Species, List[F.Species]]]) – The product.

  • k_0 (float) – The forward rate constant pre-exponential factor.

  • E_k (float) – The forward rate constant activation energy.

  • p_0 (float) – The backward rate constant pre-exponential factor.

  • E_p (float) – The backward rate constant activation energy.

  • volume (F.VolumeSubdomain1D) – The volume subdomain where the reaction

  • place. (takes)

Examples

:: testsetup:: Reaction

from festim import Reaction, Species, ImplicitSpecies

:: testcode:: Reaction

# create a volume subdomain # create two species reactant = [F.Species(β€œA”), F.Species(β€œB”)]

# create a product species product = F.Species(β€œC”)

# create a reaction between the two species reaction = Reaction(reactant, product, k_0=1.0, E_k=0.2, p_0=0.1, E_p=0.3) print(reaction) # A + B <–> C

# compute the reaction term at a given temperature temperature = 300.0 reaction_term = reaction.reaction_term(temperature)

reaction_term(temperature, reactant_concentrations: list | None = None, product_concentrations: list | None = None) Expr[source]#

Compute the reaction term at a given temperature.

Parameters:
  • temperature – The temperature at which the reaction term is computed.

  • reactant_concentrations – The concentrations of the reactants. Must be the same length as the reactants. If None, the concentration attribute of each reactant is used. If an element is None, the concentration attribute of the reactant is used.

  • product_concentrations – The concentrations of the products. Must be the same length as the products. If None, the concentration attribute of each product is used. If an element is None, the concentration attribute of the product is used.

Returns:

The reaction term to be used in a formulation.

class Settings(atol, rtol, max_iterations=30, transient=True, final_time=None, element_degree=1, stepsize=None, convergence_criterion: Literal['residual', 'incremental'] = 'residual')[source]#

Bases: object

Settings for a festim simulation.

Parameters:
  • atol (float or callable) – Absolute tolerance for the solver.

  • rtol (float or callable) – Relative tolerance for the solver.

  • max_iterations (int, optional) – Maximum number of iterations for the solver. Defaults to 30.

  • transient (bool, optional) – Whether the simulation is transient or not.

  • final_time (float, optional) – Final time for a transient simulation. Defaults to None

  • element_degree (int, optional) – Degree order for finite element. Defaults to 1.

  • stepsize (festim.Stepsize, optional) – stepsize for a transient simulation. Defaults to None

  • convergence_criterion – resiudal or incremental (for Newton solver)

Variables:
  • atol (float or callable) – Absolute tolerance for the solver.

  • rtol (float or callable) – Relative tolerance for the solver.

  • max_iterations (int) – Maximum number of iterations for the solver.

  • transient (bool) – Whether the simulation is transient or not.

  • final_time (float) – Final time for a transient simulation.

  • element_degree (int) – Degree order for finite element.

  • stepsize (festim.Stepsize) – stepsize for a transient simulation.

  • convergence_criterion – resiudal or incremental (for Newton solver)

class HeatSource(value, volume)[source]#

Bases: SourceBase

Heat source class.

Parameters:
  • value – the value of the source

  • volume – the volume subdomains where the source is applied

Variables:
  • value (float | int | dolfinx.fem.function.Constant | numpy.ndarray | dolfinx.fem.function.Expression | ufl.core.expr.Expr | dolfinx.fem.function.Function) – the value of the source

  • volume (festim.subdomain.volume_subdomain.VolumeSubdomain) – the volume subdomains where the source is applied

Examples

from festim import HeatSource

HeatSource(volume=my_vol, value=1)
HeatSource(volume=my_vol, value=lambda x: 1 + x[0])
HeatSource(volume=my_vol, value=lambda t: 1 + t)
HeatSource(volume=my_vol, value=lambda x, t: 1 + x[0] + t)
class ParticleSource(value, volume, species: Species)[source]#

Bases: SourceBase

Particle source class.

Parameters:
  • value – the value of the source

  • volume – the volume subdomains where the source is applied

  • species – the species to which the source is applied

Variables:
  • value (float | int | dolfinx.fem.function.Constant | numpy.ndarray | dolfinx.fem.function.Expression | ufl.core.expr.Expr | dolfinx.fem.function.Function) – the value of the source

  • volume (festim.subdomain.volume_subdomain.VolumeSubdomain) – the volume subdomains where the source is applied

  • species (festim.species.Species) – the species to which the source is applied

Examples

from festim import ParticleSource

ParticleSource(volume=my_vol, value=1, species="H")
ParticleSource(volume=my_vol, value=lambda x: 1 + x[0], species="H")
ParticleSource(volume=my_vol, value=lambda t: 1 + t, species="H")
ParticleSource(volume=my_vol, value=lambda T: 1 + T, species="H")
ParticleSource(volume=my_vol, value=lambda x, t: 1 + x[0] + t, species="H")
class SourceBase(value: float | int | Constant | ndarray | Expression | Expr | Function | Value, volume: VolumeSubdomain)[source]#

Bases: object

Source base class.

Parameters:
  • value – the value of the source

  • volume – the volume subdomains where the source is applied

Variables:
  • value (float | int | dolfinx.fem.function.Constant | numpy.ndarray | dolfinx.fem.function.Expression | ufl.core.expr.Expr | dolfinx.fem.function.Function) – the value of the source

  • volume (festim.subdomain.volume_subdomain.VolumeSubdomain) – the volume subdomains where the source is applied

class ImplicitSpecies(n: float | callable, others: list[Species] | None = None, name: str | None = None)[source]#

Bases: object

Implicit species class for H transport simulation. c = n - others

Parameters:
  • n – the total concentration of the species

  • others – the list of species from which the implicit species concentration is computed (c = n - others)

  • name – a name given to the species. Defaults to None.

Variables:
  • n (float | callable) – the total concentration of the species

  • others (list[festim.species.Species] | None) – the list of species from which the implicit species concentration is computed (c = n - others)

  • name (str | None) – a name given to the species. Defaults to None.

  • concentration (ufl.form.Form) – the concentration of the species

  • value_fenics (dolfinx.fem.function.Constant | ufl.core.expr.Expr) – the total concentration as a fenics object

create_value_fenics(mesh, t: Constant)[source]#

Creates the value of the density as a fenics object and sets it to self.value_fenics. If the value is a constant, it is converted to a fenics.Constant. If the value is a function of t, it is converted to a fenics.Constant. Otherwise, it is converted to a ufl Expression.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – the mesh

  • t (dolfinx.fem.Constant) – the time

update_density(t)[source]#

Updates the density value (only if the density is a function of time only)

Parameters:

t (float) – the time

class Species(name: str | None = None, mobile: bool = True, subdomains: list[VolumeSubdomain] | VolumeSubdomain | None = None)[source]#

Bases: object

Hydrogen species class for H transport simulation.

Parameters:
  • name – a name given to the species. Defaults to None.

  • mobile – whether the species is mobile or not. Defaults to True.

  • subdomain – the volume subdomain where the species is. Defaults to None.

Variables:
  • name (str | None) – a name given to the species.

  • mobile (bool) – whether the species is mobile or not.

  • solution (dolfinx.fem.function.Function | None) – the solution for the current timestep

  • prev_solution (dolfinx.fem.function.Function | None) – the solution for the previous timestep

  • test_function (ufl.argument.Argument | None) – the testfunction associated with this species

  • sub_function – the sub function of the species in case of multiple species in the same function space

  • sub_function_space (dolfinx.fem.function.FunctionSpace | None) – the subspace of the function space

  • collapsed_function_space (dolfinx.fem.function.FunctionSpace | None) – the collapsed function space for a species in the function space. In case single species case, this is None.

  • map_sub_to_main_solution (list | None) – the mapping from the sub solution dofs to the main solution dofs

  • post_processing_solution (dolfinx.fem.function.Function | None) – the solution for post processing

  • concentration (dolfinx.fem.function.Function | None) – the concentration of the species

  • subdomains (list[festim.subdomain.volume_subdomain.VolumeSubdomain] | festim.subdomain.volume_subdomain.VolumeSubdomain | None) – the volume subdomains where the species is

  • subdomain_to_solution (dict) – a dictionary mapping subdomains to solutions

  • subdomain_to_prev_solution (dict) – a dictionary mapping subdomains to previous solutions

  • subdomain_to_test_function (dict) – a dictionary mapping subdomains to test functions

  • subdomain_to_post_processing_solution (dict) – a dictionary mapping subdomains to post processing solutions

  • subdomain_to_collapsed_function_space (dict) – a dictionary mapping subdomains to collapsed function spaces

  • subdomain_to_function_space (dict) – a dictionary mapping subdomains to function spaces

Examples

:: testsetup:: Species

from festim import Species

:: testcode:: Species

Species(name=”H”) Species(name=”Trap”, mobile=False)

property legacy: bool#

Check if we are using FESTIM 1.0 implementation or FESTIM 2.0.

find_species_from_name(name: str, species: list)[source]#

Returns the correct species object from a list of species based on a string.

Parameters:
  • name (str) – the name of the species

  • species (list) – the list of species

Returns:

the species object with the correct name

Return type:

species (festim.Species)

Raises:

ValueError – if the species name is not found in the list of species

class Stepsize(initial_value, growth_factor=None, cutback_factor=None, target_nb_iterations=None, max_stepsize=None, milestones=None)[source]#

Bases: object

A class for evaluating the stepsize of transient simulations.

Parameters:
  • initial_value (float, int) – initial stepsize.

  • growth_factor (float, optional) – factor by which the stepsize is increased when adapting

  • cutback_factor (float, optional) – factor by which the stepsize is decreased when adapting

  • target_nb_iterations (int, optional) – number of Newton iterations over (resp. under) which the stepsize is increased (resp. decreased)

  • max_stepsize (float or callable, optional) – Maximum stepsize. If callable, has to be a function of t. Defaults to None.

  • milestones (list, optional) – list of times by which the simulation must pass. Defaults to an empty list.

Variables:
  • initial_value (float, int) – initial stepsize.

  • growth_factor (float) – factor by which the stepsize is increased when adapting

  • cutback_factor (float) – factor by which the stepsize is decreased when adapting

  • target_nb_iterations (int) – number of Newton iterations over (resp. under) which the stepsize is increased (resp. decreased)

  • adaptive (bool) – True if the stepsize is adaptive, False otherwise.

  • max_stepsize (float, callable) – Maximum stepsize.

  • milestones (list) – list of times by which the simulation must pass.

get_max_stepsize(t)[source]#

Returns the maximum stepsize at time t.

Parameters:

t (float) – the current time

Returns:

the maximum stepsize at time t

Return type:

float or None

is_adapt(t)[source]#

Methods that defines if the stepsize should be adapted or not.

Parameters:

t (float) – the current time

Returns:

True if needs to adapt, False otherwise.

Return type:

bool

next_milestone(current_time: float)[source]#

Returns the next milestone that the simulation must pass. Returns None if there are no more milestones.

Parameters:

current_time (float) – current time.

Returns:

next milestone.

Return type:

float

class Trap(name: str, mobile_species, k_0, E_k, p_0, E_p, n, volume)[source]#

Bases: Species

Trap species class for H transport simulation.

This class only works for 1 mobile species and 1 trapping level and is for convenience, for more details see notes.

Parameters:
  • name (str, optional) – a name given to the trap. Defaults to None.

  • mobile_species (_Species) – the mobile species to be trapped

  • k_0 (float) – the trapping rate constant pre-exponential factor (m3 s-1)

  • E_k (float) – the trapping rate constant activation energy (eV)

  • p_0 (float) – the detrapping rate constant pre-exponential factor (s-1)

  • E_p (float) – the detrapping rate constant activation energy (eV)

  • volume (F.VolumeSubdomain1D) – The volume subdomain where the trap is.

Variables:
  • name (str, optional) – a name given to the trap. Defaults to None.

  • mobile_species (_Species) – the mobile species to be trapped

  • k_0 (float) – the trapping rate constant pre-exponential factor (m3 s-1)

  • E_k (float) – the trapping rate constant activation energy (eV)

  • p_0 (float) – the detrapping rate constant pre-exponential factor (s-1)

  • E_p (float) – the detrapping rate constant activation energy (eV)

  • volume (F.VolumeSubdomain1D) – The volume subdomain where the trap is.

  • trapped_concentration (_Species) – The immobile trapped concentration

  • trap_reaction (_Reaction) – The reaction for trapping the mobile conc.

  • empty_trap_sites (F.ImplicitSpecies) – The implicit species for the

  • sites (empty trap)

Examples

trap = Trap(name="Trap", mobile_species=H, k_0=1.0, E_k=0.2,
p_0=0.1, E_p=0.3, n=100, volume=my_vol)

my_model = HydrogenTransportProblem()
my_model.traps = [trap]

Notes

This convenience class replaces the need to specify an implicit species and the associated reaction, thus:

cm = _Species("mobile")
my_trap = F.Trap(
    name="trapped",
    mobile_species=cm,
    k_0=1,
    E_k=1,
    p_0=1,
    E_p=1,
    n=1,
    volume=my_vol,
)
my_model.species = [cm]
my_model.traps = [my_trap]

is equivalent to:

cm = _Species("mobile")
ct = _Species("trapped")
trap_sites = F.ImplicitSpecies(n=1, others=[ct])
trap_reaction = _Reaction(
    reactant=[cm, trap_sites],
    product=ct,
    k_0=1,
    E_k=1,
    p_0=1,
    E_p=1,
    volume=my_vol,
)
my_model.species = [cm, ct]
my_model.reactions = [trap_reaction]
create_species_and_reaction()[source]#

Create the immobile trapped species object and the reaction for trapping.