/
system.py
2050 lines (1666 loc) 路 71 KB
/
system.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
"""
System class for power system data and methods
"""
# [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: system.py
import configparser
import importlib
import logging
import os
import sys
import inspect
import dill
from collections import OrderedDict
from typing import Dict, Tuple, Union, Optional
import andes.io
from andes.models import file_classes
from andes.models.group import GroupBase
from andes.variables import FileMan, DAE
from andes.routines import all_routines
from andes.utils.tab import Tab
from andes.utils.misc import elapsed
from andes.utils.paths import confirm_overwrite
from andes.utils.paths import get_config_path, andes_root
from andes.utils.paths import get_pycode_path, get_pkl_path
from andes.core import Config, Model, AntiWindup
from andes.io.streaming import Streaming
from andes.shared import np, jac_names, dilled_vars, IP_ADD
from andes.shared import matrix, spmatrix, sparse, Pool
logger = logging.getLogger(__name__)
dill.settings['recurse'] = True
class ExistingModels:
"""
Storage class for existing models
"""
def __init__(self):
self.pflow = OrderedDict()
self.tds = OrderedDict() # if a model needs to be initialized before TDS, set `flags.tds = True`
self.pflow_tds = OrderedDict()
class System:
"""
System contains models and routines for modeling and simulation.
System contains a several special `OrderedDict` member attributes for housekeeping.
These attributes include `models`, `groups`, `routines` and `calls` for loaded models, groups,
analysis routines, and generated numerical function calls, respectively.
Notes
-----
System stores model and routine instances as attributes.
Model and routine attribute names are the same as their class names.
For example, `Bus` is stored at ``system.Bus``, the power flow calculation routine is at
``system.PFlow``, and the numerical DAE instance is at ``system.dae``. See attributes for the list of
attributes.
Attributes
----------
dae : andes.variables.dae.DAE
Numerical DAE storage
files : andes.variables.fileman.FileMan
File path storage
config : andes.core.Config
System config storage
models : OrderedDict
model name and instance pairs
groups : OrderedDict
group name and instance pairs
routines : OrderedDict
routine name and instance pairs
"""
def __init__(self,
case: Optional[str] = None,
name: Optional[str] = None,
config: Optional[Dict] = None,
config_path: Optional[str] = None,
default_config: Optional[bool] = False,
options: Optional[Dict] = None,
**kwargs
):
self.name = name
self.options = {}
if options is not None:
self.options.update(options)
if kwargs:
self.options.update(kwargs)
self.calls = OrderedDict() # a dictionary with model names (keys) and their ``calls`` instance
self.models = OrderedDict() # model names and instances
self.groups = OrderedDict() # group names and instances
self.routines = OrderedDict() # routine names and instances
self.switch_times = np.array([]) # an array of ordered event switching times
self.switch_dict = OrderedDict() # time: OrderedDict of associated models
self.with_calls = False # if generated function calls have been loaded
self.n_switches = 0 # number of elements in `self.switch_times`
self.exit_code = 0 # command-line exit code, 0 - normal, others - error.
# get and load default config file
self._config_path = get_config_path()
if config_path is not None:
self._config_path = config_path
if default_config is True:
self._config_path = None
self._config_object = self.load_config(self._config_path)
self.config = Config(self.__class__.__name__, dct=config)
self.config.load(self._config_object)
# custom configuration for system goes after this line
self.config.add(OrderedDict((('freq', 60),
('mva', 100),
('ipadd', 1),
('seed', 'None'),
('diag_eps', 1e-8),
('warn_limits', 1),
('warn_abnormal', 1),
('dime_enabled', 0),
('dime_name', 'andes'),
('dime_address', 'ipc:///tmp/dime2'),
('numba', 0),
('numba_parallel', 0),
('numba_cache', 1),
('numba_nopython', 0),
('yapf_pycode', 0),
('np_divide', 'warn'),
('np_invalid', 'warn'),
('pickle_path', get_pkl_path())
)))
self.config.add_extra("_help",
freq='base frequency [Hz]',
mva='system base MVA',
ipadd='use spmatrix.ipadd if available',
seed='seed (or None) for random number generator',
diag_eps='small value for Jacobian diagonals',
warn_limits='warn variables initialized at limits',
warn_abnormal='warn initialization out of normal values',
numba='use numba for JIT compilation',
numba_parallel='enable parallel for numba.jit',
numba_cache='enable machine code caching for numba.jit',
numba_nopython='nopython mode for numba',
yapf_pycode='format generated code with yapf',
np_divide='treatment for division by zero',
np_invalid='treatment for invalid floating-point ops.',
pickle_path='path models should be (un)dilled to/from',
)
self.config.add_extra("_alt",
freq="float",
mva="float",
ipadd=(0, 1),
seed='int or None',
warn_limits=(0, 1),
warn_abnormal=(0, 1),
numba=(0, 1),
numba_parallel=(0, 1),
numba_cache=(0, 1),
numba_nopython=(0, 1),
yapf_pycode=(0, 1),
np_divide={'ignore', 'warn', 'raise', 'call', 'print', 'log'},
np_invalid={'ignore', 'warn', 'raise', 'call', 'print', 'log'},
)
self.config.check()
self._set_numpy()
self.exist = ExistingModels()
self.files = FileMan(case=case, **self.options) # file path manager
self.dae = DAE(system=self) # numerical DAE storage
self.streaming = Streaming(self) # Dime2 streaming
# dynamic imports of groups, models and routines
self.import_groups()
self.import_models()
self.import_routines() # routine imports come after models
self._getters = dict(f=list(), g=list(), x=list(), y=list())
self._adders = dict(f=list(), g=list(), x=list(), y=list())
self._setters = dict(f=list(), g=list(), x=list(), y=list())
self.antiwindups = list()
self.no_check_init = list() # states for which initialization check is omitted
# internal flags
self.is_setup = False # if system has been setup
def _set_numpy(self):
"""
Configure NumPy based on Config.
"""
# set up numpy random seed
if isinstance(self.config.seed, int):
np.random.seed(self.config.seed)
logger.debug("Random seed set to <%d>.", self.config.seed)
np.seterr(divide=self.config.np_divide,
invalid=self.config.np_invalid,
)
def reload(self, case, **kwargs):
"""
Reload a new case in the same System object.
"""
self.options.update(kwargs)
self.files.set(case=case, **kwargs)
# TODO: clear all flags and empty data
andes.io.parse(self)
self.setup()
def _clear_adder_setter(self):
"""
Clear adders and setters storage
"""
self._getters = dict(f=list(), g=list(), x=list(), y=list())
self._adders = dict(f=list(), g=list(), x=list(), y=list())
self._setters = dict(f=list(), g=list(), x=list(), y=list())
def prepare(self, quick=False, incremental=False, models=None, nomp=False, ncpu=os.cpu_count()):
"""
Generate numerical functions from symbolically defined models.
All procedures in this function must be independent of test case.
Parameters
----------
quick : bool, optional
True to skip pretty-print generation to reduce code generation time.
incremental : bool, optional
True to generate only for modified models, incrementally.
models : list, OrderedDict, None
List or OrderedList of models to prepare
nomp : bool
True to disable multiprocessing
Notes
-----
Option ``incremental`` compares the md5 checksum of all var and
service strings, and only regenerate for updated models.
Examples
--------
If one needs to print out LaTeX-formatted equations in a Jupyter Notebook, one need to generate such
equations with ::
import andes
sys = andes.prepare()
Alternatively, one can explicitly create a System and generate the code ::
import andes
sys = andes.System()
sys.prepare()
Warnings
--------
Generated lambda functions will be serialized to file, but pretty prints (SymPy objects) can only exist in
the System instance on which prepare is called.
"""
# info
if incremental is True:
mode_text = 'rapid incremental mode'
elif quick is True:
mode_text = 'quick mode'
else:
mode_text = 'full mode'
logger.info('Numerical code generation (%s) started...', mode_text)
t0, _ = elapsed()
# consistency check for group parameters and variables
self._check_group_common()
# get `pycode` folder path without automatic creation
pycode_path = get_pycode_path(self.options.get("pycode_path"), mkdir=False)
# determine which models to prepare based on mode and `models` list.
if incremental and models is None:
if not self.with_calls:
self._load_calls()
models = self._find_stale_models()
elif not incremental and models is None:
models = self.models
else:
models = self._to_orddct(models)
total = len(models)
width = len(str(total))
if nomp is False:
print(f"Generating code for {total} models on {ncpu} processes.")
self._mp_prepare(models, quick, pycode_path, ncpu=ncpu)
else:
for idx, (name, model) in enumerate(models.items()):
print(f"\r\x1b[K Generating code for {name} ({idx+1:>{width}}/{total:>{width}}).",
end='\r', flush=True)
model.prepare(quick=quick, pycode_path=pycode_path)
if len(models) > 0:
self._finalize_pycode(pycode_path)
self._store_calls(models)
self.dill()
_, s = elapsed(t0)
logger.info('Generated numerical code for %d models in %s.', len(models), s)
def _mp_prepare(self, models, quick, pycode_path, ncpu):
"""
Wrapper function for multiprocess prepare.
"""
# create empty models without dependency
if len(models) == 0:
return
model_names = list(models.keys())
model_list = list()
for file, cls_list in file_classes.items():
for model_name in cls_list:
if model_name not in model_names:
continue
the_module = importlib.import_module('andes.models.' + file)
the_class = getattr(the_module, model_name)
model_list.append(the_class(system=None, config=self._config_object))
yapf_pycode = self.config.yapf_pycode
def _prep_model(model: Model, ):
"""
Wrapper function to call prepare on a model.
"""
model.prepare(quick=quick,
pycode_path=pycode_path,
yapf_pycode=yapf_pycode
)
Pool(ncpu).map(_prep_model, model_list)
def _finalize_pycode(self, pycode_path):
"""
Helper function for finalizing pycode generation by
writing ``__init__.py`` and reloading ``pycode`` package.
"""
init_path = os.path.join(pycode_path, '__init__.py')
with open(init_path, 'w') as f:
f.write(f"__version__ = '{andes.__version__}'\n\n")
for name in self.models.keys():
f.write(f"from . import {name:20s} # NOQA\n")
f.write('\n')
logger.info('Saved generated pycode to "%s"', pycode_path)
# RELOAD REQUIRED as the generated Jacobian arguments may be in a different order
self._call_from_pycode()
def _find_stale_models(self):
"""
Find models whose ModelCall are stale using md5 checksum.
"""
out = OrderedDict()
for model in self.models.values():
calls_md5 = getattr(model.calls, 'md5', None)
if calls_md5 != model.get_md5():
out[model.class_name] = model
return out
def _to_orddct(self, model_list):
"""
Helper function to convert a list of model names to OrderedDict
with name as keys and model instances as values.
"""
if isinstance(model_list, OrderedDict):
return model_list
if isinstance(model_list, list):
out = OrderedDict()
for name in model_list:
if name not in self.models:
logger.error("Model <%s> does not exist. Check your inputs.", name)
continue
out[name] = self.models[name]
return out
else:
raise TypeError("Type %s not recognized" % type(model_list))
def setup(self):
"""
Set up system for studies.
This function is to be called after adding all device data.
"""
ret = True
t0, _ = elapsed()
if self.is_setup:
logger.warning('System has been setup. Calling setup twice is not allowed.')
ret = False
return ret
self.collect_ref()
self._list2array() # `list2array` must come before `link_ext_param`
if not self.link_ext_param():
ret = False
self.find_devices() # find or add required devices
# === no device addition or removal after this point ===
self.calc_pu_coeff() # calculate parameters in system per units
self.store_existing() # store models with routine flags
# assign address at the end before adding devices and processing parameters
self.set_address(self.exist.pflow)
self.set_dae_names(self.exist.pflow)
self.store_sparse_pattern(self.exist.pflow)
self.store_adder_setter(self.exist.pflow)
if ret is True:
self.is_setup = True # set `is_setup` if no error occurred
else:
logger.error("System setup failed. Please resolve the reported issue(s).")
self.exit_code += 1
_, s = elapsed(t0)
logger.info('System internal structure set up in %s.', s)
return ret
def store_existing(self):
"""
Store existing models in `System.existing`.
TODO: Models with `TimerParam` will need to be stored anyway.
This will allow adding switches on the fly.
"""
self.exist.pflow = self.find_models('pflow')
self.exist.tds = self.find_models('tds')
self.exist.pflow_tds = self.find_models(('tds', 'pflow'))
def reset(self, force=False):
"""
Reset to the state after reading data and setup (before power flow).
Warnings
--------
If TDS is initialized, reset will lead to unpredictable state.
"""
if self.TDS.initialized is True and not force:
logger.error('Reset failed because TDS is initialized. \nPlease reload the test case to start over.')
return
self.dae.reset()
self.call_models('a_reset', models=self.models)
self.e_clear(models=self.models)
self._p_restore()
self.is_setup = False
self.setup()
def add(self, model, param_dict=None, **kwargs):
"""
Add a device instance for an existing model.
This methods calls the ``add`` method of `model` and registers the device `idx` to group.
"""
if model not in self.models:
logger.warning("<%s> is not an existing model.", model)
return
if self.is_setup:
raise NotImplementedError("Adding devices are not allowed after setup.")
group_name = self.__dict__[model].group
group = self.groups[group_name]
if param_dict is None:
param_dict = {}
if kwargs is not None:
param_dict.update(kwargs)
idx = param_dict.pop('idx', None)
if idx is np.nan:
idx = None
idx = group.get_next_idx(idx=idx, model_name=model)
self.__dict__[model].add(idx=idx, **param_dict)
group.add(idx=idx, model=self.__dict__[model])
return idx
def find_devices(self):
"""
Add dependent devices for all model based on `DeviceFinder`.
"""
for mdl in self.models.values():
if len(mdl.services_fnd) == 0:
continue
for fnd in mdl.services_fnd.values():
fnd.find_or_add(self)
def set_address(self, models):
"""
Set addresses for differential and algebraic variables.
"""
for mdl in models.values():
if mdl.flags.address is True:
logger.debug('%s internal address exists', mdl.class_name)
continue
if mdl.n == 0:
continue
# set internal variable addresses
logger.debug('Setting internal address for %s', mdl.class_name)
n = mdl.n
m0 = self.dae.m
n0 = self.dae.n
m_end = m0 + len(mdl.algebs) * n
n_end = n0 + len(mdl.states) * n
collate = mdl.flags.collate
if not collate:
for idx, item in enumerate(mdl.algebs.values()):
item.set_address(np.arange(m0 + idx * n, m0 + (idx + 1) * n), contiguous=True)
for idx, item in enumerate(mdl.states.values()):
item.set_address(np.arange(n0 + idx * n, n0 + (idx + 1) * n), contiguous=True)
else:
for idx, item in enumerate(mdl.algebs.values()):
item.set_address(np.arange(m0 + idx, m_end, len(mdl.algebs)), contiguous=False)
for idx, item in enumerate(mdl.states.values()):
item.set_address(np.arange(n0 + idx, n_end, len(mdl.states)), contiguous=False)
self.dae.m = m_end
self.dae.n = n_end
# set external variable addresses
for mdl in models.values():
# handle external groups
for name, instance in mdl.cache.vars_ext.items():
ext_name = instance.model
try:
ext_model = self.__dict__[ext_name]
except KeyError:
raise KeyError('<%s> is not a model or group name.' % ext_name)
try:
instance.link_external(ext_model)
except (IndexError, KeyError) as e:
logger.error('Error: <%s> cannot retrieve <%s> from <%s> using <%s>:\n %s',
mdl.class_name, instance.name, instance.model,
instance.indexer.name, repr(e))
# set external variable RHS addresses
for mdl in models.values():
if mdl.flags.address is True:
logger.debug('%s RHS address exists', mdl.class_name)
continue
if mdl.n == 0:
continue
for item in mdl.states_ext.values():
# skip if no equation, i.e., no RHS value
if item.e_str is None:
continue
item.set_address(np.arange(self.dae.p, self.dae.p + item.n))
self.dae.p += item.n
for item in mdl.algebs_ext.values():
if item.e_str is None:
continue
item.set_address(np.arange(self.dae.q, self.dae.q + item.n))
self.dae.q += item.n
mdl.flags.address = True
# allocate memory for DAE arrays
self.dae.resize_arrays()
# set `v` and `e` in variables
self.set_var_arrays(models=models)
self.dae.alloc_or_extend_names()
def set_dae_names(self, models):
"""
Set variable names for differential and algebraic variables,
right-hand side of external equations, and discrete flags.
"""
for mdl in models.values():
_set_xy_name(mdl, mdl.states, (self.dae.x_name, self.dae.x_tex_name))
_set_xy_name(mdl, mdl.algebs, (self.dae.y_name, self.dae.y_tex_name))
_set_hi_name(mdl, mdl.states_ext, (self.dae.h_name, self.dae.h_tex_name))
_set_hi_name(mdl, mdl.algebs_ext, (self.dae.i_name, self.dae.i_tex_name))
# add discrete flag names
if self.TDS.config.store_z == 1:
_set_z_name(mdl, self.dae, (self.dae.z_name, self.dae.z_tex_name))
def set_var_arrays(self, models, inplace=True, alloc=True):
"""
Set arrays (`v` and `e`) in internal variables.
Parameters
----------
models : OrderedDict, list, Model, optional
Models to execute.
inplace : bool
True to retrieve arrays that share memory with dae
alloc : bool
True to allocate for arrays internally
"""
for mdl in models.values():
if mdl.n == 0:
continue
for var in mdl.cache.vars_int.values():
var.set_arrays(self.dae, inplace=inplace, alloc=alloc)
for var in mdl.cache.vars_ext.values():
var.set_arrays(self.dae, inplace=inplace, alloc=alloc)
def _init_numba(self, models: OrderedDict):
"""
Helper function to compile all functions with Numba before init.
"""
if not self.config.numba:
return
use_parallel = bool(self.config.numba_parallel)
use_cache = bool(self.config.numba_cache)
nopython = bool(self.config.numba_nopython)
logger.info("Numba compilation initiated, parallel=%s, cache=%s.",
use_parallel, use_cache)
for mdl in models.values():
mdl.numba_jitify(parallel=use_parallel,
cache=use_cache,
nopython=nopython,
)
def init(self, models: OrderedDict, routine: str):
"""
Initialize the variables for each of the specified models.
For each model, the initialization procedure is:
- Get values for all `ExtService`.
- Call the model `init()` method, which initializes internal variables.
- Copy variables to DAE and then back to the model.
"""
try:
self._init_numba(models)
except ImportError:
logger.warning("Numba not found. JIT compilation is skipped.")
for mdl in models.values():
# link externals first
for instance in mdl.services_ext.values():
ext_name = instance.model
try:
ext_model = self.__dict__[ext_name]
except KeyError:
raise KeyError('<%s> is not a model or group name.' % ext_name)
try:
instance.link_external(ext_model)
except (IndexError, KeyError) as e:
logger.error('Error: <%s> cannot retrieve <%s> from <%s> using <%s>:\n %s',
mdl.class_name, instance.name, instance.model,
instance.indexer.name, repr(e))
# initialize variables second
mdl.init(routine=routine)
self.vars_to_dae(mdl)
self.vars_to_models()
self.s_update_post(models)
# store the inverse of time constants
self._store_tf(models)
def store_adder_setter(self, models):
"""
Store non-inplace adders and setters for variables and equations.
"""
self._clear_adder_setter()
for mdl in models.values():
# Note:
# We assume that a Model with no device is not addressed and, therefore,
# contains no value in each variable.
# It is always true for the current architecture.
if not mdl.n:
continue
# ``getters` that retrieve variable values from DAE
for var in mdl.cache.v_getters.values():
self._getters[var.v_code].append(var)
# ``adders`` that add variable values to the DAE array
for var in mdl.cache.v_adders.values():
self._adders[var.v_code].append(var)
for var in mdl.cache.e_adders.values():
self._adders[var.e_code].append(var)
# ``setters`` that force set variable values in the DAE array
for var in mdl.cache.v_setters.values():
self._setters[var.v_code].append(var)
for var in mdl.cache.e_setters.values():
self._setters[var.e_code].append(var)
# ``antiwindups`` stores all AntiWindup instances
for item in mdl.discrete.values():
if isinstance(item, AntiWindup):
self.antiwindups.append(item)
return
def store_no_check_init(self, models):
"""
Store differential variables with ``check_init == False``.
"""
self.no_check_init = list()
for mdl in models.values():
if mdl.n == 0:
continue
for var in mdl.states.values():
if var.check_init is False:
self.no_check_init.extend(var.a)
def link_ext_param(self, model=None):
"""
Retrieve values for ``ExtParam`` for the given models.
"""
if model is None:
models = self.models
else:
models = self._get_models(model)
ret = True
for model in models.values():
# get external parameters with `link_external` and then calculate the pu coeff
for instance in model.params_ext.values():
ext_name = instance.model
ext_model = self.__dict__[ext_name]
try:
instance.link_external(ext_model)
except (IndexError, KeyError) as e:
logger.error('Error: <%s> cannot retrieve <%s> from <%s> using <%s>:\n %s',
model.class_name, instance.name, instance.model,
instance.indexer.name, repr(e))
ret = False
return ret
def calc_pu_coeff(self):
"""
Perform per unit value conversion.
This function calculates the per unit conversion factors, stores input parameters to `vin`, and perform
the conversion.
"""
Sb = self.config.mva
for mdl in self.models.values():
# default Sn to Sb if not provided. Some controllers might not have Sn or Vn.
if 'Sn' in mdl.__dict__:
Sn = mdl.Sn.v
else:
Sn = Sb
# If both Vn and Vn1 are not provided, default to Vn = Vb = 1
# test if is shunt-connected or series-connected to bus, or unconnected to bus
Vb, Vn = 1, 1
if 'bus' in mdl.__dict__:
Vb = self.Bus.get(src='Vn', idx=mdl.bus.v, attr='v')
Vn = mdl.Vn.v if 'Vn' in mdl.__dict__ else Vb
elif 'bus1' in mdl.__dict__:
Vb = self.Bus.get(src='Vn', idx=mdl.bus1.v, attr='v')
Vn = mdl.Vn1.v if 'Vn1' in mdl.__dict__ else Vb
Zn = Vn ** 2 / Sn
Zb = Vb ** 2 / Sb
# process dc parameter pu conversion
Vdcb, Vdcn, Idcn = 1, 1, 1
if 'node' in mdl.__dict__:
Vdcb = self.Node.get(src='Vdcn', idx=mdl.node.v, attr='v')
Vdcn = mdl.Vdcn.v if 'Vdcn' in mdl.__dict__ else Vdcb
Idcn = mdl.Idcn.v if 'Idcn' in mdl.__dict__ else (Sb / Vdcb)
elif 'node1' in mdl.__dict__:
Vdcb = self.Node.get(src='Vdcn', idx=mdl.node1.v, attr='v')
Vdcn = mdl.Vdcn1.v if 'Vdcn1' in mdl.__dict__ else Vdcb
Idcn = mdl.Idcn.v if 'Idcn' in mdl.__dict__ else (Sb / Vdcb)
Idcb = Sb / Vdcb
Rb = Vdcb / Idcb
Rn = Vdcn / Idcn
coeffs = {'voltage': Vn / Vb,
'power': Sn / Sb,
'ipower': Sb / Sn,
'current': (Sn / Vn) / (Sb / Vb),
'z': Zn / Zb,
'y': Zb / Zn,
'dc_voltage': Vdcn / Vdcb,
'dc_current': Idcn / Idcb,
'r': Rn / Rb,
'g': Rb / Rn,
}
for prop, coeff in coeffs.items():
for p in mdl.find_param(prop).values():
p.set_pu_coeff(coeff)
def l_update_var(self, models: OrderedDict, niter=None, err=None):
"""
Update variable-based limiter discrete states by calling ``l_update_var`` of models.
This function is must be called before any equation evaluation.
"""
self.call_models('l_update_var', models,
dae_t=self.dae.t, niter=niter, err=err)
def l_update_eq(self, models: OrderedDict):
"""
Update equation-dependent limiter discrete components by calling ``l_check_eq`` of models.
Force set equations after evaluating equations.
This function is must be called after differential equation updates.
"""
self.call_models('l_check_eq', models)
def s_update_var(self, models: OrderedDict):
"""
Update variable services by calling ``s_update_var`` of models.
This function is must be called before any equation evaluation after
limiter update function `l_update_var`.
"""
self.call_models('s_update_var', models)
def s_update_post(self, models: OrderedDict):
"""
Update variable services by calling ``s_update_post`` of models.
This function is called at the end of `System.init()`.
"""
self.call_models('s_update_post', models)
def fg_to_dae(self):
"""
Collect equation values into the DAE arrays.
Additionally, the function resets the differential equations associated with variables pegged by
anti-windup limiters.
"""
self._e_to_dae(('f', 'g'))
# reset mismatches for islanded buses
self.g_islands()
# update variable values set by anti-windup limiters
for item in self.antiwindups:
if len(item.x_set) > 0:
for key, val, _ in item.x_set:
np.put(self.dae.x, key, val)
def f_update(self, models: OrderedDict):
"""
Call the differential equation update method for models in sequence.
Notes
-----
Updated equation values remain in models and have not been collected into DAE at the end of this step.
"""
try:
self.call_models('f_update', models)
except TypeError as e:
logger.error("f_update failed. Have you run `andes prepare -i` after updating?")
raise e
def g_update(self, models: OrderedDict):
"""
Call the algebraic equation update method for models in sequence.
Notes
-----
Like `f_update`, updated values have not collected into DAE at the end of the step.
"""
try:
self.call_models('g_update', models)
except TypeError as e:
logger.error("g_update failed. Have you run `andes prepare -i` after updating?")
raise e
def g_islands(self):
"""
Reset algebraic mismatches for islanded buses.
"""
if self.Bus.n_islanded_buses == 0:
return
self.dae.g[self.Bus.islanded_a] = 0.0
self.dae.g[self.Bus.islanded_v] = 0.0
def j_update(self, models: OrderedDict, info=None):
"""
Call the Jacobian update method for models in sequence.
The procedure is
- Restore the sparsity pattern with :py:func:`andes.variables.dae.DAE.restore_sparse`
- For each sparse matrix in (fx, fy, gx, gy), evaluate the Jacobian function calls and add values.
Notes
-----
Updated Jacobians are immediately reflected in the DAE sparse matrices (fx, fy, gx, gy).
"""
self.call_models('j_update', models)
self.dae.restore_sparse()
# collect sparse values into sparse structures
for j_name in jac_names:
j_size = self.dae.get_size(j_name)
for mdl in models.values():
for rows, cols, vals in mdl.triplets.zip_ijv(j_name):
try:
if self.config.ipadd and IP_ADD:
self.dae.__dict__[j_name].ipadd(vals, rows, cols)
else:
self.dae.__dict__[j_name] += spmatrix(vals, rows, cols, j_size, 'd')
except TypeError as e:
logger.error("Error adding Jacobian triplets to existing sparsity pattern.")
logger.error(f'{mdl.class_name}: j_name {j_name}, row={rows}, col={cols}, val={vals}, '
f'j_size={j_size}')
raise e
self.j_islands()
if info:
logger.debug("Jacobian updated at t=%.6f: %s.", self.dae.t, info)
else:
logger.debug("Jacobian updated at t=%.6f.", self.dae.t)
def j_islands(self):
"""
Set gy diagonals to eps for `a` and `v` variables of islanded buses.
"""
if self.Bus.n_islanded_buses == 0:
return
aidx = self.Bus.islanded_a
vidx = self.Bus.islanded_v
if self.config.ipadd and IP_ADD:
self.dae.gy.ipset(self.config.diag_eps, aidx, aidx)
self.dae.gy.ipset(self.config.diag_eps, vidx, vidx)
else:
avals = [-self.dae.gy[int(idx), int(idx)] + self.config.diag_eps for idx in aidx]
vvals = [-self.dae.gy[int(idx), int(idx)] + self.config.diag_eps for idx in vidx]
self.dae.gy += spmatrix(avals, aidx, aidx, self.dae.gy.size, 'd')
self.dae.gy += spmatrix(vvals, vidx, vidx, self.dae.gy.size, 'd')
def store_sparse_pattern(self, models: OrderedDict):
"""
Collect and store the sparsity pattern of Jacobian matrices.
This is a runtime function specific to cases.
Notes
-----
For `gy` matrix, always make sure the diagonal is reserved.
It is a safeguard if the modeling user omitted the diagonal
term in the equations.
"""
self.call_models('store_sparse_pattern', models)
# add variable jacobian values
for jname in jac_names:
ii, jj, vv = list(), list(), list()