-
-
Notifications
You must be signed in to change notification settings - Fork 765
Expand file tree
/
Copy pathbase_model.py
More file actions
2483 lines (2145 loc) · 94.4 KB
/
base_model.py
File metadata and controls
2483 lines (2145 loc) · 94.4 KB
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 __future__ import annotations
import copy
import json
import numbers
import warnings
from collections import OrderedDict
from enum import Enum
from itertools import chain
from pathlib import Path
import casadi
import numpy as np
import scipy
import pybamm
from pybamm.expression_tree.operations.serialise import Serialise
from pybamm.models.event import EventType
from pybamm.models.symbol_processor import SymbolProcessor
class ModelSolutionObservability(str, Enum):
"""
Enum to specify the observability states for a PyBaMM model's solution.
This enum tracks why a solution may or may not be observable via
``solution.observe(symbol)``.
"""
ENABLED = "solution is observable"
DISABLED = "`disable_solution_observability()` was called on the model"
SOLVER_OUTPUT_VARIABLES = "the solver includes `output_variables`"
MISSING_INPUT_PARAMETERS = "some input parameters were not provided to the solver"
REPARAMETERISED_MODEL = (
"the model was re-parameterised with `ParameterValues.process_model()`"
)
REDISCRETISED_MODEL = (
"the model was re-discretised with `Discretisation.process_model()`"
)
def __bool__(self) -> bool:
return bool(self == ModelSolutionObservability.ENABLED)
_BUILTIN_MODULE_NAMES = (
"lithium_ion",
"lead_acid",
"equivalent_circuit",
"sodium_ion",
)
class BaseModel:
"""
Base model class for other models to extend.
Attributes
----------
name: str
A string representing the name of the model.
submodels: dict
A dictionary of submodels that the model is composed of.
use_jacobian: bool
Whether to use the Jacobian when solving the model (default is True).
convert_to_format: str
Specifies the format to convert the expression trees representing the RHS,
algebraic equations, Jacobian, and events.
Options are:
- None: retain PyBaMM expression tree structure.
- "python": convert to Python code for evaluating `evaluate(t, y)` on expressions.
- "casadi": convert to CasADi expression tree for Jacobian calculation.
- "jax": convert to JAX expression tree.
Default is "casadi".
is_discretised: bool
Indicates whether the model has been discretised (default is False).
y_slices: None or list
Slices of the concatenated state vector after discretisation, used to track
different submodels in the full concatenated solution vector.
"""
def __init__(self, name="Unnamed model"):
self.name = name
self._options = {}
self._built = False
self._built_fundamental = False
# Initialise empty model
self.submodels = {}
self._rhs = {}
self._algebraic = {}
self._initial_conditions = {}
self._boundary_conditions = {}
self._variables_by_submodel = {}
self._variables = pybamm.FuzzyDict({})
self._variables_processed = {}
self._coupled_variables = {}
self._summary_variables = []
self._events = []
self._events_dict = None
self._concatenated_rhs = None
self._concatenated_algebraic = None
self._concatenated_initial_conditions = None
self._mass_matrix = None
self._mass_matrix_inv = None
self._jacobian = None
self._jacobian_algebraic = None
self._parameters = None
self._input_parameters = None
self._required_input_parameters = None
self._fixed_input_parameters = {}
self._parameter_info = None
self._is_standard_form_dae = None
self._variables_casadi = {}
self._geometry = pybamm.Geometry({})
self._symbol_processor = SymbolProcessor()
self._solution_observable = ModelSolutionObservability.ENABLED
# Default behaviour is to use the jacobian
self.use_jacobian = True
self.convert_to_format = "casadi"
# Model is not initially discretised or parameterised
self.is_discretised = False
self.is_parameterised = False
self.y_slices = None
self.len_rhs_and_alg = None
# Non-lithium ion models shouldn't calculate eSOH parameters
self._calc_esoh = False
# Root solver
self._algebraic_root_solver = None
@classmethod
def deserialise(cls, properties: dict):
"""
Create a model instance from a serialised object.
"""
# append the model name with _saved to differentiate
instance = cls(name=properties["name"] + "_saved")
instance.options = properties["options"]
return cls.generic_deserialise(instance, properties)
@classmethod
def generic_deserialise(cls, instance, properties):
# 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._variables_processed = dict(properties.get("_variables_processed", {}))
def assign_meshes_to_variables(variables_dict, mesh):
if not mesh:
return
for var in variables_dict.values():
if var.domain != []:
var.mesh = mesh[var.domain]
if var.domains["secondary"] != []:
var.secondary_mesh = mesh[var.domains["secondary"]]
else:
var.secondary_mesh = None
if var.domains["tertiary"] != []:
var.tertiary_mesh = mesh[var.domains["tertiary"]]
else:
var.tertiary_mesh = None
# add optional properties not required for model to solve
_variables = properties.get("variables") or {}
instance._variables = pybamm.FuzzyDict(_variables)
assign_meshes_to_variables(instance._variables, properties.get("mesh"))
if properties["geometry"]:
instance._geometry = pybamm.Geometry(properties["geometry"])
# Also assign meshes to _variables_processed
assign_meshes_to_variables(
instance._variables_processed, properties.get("mesh")
)
# Model has already been discretised and parameterised
instance.is_discretised = True
instance.is_parameterised = True
instance._solution_observable = ModelSolutionObservability[
properties.get(
"_solution_observable", ModelSolutionObservability.DISABLED.value
)
]
return instance
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def rhs(self):
"""Returns a dictionary mapping expressions (variables) to expressions that represent
the right-hand side (RHS) of the model's differential equations."""
return self._rhs
@rhs.setter
def rhs(self, rhs):
self._rhs = EquationDict("rhs", rhs)
@property
def algebraic(self):
"""Returns a dictionary mapping expressions (variables) to expressions that represent
the algebraic equations of the model."""
return self._algebraic
@algebraic.setter
def algebraic(self, algebraic):
self._algebraic = EquationDict("algebraic", algebraic)
@property
def initial_conditions(self):
"""Returns a dictionary mapping expressions (variables) to expressions that represent
the initial conditions for the state variables."""
return self._initial_conditions
@initial_conditions.setter
def initial_conditions(self, initial_conditions):
self._initial_conditions = EquationDict(
"initial_conditions", initial_conditions
)
@property
def boundary_conditions(self):
"""Returns a dictionary mapping expressions (variables) to expressions representing
the boundary conditions of the model."""
return self._boundary_conditions
@boundary_conditions.setter
def boundary_conditions(self, boundary_conditions):
self._boundary_conditions = BoundaryConditionsDict(boundary_conditions)
@property
def coupled_variables(self):
"""Returns a dictionary mapping strings to expressions representing variables needed by the model but whose equations were set by other models."""
return self._coupled_variables
@coupled_variables.setter
def coupled_variables(self, coupled_variables):
for name, var in coupled_variables.items():
if (
isinstance(var, pybamm.CoupledVariable)
and var.name != name
# Exception if the variable is also there under its own name
and not (
var.name in coupled_variables and coupled_variables[var.name] == var
)
):
raise ValueError(
f"Coupled variable with name '{var.name}' is in coupled variables dictionary with "
f"name '{name}'. Names must match."
)
self._coupled_variables = coupled_variables
def list_coupled_variables(self):
return list(self._coupled_variables.keys())
@property
def variables(self):
"""Returns a dictionary mapping strings to expressions representing the model's useful variables."""
return self._variables
@variables.setter
def variables(self, variables):
for name, var in variables.items():
if (
isinstance(var, pybamm.Variable)
and var.name != name
# Exception if the variable is also there under its own name
and not (var.name in variables and variables[var.name] == var)
):
raise ValueError(
f"Variable with name '{var.name}' is in variables dictionary with "
f"name '{name}'. Names must match."
)
self._variables = pybamm.FuzzyDict(variables)
def get_processed_variables_dict(self) -> dict[str, pybamm.Symbol]:
"""
Get a dictionary of processed variables.
"""
return dict(self._variables_processed)
def get_processed_variable(self, name: str) -> pybamm.Symbol:
"""
Get a processed variable by name.
Parameters
----------
name : str
The name of the variable to get.
Returns
-------
pybamm.Symbol
The processed variable.
Raises
------
KeyError
If the variable is not found.
"""
value = self._variables_processed.get(name)
if value is not None:
return value
value = self._variables[name]
self.process_and_register_variable(name, value)
return self._variables_processed[name]
def get_processed_variable_or_event(self, name: str) -> pybamm.Symbol:
"""
Get a processed variable or event by name.
Parameters
----------
name : str
The name of the variable or event to get.
Returns
-------
pybamm.Symbol
The processed variable or event expression.
Raises
------
KeyError
If the variable or event is not found.
"""
value = self._variables_processed.get(name)
if value is not None:
return value
value = self._variables.get(name)
if value is not None:
self.process_and_register_variable(name, value)
return self._variables_processed[name]
value = self.events_dict.get(name)
if value is not None:
return value
# Raise a more helpful error message from the fuzzy dict
return self.variables_and_events[name]
def process_and_register_variable(self, name: str, symbol: pybamm.Symbol):
"""
Process a variable and store it in _variables_processed.
This method does NOT modify self.variables - the original variable
expression is preserved. The processed variable is stored separately
in _variables_processed.
CoupledVariables in the symbol are resolved by recursively getting
the processed version of the referenced variable.
Parameters
----------
name : str
The name of the variable.
symbol : pybamm.Symbol
The unprocessed variable symbol.
"""
if name in self._variables_processed:
return
pybamm.logger.info(f"Processing variable '{name}' for model '{self.name}'")
if not self.symbol_processor:
raise ValueError(
f"Cannot process variable '{name}' without a `symbol_processor`."
)
symbol = self._resolve_coupled_variables(symbol)
value = self.symbol_processor(name=name, symbol=symbol)
self._variables_processed[name] = value
def _resolve_coupled_variables(self, symbol: pybamm.Symbol) -> pybamm.Symbol:
"""Resolve CoupledVariables by looking up their targets in self._variables."""
if isinstance(symbol, pybamm.CoupledVariable):
if symbol.name not in self._variables:
raise ValueError(
f"CoupledVariable '{symbol.name}' not found in model.variables"
)
return self._resolve_coupled_variables(self._variables[symbol.name])
elif hasattr(symbol, "children") and symbol.children:
new_children = []
changed = False
for child in symbol.children:
new_child = self._resolve_coupled_variables(child)
new_children.append(new_child)
if new_child is not child:
changed = True
if changed:
return symbol.create_copy(new_children=new_children)
return symbol
def update_processed_variables(self, processed_vars: dict[str, pybamm.Symbol]):
"""
Update the _variables_processed dict with new processed variables.
Parameters
----------
processed_vars : dict or list
Either a dictionary of {name: processed_symbol} pairs, or a list of
names (for backward compatibility, where the processed symbol is
taken from self.variables).
"""
if not processed_vars:
return
self._variables_processed.update(processed_vars)
def variable_names(self):
return list(self._variables.keys())
@property
def variables_and_events(self):
"""Returns a dictionary containing both models variables and events."""
try:
return self._variables_and_events
except AttributeError:
self._variables_and_events = self.variables.copy()
self._variables_and_events.update(self.events_dict)
return self._variables_and_events
@property
def symbol_processor(self) -> SymbolProcessor:
return self._symbol_processor
@property
def events(self):
"""Returns a dictionary mapping expressions (variables) to expressions that represent
the initial conditions for the state variables."""
return self._events
@events.setter
def events(self, events):
self._events = events
@property
def events_dict(self) -> dict[str, pybamm.Symbol]:
if self._events_dict is None:
self._events_dict = {
f"Event: {event.name}": event.expression for event in self.events
}
return self._events_dict
@property
def concatenated_rhs(self):
"""Returns the concatenated right-hand side (RHS) expressions for the model after discretisation."""
return self._concatenated_rhs
@concatenated_rhs.setter
def concatenated_rhs(self, concatenated_rhs):
self._concatenated_rhs = concatenated_rhs
@property
def concatenated_algebraic(self):
"""Returns the concatenated algebraic equations for the model after discretisation."""
return self._concatenated_algebraic
@concatenated_algebraic.setter
def concatenated_algebraic(self, concatenated_algebraic):
self._concatenated_algebraic = concatenated_algebraic
@property
def concatenated_initial_conditions(self):
"""Returns the initial conditions for all variables after discretization, providing the
initial values for the state variables."""
return self._concatenated_initial_conditions
@concatenated_initial_conditions.setter
def concatenated_initial_conditions(self, concatenated_initial_conditions):
self._concatenated_initial_conditions = concatenated_initial_conditions
@property
def built(self):
"Returns a boolean for the model built status."
return self._built
@property
def mass_matrix(self):
"""Returns the mass matrix for the system of differential equations after discretisation."""
return self._mass_matrix
@mass_matrix.setter
def mass_matrix(self, mass_matrix):
self._mass_matrix = mass_matrix
@property
def jacobian(self):
"""Returns the Jacobian matrix for the model, computed automatically if `use_jacobian` is True."""
return self._jacobian
@jacobian.setter
def jacobian(self, jacobian):
self._jacobian = jacobian
@property
def jacobian_rhs(self):
"""Returns the Jacobian matrix for the right-hand side (RHS) part of the model, computed
if `use_jacobian` is True."""
return self._jacobian_rhs
@jacobian_rhs.setter
def jacobian_rhs(self, jacobian_rhs):
self._jacobian_rhs = jacobian_rhs
@property
def jacobian_algebraic(self):
"""Returns the Jacobian matrix for the algebraic part of the model, computed automatically
during solver setup if `use_jacobian` is True."""
return self._jacobian_algebraic
@jacobian_algebraic.setter
def jacobian_algebraic(self, jacobian_algebraic):
self._jacobian_algebraic = jacobian_algebraic
@property
def param(self):
"""Returns a dictionary to store parameter values for the model."""
return self._param
@param.setter
def param(self, values):
self._param = values
@property
def options(self):
"""Returns the model options dictionary that allows customization of the model's behavior."""
return self._options
@options.setter
def options(self, options):
self._options = options
@property
def timescale(self):
raise NotImplementedError(
"timescale has been removed since models are now dimensional"
)
@timescale.setter
def timescale(self, value):
raise NotImplementedError(
"timescale has been removed since models are now dimensional"
)
@property
def length_scales(self):
raise NotImplementedError(
"length_scales has been removed since models are now dimensional"
)
@length_scales.setter
def length_scales(self, values):
raise NotImplementedError(
"length_scales has been removed since models are now dimensional"
)
@property
def geometry(self):
"""Returns the geometry of the model."""
return self._geometry
@property
def default_var_pts(self):
"""Returns a dictionary of the default variable points for the model, which is empty by default."""
return {}
@property
def default_geometry(self):
"""Returns a dictionary of the default geometry for the model, which is empty by default."""
return {}
@property
def default_submesh_types(self):
"""Returns a dictionary of the default submesh types for the model, which is empty by default."""
return {}
@property
def default_spatial_methods(self):
"""Returns a dictionary of the default spatial methods for the model, which is empty by default."""
return {}
@property
def default_solver(self):
"""Returns the default solver for the model, based on whether it is an ODE/DAE or algebraic model."""
if len(self.rhs) == 0 and len(self.algebraic) != 0:
return pybamm.NonlinearSolver()
else:
return pybamm.IDAKLUSolver()
@property
def default_quick_plot_variables(self):
"""Returns the default variables for quick plotting (None by default)."""
return None
@property
def default_parameter_values(self):
"""Returns the default parameter values for the model (an empty set of parameters by default)."""
return pybamm.ParameterValues({})
@property
def fixed_input_parameters(self) -> set[pybamm.Symbol]:
"""Returns a set of all fixed input parameter symbols used in the parameter values."""
return self._fixed_input_parameters
@fixed_input_parameters.setter
def fixed_input_parameters(self, fixed_input_parameters: set[pybamm.Symbol]):
self._fixed_input_parameters = fixed_input_parameters
@property
def parameters(self):
"""Returns a list of all parameter symbols used in the model."""
self._parameters = self._find_symbols(
(pybamm.Parameter, pybamm.InputParameter, pybamm.FunctionParameter)
)
return self._parameters
@property
def input_parameters(self):
"""Returns a list of all input parameter symbols used in the model."""
if self._input_parameters is None:
self._input_parameters = self._find_symbols(pybamm.InputParameter)
return self._input_parameters
@property
def required_input_parameters(self):
"""Returns a list of all input parameter symbols used in the model."""
if self._required_input_parameters is None:
self._required_input_parameters = self._find_symbols(
pybamm.InputParameter, fixed_input_parameters={}
)
return self._required_input_parameters
@property
def is_standard_form_dae(self) -> bool:
"""
Check if the model is a DAE in standard form with a mass matrix that is all
zeros except for along the diagonal, which is either ones or zeros.
"""
if self._is_standard_form_dae is None:
self._is_standard_form_dae = self._check_standard_form_dae()
return self._is_standard_form_dae
@property
def is_processed(self) -> bool:
"""
Returns True if the model is processed by `Discretisation.process_model` or `ParameterValues.process_model`.
"""
return self._variables_processed or self.is_discretised or self.is_parameterised
def disable_symbol_processing(self, reason: ModelSolutionObservability):
"""
Disable custom symbol processing by the model.
Parameters
----------
reason : ModelSolutionObservability, optional
The reason why symbol processing is being disabled.
Defaults to ModelSolutionObservability.DISABLED.
"""
self.disable_solution_observability(reason)
self.symbol_processor.disable()
@property
def can_process_symbols(self) -> bool:
"""
Returns ``True`` if the model has a symbol processor that is
capable of processing symbols.
"""
return bool(self.symbol_processor.can_process_symbols)
@property
def solution_observable(self) -> bool:
"""
Returns the observability state for ``solution.observe(symbol)``.
Returns ``ModelSolutionObservability.ENABLED`` if observable, otherwise
returns a reason why the solution is not observable.
"""
return self.can_process_symbols and bool(self._solution_observable)
@property
def solution_observable_status(self) -> ModelSolutionObservability:
"""
Returns the status of the solution observability as a string.
"""
return self._solution_observable
def disable_solution_observability(self, reason: ModelSolutionObservability):
"""
Disable observing the solution with ``solution.observe(symbol)``.
Parameters
----------
reason : ModelSolutionObservability
The reason why the solution is or is not observable.
"""
if not isinstance(reason, ModelSolutionObservability):
raise ValueError(
f"Invalid reason: {reason}. Must be a ModelSolutionObservability enum value."
)
if reason:
raise ValueError(
"Cannot re-enable solution observability after it has been disabled."
)
self._solution_observable = reason
@property
def calc_esoh(self):
"""Whether to include eSOH variables in the summary variables."""
return self._calc_esoh
@property
def algebraic_root_solver(self):
return self._algebraic_root_solver
@algebraic_root_solver.setter
def algebraic_root_solver(self, algebraic_root_solver):
self._algebraic_root_solver = algebraic_root_solver
@property
def y0(self):
if not hasattr(self, "y0_list") or self.y0_list is None:
return None
elif len(self.y0_list) == 1:
return self.y0_list[0]
else:
raise ValueError(
"Model contains multiple initial states. Access using y0_list instead."
)
def get_parameter_info(self, by_submodel=False):
"""
Extracts the parameter information and returns it as a dictionary.
To get a list of all parameter-like objects without extra information,
use :py:attr:`model.parameters`.
Parameters
----------
by_submodel : bool, optional
Whether to return the parameter info sub-model wise or not (default False)
"""
parameter_info = {}
if by_submodel:
for submodel_name, submodel_vars in self._variables_by_submodel.items():
submodel_info = {}
for var_name, var_symbol in submodel_vars.items():
if isinstance(var_symbol, pybamm.Parameter):
submodel_info[var_name] = (var_symbol, "Parameter")
elif isinstance(var_symbol, pybamm.InputParameter):
if not var_symbol.domain:
submodel_info[var_name] = (var_symbol, "InputParameter")
else:
submodel_info[var_name] = (
var_symbol,
f"InputParameter in {var_symbol.domain}",
)
elif isinstance(var_symbol, pybamm.FunctionParameter):
input_names = "', '".join(var_symbol.input_names)
submodel_info[var_name] = (
var_symbol,
f"FunctionParameter with inputs(s) '{input_names}'",
)
else:
submodel_info[var_name] = (var_symbol, "Unknown Type")
parameters = self._find_symbols_by_submodel(
pybamm.Parameter, submodel_name
)
for param in parameters:
submodel_info[param.name] = (param, "Parameter")
input_parameters = self._find_symbols_by_submodel(
pybamm.InputParameter, submodel_name
)
for input_param in input_parameters:
if not input_param.domain:
submodel_info[input_param.name] = (
input_param,
"InputParameter",
)
else:
submodel_info[input_param.name] = (
input_param,
f"InputParameter in {input_param.domain}",
)
function_parameters = self._find_symbols_by_submodel(
pybamm.FunctionParameter, submodel_name
)
for func_param in function_parameters:
if func_param.name not in parameter_info:
input_names = "', '".join(func_param.input_names)
submodel_info[func_param.name] = (
func_param,
f"FunctionParameter with inputs(s) '{input_names}'",
)
parameter_info[submodel_name] = submodel_info
else:
parameters = self._find_symbols(pybamm.Parameter)
for param in parameters:
parameter_info[param.name] = (param, "Parameter")
input_parameters = self._find_symbols(pybamm.InputParameter)
for input_param in input_parameters:
if not input_param.domain:
parameter_info[input_param.name] = (input_param, "InputParameter")
else:
parameter_info[input_param.name] = (
input_param,
f"InputParameter in {input_param.domain}",
)
function_parameters = self._find_symbols(pybamm.FunctionParameter)
for func_param in function_parameters:
if func_param.name not in parameter_info:
input_names = "', '".join(func_param.input_names)
parameter_info[func_param.name] = (
func_param,
f"FunctionParameter with inputs(s) '{input_names}'",
)
return parameter_info
def _calculate_max_lengths(self, parameter_dict):
"""
Calculate the maximum length of parameters and parameter type in a dictionary
Parameters
----------
parameter_dict : dict
The dict from which maximum lengths are calculated
"""
max_name_length = max(
len(getattr(parameter, "name", str(parameter)))
for parameter, _ in parameter_dict.values()
)
max_type_length = max(
len(parameter_type) for _, parameter_type in parameter_dict.values()
)
return max_name_length, max_type_length
def _check_standard_form_dae(self):
"""
Check if the model is a DAE in standard form with a mass matrix that is all
zeros except for along the diagonal, which is either ones or zeros.
For example, the following is standard form:
M*y' = f(y, y', t)
M = [I 0
0 0]
The following explicit ODE is also a standard form DAE:
M = I
The following is not standard form:
M = [2I 0
0 0]
"""
if self.mass_matrix is None:
return False
n_rhs = self.len_rhs
if n_rhs == 0:
return False
mass = self.mass_matrix.entries
M_ode = mass[:n_rhs, :n_rhs]
if scipy.sparse.issparse(M_ode):
identity = scipy.sparse.identity(n_rhs, format="csr")
return (M_ode - identity).nnz == 0
else:
return np.allclose(M_ode, np.eye(n_rhs))
def _format_table_row(
self, param_name, param_type, max_name_length, max_type_length
):
"""
Format the parameter information in a formatted table
Parameters
----------
param_name : str
The name of the parameter
param_type : str
The type of the parameter
max_name_length : int
The maximum length of the parameter in the dictionary
max_type_length : int
The maximum length of the parameter type in the dictionary
"""
param_name_lines = [
param_name[i : i + max_name_length]
for i in range(0, len(param_name), max_name_length)
]
param_type_lines = [
param_type[i : i + max_type_length]
for i in range(0, len(param_type), max_type_length)
]
max_lines = max(len(param_name_lines), len(param_type_lines))
return [
f"│ {param_name_lines[i]:<{max_name_length}} │ {param_type_lines[i]:<{max_type_length}} │"
for i in range(max_lines)
]
def print_parameter_info(self, by_submodel=False):
"""
Print parameter information in a formatted table from a dictionary of parameters
Parameters
----------
by_submodel : bool, optional
Whether to print the parameter info sub-model wise or not (default False)
"""
if by_submodel:
parameter_info = self.get_parameter_info(by_submodel=True)
for submodel_name, submodel_vars in parameter_info.items():
if not submodel_vars:
print(f"'{submodel_name}' submodel parameters: \nNo parameters\n")
else:
print(f"'{submodel_name}' submodel parameters:")
(
max_param_name_length,
max_param_type_length,
) = self._calculate_max_lengths(submodel_vars)
table = [
f"┌─{'─' * max_param_name_length}─┬─{'─' * max_param_type_length}─┐",
f"│ {'Parameter':<{max_param_name_length}} │ {'Type of parameter':<{max_param_type_length}} │",
f"├─{'─' * max_param_name_length}─┼─{'─' * max_param_type_length}─┤",
]
for param, param_type in submodel_vars.values():
param_name = getattr(param, "name", str(param))
table.extend(
self._format_table_row(
param_name,
param_type,
max_param_name_length,
max_param_type_length,
)
)
table.extend(
[
f"└─{'─' * max_param_name_length}─┴─{'─' * max_param_type_length}─┘",
]
)
table = "\n".join(table) + "\n"
table.encode("utf-8")
print(table)
else:
info = self.get_parameter_info()
max_param_name_length, max_param_type_length = self._calculate_max_lengths(
info
)
table = [
f"┌─{'─' * max_param_name_length}─┬─{'─' * max_param_type_length}─┐",
f"│ {'Parameter':<{max_param_name_length}} │ {'Type of parameter':<{max_param_type_length}} │",
f"├─{'─' * max_param_name_length}─┼─{'─' * max_param_type_length}─┤",
]
for param, param_type in info.values():
param_name = getattr(param, "name", str(param))
table.extend(
self._format_table_row(
param_name,
param_type,
max_param_name_length,
max_param_type_length,