-
-
Notifications
You must be signed in to change notification settings - Fork 481
/
base_battery_model.py
1540 lines (1415 loc) · 67.1 KB
/
base_battery_model.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
#
# Base battery model class
#
import pybamm
from functools import cached_property
from pybamm.expression_tree.operations.serialise import Serialise
def represents_positive_integer(s):
"""Check if a string represents a positive integer"""
try:
val = int(s)
except ValueError:
return False
else:
return val > 0
class BatteryModelOptions(pybamm.FuzzyDict):
"""
Attributes
----------
options: dict
A dictionary of options to be passed to the model. The options that can
be set are listed below. Note that not all of the options are compatible with
each other and with all of the models implemented in PyBaMM. Each option is
optional and takes a default value if not provided.
In general, the option provided must be a string, but there are some cases
where a 2-tuple of strings can be provided instead to indicate a different
option for the negative and positive electrodes.
* "calculate discharge energy": str
Whether to calculate the discharge energy, throughput energy and
throughput capacity in addition to discharge capacity. Must be one of
"true" or "false". "false" is the default, since calculating discharge
energy can be computationally expensive for simple models like SPM.
* "cell geometry" : str
Sets the geometry of the cell. Can be "arbitrary" (default) or
"pouch". The arbitrary geometry option solves a 1D electrochemical
model with prescribed cell volume and cross-sectional area, and
(if thermal effects are included) solves a lumped thermal model
with prescribed surface area for cooling.
* "calculate heat source for isothermal models" : str
Whether to calculate the heat source terms during isothermal operation.
Can be "true" or "false". If "false", the heat source terms are set
to zero. Default is "false" since this option may require additional
parameters not needed by the electrochemical model.
* "convection" : str
Whether to include the effects of convection in the model. Can be
"none" (default), "uniform transverse" or "full transverse".
Must be "none" for lithium-ion models.
* "current collector" : str
Sets the current collector model to use. Can be "uniform" (default),
"potential pair" or "potential pair quite conductive".
* "diffusivity" : str
Sets the model for the diffusivity. Can be "single"
(default) or "current sigmoid". A 2-tuple can be provided for different
behaviour in negative and positive electrodes.
* "dimensionality" : int
Sets the dimension of the current collector problem. Can be 0
(default), 1 or 2.
* "electrolyte conductivity" : str
Can be "default" (default), "full", "leading order", "composite" or
"integrated".
* "exchange-current density" : str
Sets the model for the exchange-current density. Can be "single"
(default) or "current sigmoid". A 2-tuple can be provided for different
behaviour in negative and positive electrodes.
* "hydrolysis" : str
Whether to include hydrolysis in the model. Only implemented for
lead-acid models. Can be "false" (default) or "true". If "true", then
"surface form" cannot be 'false'.
* "intercalation kinetics" : str
Model for intercalation kinetics. Can be "symmetric Butler-Volmer"
(default), "asymmetric Butler-Volmer", "linear", "Marcus",
"Marcus-Hush-Chidsey" (which uses the asymptotic form from Zeng 2014),
or "MSMR" (which uses the form from Baker 2018). A 2-tuple can be
provided for different behaviour in negative and positive electrodes.
* "interface utilisation": str
Can be "full" (default), "constant", or "current-driven".
* "lithium plating" : str
Sets the model for lithium plating. Can be "none" (default),
"reversible", "partially reversible", or "irreversible".
* "lithium plating porosity change" : str
Whether to include porosity change due to lithium plating, can be
"false" (default) or "true".
* "loss of active material" : str
Sets the model for loss of active material. Can be "none" (default),
"stress-driven", "reaction-driven", "current-driven", or
"stress and reaction-driven".
A 2-tuple can be provided for different behaviour in negative and
positive electrodes.
* "number of MSMR reactions" : str
Sets the number of reactions to use in the MSMR model in each electrode.
A 2-tuple can be provided to give a different number of reactions in
the negative and positive electrodes. Default is "none". Can be any
2-tuple of strings of integers. For example, set to ("6", "4") for a
negative electrode with 6 reactions and a positive electrode with 4
reactions.
* "open-circuit potential" : str
Sets the model for the open circuit potential. Can be "single"
(default), "current sigmoid", "Wycisk", or "MSMR". If "MSMR" then the "particle"
option must also be "MSMR". A 2-tuple can be provided for different
behaviour in negative and positive electrodes.
* "operating mode" : str
Sets the operating mode for the model. This determines how the current
is set. Can be:
- "current" (default) : the current is explicity supplied
- "voltage"/"power"/"resistance" : solve an algebraic equation for \
current such that voltage/power/resistance is correct
- "differential power"/"differential resistance" : solve a \
differential equation for the power or resistance
- "explicit power"/"explicit resistance" : current is defined in terms \
of the voltage such that power/resistance is correct
- "CCCV": a special implementation of the common constant-current \
constant-voltage charging protocol, via an ODE for the current
- callable : if a callable is given as this option, the function \
defines the residual of an algebraic equation. The applied current \
will be solved for such that the algebraic constraint is satisfied.
* "particle" : str
Sets the submodel to use to describe behaviour within the particle.
Can be "Fickian diffusion" (default), "uniform profile",
"quadratic profile", "quartic profile", or "MSMR". If "MSMR" then the
"open-circuit potential" option must also be "MSMR". A 2-tuple can be
provided for different behaviour in negative and positive electrodes.
* "particle mechanics" : str
Sets the model to account for mechanical effects such as particle
swelling and cracking. Can be "none" (default), "swelling only",
or "swelling and cracking".
A 2-tuple can be provided for different behaviour in negative and
positive electrodes.
* "particle phases": str
Number of phases present in the electrode. A 2-tuple can be provided for
different behaviour in negative and positive electrodes.
For example, set to ("2", "1") for a negative electrode with 2 phases,
e.g. graphite and silicon.
* "particle shape" : str
Sets the model shape of the electrode particles. This is used to
calculate the surface area to volume ratio. Can be "spherical"
(default), or "no particles".
* "particle size" : str
Sets the model to include a single active particle size or a
distribution of sizes at any macroscale location. Can be "single"
(default) or "distribution". Option applies to both electrodes.
* "SEI" : str
Set the SEI submodel to be used. Options are:
- "none": :class:`pybamm.sei.NoSEI` (no SEI growth)
- "constant": :class:`pybamm.sei.Constant` (constant SEI thickness)
- "reaction limited", "reaction limited (asymmetric)", \
"solvent-diffusion limited", "electron-migration limited", \
"interstitial-diffusion limited", "ec reaction limited" \
or "ec reaction limited (asymmetric)": :class:`pybamm.sei.SEIGrowth`
* "SEI film resistance" : str
Set the submodel for additional term in the overpotential due to SEI.
The default value is "none" if the "SEI" option is "none", and
"distributed" otherwise. This is because the "distributed" model is more
complex than the model with no additional resistance, which adds
unnecessary complexity if there is no SEI in the first place
- "none": no additional resistance\
.. math::
\\eta_r = \\frac{F}{RT} * (\\phi_s - \\phi_e - U)
- "distributed": properly included additional resistance term\
.. math::
\\eta_r = \\frac{F}{RT}
* (\\phi_s - \\phi_e - U - R_{sei} * L_{sei} * j)
- "average": constant additional resistance term (approximation to the \
true model). This model can give similar results to the \
"distributed" case without needing to make j an algebraic state\
.. math::
\\eta_r = \\frac{F}{RT}
* (\\phi_s - \\phi_e - U - R_{sei} * L_{sei} * \\frac{I}{aL})
* "SEI on cracks" : str
Whether to include SEI growth on particle cracks, can be "false"
(default) or "true".
* "SEI porosity change" : str
Whether to include porosity change due to SEI formation, can be "false"
(default) or "true".
* "stress-induced diffusion" : str
Whether to include stress-induced diffusion, can be "false" or "true".
The default is "false" if "particle mechanics" is "none" and "true"
otherwise. A 2-tuple can be provided for different behaviour in negative
and positive electrodes.
* "surface form" : str
Whether to use the surface formulation of the problem. Can be "false"
(default), "differential" or "algebraic".
* "thermal" : str
Sets the thermal model to use. Can be "isothermal" (default), "lumped",
"x-lumped", or "x-full". The 'cell geometry' option must be set to
'pouch' for 'x-lumped' or 'x-full' to be valid. Using the 'x-lumped'
option with 'dimensionality' set to 0 is equivalent to using the
'lumped' option.
* "total interfacial current density as a state" : str
Whether to make a state for the total interfacial current density and
solve an algebraic equation for it. Default is "false", unless "SEI film
resistance" is distributed in which case it is automatically set to
"true".
* "working electrode" : str
Can be "both" (default) for a standard battery or "positive" for a
half-cell where the negative electrode is replaced with a lithium metal
counter electrode.
* "x-average side reactions": str
Whether to average the side reactions (SEI growth, lithium plating and
the respective porosity change) over the x-axis in Single Particle
Models, can be "false" or "true". Default is "false" for SPMe and
"true" for SPM.
"""
def __init__(self, extra_options):
self.possible_options = {
"calculate discharge energy": ["false", "true"],
"calculate heat source for isothermal models": ["false", "true"],
"cell geometry": ["arbitrary", "pouch"],
"contact resistance": ["false", "true"],
"convection": ["none", "uniform transverse", "full transverse"],
"current collector": [
"uniform",
"potential pair",
"potential pair quite conductive",
],
"diffusivity": ["single", "current sigmoid"],
"dimensionality": [0, 1, 2],
"electrolyte conductivity": [
"default",
"full",
"leading order",
"composite",
"integrated",
],
"exchange-current density": ["single", "current sigmoid"],
"hydrolysis": ["false", "true"],
"intercalation kinetics": [
"symmetric Butler-Volmer",
"asymmetric Butler-Volmer",
"linear",
"Marcus",
"Marcus-Hush-Chidsey",
"MSMR",
],
"interface utilisation": ["full", "constant", "current-driven"],
"lithium plating": [
"none",
"reversible",
"partially reversible",
"irreversible",
],
"lithium plating porosity change": ["false", "true"],
"loss of active material": [
"none",
"stress-driven",
"reaction-driven",
"current-driven",
"stress and reaction-driven",
],
"number of MSMR reactions": ["none"],
"open-circuit potential": ["single", "current sigmoid", "MSMR", "Wycisk"],
"operating mode": [
"current",
"voltage",
"power",
"differential power",
"explicit power",
"resistance",
"differential resistance",
"explicit resistance",
"CCCV",
],
"particle": [
"Fickian diffusion",
"fast diffusion",
"uniform profile",
"quadratic profile",
"quartic profile",
"MSMR",
],
"particle mechanics": ["none", "swelling only", "swelling and cracking"],
"particle phases": ["1", "2"],
"particle shape": ["spherical", "no particles"],
"particle size": ["single", "distribution"],
"SEI": [
"none",
"constant",
"reaction limited",
"reaction limited (asymmetric)",
"solvent-diffusion limited",
"electron-migration limited",
"interstitial-diffusion limited",
"ec reaction limited",
"ec reaction limited (asymmetric)",
],
"SEI film resistance": ["none", "distributed", "average"],
"SEI on cracks": ["false", "true"],
"SEI porosity change": ["false", "true"],
"stress-induced diffusion": ["false", "true"],
"surface form": ["false", "differential", "algebraic"],
"thermal": ["isothermal", "lumped", "x-lumped", "x-full"],
"total interfacial current density as a state": ["false", "true"],
"transport efficiency": [
"Bruggeman",
"ordered packing",
"hyperbola of revolution",
"overlapping spheres",
"tortuosity factor",
"random overlapping cylinders",
"heterogeneous catalyst",
"cation-exchange membrane",
],
"working electrode": ["both", "positive"],
"x-average side reactions": ["false", "true"],
}
default_options = {
name: options[0] for name, options in self.possible_options.items()
}
extra_options = extra_options or {}
working_electrode_option = extra_options.get("working electrode", "both")
SEI_option = extra_options.get("SEI", "none") # return "none" if not given
SEI_cr_option = extra_options.get("SEI on cracks", "false")
plating_option = extra_options.get("lithium plating", "none")
# For the full cell model, if "SEI", "SEI on cracks" and "lithium plating"
# options are not provided as tuples, change them to tuples with "none" or
# "false" on the positive electrode. To use these options on the positive
# electrode of a full cell, the tuple must be provided by the user
if working_electrode_option == "both":
if not (isinstance(SEI_option, tuple)) and SEI_option != "none":
extra_options["SEI"] = (SEI_option, "none")
if not (isinstance(SEI_cr_option, tuple)) and SEI_cr_option != "false":
extra_options["SEI on cracks"] = (SEI_cr_option, "false")
if not (isinstance(plating_option, tuple)) and plating_option != "none":
extra_options["lithium plating"] = (plating_option, "none")
# Change the default for cell geometry based on the current collector
# dimensionality
# return "none" if option not given
dimensionality_option = extra_options.get("dimensionality", "none")
if dimensionality_option in [1, 2]:
default_options["cell geometry"] = "pouch"
# The "cell geometry" option will still be overridden by extra_options if
# provided
# Change the default for cell geometry based on the thermal model
# return "none" if option not given
thermal_option = extra_options.get("thermal", "none")
if thermal_option == "x-full":
default_options["cell geometry"] = "pouch"
# The "cell geometry" option will still be overridden by extra_options if
# provided
# Change the default for SEI film resistance based on which SEI option is
# provided
# return "none" if option not given
sei_option = extra_options.get("SEI", "none")
if sei_option == "none":
default_options["SEI film resistance"] = "none"
else:
default_options["SEI film resistance"] = "distributed"
# The "SEI film resistance" option will still be overridden by extra_options if
# provided
# Change the default for particle mechanics based on which half-cell,
# SEI on cracks and LAM options are provided
# return "false", "false" and "none" respectively if options not given
SEI_cracks_option = extra_options.get("SEI on cracks", "false")
LAM_opt = extra_options.get("loss of active material", "none")
if SEI_cracks_option == "true":
default_options["particle mechanics"] = "swelling and cracking"
elif SEI_cracks_option == ("true", "false"):
if "stress-driven" in LAM_opt or "stress and reaction-driven" in LAM_opt:
default_options["particle mechanics"] = (
"swelling and cracking",
"swelling only",
)
else:
default_options["particle mechanics"] = (
"swelling and cracking",
"none",
)
else:
if "stress-driven" in LAM_opt or "stress and reaction-driven" in LAM_opt:
default_options["particle mechanics"] = "swelling only"
else:
default_options["particle mechanics"] = "none"
# The "particle mechanics" option will still be overridden by extra_options if
# provided
# Change the default for stress-induced diffusion based on which particle
# mechanics option is provided. If the user doesn't supply a particle mechanics
# option set the default stress-induced diffusion option based on the default
# particle mechanics option which may change depending on other options
# (e.g. for stress-driven LAM the default mechanics option is "swelling only")
mechanics_option = extra_options.get("particle mechanics", "none")
if (
mechanics_option == "none"
and default_options["particle mechanics"] == "none"
):
default_options["stress-induced diffusion"] = "false"
else:
default_options["stress-induced diffusion"] = "true"
# The "stress-induced diffusion" option will still be overridden by
# extra_options if provided
# Change the default for surface form based on which particle
# phases option is provided.
# return "1" if option not given
phases_option = extra_options.get("particle phases", "1")
if phases_option == "1":
default_options["surface form"] = "false"
else:
default_options["surface form"] = "algebraic"
# The "surface form" option will still be overridden by
# extra_options if provided
# Change default SEI model based on which lithium plating option is provided
# return "none" if option not given
plating_option = extra_options.get("lithium plating", "none")
if plating_option == "partially reversible":
default_options["SEI"] = "constant"
elif plating_option == ("partially reversible", "none"):
default_options["SEI"] = ("constant", "none")
else:
default_options["SEI"] = "none"
# The "SEI" option will still be overridden by extra_options if provided
options = pybamm.FuzzyDict(default_options)
# any extra options overwrite the default options
for name, opt in extra_options.items():
if name in default_options:
options[name] = opt
else:
if name == "particle cracking":
raise pybamm.OptionError(
"The 'particle cracking' option has been renamed. "
"Use 'particle mechanics' instead."
)
else:
raise pybamm.OptionError(
f"Option '{name}' not recognised. Best matches are {options.get_best_matches(name)}"
)
# If any of "open-circuit potential", "particle" or "intercalation kinetics" is
# "MSMR" then all of them must be "MSMR".
# Note: this check is currently performed on full cells, but is loosened for
# half-cells where you must pass a tuple of options to only set MSMR models in
# the working electrode
msmr_check_list = [
options[opt] == "MSMR"
for opt in ["open-circuit potential", "particle", "intercalation kinetics"]
]
if (
options["working electrode"] == "both"
and any(msmr_check_list)
and not all(msmr_check_list)
):
raise pybamm.OptionError(
"If any of 'open-circuit potential', 'particle' or "
"'intercalation kinetics' is 'MSMR' then all of them must be 'MSMR'"
)
# If "SEI film resistance" is "distributed" then "total interfacial current
# density as a state" must be "true"
if options["SEI film resistance"] == "distributed":
options["total interfacial current density as a state"] = "true"
# Check that extra_options did not try to provide a clashing option
if (
extra_options.get("total interfacial current density as a state")
== "false"
):
raise pybamm.OptionError(
"If 'sei film resistance' is 'distributed' then 'total interfacial "
"current density as a state' must be 'true'"
)
# If "SEI film resistance" is not "none" and there are multiple phases
# then "total interfacial current density as a state" must be "true"
if (
options["SEI film resistance"] != "none"
and options["particle phases"] != "1"
):
options["total interfacial current density as a state"] = "true"
# Check that extra_options did not try to provide a clashing option
if (
extra_options.get("total interfacial current density as a state")
== "false"
):
raise pybamm.OptionError(
"If 'SEI film resistance' is not 'none' "
"and there are multiple phases then 'total interfacial "
"current density as a state' must be 'true'"
)
# Options not yet compatible with contact resistance
if options["contact resistance"] == "true":
if options["operating mode"] == "explicit power":
raise NotImplementedError(
"Contact resistance not yet supported for explicit power."
)
if options["operating mode"] == "explicit resistance":
raise NotImplementedError(
"Contact resistance not yet supported for explicit resistance."
)
# Options not yet compatible with particle-size distributions
if options["particle size"] == "distribution":
if options["lithium plating"] != "none":
raise NotImplementedError(
"Lithium plating submodels do not yet support particle-size "
"distributions."
)
if options["particle"] in ["quadratic profile", "quartic profile"]:
raise NotImplementedError(
"'quadratic' and 'quartic' concentration profiles have not yet "
"been implemented for particle-size ditributions"
)
if options["particle mechanics"] != "none":
raise NotImplementedError(
"Particle mechanics submodels do not yet support particle-size"
" distributions."
)
if options["particle shape"] != "spherical":
raise NotImplementedError(
"Particle shape must be 'spherical' for particle-size distribution"
" submodels."
)
if options["SEI"] != "none":
raise NotImplementedError(
"SEI submodels do not yet support particle-size distributions."
)
if options["stress-induced diffusion"] == "true":
raise NotImplementedError(
"stress-induced diffusion cannot yet be included in "
"particle-size distributions."
)
if options["thermal"] == "x-full":
raise NotImplementedError(
"X-full thermal submodels do not yet support particle-size"
" distributions."
)
# Renamed options
if options["particle"] == "fast diffusion":
raise pybamm.OptionError(
"The 'fast diffusion' option has been renamed. "
"Use 'uniform profile' instead."
)
if options["SEI porosity change"] in [True, False]:
raise pybamm.OptionError(
"SEI porosity change must now be given in string format "
"('true' or 'false')"
)
if options["working electrode"] == "negative":
raise pybamm.OptionError(
"The 'negative' working electrode option has been removed because "
"the voltage - and therefore the energy stored - would be negative."
"Use the 'positive' working electrode option instead and set whatever "
"would normally be the negative electrode as the positive electrode."
)
# Some standard checks to make sure options are compatible
if options["dimensionality"] == 0:
if options["current collector"] not in ["uniform"]:
raise pybamm.OptionError(
"current collector model must be uniform in 0D model"
)
if options["convection"] == "full transverse":
raise pybamm.OptionError(
"cannot have transverse convection in 0D model"
)
if (
options["thermal"] in ["x-lumped", "x-full"]
and options["cell geometry"] != "pouch"
):
raise pybamm.OptionError(
options["thermal"] + " model must have pouch cell geometry."
)
if options["thermal"] == "x-full" and options["dimensionality"] != 0:
n = options["dimensionality"]
raise pybamm.OptionError(
f"X-full thermal submodels do not yet support {n}D current collectors"
)
if isinstance(options["stress-induced diffusion"], str):
if (
options["stress-induced diffusion"] == "true"
and options["particle mechanics"] == "none"
):
raise pybamm.OptionError(
"cannot have stress-induced diffusion without a particle "
"mechanics model"
)
if options["working electrode"] != "both":
if options["thermal"] == "x-full":
raise pybamm.OptionError(
"X-full thermal submodel is not compatible with half-cell models"
)
elif options["thermal"] == "x-lumped" and options["dimensionality"] != 0:
n = options["dimensionality"]
raise pybamm.OptionError(
f"X-lumped thermal submodels do not yet support {n}D "
"current collectors in a half-cell configuration"
)
if options["particle phases"] not in ["1", ("1", "1")]:
if not (
options["surface form"] != "false"
and options["particle size"] == "single"
and options["particle"] == "Fickian diffusion"
and options["particle mechanics"] == "none"
and options["loss of active material"] == "none"
):
raise pybamm.OptionError(
"If there are multiple particle phases: 'surface form' cannot be "
"'false', 'particle size' must be 'single', 'particle' must be "
"'Fickian diffusion'. Also the following must "
"be 'none': 'particle mechanics', 'loss of active material'"
)
# Check options are valid
for option, value in options.items():
if isinstance(value, str) or option in [
"dimensionality",
"operating mode",
]: # some options accept non-strings
value = (value,)
else:
if not (
option
in [
"diffusivity",
"exchange-current density",
"intercalation kinetics",
"interface utilisation",
"lithium plating",
"loss of active material",
"number of MSMR reactions",
"open-circuit potential",
"particle",
"particle mechanics",
"particle phases",
"particle size",
"SEI",
"SEI on cracks",
"stress-induced diffusion",
]
and isinstance(value, tuple)
and len(value) == 2
):
# more possible options that can take 2-tuples to be added
# as they come
raise pybamm.OptionError(
f"\n'{value}' is not recognized in option '{option}'. "
"Values must be strings or (in some cases) "
"2-tuples of strings"
)
# flatten value
value_list = []
for val in value:
if isinstance(val, tuple):
value_list.extend(list(val))
else:
value_list.append(val)
for val in value_list:
if val not in self.possible_options[option]:
if option == "operating mode" and callable(val):
# "operating mode" can be a function
pass
elif (
option == "number of MSMR reactions"
and represents_positive_integer(val)
):
# "number of MSMR reactions" can be a positive integer
pass
else:
raise pybamm.OptionError(
f"\n'{val}' is not recognized in option '{option}'. "
f"Possible values are {self.possible_options[option]}"
)
super().__init__(options.items())
@property
def phases(self):
try:
return self._phases
except AttributeError:
self._phases = {}
for domain in ["negative", "positive"]:
number = int(getattr(self, domain)["particle phases"])
phases = ["primary"]
if number >= 2:
phases.append("secondary")
self._phases[domain] = phases
return self._phases
@cached_property
def whole_cell_domains(self):
if self["working electrode"] == "positive":
return ["separator", "positive electrode"]
elif self["working electrode"] == "both":
return ["negative electrode", "separator", "positive electrode"]
else:
raise NotImplementedError # future proofing
@property
def electrode_types(self):
try:
return self._electrode_types
except AttributeError:
self._electrode_types = {}
for domain in ["negative", "positive"]:
if f"{domain} electrode" in self.whole_cell_domains:
self._electrode_types[domain] = "porous"
else:
self._electrode_types[domain] = "planar"
return self._electrode_types
def print_options(self):
"""
Print the possible options with the ones currently selected
"""
for key, value in self.items():
print(f"{key!r}: {value!r} (possible: {self.possible_options[key]!r})")
def print_detailed_options(self):
"""
Print the docstring for Options
"""
print(self.__doc__)
@property
def negative(self):
"Returns the options for the negative electrode"
# index 0 in a 2-tuple for the negative electrode
return BatteryModelDomainOptions(self.items(), 0)
@property
def positive(self):
"Returns the options for the positive electrode"
# index 1 in a 2-tuple for the positive electrode
return BatteryModelDomainOptions(self.items(), 1)
class BatteryModelDomainOptions(dict):
def __init__(self, dict_items, index):
super().__init__(dict_items)
self.index = index
def __getitem__(self, key):
options = super().__getitem__(key)
if isinstance(options, str):
return options
else:
# 2-tuple, first is negative domain, second is positive domain
return options[self.index]
@property
def primary(self):
return BatteryModelPhaseOptions(self, 0)
@property
def secondary(self):
return BatteryModelPhaseOptions(self, 1)
class BatteryModelPhaseOptions(dict):
def __init__(self, domain_options, index):
super().__init__(domain_options.items())
self.domain_options = domain_options
self.index = index
def __getitem__(self, key):
options = self.domain_options.__getitem__(key)
if isinstance(options, str):
return options
else:
# 2-tuple, first is primary phase, second is secondary phase
return options[self.index]
class BaseBatteryModel(pybamm.BaseModel):
"""
Base model class with some default settings and required variables
Parameters
----------
options : dict-like, optional
A dictionary of options to be passed to the model. If this is a dict (and not
a subtype of dict), it will be processed by :class:`pybamm.BatteryModelOptions`
to ensure that the options are valid. If this is a subtype of dict, it is
assumed that the options have already been processed and are valid. This allows
for the use of custom options classes. The default options are given by
:class:`pybamm.BatteryModelOptions`.
name : str, optional
The name of the model. The default is "Unnamed battery model".
"""
def __init__(self, options=None, name="Unnamed battery model"):
super().__init__(name)
self.options = options
@classmethod
def deserialise(cls, properties: dict):
"""
Create a model instance from a serialised object.
"""
# append the model name with _saved to differentiate
instance = cls(
options=properties["options"], name=properties["name"] + "_saved"
)
# Initialise model with stored variables that have already been discretised
instance._concatenated_rhs = properties["concatenated_rhs"]
instance._concatenated_algebraic = properties["concatenated_algebraic"]
instance._concatenated_initial_conditions = properties[
"concatenated_initial_conditions"
]
instance.len_rhs = instance.concatenated_rhs.size
instance.len_alg = instance.concatenated_algebraic.size
instance.len_rhs_and_alg = instance.len_rhs + instance.len_alg
instance.bounds = properties["bounds"]
instance.events = properties["events"]
instance.mass_matrix = properties["mass_matrix"]
instance.mass_matrix_inv = properties["mass_matrix_inv"]
# add optional properties not required for model to solve
if properties["variables"]:
instance._variables = pybamm.FuzzyDict(properties["variables"])
# assign meshes to each variable
for var in instance._variables.values():
if var.domain != []:
var.mesh = properties["mesh"][var.domain]
else:
var.mesh = None
if var.domains["secondary"] != []:
var.secondary_mesh = properties["mesh"][var.domains["secondary"]]
else:
var.secondary_mesh = None
instance._geometry = pybamm.Geometry(properties["geometry"])
else:
# Delete the default variables which have not been discretised
instance._variables = pybamm.FuzzyDict({})
# Model has already been discretised
instance.is_discretised = True
return instance
@property
def default_geometry(self):
return pybamm.battery_geometry(options=self.options)
@property
def default_var_pts(self):
base_var_pts = {
"x_n": 20,
"x_s": 20,
"x_p": 20,
"r_n": 20,
"r_p": 20,
"r_n_prim": 20,
"r_p_prim": 20,
"r_n_sec": 20,
"r_p_sec": 20,
"y": 10,
"z": 10,
"R_n": 30,
"R_p": 30,
}
# Reduce the default points for 2D current collectors
if self.options["dimensionality"] == 2:
base_var_pts.update({"x_n": 10, "x_s": 10, "x_p": 10})
return base_var_pts
@property
def default_submesh_types(self):
base_submeshes = {
"negative electrode": pybamm.Uniform1DSubMesh,
"separator": pybamm.Uniform1DSubMesh,
"positive electrode": pybamm.Uniform1DSubMesh,
"negative particle": pybamm.Uniform1DSubMesh,
"positive particle": pybamm.Uniform1DSubMesh,
"negative primary particle": pybamm.Uniform1DSubMesh,
"positive primary particle": pybamm.Uniform1DSubMesh,
"negative secondary particle": pybamm.Uniform1DSubMesh,
"positive secondary particle": pybamm.Uniform1DSubMesh,
"negative particle size": pybamm.Uniform1DSubMesh,
"positive particle size": pybamm.Uniform1DSubMesh,
}
if self.options["dimensionality"] == 0:
base_submeshes["current collector"] = pybamm.SubMesh0D
elif self.options["dimensionality"] == 1:
base_submeshes["current collector"] = pybamm.Uniform1DSubMesh
elif self.options["dimensionality"] == 2:
base_submeshes["current collector"] = pybamm.ScikitUniform2DSubMesh
return base_submeshes
@property
def default_spatial_methods(self):
base_spatial_methods = {
"macroscale": pybamm.FiniteVolume(),
"negative particle": pybamm.FiniteVolume(),
"positive particle": pybamm.FiniteVolume(),
"negative primary particle": pybamm.FiniteVolume(),
"positive primary particle": pybamm.FiniteVolume(),
"negative secondary particle": pybamm.FiniteVolume(),
"positive secondary particle": pybamm.FiniteVolume(),
"negative particle size": pybamm.FiniteVolume(),
"positive particle size": pybamm.FiniteVolume(),
}
if self.options["dimensionality"] == 0:
# 0D submesh - use base spatial method
base_spatial_methods["current collector"] = (
pybamm.ZeroDimensionalSpatialMethod()
)
elif self.options["dimensionality"] == 1:
base_spatial_methods["current collector"] = pybamm.FiniteVolume()
elif self.options["dimensionality"] == 2:
base_spatial_methods["current collector"] = pybamm.ScikitFiniteElement()
return base_spatial_methods
@property
def options(self):
return self._options
@options.setter
def options(self, extra_options):
# if extra_options is a dict then process it into a BatteryModelOptions
# this does not catch cases that subclass the dict type
# so other submodels can pass in their own options class if needed
if extra_options is None or type(extra_options) == dict: # noqa: E721
options = BatteryModelOptions(extra_options)
else:
options = extra_options
# Options that are incompatible with models
if isinstance(self, pybamm.lithium_ion.BaseModel):
if options["convection"] != "none":
raise pybamm.OptionError(
"convection not implemented for lithium-ion models"
)
if isinstance(self, pybamm.lithium_ion.SPMe):
if options["electrolyte conductivity"] not in [
"default",
"composite",
"integrated",
]:
raise pybamm.OptionError(
"electrolyte conductivity '{}' not suitable for SPMe".format(
options["electrolyte conductivity"]
)
)
if isinstance(self, pybamm.lithium_ion.SPM) and not isinstance(
self, pybamm.lithium_ion.SPMe
):
if options["x-average side reactions"] == "false":
raise pybamm.OptionError(
"x-average side reactions cannot be 'false' for SPM models"
)
if isinstance(self, pybamm.lithium_ion.SPM):
if (
"distribution" in options["particle size"]
and options["surface form"] == "false"
):
raise pybamm.OptionError(
"surface form must be 'algebraic' or 'differential' if "
" 'particle size' contains a 'distribution'"
)
if isinstance(self, pybamm.lead_acid.BaseModel):
if options["thermal"] != "isothermal" and options["dimensionality"] != 0:
raise pybamm.OptionError(
"Lead-acid models can only have thermal "
"effects if dimensionality is 0."
)
if options["SEI"] != "none" or options["SEI film resistance"] != "none":
raise pybamm.OptionError("Lead-acid models cannot have SEI formation")
if options["lithium plating"] != "none":
raise pybamm.OptionError("Lead-acid models cannot have lithium plating")
if options["open-circuit potential"] == "MSMR":
raise pybamm.OptionError(
"Lead-acid models cannot use the MSMR open-circuit potential model"
)