-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathhydrogen_transport_problem.py
1266 lines (1098 loc) · 46.9 KB
/
hydrogen_transport_problem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections.abc import Callable
from mpi4py import MPI
import basix
import dolfinx
import numpy.typing as npt
import tqdm.autonotebook
import ufl
from dolfinx import fem
from scifem import NewtonSolver
import festim.boundary_conditions
import festim.problem
from festim import (
boundary_conditions,
exports,
k_B,
problem,
)
from festim import (
reaction as _reaction,
)
from festim import (
species as _species,
)
from festim import (
subdomain as _subdomain,
)
from festim.helpers import as_fenics_constant
from festim.mesh import Mesh
__all__ = ["HydrogenTransportProblem", "HTransportProblemDiscontinuous"]
class HydrogenTransportProblem(problem.ProblemBase):
"""
Hydrogen Transport Problem.
Args:
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
solver_parameters (dict): the solver parameters of the model
exports (list of festim.Export): the exports of the model
traps (list of F.Trap): the traps of the model
Attributes:
mesh : The mesh
subdomains: The subdomains
species: The species
reactions: the reaction
temperature: The temperature in unit `K`
sources: The hydrogen sources
initial_conditions: The initial conditions
boundary_conditions: List of Dirichlet boundary conditions
solver_parameters (dict): the solver parameters
exports (list of festim.Export): the export
traps (list of F.Trap): the traps 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
multispecies (bool): True if the model has more than one species.
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
.. highlight:: python
.. code-block:: python
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
.. highlight:: python
.. code-block:: python
my_model = F.HydrogenTransportProblem(
mesh=F.Mesh(...),
subdomains=[F.Subdomain(...)],
species=[F.Species(name="H"), F.Species(name="Trap")],
)
my_model.initialise()
"""
def __init__(
self,
mesh: Mesh | None = None,
subdomains: (
list[_subdomain.VolumeSubdomain | _subdomain.SurfaceSubdomain] | None
) = None,
species: list[_species.Species] | None = None,
reactions: list[_reaction.Reaction] | None = None,
temperature: (
float
| int
| fem.Constant
| fem.Function
| Callable[
[npt.NDArray[dolfinx.default_scalar_type]],
npt.NDArray[dolfinx.default_scalar_type],
]
| Callable[
[npt.NDArray[dolfinx.default_scalar_type], fem.Constant],
npt.NDArray[dolfinx.default_scalar_type],
]
| None
) = None,
sources=None,
initial_conditions=None,
boundary_conditions=None,
settings=None,
exports=None,
traps=None,
):
super().__init__(
mesh=mesh,
sources=sources,
exports=exports,
subdomains=subdomains,
boundary_conditions=boundary_conditions,
settings=settings,
)
self.species = species or []
self.temperature = temperature
self.reactions = reactions or []
self.initial_conditions = initial_conditions or []
self.traps = traps or []
self.temperature_fenics = None
self._vtxfiles: list[dolfinx.io.VTXWriter] = []
@property
def temperature(self):
return self._temperature
@temperature.setter
def temperature(self, value):
if value is None:
self._temperature = value
elif isinstance(value, (float, int, fem.Constant, fem.Function)):
self._temperature = value
elif callable(value):
self._temperature = value
else:
raise TypeError(
"Value must be a float, int, fem.Constant, fem.Function, or callable"
)
@property
def temperature_fenics(self):
return self._temperature_fenics
@temperature_fenics.setter
def temperature_fenics(self, value):
if value is None:
self._temperature_fenics = value
return
elif not isinstance(
value,
(fem.Constant, fem.Function),
):
raise TypeError("Value must be a fem.Constant or fem.Function")
self._temperature_fenics = value
@property
def temperature_time_dependent(self):
if self.temperature is None:
return False
if isinstance(self.temperature, fem.Constant):
return False
if callable(self.temperature):
arguments = self.temperature.__code__.co_varnames
return "t" in arguments
else:
return False
@property
def multispecies(self):
return len(self.species) > 1
@property
def species(self) -> list[_species.Species]:
return self._species
@species.setter
def species(self, value):
# check that all species are of type festim.Species
for spe in value:
if not isinstance(spe, _species.Species):
raise TypeError(
f"elements of species must be of type festim.Species not "
f"{type(spe)}"
)
self._species = value
@property
def facet_meshtags(self):
return self._facet_meshtags
@facet_meshtags.setter
def facet_meshtags(self, value):
if value is None:
self._facet_meshtags = value
elif isinstance(value, dolfinx.mesh.MeshTags):
self._facet_meshtags = value
else:
raise TypeError("value must be of type dolfinx.mesh.MeshTags")
@property
def volume_meshtags(self):
return self._volume_meshtags
@volume_meshtags.setter
def volume_meshtags(self, value):
if value is None:
self._volume_meshtags = value
elif isinstance(value, dolfinx.mesh.MeshTags):
self._volume_meshtags = value
else:
raise TypeError("value must be of type dolfinx.mesh.MeshTags")
def initialise(self):
self.create_species_from_traps()
self.define_function_spaces()
self.define_meshtags_and_measures()
self.assign_functions_to_species()
self.t = fem.Constant(self.mesh.mesh, 0.0)
if self.settings.transient:
# TODO should raise error if no stepsize is provided
# TODO Should this be an attribute of festim.Stepsize?
self.dt = as_fenics_constant(
self.settings.stepsize.initial_value, self.mesh.mesh
)
self.define_temperature()
self.define_boundary_conditions()
self.create_source_values_fenics()
self.create_flux_values_fenics()
self.create_initial_conditions()
self.create_formulation()
self.create_solver()
self.initialise_exports()
def create_species_from_traps(self):
"""Generate a species and reaction per trap defined in self.traps"""
for trap in self.traps:
trap.create_species_and_reaction()
self.species.append(trap.trapped_concentration)
self.reactions.append(trap.reaction)
def define_temperature(self):
"""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.
"""
# check if temperature is None
if self.temperature is None:
raise ValueError("the temperature attribute needs to be defined")
# if temperature is a float or int, create a fem.Constant
elif isinstance(self.temperature, (float, int)):
self.temperature_fenics = as_fenics_constant(
self.temperature, self.mesh.mesh
)
# if temperature is a fem.Constant or function, pass it to temperature_fenics
elif isinstance(self.temperature, (fem.Constant, fem.Function)):
self.temperature_fenics = self.temperature
# if temperature is callable, process accordingly
elif callable(self.temperature):
arguments = self.temperature.__code__.co_varnames
if "t" in arguments and "x" not in arguments:
if not isinstance(self.temperature(t=float(self.t)), (float, int)):
raise ValueError(
f"self.temperature should return a float or an int, not "
f"{type(self.temperature(t=float(self.t)))} "
)
# only t is an argument
self.temperature_fenics = as_fenics_constant(
mesh=self.mesh.mesh, value=self.temperature(t=float(self.t))
)
else:
x = ufl.SpatialCoordinate(self.mesh.mesh)
degree = 1
element_temperature = basix.ufl.element(
basix.ElementFamily.P,
self.mesh.mesh.basix_cell(),
degree,
basix.LagrangeVariant.equispaced,
)
function_space_temperature = fem.functionspace(
self.mesh.mesh, element_temperature
)
self.temperature_fenics = fem.Function(function_space_temperature)
kwargs = {}
if "t" in arguments:
kwargs["t"] = self.t
if "x" in arguments:
kwargs["x"] = x
# store the expression of the temperature
# to update the temperature_fenics later
self.temperature_expr = fem.Expression(
self.temperature(**kwargs),
function_space_temperature.element.interpolation_points(),
)
self.temperature_fenics.interpolate(self.temperature_expr)
def initialise_exports(self):
"""Defines the export writers of the model, if field is given as
a string, find species object in self.species"""
for export in self.exports:
# if name of species is given then replace with species object
if isinstance(export.field, list):
for idx, field in enumerate(export.field):
if isinstance(field, str):
export.field[idx] = _species.find_species_from_name(
field, self.species
)
elif isinstance(export.field, str):
export.field = _species.find_species_from_name(
export.field, self.species
)
# Initialize XDMFFile for writer
if isinstance(export, exports.XDMFExport):
export.define_writer(MPI.COMM_WORLD)
if isinstance(export, exports.VTXSpeciesExport):
functions = export.get_functions()
self._vtxfiles.append(
dolfinx.io.VTXWriter(
functions[0].function_space.mesh.comm,
export.filename,
functions,
engine="BP5",
)
)
# compute diffusivity function for surface fluxes
spe_to_D_global = {} # links species to global D function
spe_to_D_global_expr = {} # links species to D expression
for export in self.exports:
if isinstance(export, exports.SurfaceQuantity):
if export.field in spe_to_D_global:
# if already computed then use the same D
D = spe_to_D_global[export.field]
D_expr = spe_to_D_global_expr[export.field]
else:
# compute D and add it to the dict
D, D_expr = self.define_D_global(export.field)
spe_to_D_global[export.field] = D
spe_to_D_global_expr[export.field] = D_expr
# add the global D to the export
export.D = D
export.D_expr = D_expr
def define_D_global(self, species):
"""Defines the global diffusion coefficient for a given species
Args:
species (F.Species): the species
Returns:
dolfinx.fem.Function, dolfinx.fem.Expression: the global diffusion
coefficient and the expression of the global diffusion coefficient
for a given species
"""
assert isinstance(species, _species.Species)
D_0 = fem.Function(self.V_DG_0)
E_D = fem.Function(self.V_DG_0)
for vol in self.volume_subdomains:
cell_indices = vol.locate_subdomain_entities(self.mesh.mesh)
# replace values of D_0 and E_D by values from the material
D_0.x.array[cell_indices] = vol.material.get_D_0(species=species)
E_D.x.array[cell_indices] = vol.material.get_E_D(species=species)
# create global D function
D = fem.Function(self.V_DG_1)
expr = D_0 * ufl.exp(
-E_D / as_fenics_constant(k_B, self.mesh.mesh) / self.temperature_fenics
)
D_expr = fem.Expression(expr, self.V_DG_1.element.interpolation_points())
D.interpolate(D_expr)
return D, D_expr
def define_function_spaces(self):
"""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"""
# TODO: expose degree as a property to the user (element_degree ?) in ProblemBase
degree = 1
element_CG = basix.ufl.element(
basix.ElementFamily.P,
self.mesh.mesh.basix_cell(),
degree,
basix.LagrangeVariant.equispaced,
)
if not self.multispecies:
element = element_CG
else:
elements = []
for spe in self.species:
if isinstance(spe, _species.Species):
elements.append(element_CG)
element = basix.ufl.mixed_element(elements)
self.function_space = fem.functionspace(self.mesh.mesh, element)
# create global DG function spaces of degree 0 and 1
element_DG0 = basix.ufl.element(
"DG",
self.mesh.mesh.basix_cell(),
0,
basix.LagrangeVariant.equispaced,
)
element_DG1 = basix.ufl.element(
"DG",
self.mesh.mesh.basix_cell(),
1,
basix.LagrangeVariant.equispaced,
)
self.V_DG_0 = fem.functionspace(self.mesh.mesh, element_DG0)
self.V_DG_1 = fem.functionspace(self.mesh.mesh, element_DG1)
self.u = fem.Function(self.function_space)
self.u_n = fem.Function(self.function_space)
def assign_functions_to_species(self):
"""Creates the solution, prev solution, test function and
post-processing solution for each species, if model is multispecies,
created a collapsed function space for each species"""
if not self.multispecies:
sub_solutions = [self.u]
sub_prev_solution = [self.u_n]
sub_test_functions = [ufl.TestFunction(self.function_space)]
self.species[0].sub_function_space = self.function_space
self.species[0].post_processing_solution = self.u
else:
sub_solutions = list(ufl.split(self.u))
sub_prev_solution = list(ufl.split(self.u_n))
sub_test_functions = list(ufl.TestFunctions(self.function_space))
for idx, spe in enumerate(self.species):
spe.sub_function_space = self.function_space.sub(idx)
spe.post_processing_solution = self.u.sub(idx)
spe.collapsed_function_space, _ = self.function_space.sub(
idx
).collapse()
for idx, spe in enumerate(self.species):
spe.solution = sub_solutions[idx]
spe.prev_solution = sub_prev_solution[idx]
spe.test_function = sub_test_functions[idx]
def define_boundary_conditions(self):
for bc in self.boundary_conditions:
if isinstance(bc.species, str):
# if name of species is given then replace with species object
bc.species = _species.find_species_from_name(bc.species, self.species)
super().define_boundary_conditions()
def create_dirichletbc_form(self, bc):
"""Creates a dirichlet boundary condition form
Args:
bc (festim.DirichletBC): the boundary condition
Returns:
dolfinx.fem.bcs.DirichletBC: A representation of
the boundary condition for modifying linear systems.
"""
# create value_fenics
if not self.multispecies:
function_space_value = bc.species.sub_function_space
else:
function_space_value = bc.species.collapsed_function_space
bc.create_value(
temperature=self.temperature_fenics,
function_space=function_space_value,
t=self.t,
)
# get dofs
if self.multispecies and isinstance(bc.value_fenics, (fem.Function)):
function_space_dofs = (
bc.species.sub_function_space,
bc.species.collapsed_function_space,
)
else:
function_space_dofs = bc.species.sub_function_space
bc_dofs = bc.define_surface_subdomain_dofs(
facet_meshtags=self.facet_meshtags,
function_space=function_space_dofs,
)
# create form
if not self.multispecies and isinstance(bc.value_fenics, (fem.Function)):
# no need to pass the functionspace since value_fenics is already a Function
function_space_form = None
else:
function_space_form = bc.species.sub_function_space
form = fem.dirichletbc(
value=bc.value_fenics,
dofs=bc_dofs,
V=function_space_form,
)
return form
def create_source_values_fenics(self):
"""For each source create the value_fenics"""
for source in self.sources:
# create value_fenics for all F.ParticleSource objects
if isinstance(source, festim.source.ParticleSource):
source.create_value_fenics(
mesh=self.mesh.mesh,
temperature=self.temperature_fenics,
t=self.t,
)
def create_flux_values_fenics(self):
"""For each particle flux create the value_fenics"""
for bc in self.boundary_conditions:
# create value_fenics for all F.ParticleFluxBC objects
if isinstance(bc, boundary_conditions.ParticleFluxBC):
bc.create_value_fenics(
mesh=self.mesh.mesh,
temperature=self.temperature_fenics,
t=self.t,
)
def create_initial_conditions(self):
"""For each initial condition, create the value_fenics and assign it to
the previous solution of the condition's species"""
if len(self.initial_conditions) > 0 and not self.settings.transient:
raise ValueError(
"Initial conditions can only be defined for transient simulations"
)
function_space_value = None
for condition in self.initial_conditions:
# create value_fenics for condition
function_space_value = None
if callable(condition.value):
# if bc.value is a callable then need to provide a functionspace
if not self.multispecies:
function_space_value = condition.species.sub_function_space
else:
function_space_value = condition.species.collapsed_function_space
condition.create_expr_fenics(
mesh=self.mesh.mesh,
temperature=self.temperature_fenics,
function_space=function_space_value,
)
# assign to previous solution of species
if not self.multispecies:
condition.species.prev_solution.interpolate(condition.expr_fenics)
else:
idx = self.species.index(condition.species)
self.u_n.sub(idx).interpolate(condition.expr_fenics)
def create_formulation(self):
"""Creates the formulation of the model"""
self.formulation = 0
# add diffusion and time derivative for each species
for spe in self.species:
u = spe.solution
u_n = spe.prev_solution
v = spe.test_function
for vol in self.volume_subdomains:
D = vol.material.get_diffusion_coefficient(
self.mesh.mesh, self.temperature_fenics, spe
)
if spe.mobile:
self.formulation += ufl.dot(D * ufl.grad(u), ufl.grad(v)) * self.dx(
vol.id
)
if self.settings.transient:
self.formulation += ((u - u_n) / self.dt) * v * self.dx(vol.id)
for reaction in self.reactions:
for reactant in reaction.reactant:
if isinstance(reactant, festim.species.Species):
self.formulation += (
reaction.reaction_term(self.temperature_fenics)
* reactant.test_function
* self.dx(reaction.volume.id)
)
# product
if isinstance(reaction.product, list):
products = reaction.product
else:
products = [reaction.product]
for product in products:
self.formulation += (
-reaction.reaction_term(self.temperature_fenics)
* product.test_function
* self.dx(reaction.volume.id)
)
# add sources
for source in self.sources:
self.formulation -= (
source.value_fenics
* source.species.test_function
* self.dx(source.volume.id)
)
# add fluxes
for bc in self.boundary_conditions:
if isinstance(bc, boundary_conditions.ParticleFluxBC):
self.formulation -= (
bc.value_fenics
* bc.species.test_function
* self.ds(bc.subdomain.id)
)
# check if each species is defined in all volumes
if not self.settings.transient:
for spe in self.species:
# if species mobile, already defined in diffusion term
if not spe.mobile:
not_defined_in_volume = self.volume_subdomains.copy()
for vol in self.volume_subdomains:
# check reactions
for reaction in self.reactions:
if vol == reaction.volume:
not_defined_in_volume.remove(vol)
# add c = 0 to formulation where needed
for vol in not_defined_in_volume:
self.formulation += (
spe.solution * spe.test_function * self.dx(vol.id)
)
def update_time_dependent_values(self):
super().update_time_dependent_values()
if not self.temperature_time_dependent:
return
t = float(self.t)
if isinstance(self.temperature_fenics, fem.Constant):
self.temperature_fenics.value = self.temperature(t=t)
elif isinstance(self.temperature_fenics, fem.Function):
self.temperature_fenics.interpolate(self.temperature_expr)
for bc in self.boundary_conditions:
if bc.temperature_dependent:
bc.update(t=t)
for source in self.sources:
if source.temperature_dependent:
source.update(t=t)
def post_processing(self):
"""Post processes the model"""
if self.temperature_time_dependent:
# update global D if temperature time dependent or internal
# variables time dependent
species_not_updated = self.species.copy() # make a copy of the species
for export in self.exports:
if isinstance(export, exports.SurfaceFlux):
# if the D of the species has not been updated yet
if export.field in species_not_updated:
export.D.interpolate(export.D_expr)
species_not_updated.remove(export.field)
for export in self.exports:
# TODO if export type derived quantity
if isinstance(export, exports.SurfaceQuantity):
if isinstance(
export,
(exports.SurfaceFlux, exports.TotalSurface, exports.AverageSurface),
):
export.compute(
self.ds,
)
else:
export.compute()
# update export data
export.t.append(float(self.t))
# if filename given write export data to file
if export.filename is not None:
export.write(t=float(self.t))
elif isinstance(export, exports.VolumeQuantity):
if isinstance(export, (exports.TotalVolume, exports.AverageVolume)):
export.compute(self.dx)
else:
export.compute()
# update export data
export.t.append(float(self.t))
# if filename given write export data to file
if export.filename is not None:
export.write(t=float(self.t))
if isinstance(export, exports.XDMFExport):
export.write(float(self.t))
# should we move this to problem.ProblemBase?
for vtxfile in self._vtxfiles:
vtxfile.write(float(self.t))
class HTransportProblemDiscontinuous(HydrogenTransportProblem):
interfaces: list[_subdomain.Interface]
petsc_options: dict
surface_to_volume: dict
def __init__(
self,
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[_subdomain.Interface] | None = None,
surface_to_volume: dict | None = None,
petsc_options: dict | None = None,
):
"""Class for a multi-material hydrogen transport problem
For other arguments see ``festim.HydrogenTransportProblem``.
Args:
interfaces (list, optional): list of interfaces (``festim.Interface``
objects). Defaults to None.
surface_to_volume (dict, optional): correspondance dictionary linking
each ``festim.SurfaceSubdomain`` objects to a ``festim.VolumeSubdomain``
object). Defaults to None.
petsc_options (dict, optional): petsc options to be passed to the
``festim.NewtonSolver`` object. If None, the default options are:
```
default_petsc_options = {
"ksp_type": "preonly",
"pc_type": "lu",
"pc_factor_mat_solver_type": "mumps",
}
```
Defaults to None.
"""
super().__init__(
mesh,
subdomains,
species,
reactions,
temperature,
sources,
initial_conditions,
boundary_conditions,
settings,
exports,
traps,
)
self.interfaces = interfaces or []
self.surface_to_volume = surface_to_volume or {}
default_petsc_options = {
"ksp_type": "preonly",
"pc_type": "lu",
"pc_factor_mat_solver_type": "mumps",
}
self.petsc_options = petsc_options or default_petsc_options
self._vtxfiles: list[dolfinx.io.VTXWriter] = []
def initialise(self):
# check that all species have a list of F.VolumeSubdomain as this is
# different from F.HydrogenTransportProblem
for spe in self.species:
if not isinstance(spe.subdomains, list):
raise TypeError("subdomains attribute should be list")
self.define_meshtags_and_measures()
# create submeshes and transfer meshtags to subdomains
for subdomain in self.volume_subdomains:
subdomain.create_subdomain(self.mesh.mesh, self.volume_meshtags)
subdomain.transfer_meshtag(self.mesh.mesh, self.facet_meshtags)
for interface in self.interfaces:
interface.mt = self.volume_meshtags
interface.parent_mesh = self.mesh.mesh
self.create_species_from_traps()
self.t = fem.Constant(self.mesh.mesh, 0.0)
if self.settings.transient:
# TODO should raise error if no stepsize is provided
# TODO Should this be an attribute of festim.Stepsize?
self.dt = as_fenics_constant(
self.settings.stepsize.initial_value, self.mesh.mesh
)
self.define_temperature()
self.create_source_values_fenics()
self.create_flux_values_fenics()
self.create_initial_conditions()
for subdomain in self.volume_subdomains:
self.define_function_spaces(subdomain)
self.create_subdomain_formulation(subdomain)
subdomain.u.name = f"u_{subdomain.id}"
self.define_boundary_conditions()
self.create_formulation()
self.create_solver()
self.initialise_exports()
def create_dirichletbc_form(self, bc: boundary_conditions.FixedConcentrationBC):
"""
Creates the ``value_fenics`` attribute for a given
``festim.FixedConcentrationBC`` and returns the appropriate
``dolfinx.fem.DirichletBC`` object.
Args:
bc (festim.FixedConcentrationBC): the dirichlet BC
Returns:
dolfinx.fem.DirichletBC: the appropriate dolfinx representation
generated from ``dolfinx.fem.dirichletbc()``
"""
fdim = self.mesh.mesh.topology.dim - 1
volume_subdomain = self.surface_to_volume[bc.subdomain]
sub_V = bc.species.subdomain_to_function_space[volume_subdomain]
collapsed_V, _ = sub_V.collapse()
bc.create_value(
temperature=self.temperature_fenics,
function_space=collapsed_V,
t=self.t,
)
volume_subdomain.submesh.topology.create_connectivity(
volume_subdomain.submesh.topology.dim - 1,
volume_subdomain.submesh.topology.dim,
)
# mapping between sub_function space and collapsed is only needed if
# value_fenics is a function of the collapsed space
if isinstance(bc.value_fenics, fem.Function):
function_space_dofs = (sub_V, collapsed_V)
else:
function_space_dofs = sub_V
bc_dofs = dolfinx.fem.locate_dofs_topological(
function_space_dofs,
fdim,
volume_subdomain.ft.find(bc.subdomain.id),
)
form = dolfinx.fem.dirichletbc(bc.value_fenics, bc_dofs, sub_V)
return form
def create_initial_conditions(self):
if self.initial_conditions:
raise NotImplementedError(
"initial conditions not yet implemented for discontinuous"
)
def define_function_spaces(self, subdomain: _subdomain.VolumeSubdomain):
"""
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.
Args:
subdomain (F.VolumeSubdomain): a subdomain of the geometry
"""
# get number of species defined in the subdomain
all_species = [
species for species in self.species if subdomain in species.subdomains
]
# instead of using the set function we use a list to keep the order
unique_species = []
for species in all_species:
if species not in unique_species:
unique_species.append(species)
nb_species = len(unique_species)
degree = 1
element_CG = basix.ufl.element(
basix.ElementFamily.P,
subdomain.submesh.basix_cell(),
degree,
basix.LagrangeVariant.equispaced,
)
element = basix.ufl.mixed_element([element_CG] * nb_species)
V = dolfinx.fem.functionspace(subdomain.submesh, element)
u = dolfinx.fem.Function(V)
u_n = dolfinx.fem.Function(V)
# store attributes in the subdomain object
subdomain.u = u
subdomain.u_n = u_n
# split the functions and assign the subfunctions to the species
us = list(ufl.split(u))
u_ns = list(ufl.split(u_n))
vs = list(ufl.TestFunctions(V))
for i, species in enumerate(unique_species):
species.subdomain_to_solution[subdomain] = us[i]
species.subdomain_to_prev_solution[subdomain] = u_ns[i]
species.subdomain_to_test_function[subdomain] = vs[i]
species.subdomain_to_function_space[subdomain] = V.sub(i)
species.subdomain_to_post_processing_solution[subdomain] = u.sub(
i
).collapse()
species.subdomain_to_collapsed_function_space[subdomain] = V.sub(
i
).collapse()
name = f"{species.name}_{subdomain.id}"
species.subdomain_to_post_processing_solution[subdomain].name = name
def create_subdomain_formulation(self, subdomain: _subdomain.VolumeSubdomain):
"""
Creates the variational formulation for each subdomain and stores it in ``subdomain.F``
Args:
subdomain (F.VolumeSubdomain): a subdomain of the geometry
"""
form = 0
# add diffusion and time derivative for each species
for spe in self.species:
if subdomain not in spe.subdomains:
continue
u = spe.subdomain_to_solution[subdomain]