forked from pybamm-team/PyBaMM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_operators.py
1550 lines (1308 loc) · 55.1 KB
/
binary_operators.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
#
# Binary operator classes
#
from __future__ import annotations
import numbers
import numpy as np
import sympy
from scipy.sparse import csr_matrix, issparse
import functools
import pybamm
from typing import Callable, cast
# create type alias(s)
from pybamm.type_definitions import ChildSymbol, ChildValue, Numeric
def _preprocess_binary(
left: ChildSymbol, right: ChildSymbol
) -> tuple[pybamm.Symbol, pybamm.Symbol]:
if isinstance(left, (float, int, np.number)):
left = pybamm.Scalar(left)
elif isinstance(left, np.ndarray):
if left.ndim > 1:
raise ValueError("left must be a 1D array")
left = pybamm.Vector(left)
if isinstance(right, (float, int, np.number)):
right = pybamm.Scalar(right)
elif isinstance(right, np.ndarray):
if right.ndim > 1:
raise ValueError("right must be a 1D array")
right = pybamm.Vector(right)
# Check both left and right are pybamm Symbols
if not (isinstance(left, pybamm.Symbol) and isinstance(right, pybamm.Symbol)):
raise NotImplementedError(
f"""BinaryOperator not implemented for symbols of type {type(left)} and {type(right)}"""
)
# Do some broadcasting in special cases, to avoid having to do this manually
if left.domain != [] and right.domain != [] and left.domain != right.domain:
if left.domain == right.secondary_domain:
left = pybamm.PrimaryBroadcast(left, right.domain)
elif right.domain == left.secondary_domain:
right = pybamm.PrimaryBroadcast(right, left.domain)
return left, right
class BinaryOperator(pybamm.Symbol):
"""
A node in the expression tree representing a binary operator (e.g. `+`, `*`)
Derived classes will specify the particular operator
Parameters
----------
name : str
name of the node
left : :class:`Symbol` or :class:`Number`
lhs child node (converted to :class:`Scalar` if Number)
right : :class:`Symbol` or :class:`Number`
rhs child node (converted to :class:`Scalar` if Number)
"""
def __init__(
self, name: str, left_child: ChildSymbol, right_child: ChildSymbol
) -> None:
left, right = _preprocess_binary(left_child, right_child)
domains = self.get_children_domains([left, right])
super().__init__(name, children=[left, right], domains=domains)
self.left = self.children[0]
self.right = self.children[1]
@classmethod
def _from_json(cls, snippet: dict):
"""Use to instantiate when deserialising; discretisation has
already occured so pre-processing of binaries is not necessary."""
instance = cls.__new__(cls)
super(BinaryOperator, instance).__init__(
snippet["name"],
children=[snippet["children"][0], snippet["children"][1]],
domains=snippet["domains"],
)
instance.left = instance.children[0]
instance.right = instance.children[1]
return instance
def __str__(self):
"""See :meth:`pybamm.Symbol.__str__()`."""
# Possibly add brackets for clarity
if isinstance(self.left, pybamm.BinaryOperator) and not (
(self.left.name == self.name)
or (self.left.name == "*" and self.name == "/")
or (self.left.name == "+" and self.name == "-")
or self.name == "+"
):
left_str = f"({self.left!s})"
else:
left_str = f"{self.left!s}"
if isinstance(self.right, pybamm.BinaryOperator) and not (
(self.name == "*" and self.right.name in ["*", "/"]) or self.name == "+"
):
right_str = f"({self.right!s})"
else:
right_str = f"{self.right!s}"
return f"{left_str} {self.name} {right_str}"
def create_copy(
self,
new_children: list[pybamm.Symbol] | None = None,
perform_simplifications: bool = True,
):
"""See :meth:`pybamm.Symbol.new_copy()`."""
if new_children and len(new_children) != 2:
raise ValueError(
f"Symbol of type {type(self)} must have exactly two children."
)
children = self._children_for_copying(new_children)
if not perform_simplifications:
out = self.__class__(children[0], children[1])
else:
# creates a new instance using the overloaded binary operator to perform
# additional simplifications, rather than just calling the constructor
out = self._binary_new_copy(children[0], children[1])
out.copy_domains(self)
return out
def _binary_new_copy(self, left: ChildSymbol, right: ChildSymbol):
"""
Performs the overloaded binary operation on the two symbols `left` and `right`,
to create a binary class instance after performing appropriate simplifying
checks.
Default behaviour for _binary_new_copy copies the behaviour of `_binary_evaluate`,
but since `left` and `right` are symbols this creates a new symbol instead of
returning a value.
"""
return self._binary_evaluate(left, right)
def evaluate(
self,
t: float | None = None,
y: np.ndarray | None = None,
y_dot: np.ndarray | None = None,
inputs: dict | str | None = None,
):
"""See :meth:`pybamm.Symbol.evaluate()`."""
left = self.left.evaluate(t, y, y_dot, inputs)
right = self.right.evaluate(t, y, y_dot, inputs)
return self._binary_evaluate(left, right)
def _evaluate_for_shape(self):
"""See :meth:`pybamm.Symbol.evaluate_for_shape()`."""
left = self.children[0].evaluate_for_shape()
right = self.children[1].evaluate_for_shape()
return self._binary_evaluate(left, right)
def _binary_jac(self, left_jac, right_jac):
"""Calculate the Jacobian of a binary operator."""
raise NotImplementedError
def _binary_evaluate(self, left, right):
"""Perform binary operation on nodes 'left' and 'right'."""
raise NotImplementedError(
f"{self.__class__} does not implement _binary_evaluate."
)
def _evaluates_on_edges(self, dimension: str) -> bool:
"""See :meth:`pybamm.Symbol._evaluates_on_edges()`."""
return self.left.evaluates_on_edges(dimension) or self.right.evaluates_on_edges(
dimension
)
def is_constant(self):
"""See :meth:`pybamm.Symbol.is_constant()`."""
return self.left.is_constant() and self.right.is_constant()
def _sympy_operator(self, left, right):
"""Apply appropriate SymPy operators."""
return self._binary_evaluate(left, right)
def to_equation(self):
"""Convert the node and its subtree into a SymPy equation."""
if self.print_name is not None:
return sympy.Symbol(self.print_name)
else:
child1, child2 = self.children
eq1 = child1.to_equation()
eq2 = child2.to_equation()
return self._sympy_operator(eq1, eq2)
def to_json(self):
"""
Method to serialise a BinaryOperator object into JSON.
"""
json_dict = {"name": self.name, "id": self.id, "domains": self.domains}
return json_dict
class Power(BinaryOperator):
"""
A node in the expression tree representing a `**` power operator.
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("**", left, right)
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
# apply chain rule and power rule
base, exponent = self.orphans
# derivative if variable is in the base
diff = exponent * (base ** (exponent - 1)) * base.diff(variable)
# derivative if variable is in the exponent (rare, check separately to avoid
# unecessarily big tree)
if any(variable == x for x in exponent.pre_order()):
diff += (base**exponent) * pybamm.log(base) * exponent.diff(variable)
return diff
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# apply chain rule and power rule
left, right = self.orphans
if right.evaluates_to_constant_number():
return (right * left ** (right - 1)) * left_jac
elif left.evaluates_to_constant_number():
return (left**right * pybamm.log(left)) * right_jac
else:
return (left ** (right - 1)) * (
right * left_jac + left * pybamm.log(left) * right_jac
)
def _binary_evaluate(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
# don't raise RuntimeWarning for NaNs
with np.errstate(invalid="ignore"):
return left**right
class Addition(BinaryOperator):
"""
A node in the expression tree representing an addition operator.
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("+", left, right)
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
return self.left.diff(variable) + self.right.diff(variable)
def _binary_jac(self, left_jac: ChildValue, right_jac: ChildValue):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
return left_jac + right_jac
def _binary_evaluate(self, left: ChildValue, right: ChildValue):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
return left + right
class Subtraction(BinaryOperator):
"""
A node in the expression tree representing a subtraction operator.
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("-", left, right)
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
return self.left.diff(variable) - self.right.diff(variable)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
return left_jac - right_jac
def _binary_evaluate(self, left: ChildValue, right: ChildValue):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
return left - right
class Multiplication(BinaryOperator):
"""
A node in the expression tree representing a multiplication operator
(Hadamard product). Overloads cases where the "*" operator would usually return a
matrix multiplication (e.g. scipy.sparse.coo.coo_matrix)
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("*", left, right)
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
# apply product rule
left, right = self.orphans
return left.diff(variable) * right + left * right.diff(variable)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# apply product rule
left, right = self.orphans
if left.evaluates_to_constant_number():
return left * right_jac
else:
return right * left_jac + left * right_jac
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
if issparse(left):
return csr_matrix(left.multiply(right))
elif issparse(right):
# Hadamard product is commutative, so we can switch right and left
return csr_matrix(right.multiply(left))
else:
return left * right
class MatrixMultiplication(BinaryOperator):
"""
A node in the expression tree representing a matrix multiplication operator.
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("@", left, right)
def diff(self, variable):
"""See :meth:`pybamm.Symbol.diff()`."""
# We shouldn't need this
raise NotImplementedError(
"diff not implemented for symbol of type 'MatrixMultiplication'"
)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# We only need the case where left is an array and right
# is a (slice of a) state vector, e.g. for discretised spatial
# operators of the form D @ u (also catch cases of (-D) @ u)
left, right = self.orphans
if isinstance(left, pybamm.Array) or (
isinstance(left, pybamm.Negate) and isinstance(left.child, pybamm.Array)
):
left = pybamm.Matrix(csr_matrix(left.evaluate()))
return left @ right_jac
else:
raise NotImplementedError(
f"""jac of 'MatrixMultiplication' is only
implemented for left of type 'pybamm.Array',
not {left.__class__}"""
)
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
return left @ right
def _sympy_operator(self, left, right):
"""Override :meth:`pybamm.BinaryOperator._sympy_operator`"""
left = sympy.Matrix(left)
right = sympy.Matrix(right)
return left * right
class Division(BinaryOperator):
"""
A node in the expression tree representing a division operator.
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("/", left, right)
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
# apply quotient rule
top, bottom = self.orphans
return (top.diff(variable) * bottom - top * bottom.diff(variable)) / bottom**2
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# apply quotient rule
left, right = self.orphans
if left.evaluates_to_constant_number():
return -left / right**2 * right_jac
else:
return (right * left_jac - left * right_jac) / right**2
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
if issparse(left):
return csr_matrix(left.multiply(1 / right))
else:
return left / right
class Inner(BinaryOperator):
"""
A node in the expression tree which represents the inner (or dot) product. This
operator should be used to take the inner product of two mathematical vectors
(as opposed to the computational vectors arrived at post-discretisation) of the
form v = v_x e_x + v_y e_y + v_z e_z where v_x, v_y, v_z are scalars
and e_x, e_y, e_z are x-y-z-directional unit vectors. For v and w mathematical
vectors, inner product returns v_x * w_x + v_y * w_y + v_z * w_z. In addition,
for some spatial discretisations mathematical vector quantities (such as
i = grad(phi) ) are evaluated on a different part of the grid to mathematical
scalars (e.g. for finite volume mathematical scalars are evaluated on the nodes but
mathematical vectors are evaluated on cell edges). Therefore, inner also transfers
the inner product of the vector onto the scalar part of the grid if required
by a particular discretisation.
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("inner product", left, right)
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
# apply product rule
left, right = self.orphans
return left.diff(variable) * right + left * right.diff(variable)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# apply product rule
left, right = self.orphans
if left.evaluates_to_constant_number():
return left * right_jac
elif right.evaluates_to_constant_number():
return right * left_jac
else:
return right * left_jac + left * right_jac
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
if issparse(left):
return left.multiply(right)
elif issparse(right):
# Hadamard product is commutative, so we can switch right and left
return right.multiply(left)
else:
return left * right
def _binary_new_copy(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator._binary_new_copy()`."""
return pybamm.inner(left, right)
def _evaluates_on_edges(self, dimension: str) -> bool:
"""See :meth:`pybamm.Symbol._evaluates_on_edges()`."""
return False
def inner(left_child, right_child):
"""Return inner product of two symbols."""
left, right = _preprocess_binary(left_child, right_child)
# simplify multiply by scalar zero, being careful about shape
if pybamm.is_scalar_zero(left):
return pybamm.zeros_like(right)
if pybamm.is_scalar_zero(right):
return pybamm.zeros_like(left)
# if one of the children is a zero matrix, we have to be careful about shapes
if pybamm.is_matrix_zero(left) or pybamm.is_matrix_zero(right):
return pybamm.zeros_like(pybamm.Inner(left, right))
# anything multiplied by a scalar one returns itself
if pybamm.is_scalar_one(left):
return right
if pybamm.is_scalar_one(right):
return left
return pybamm.simplify_if_constant(pybamm.Inner(left, right))
class Equality(BinaryOperator):
"""
A node in the expression tree representing an equality comparison between two
nodes. Returns 1 if the two nodes evaluate to the same thing and 0 otherwise.
"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("==", left, right)
def diff(self, variable):
"""See :meth:`pybamm.Symbol.diff()`."""
# Equality should always be multiplied by something else so hopefully don't
# need to worry about shape
return pybamm.Scalar(0)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# Equality should always be multiplied by something else so hopefully don't
# need to worry about shape
return pybamm.Scalar(0)
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
# numpy 1.25 deprecation warning: extract value from numpy arrays
if isinstance(right, np.ndarray):
return int(left == right.item())
else:
return int(left == right)
def _binary_new_copy(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""
Overwrites `pybamm.BinaryOperator._binary_new_copy()` to return a new instance of
`pybamm.Equality` rather than using `binary_evaluate` to return a value.
"""
return pybamm.Equality(left, right)
class _Heaviside(BinaryOperator):
"""
A node in the expression tree representing a heaviside step function.
This class is semi-private and should not be called directly, use `EqualHeaviside`
or `NotEqualHeaviside` instead, or `<` or `<=`.
Adding this operation to the rhs or algebraic equations in a model can often cause a
discontinuity in the solution. For the specific cases listed below, this will be
automatically handled by the solver. In the general case, you can explicitly tell
the solver of discontinuities by adding a :class:`Event` object with
:class:`EventType` DISCONTINUITY to the model's list of events.
In the case where the Heaviside function is of the form `pybamm.t < x`, `pybamm.t <=
x`, `x < pybamm.t`, or `x <= pybamm.t`, where `x` is any constant equation, this
DISCONTINUITY event will automatically be added by the solver.
"""
def __init__(
self,
name: str,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__(name, left, right)
def diff(self, variable):
"""See :meth:`pybamm.Symbol.diff()`."""
# Heaviside should always be multiplied by something else so hopefully don't
# need to worry about shape
return pybamm.Scalar(0)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# Heaviside should always be multiplied by something else so hopefully don't
# need to worry about shape
return pybamm.Scalar(0)
def _evaluate_for_shape(self):
"""
Returns an array of NaNs of the correct shape.
See :meth:`pybamm.Symbol.evaluate_for_shape()`.
"""
left = self.children[0].evaluate_for_shape()
right = self.children[1].evaluate_for_shape()
# _binary_evaluate will return an array of bools, so we multiply by NaN to get
# an array of NaNs
return self._binary_evaluate(left, right) * np.nan
class EqualHeaviside(_Heaviside):
"""A heaviside function with equality (return 1 when left = right)"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator.__init__()`."""
super().__init__("<=", left, right)
def __str__(self):
"""See :meth:`pybamm.Symbol.__str__()`."""
return f"{self.left!s} <= {self.right!s}"
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
# don't raise RuntimeWarning for NaNs
with np.errstate(invalid="ignore"):
return left <= right
class NotEqualHeaviside(_Heaviside):
"""A heaviside function without equality (return 0 when left = right)"""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
super().__init__("<", left, right)
def __str__(self):
"""See :meth:`pybamm.Symbol.__str__()`."""
return f"{self.left!s} < {self.right!s}"
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
# don't raise RuntimeWarning for NaNs
with np.errstate(invalid="ignore"):
return left < right
class Modulo(BinaryOperator):
"""Calculates the remainder of an integer division."""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
super().__init__("%", left, right)
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
# apply chain rule and power rule
left, right = self.orphans
# derivative if variable is in the base
diff = left.diff(variable)
# derivative if variable is in the right term (rare, check separately to avoid
# unecessarily big tree)
if any(variable == x for x in right.pre_order()):
diff += -pybamm.Floor(left / right) * right.diff(variable)
return diff
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
# apply chain rule and power rule
left, right = self.orphans
if right.evaluates_to_constant_number():
return left_jac
elif left.evaluates_to_constant_number():
return -right_jac * pybamm.Floor(left / right)
else:
return left_jac - right_jac * pybamm.Floor(left / right)
def __str__(self):
"""See :meth:`pybamm.Symbol.__str__()`."""
return f"{self.left!s} mod {self.right!s}"
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
return left % right
class Minimum(BinaryOperator):
"""Returns the smaller of two objects."""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
super().__init__("minimum", left, right)
def __str__(self):
"""See :meth:`pybamm.Symbol.__str__()`."""
return f"minimum({self.left!s}, {self.right!s})"
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
left, right = self.orphans
return (left <= right) * left.diff(variable) + (left > right) * right.diff(
variable
)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
left, right = self.orphans
return (left <= right) * left_jac + (left > right) * right_jac
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
# don't raise RuntimeWarning for NaNs
return np.minimum(left, right)
def _binary_new_copy(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator._binary_new_copy()`."""
return pybamm.minimum(left, right)
def _sympy_operator(self, left, right):
"""Override :meth:`pybamm.BinaryOperator._sympy_operator`"""
return sympy.Min(left, right)
class Maximum(BinaryOperator):
"""Returns the greater of two objects."""
def __init__(
self,
left: ChildSymbol,
right: ChildSymbol,
):
super().__init__("maximum", left, right)
def __str__(self):
"""See :meth:`pybamm.Symbol.__str__()`."""
return f"maximum({self.left!s}, {self.right!s})"
def _diff(self, variable: pybamm.Symbol):
"""See :meth:`pybamm.Symbol._diff()`."""
left, right = self.orphans
return (left >= right) * left.diff(variable) + (left < right) * right.diff(
variable
)
def _binary_jac(self, left_jac, right_jac):
"""See :meth:`pybamm.BinaryOperator._binary_jac()`."""
left, right = self.orphans
return (left >= right) * left_jac + (left < right) * right_jac
def _binary_evaluate(self, left, right):
"""See :meth:`pybamm.BinaryOperator._binary_evaluate()`."""
# don't raise RuntimeWarning for NaNs
return np.maximum(left, right)
def _binary_new_copy(
self,
left: ChildSymbol,
right: ChildSymbol,
):
"""See :meth:`pybamm.BinaryOperator._binary_new_copy()`."""
return pybamm.maximum(left, right)
def _sympy_operator(self, left, right):
"""Override :meth:`pybamm.BinaryOperator._sympy_operator`"""
return sympy.Max(left, right)
def _simplify_elementwise_binary_broadcasts(
left_child: ChildSymbol,
right_child: ChildSymbol,
) -> tuple[pybamm.Symbol, pybamm.Symbol]:
left, right = _preprocess_binary(left_child, right_child)
def unpack_broadcast_recursive(symbol: pybamm.Symbol) -> pybamm.Symbol:
if isinstance(symbol, pybamm.Broadcast):
if symbol.child.domain == []:
return symbol.orphans[0]
elif (
isinstance(symbol.child, pybamm.Broadcast)
and symbol.child.broadcasts_to_nodes
):
out = unpack_broadcast_recursive(symbol.orphans[0])
if out.domain == []:
return out
return symbol
# No need to broadcast if the other symbol already has the shape that is being
# broadcasted to
# Do this recursively
if left.domains == right.domains:
if isinstance(left, pybamm.Broadcast) and left.broadcasts_to_nodes:
left = unpack_broadcast_recursive(left)
elif isinstance(right, pybamm.Broadcast) and right.broadcasts_to_nodes:
right = unpack_broadcast_recursive(right)
return left, right
def _simplified_binary_broadcast_concatenation(
left: pybamm.Symbol,
right: pybamm.Symbol,
operator: Callable,
) -> pybamm.Broadcast | None:
"""
Check if there are concatenations or broadcasts that we can commute the operator
with
"""
# Broadcast commutes with elementwise operators
if isinstance(left, pybamm.Broadcast) and right.domain == []:
return left.create_copy([operator(left.orphans[0], right)])
elif isinstance(right, pybamm.Broadcast) and left.domain == []:
return right.create_copy([operator(left, right.orphans[0])])
# Concatenation commutes with elementwise operators
# If one of the sides is constant then commute concatenation with the operator
# Don't do this for ConcatenationVariable objects as these will
# be simplified differently later on
if isinstance(left, pybamm.Concatenation) and not isinstance(
left, pybamm.ConcatenationVariable
):
if right.evaluates_to_constant_number():
return left.create_copy([operator(child, right) for child in left.orphans])
elif isinstance(right, pybamm.Concatenation) and not isinstance(
right, pybamm.ConcatenationVariable
):
return left.create_copy(
[
operator(left_child, right_child)
for left_child, right_child in zip(left.orphans, right.orphans)
]
)
if isinstance(right, pybamm.Concatenation) and not isinstance(
right, pybamm.ConcatenationVariable
):
if left.evaluates_to_constant_number():
return right.create_copy([operator(left, child) for child in right.orphans])
return None
def simplified_power(
left: ChildSymbol,
right: ChildSymbol,
):
left, right = _simplify_elementwise_binary_broadcasts(left, right)
# Check for Concatenations and Broadcasts
out = _simplified_binary_broadcast_concatenation(left, right, simplified_power)
if out is not None:
return out
# anything to the power of zero is one
if pybamm.is_scalar_zero(right):
return pybamm.ones_like(left)
# zero to the power of anything is zero
if pybamm.is_scalar_zero(left):
return pybamm.Scalar(0)
# anything to the power of one is itself
if pybamm.is_scalar_one(right):
return left
if isinstance(left, Multiplication):
# Simplify (a * b) ** c to (a ** c) * (b ** c)
# if (a ** c) is constant or (b ** c) is constant
if left.left.is_constant() or left.right.is_constant():
l_left, l_right = left.orphans
new_left = l_left**right
new_right = l_right**right
if new_left.is_constant() or new_right.is_constant():
return new_left * new_right
elif isinstance(left, Division):
# Simplify (a / b) ** c to (a ** c) / (b ** c)
# if (a ** c) is constant or (b ** c) is constant
if left.left.is_constant() or left.right.is_constant():
l_left, l_right = left.orphans
new_left = l_left**right
new_right = l_right**right
if new_left.is_constant() or new_right.is_constant():
return new_left / new_right
return pybamm.simplify_if_constant(pybamm.Power(left, right))
def add(left: ChildSymbol, right: ChildSymbol):
"""
Note
----
We check for scalars first, then matrices. This is because
(Zero Matrix) + (Zero Scalar)
should return (Zero Matrix), not (Zero Scalar).
"""
left, right = _simplify_elementwise_binary_broadcasts(left, right)
# Move constant to always be on the left
if right.is_constant() and not left.is_constant():
left, right = right, left
# Check for Concatenations and Broadcasts
out = _simplified_binary_broadcast_concatenation(left, right, add)
if out is not None:
return out
# anything added by a scalar zero returns the other child
if pybamm.is_scalar_zero(left):
return right
# Check matrices after checking scalars
if pybamm.is_matrix_zero(left):
if right.evaluates_to_number():
return right * pybamm.ones_like(left)
# If left object is zero and has size smaller than or equal to right object in
# all dimensions, we can safely return the right object. For example, adding a
# zero vector a matrix, we can just return the matrix.
# When checking evaluation on edges, check dimensions of left object only
elif all(
left_dim_size <= right_dim_size
for left_dim_size, right_dim_size in zip(
left.shape_for_testing, right.shape_for_testing
)
) and all(
left.evaluates_on_edges(dim) == right.evaluates_on_edges(dim)
for dim in left.domains.keys()
):
return right
# Return constant if both sides are constant
if left.is_constant() and right.is_constant():
return pybamm.simplify_if_constant(Addition(left, right))
# Simplify A @ c + B @ c to (A + B) @ c if (A + B) is constant
# This is a common construction that appears from discretisation of spatial
# operators
elif (
isinstance(left, MatrixMultiplication)
and isinstance(right, MatrixMultiplication)
and left.right == right.right
):
l_left, l_right = left.orphans
r_left = right.orphans[0]
new_left = l_left + r_left
if new_left.is_constant():
new_sum = new_left @ l_right
new_sum.copy_domains(Addition(left, right))
return new_sum
# Turn a + (-b) into a - b
if isinstance(right, pybamm.Negate):
return left - right.orphans[0]
# Turn (-a) + b into b - a
# check for is_constant() to avoid infinite recursion
if isinstance(left, pybamm.Negate) and not left.is_constant():
return right - left.orphans[0]
if left.is_constant():
if isinstance(right, (Addition, Subtraction)) and right.left.is_constant():
# Simplify a + (b +- c) to (a + b) +- c if (a + b) is constant
r_left, r_right = right.orphans
return right.create_copy([left + r_left, r_right])
if isinstance(left, Subtraction):
if right == left.right:
# Simplify (a - b) + b to a
# Make sure shape is preserved
return left.left * pybamm.ones_like(left.right)
if isinstance(right, Subtraction):
if left == right.right:
# Simplify a + (b - a) to b
# Make sure shape is preserved