forked from CURENT/andes
/
discrete.py
1574 lines (1207 loc) 路 50.4 KB
/
discrete.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
# [ANDES] (C)2015-2021 Hantao Cui
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# File name: discrete.py
import logging
from typing import List, Tuple, Union
import numpy as np
from andes.core.common import dummify
from andes.utils.func import interp_n2
from andes.utils.tab import Tab
logger = logging.getLogger(__name__)
class Discrete:
"""
Base discrete class.
Discrete classes export flag arrays (usually boolean) .
"""
def __init__(self, name=None, tex_name=None, info=None, no_warn=False,
min_iter=2, err_tol=1e-2,
):
self.name = name
self.tex_name = tex_name
self.info = info
self.owner = None
if not hasattr(self, 'export_flags'):
self.export_flags = []
if not hasattr(self, 'export_flags_tex'):
self.export_flags_tex = []
self.input_list = [] # references to input variables
self.param_list = [] # references to parameters
self.x_set = list()
self.y_set = list() # NOT being used
self.warn_flags = [] # warn if flags in `warn_flags` not initialized to zero
self.no_warn = no_warn
# default minimum iteration number and error tolerance to allow checking
# To enable `min_iter` and `err_tol`, a `Discrete` subclass needs to call
# `check_iter_err()` manually in `check_var()` and/or `check_eq()`.
self.min_iter = min_iter
self.err_tol = err_tol
self.has_check_var = False # if subclass implements `check_var()`
self.has_check_eq = False # if subclass implements `check_eq()`
def check_var(self, *args, **kwargs):
"""
This function is called in ``l_update_var`` before evaluating equations.
It should update internal flags only.
Parameters
----------
adjust_upper : bool
True to adjust the upper limit to the value of the variable.
Supported by limiters.
adjust_lower : bool
True to adjust the lower limit to the value of the variable.
Supported by limiters.
"""
pass
def check_eq(self, **kwargs):
"""
This function is called in ``l_check_eq`` after updating equations.
It updates internal flags, set differential equations, and record pegged variables.
"""
pass
def get_names(self):
"""
Available symbols from this class
Returns
-------
"""
return [f'{self.name}_{flag}' for flag in self.export_flags]
def get_tex_names(self):
"""
Return tex_names of exported flags.
TODO: Fix the bug described in the warning below.
Warnings
--------
If underscore `_` appears in both flag tex_name and `self.tex_name` (for example, when this discrete is
within a block), the exported tex_name will become invalid for SymPy.
Variable name substitution will fail.
Returns
-------
list
A list of tex_names for all exported flags.
"""
return [rf'{flag_tex}^{self.tex_name}' for flag_tex in self.export_flags_tex]
def get_values(self):
return [self.__dict__[flag] for flag in self.export_flags]
@property
def class_name(self):
return self.__class__.__name__
def list2array(self, n):
"""
Allocate memory for the discrete flags specified in `self.export_flags`.
Parameters
----------
n : int
Number of elements in the array. Provided by the calling function.
"""
for flag in self.export_flags:
self.__dict__[flag] = self.__dict__[flag] * np.ones(n, dtype=float)
def warn_init_limit(self):
"""
Warn if associated variables are initialized at limits.
"""
if self.no_warn:
return
for f, limit in self.warn_flags:
if f not in self.export_flags:
logger.error('warn_flags contain unknown flag %s', f)
continue
mask = np.ones(self.owner.n, dtype=bool)
if limit == 'upper':
mask = self.mask_upper
elif limit == 'lower':
mask = self.mask_lower
else:
logger.debug('Unknown limit name <%s>', limit)
# process online devices only
flag_vals = np.logical_and(self.__dict__[f], self.owner.u.v)
# ignore limits that has been adjusted
flag_vals = np.logical_and(flag_vals, np.logical_not(mask))
pos = np.argwhere(np.not_equal(flag_vals, 0)).ravel()
if len(pos) == 0:
continue
# convert limie values to arrays
if isinstance(self.__dict__[limit].v, np.ndarray):
lim_value = self.__dict__[limit].v
else:
lim_value = self.__dict__[limit].v * np.ones(self.owner.n)
at_limit_pos = list()
out_limit_pos = list()
for item in pos:
if np.isclose(lim_value[item], self.u.v[item]):
at_limit_pos.append(item)
else:
out_limit_pos.append(item)
if len(out_limit_pos) > 0:
# warn out of limits
err_msg = f'{self.owner.class_name}.{self.name} out of limits <{self.__dict__[limit].name}>'
err_data = {'idx': [self.owner.idx.v[i] for i in out_limit_pos],
'Flag': [f] * len(out_limit_pos),
'Input Value': self.u.v[out_limit_pos],
'Limit': lim_value[out_limit_pos]
}
tab = Tab(title=err_msg,
header=err_data.keys(),
data=list(map(list, zip(*err_data.values()))))
logger.warning(tab.draw())
if len(at_limit_pos) > 0:
# warn at limits
err_msg = f'{self.owner.class_name}.{self.name} at limits <{self.__dict__[limit].name}>'
err_data = {'idx': [self.owner.idx.v[i] for i in at_limit_pos],
'Flag': [f] * len(at_limit_pos),
'Input Value': self.u.v[at_limit_pos],
'Limit': lim_value[at_limit_pos]
}
tab = Tab(title=err_msg,
header=err_data.keys(),
data=list(map(list, zip(*err_data.values()))))
logger.debug(tab.draw())
def check_iter_err(self, niter=None, err=None):
"""
Check if the minimum iteration or maximum error is reached
so that this discrete block should be enabled.
Only when both `niter` and `err` are given, (niter < min_iter)
, and (err > err_tol) it will return False.
This logic will start checking the discrete states if called
from an external solver that does not feed `niter` or `err`
at each step.
Returns
-------
bool
True if it should be enabled, False otherwise
"""
if (niter is not None) and (niter < self.min_iter) and \
(err is not None) and (err > self.err_tol):
return False
return True
def __repr__(self):
return f'{self.__class__.__name__}: {self.owner.__class__.__name__}.{self.name}'
class LessThan(Discrete):
"""
Less than (<) comparison function that tests if ``u < bound``.
Exports two flags: z1 and z0.
For elements satisfying the less-than condition, the corresponding z1 = 1.
z0 is the element-wise negation of z1.
Notes
-----
The default z0 and z1, if not enabled, can be set through the constructor.
By default, the model will not adjust the limit.
"""
def __init__(self, u, bound, equal=False, enable=True, name=None, tex_name=None,
info: str = None, cache: bool = False,
z0=0, z1=1):
super().__init__(name=name, tex_name=tex_name, info=info)
self.u = u
self.bound = dummify(bound)
self.equal: bool = equal
self.enable: bool = enable
self.cache: bool = cache
self._eval: bool = False # if has been eval'ed and cached
self.z0 = np.array([z0]) # negation of `self.z1`
self.z1 = np.array([z1]) # if the less-than condition (u < bound) is True
self.export_flags = ['z0', 'z1']
self.export_flags_tex = ['z_0', 'z_1']
self.input_list.extend([self.u])
self.param_list.extend([self.bound])
self.has_check_var = True
def check_var(self, *args, **kwargs):
"""
If enabled, set flags based on inputs. Use cached values if enabled.
"""
if not self.enable:
return
if self.cache and self._eval:
return
if not self.equal:
self.z1[:] = np.less(self.u.v, self.bound.v)
else:
self.z1[:] = np.less_equal(self.u.v, self.bound.v)
self.z0[:] = np.logical_not(self.z1)
self._eval = True
class IsEqual(Discrete):
"""
Is equal (==) comparison function to test if ``u == bound``.
Exports one flag: z1.
For elements satisfying the equality condition, the corresponding z1 = 1.
Notes
-----
The default z1 when not enabled can be set through the constructor.
By default, the model will not adjust the limit.
"""
def __init__(self, u, bound, enable=True, name=None, tex_name=None,
info: str = None, cache: bool = False, z1=1):
super().__init__(name=name, tex_name=tex_name, info=info)
self.u = u
self.bound = dummify(bound)
self.enable: bool = enable
self.cache: bool = cache
self._eval: bool = False
self.z1 = np.array([z1])
self.export_flags = ['z1']
self.export_flags_tex = ['z_1']
self.input_list.extend([self.u])
self.param_list.extend([self.bound])
self.has_check_var = True
def check_var(self, *args, **kwargs):
"""
If enabled, set flags based on inputs. Use cached values if enabled.
"""
if not self.enable:
return
if self.cache and self._eval:
return
self.z1[:] = np.equal(self.u.v, self.bound.v)
self._eval = True
class Limiter(Discrete):
"""
Base limiter class.
This class compares values and sets limit values. Exported flags are `zi`, `zl` and `zu`.
Notes
-----
If not enabled, the default flags are ``zu = zl = 0``, ``zi = 1``.
Parameters
----------
u : BaseVar
Input Variable instance
lower : BaseParam
Parameter instance for the lower limit
upper : BaseParam
Parameter instance for the upper limit
no_lower : bool
True to only use the upper limit
no_upper : bool
True to only use the lower limit
sign_lower: 1 or -1
Sign to be multiplied to the lower limit
sign_upper: bool
Sign to be multiplied to the upper limit
equal : bool
True to include equal signs in comparison (>= or <=).
no_warn : bool
Disable initial limit warnings
zu : 0 or 1
Default value for `zu` if not enabled
zl : 0 or 1
Default value for `zl` if not enabled
zi : 0 or 1
Default value for `zi` if not enabled
Attributes
----------
zl : array-like
Flags of elements violating the lower limit;
A array of zeros and/or ones.
zi : array-like
Flags for within the limits
zu : array-like
Flags for violating the upper limit
"""
def __init__(self, u, lower, upper, enable=True,
name: str = None, tex_name: str = None, info: str = None,
min_iter: int = 2, err_tol: float = 0.01,
allow_adjust: bool = True,
no_lower=False, no_upper=False, sign_lower=1, sign_upper=1,
equal=True, no_warn=False,
zu=0.0, zl=0.0, zi=1.0):
Discrete.__init__(self, name=name, tex_name=tex_name, info=info,
min_iter=min_iter, err_tol=err_tol)
self.u = u
self.lower = dummify(lower)
self.upper = dummify(upper)
self.enable = enable
self.no_lower = no_lower
self.no_upper = no_upper
self.allow_adjust = allow_adjust
if sign_lower not in (1, -1):
raise ValueError("sign_lower must be 1 or -1, got %s" % sign_lower)
if sign_upper not in (1, -1):
raise ValueError("sign_upper must be 1 or -1, got %s" % sign_upper)
self.sign_lower = dummify(sign_lower)
self.sign_upper = dummify(sign_upper)
self.equal = equal
self.no_warn = no_warn
self.zu = np.array([zu])
self.zl = np.array([zl])
self.zi = np.array([zi])
self.mask_upper = None
self.mask_lower = None
self.has_check_var = True
self.export_flags.append('zi')
self.export_flags_tex.append('z_i')
self.input_list.extend([self.u])
self.param_list.extend([self.lower, self.upper])
if not self.no_lower:
self.export_flags.append('zl')
self.export_flags_tex.append('z_l')
self.warn_flags.append(('zl', 'lower'))
if not self.no_upper:
self.export_flags.append('zu')
self.export_flags_tex.append('z_u')
self.warn_flags.append(('zu', 'upper'))
def check_var(self,
allow_adjust=True, # allow flag from model
adjust_lower=False,
adjust_upper=False,
*args, **kwargs):
"""
Check the input variable and set flags.
"""
if not self.enable:
return
if not self.no_upper:
upper_v = -self.upper.v if self.sign_upper.v == -1 else self.upper.v
# FIXME: adjust will not be successful when sign is -1
if self.allow_adjust and allow_adjust and adjust_upper:
self.do_adjust_upper(self.u.v, upper_v, allow_adjust, adjust_upper)
if self.equal:
self.zu[:] = np.greater_equal(self.u.v, upper_v)
else:
self.zu[:] = np.greater(self.u.v, upper_v)
if not self.no_lower:
lower_v = -self.lower.v if self.sign_lower.v == -1 else self.lower.v
# FIXME: adjust will not be successful when sign is -1
if self.allow_adjust and allow_adjust and adjust_lower:
self.do_adjust_lower(self.u.v, lower_v, allow_adjust, adjust_lower)
if self.equal:
self.zl[:] = np.less_equal(self.u.v, lower_v)
else:
self.zl[:] = np.less(self.u.v, lower_v)
self.zi[:] = np.logical_not(np.logical_or(self.zu, self.zl))
def do_adjust_lower(self, val, lower, allow_adjust=True, adjust_lower=False):
"""
Adjust the lower limit.
Notes
-----
This method is only executed if `allow_adjust` is True
and `adjust_lower` is True.
"""
if allow_adjust:
mask = (val < lower)
if sum(mask) == 0:
return
if adjust_lower:
self._show_adjust(val, lower, mask, self.lower.name, adjusted=True)
lower[mask] = val[mask]
self.mask_lower = mask # store after adjusting
else:
self._show_adjust(val, lower, mask, self.lower.name, adjusted=False)
def _show_adjust(self, val, old_limit, mask, limit_name, adjusted=True):
"""
Helper function to show a table of the adjusted limits.
"""
idxes = np.array(self.owner.idx.v)[mask]
adjust_or_not = 'adjusted' if adjusted else 'unadjusted'
tab = Tab(title=f"{self.owner.class_name}.{self.name}: {adjust_or_not} limit <{limit_name}>",
header=['Idx', 'Input', 'Old Limit'],
data=[*zip(idxes, val[mask], old_limit[mask])],
)
if adjusted:
logger.info(tab.draw())
else:
logger.warning(tab.draw())
def do_adjust_upper(self, val, upper, allow_adjust=True, adjust_upper=False):
"""
Adjust the upper limit.
Notes
-----
This method is only executed if `allow_adjust` is True
and `adjust_upper` is True.
"""
if allow_adjust:
mask = (val > upper)
if sum(mask) == 0:
return
if adjust_upper:
self._show_adjust(val, upper, mask, self.upper.name, adjusted=True)
upper[mask] = val[mask]
self.mask_upper = mask
else:
self._show_adjust(val, upper, mask, self.lower.name, adjusted=False)
class SortedLimiter(Limiter):
"""
A limiter that sorts inputs based on the absolute or
relative amount of limit violations.
Parameters
----------
n_select : int
the number of violations to be flagged,
for each of over-limit and under-limit cases.
If `n_select` == 1, at most one over-limit
and one under-limit inputs will be flagged.
If `n_select` is zero, heuristics will be used.
abs_violation : bool
True to use the absolute violation.
False if the relative violation
abs(violation/limit) is used for sorting.
Since most variables are in per unit,
absolute violation is recommended.
"""
def __init__(self, u, lower, upper, n_select: int = 5,
name=None, tex_name=None, enable=True, abs_violation=True,
min_iter: int = 2, err_tol: float = 0.01,
allow_adjust: bool = True,
zu=0.0, zl=0.0, zi=1.0, ql=0.0, qu=0.0,
):
super().__init__(u, lower, upper,
enable=enable, name=name, tex_name=tex_name,
min_iter=min_iter, err_tol=err_tol,
allow_adjust=allow_adjust,
zu=zu, zl=zl, zi=zi,
)
self.n_select = int(n_select)
self.auto = True if self.n_select == 0 else False
self.abs_violation = abs_violation
self.ql = np.array([ql])
self.qu = np.array([qu])
# count of ones in `ql` and `qu`
self.nql = 0
self.nqu = 0
# smallest and largest `n_select`
self.min_sel = 2
self.max_sel = 50
# store the lower and upper limit values with zeros converted to a small number
self.lower_denom = None
self.upper_denom = None
self.export_flags.extend(['ql', 'qu'])
self.export_flags_tex.extend(['q_l', 'q_u'])
def list2array(self, n):
"""
Initialize maximum and minimum `n_select` based on input size.
"""
super().list2array(n)
if self.auto:
self.min_sel = max(2, int(n / 10))
self.max_sel = max(2, int(n / 2))
def check_var(self, *args, niter=None, err=None, **kwargs):
"""
Check for the largest and smallest `n_select` elements.
"""
if not self.enable:
return
if not self.check_iter_err(niter=niter, err=err):
return
super().check_var()
# first run - calculate the denominators if using relative violation
if not self.abs_violation:
if self.lower_denom is None:
self.lower_denom = np.array(self.lower.v)
self.lower_denom[self.lower_denom == 0] = 1e-6
if self.upper_denom is None:
self.upper_denom = np.array(self.upper.v)
self.upper_denom[self.upper_denom == 0] = 1e-6
# calculate violations - abs or relative
if self.abs_violation:
lower_vio = self.u.v - self.lower.v
upper_vio = self.upper.v - self.u.v
else:
lower_vio = np.abs((self.u.v - self.lower.v) / self.lower_denom)
upper_vio = np.abs((self.upper.v - self.u.v) / self.upper_denom)
# count the number of inputs flagged
if self.auto:
self.calc_select()
# sort in both ascending and descending orders
asc = np.argsort(lower_vio)
desc = np.argsort(upper_vio)
top_n = asc[:self.n_select]
bottom_n = desc[:self.n_select]
# `reset_out` is used to flag the
reset_out = np.zeros_like(self.u.v)
reset_out[top_n] = 1
reset_out[bottom_n] = 1
# set new flags
self.zl[:] = np.logical_or(np.logical_and(reset_out, self.zl),
self.ql)
self.zu[:] = np.logical_or(np.logical_and(reset_out, self.zu),
self.qu)
self.zi[:] = 1 - np.logical_or(self.zl, self.zu)
self.ql[:] = self.zl
self.qu[:] = self.zu
# compute the number of updated flags
ql1 = np.count_nonzero(self.ql)
qu1 = np.count_nonzero(self.qu)
dqu = qu1 - self.nqu
dql = ql1 - self.nql
if dqu > 0 or dql > 0:
logger.debug("SortedLimiter: flagged %s upper and %s lower limit violations",
dqu, dql)
self.nqu = qu1
self.nql = ql1
def calc_select(self):
"""
Set `n_select` automatically.
"""
ret = int((np.count_nonzero(self.zl) + np.count_nonzero(self.zu)) / 2) + 1
if ret > self.max_sel:
ret = self.max_sel
elif ret < self.min_sel:
ret = self.min_sel
self.n_select = ret
class HardLimiter(Limiter):
"""
Hard limiter for algebraic or differential variable. This class is an alias of `Limiter`.
"""
pass
class AntiWindup(Limiter):
"""
Anti-windup limiter.
Anti-windup limiter prevents the wind-up effect of a differential variable.
The derivative of the differential variable is reset if it continues to increase in the same direction
after exceeding the limits.
During the derivative return, the limiter will be inactive ::
if x > xmax and x dot > 0: x = xmax and x dot = 0
if x < xmin and x dot < 0: x = xmin and x dot = 0
This class takes one more optional parameter for specifying the equation.
Parameters
----------
state : State, ExtState
A State (or ExtState) whose equation value will be checked and, when condition satisfies, will be reset
by the anti-windup-limiter.
"""
def __init__(self, u, lower, upper, enable=True, no_warn=False,
no_lower=False, no_upper=False, sign_lower=1, sign_upper=1,
name=None, tex_name=None, info=None, state=None,
allow_adjust: bool = True,):
super().__init__(u, lower, upper, enable=enable, no_warn=no_warn,
no_lower=no_lower, no_upper=no_upper,
sign_lower=sign_lower, sign_upper=sign_upper,
name=name, tex_name=tex_name, info=info,
allow_adjust=allow_adjust,)
self.state = state if state else u
self.has_check_var = False
self.has_check_eq = True
self.no_warn = no_warn
def check_var(self, *args, **kwargs):
"""
This function is empty. Defers `check_var` to `check_eq`.
"""
pass
def check_eq(self,
allow_adjust=True,
adjust_lower=False,
adjust_upper=False,
**kwargs):
"""
Check the variables and equations and set the limiter flags.
Reset differential equation values based on limiter flags.
Notes
-----
The current implementation reallocates memory for `self.x_set` in each call.
Consider improving for speed. (TODO)
"""
if not self.no_upper:
upper_v = -self.upper.v if self.sign_upper.v == -1 else self.upper.v
if self.allow_adjust and allow_adjust and adjust_upper:
self.do_adjust_upper(self.u.v, upper_v,
allow_adjust=allow_adjust,
adjust_upper=adjust_upper)
self.zu[:] = np.logical_and(np.greater_equal(self.u.v, upper_v),
np.greater_equal(self.state.e, 0))
if not self.no_lower:
lower_v = -self.lower.v if self.sign_lower.v == -1 else self.lower.v
if self.allow_adjust and allow_adjust and adjust_lower:
self.do_adjust_lower(self.u.v, lower_v,
allow_adjust=allow_adjust,
adjust_lower=adjust_lower)
self.zl[:] = np.logical_and(np.less_equal(self.u.v, lower_v),
np.less_equal(self.state.e, 0))
self.zi[:] = np.logical_not(np.logical_or(self.zu, self.zl))
# must flush the `x_set` list at the beginning
self.x_set = list()
if not np.all(self.zi):
idx = np.where(self.zi == 0)
self.state.e[:] = self.state.e * self.zi
self.state.v[:] = self.state.v * self.zi
if not self.no_upper:
self.state.v[:] += upper_v * self.zu
if not self.no_lower:
self.state.v[:] += lower_v * self.zl
self.x_set.append((self.state.a[idx], self.state.v[idx], 0)) # (address, var. values, eqn. values)
# logger.debug(f'AntiWindup for states {self.state.a[idx]}')
# Very important note:
# The set equation values and variable values are collected by `System.fg_to_dae`:
# - Equation values is collected by `System._e_to_dae`,
# - Variable values are collected at the end of `System.fg_to_dae`.
# Also, equation values are processed in `TDS` for resetting the `q`.
class RateLimiter(Discrete):
"""
Rate limiter for a differential variable.
RateLimiter does not export any variable. It directly modifies the differential equation value.
Notes
-----
RateLimiter inherits from Discrete to avoid internal naming conflicts with `Limiter`.
Warnings
--------
RateLimiter cannot be applied to a state variable that already undergoes an AntiWindup limiter.
Use `AntiWindupRate` for a rate-limited anti-windup limiter.
"""
def __init__(self, u, lower, upper, enable=True,
no_lower=False, no_upper=False, lower_cond=1, upper_cond=1,
name=None, tex_name=None, info=None):
Discrete.__init__(self, name=name, tex_name=tex_name, info=info)
self.u = u
self.rate_lower = dummify(lower)
self.rate_upper = dummify(upper)
# `lower_cond` and `upper_cond` are arrays of 0/1 indicating whether
# the corresponding rate limit should be *enabled*.
# 0 - disabled, 1 - enabled.
# If is `None`, all rate limiters will be enabled.
self.rate_lower_cond = dummify(lower_cond)
self.rate_upper_cond = dummify(upper_cond)
self.mask_lower = None
self.mask_upper = None
self.rate_no_lower = no_lower
self.rate_no_upper = no_upper
self.enable = enable
self.zur = np.array([0])
self.zlr = np.array([0])
self.has_check_eq = True
# Note: save ops by not calculating `zir`
# self.zir = np.array([1])
# self.export_flags = ['zir']
# self.export_flags_tex = ['z_{ir}']
if not self.rate_no_lower:
self.export_flags.append('zlr')
self.export_flags_tex.append('z_{lr}')
self.warn_flags.append(('zlr', 'lower'))
if not self.rate_no_upper:
self.export_flags.append('zur')
self.export_flags_tex.append('z_{ur}')
self.warn_flags.append(('zur', 'upper'))
self.param_list.extend([self.rate_lower, self.rate_upper,
self.rate_lower_cond, self.rate_upper_cond])
def check_eq(self, **kwargs):
if not self.enable:
return
if not self.rate_no_lower:
self.zlr[:] = np.less(self.u.e, self.rate_lower.v) # 1 if at the lower rate limit
if self.rate_lower_cond is not None:
self.zlr[:] = self.zlr * self.rate_lower_cond.v # 1 if both at the lower rate limit and enabled
# for where `zlr == 1`, set the equation value to the lower limit
self.u.e[np.where(self.zlr)] = self.rate_lower.v[np.where(self.zlr)]
if not self.rate_no_upper:
self.zur[:] = np.greater(self.u.e, self.rate_upper.v)
if self.rate_upper_cond is not None:
self.zur[:] = self.zur * self.rate_upper_cond.v
self.u.e[np.where(self.zur)] = self.rate_upper.v[np.where(self.zur)]
class AntiWindupRate(AntiWindup, RateLimiter):
"""
Anti-windup limiter with rate limits
"""
def __init__(self, u, lower, upper, rate_lower, rate_upper,
no_lower=False, no_upper=False, rate_no_lower=False, rate_no_upper=False,
rate_lower_cond=None, rate_upper_cond=None,
enable=True, name=None, tex_name=None, info=None,
allow_adjust: bool = True,):
RateLimiter.__init__(self, u, lower=rate_lower, upper=rate_upper, enable=enable,
no_lower=rate_no_lower, no_upper=rate_no_upper,
lower_cond=rate_lower_cond, upper_cond=rate_upper_cond,
)
AntiWindup.__init__(self, u, lower=lower, upper=upper, enable=enable,
no_lower=no_lower, no_upper=no_upper,
name=name, tex_name=tex_name, info=info,
allow_adjust=allow_adjust,
)
def check_eq(self, **kwargs):
RateLimiter.check_eq(self, **kwargs)
AntiWindup.check_eq(self, **kwargs)
class Selector(Discrete):
"""
Selection between two variables using the provided reduce function.
The reduce function should take the given number of arguments. An example function is `np.maximum.reduce`
which can be used to select the maximum.
Names are in `s0`, `s1`.
Warnings
--------
A potential bug when more than two inputs are provided, and values in different inputs are equal.
Only two inputs are allowed.
.. deprecated:: 1.5.9
Use of this class for comparison-based output is discouraged.
Instead, use `LessThan` and `Limiter` to construct piesewise equations.
See the new implementation of ``HVGate`` and ``LVGate``.
Examples
--------
Example 1: select the largest value between `v0` and `v1` and put it into vmax.
After the definitions of `v0` and `v1`, define the algebraic variable `vmax` for the largest value,
and a selector `vs` ::
self.vmax = Algeb(v_str='maximum(v0, v1)',
tex_name='v_{max}',
e_str='vs_s0 * v0 + vs_s1 * v1 - vmax')
self.vs = Selector(self.v0, self.v1, fun=np.maximum.reduce)
The initial value of `vmax` is calculated by ``maximum(v0, v1)``, which is the element-wise maximum in SymPy
and will be generated into ``np.maximum(v0, v1)``. The equation of `vmax` is to select the values based on
`vs_s0` and `vs_s1`.
Notes
-----
A common pitfall is the 0-based indexing in the Selector flags. Note that exported flags start from 0. Namely,
`s0` corresponds to the first variable provided for the Selector constructor.
See Also
--------
numpy.ufunc.reduce : NumPy reduce function
"""
def __init__(self, *args, fun, tex_name=None, info=None):
super().__init__(tex_name=tex_name, info=info)
# TODO: only allow two inputs
self.input_vars = args
self.fun = fun
self.n = len(args)
self._inputs = None
self._outputs = None
# TODO: allow custom initial value
for i in range(len(self.input_vars)):
self.__dict__[f's{i}'] = np.array([0])
self.export_flags = [f's{i}' for i in range(len(self.input_vars))]
self.export_flags_tex = [f's_{i}' for i in range(len(self.input_vars))]
self.input_list = args
self.has_check_var = True
def check_var(self, *args, **kwargs):
"""
Set the i-th variable's flags to 1 if the return of the reduce function equals the i-th input.
"""
if self._inputs is None:
# input is only evaluated at the first time due to memory stability
self._inputs = [self.input_vars[i].v for i in range(self.n)]
if self._outputs is None:
self._outputs = self.fun(self._inputs)
else:
self._outputs[:] = self.fun(self._inputs)
for i in range(self.n):
self.__dict__[f's{i}'][:] = np.equal(self._inputs[i], self._outputs)
class Switcher(Discrete):
"""