/
system.py
2362 lines (1898 loc) 路 81.5 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-2024 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 importlib.util
import inspect
import logging
import os
import sys
import time
from collections import OrderedDict, defaultdict
from typing import Dict, Optional, Tuple, Union
import andes.io
from andes.core import AntiWindup, Config, Model
from andes.io.streaming import Streaming
from andes.models import file_classes
from andes.models.group import GroupBase
from andes.routines import all_routines
from andes.shared import (NCPUS_PHYSICAL, Pool, Process, dilled_vars,
jac_names, matrix, np, sparse, spmatrix, numba)
from andes.utils.misc import elapsed
from andes.utils.paths import (andes_root, confirm_overwrite, get_config_path,
get_pycode_path)
from andes.utils.tab import Tab
from andes.variables import DAE, FileMan
logger = logging.getLogger(__name__)
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.
Parameters
----------
no_undill : bool, optional, default=False
True to disable the call to ``System.undill()`` at the end of object creation.
False by default.
autogen_stale : bool, optional, default=True
True to automatically generate code for stale models.
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,
no_undill: Optional[bool] = False,
autogen_stale: Optional[bool] = True,
**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.model_aliases = OrderedDict() # alias: model instance
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 = load_config_rc(self._config_path)
self._update_config_object()
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_nopython', 1),
('yapf_pycode', 0),
('save_stats', 0),
('np_divide', 'warn'),
('np_invalid', 'warn'),
)))
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_nopython='nopython mode for numba',
yapf_pycode='format generated code with yapf',
save_stats='store statistics of function calls',
np_divide='treatment for division by zero',
np_invalid='treatment for invalid floating-point ops.',
)
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_nopython=(0, 1),
yapf_pycode=(0, 1),
save_stats=(0, 1),
np_divide={'ignore', 'warn', 'raise', 'call', 'print', 'log'},
np_invalid={'ignore', 'warn', 'raise', 'call', 'print', 'log'},
)
self.config.check()
_config_numpy(seed=self.config.seed,
divide=self.config.np_divide,
invalid=self.config.np_invalid,
)
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
self.call_stats = defaultdict(dict) # call statistics storage
# internal flags
self.is_setup = False # if system has been setup
if not no_undill:
self.undill(autogen_stale=autogen_stale)
def _update_config_object(self):
"""
Change config on the fly based on command-line options.
"""
config_option = self.options.get('config_option', None)
if config_option is None:
return
if len(config_option) == 0:
return
newobj = False
if self._config_object is None:
self._config_object = configparser.ConfigParser()
newobj = True
for item in config_option:
# check the validity of the config field
# each field follows the format `SECTION.FIELD = VALUE`
if item.count('=') != 1:
raise ValueError('config_option "{}" must be an assignment expression'.format(item))
field, value = item.split("=")
if field.count('.') != 1:
raise ValueError('config_option left-hand side "{}" must use format SECTION.FIELD'.format(field))
section, key = field.split(".")
section = section.strip()
key = key.strip()
value = value.strip()
if not newobj:
self._config_object.set(section, key, value)
logger.debug("Existing config option set: %s.%s=%s", section, key, value)
else:
self._config_object.add_section(section)
self._config_object.set(section, key, value)
logger.debug("New config option added: %s.%s=%s", section, key, value)
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=NCPUS_PHYSICAL):
"""
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.
"""
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._get_models(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)
_, 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 for multiprocessed code generation.
Parameters
----------
models : OrderedDict
model name : model instance pairs
quick : bool
True to skip LaTeX string generation
pycode_path : str
Path to store `pycode` folder
ncpu : int
Number of processors to use
"""
# create empty models without dependency
if len(models) == 0:
return
model_names = list(models.keys())
model_list = list()
for fname, cls_list in file_classes:
for model_name in cls_list:
if model_name not in model_names:
continue
the_module = importlib.import_module('andes.models.' + fname)
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._load_calls()
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) # needs perf. optimization
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 and (model not in self.model_aliases):
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)
# remove `uid` field
param_dict.pop('uid', None)
idx = param_dict.pop('idx', None)
if idx is not None and (not isinstance(idx, str) and np.isnan(idx)):
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.
"""
# --- Phase 1: set internal variable addresses ---
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
logger.debug('Setting internal address for %s', mdl.class_name)
collate = mdl.flags.collate
ndevice = mdl.n
# get and set internal variable addresses
xaddr = self.dae.request_address('x', ndevice=ndevice,
nvar=len(mdl.states),
collate=mdl.flags.collate,
)
yaddr = self.dae.request_address('y', ndevice=ndevice,
nvar=len(mdl.algebs),
collate=mdl.flags.collate,
)
for idx, item in enumerate(mdl.states.values()):
item.set_address(xaddr[idx], contiguous=not collate)
for idx, item in enumerate(mdl.algebs.values()):
item.set_address(yaddr[idx], contiguous=not collate)
# --- Phase 2: set external variable addresses ---
# NOTE:
# This step will retrieve the number of variables (item.n) for Phase 3.
for mdl in models.values():
# handle external groups
for instance in mdl.cache.vars_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))
# --- Phase 3: 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`) for internal variables to access dae arrays in
place.
This function needs to be called after de-serializing a System object,
where the internal variables are incorrectly assigned new memory.
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
try:
getattr(numba, '__version__')
except ImportError:
# numba not installed
logger.warning("numba is enabled but not installed. Please install numba manually.")
self.config.numba = 0
return False
use_parallel = bool(self.config.numba_parallel)
nopython = bool(self.config.numba_nopython)
logger.info("Numba compilation initiated with caching.")
for mdl in models.values():
mdl.numba_jitify(parallel=use_parallel,
nopython=nopython,
)
return True
def precompile(self,
models: Union[OrderedDict, None] = None,
nomp: bool = False,
ncpu: int = NCPUS_PHYSICAL):
"""
Trigger precompilation for the given models.
Arguments are the same as ``prepare``.
"""
t0, _ = elapsed()
if models is None:
models = self.models
else:
models = self._get_models(models)
# turn on numba for precompilation
self.config.numba = 1
self.setup()
numba_ok = self._init_numba(models)
if not numba_ok:
return
def _precompile_model(model: Model):
model.precompile()
logger.info("Compilation in progress. This might take a minute...")
if nomp is True:
for name, mdl in models.items():
_precompile_model(mdl)
logger.debug("Model <%s> compiled.", name)
# multi-processed implementation. `Pool.map` runs very slow somehow.
else:
jobs = []
for idx, (name, mdl) in enumerate(models.items()):
job = Process(
name='Process {0:d}'.format(idx),
target=_precompile_model,
args=(mdl,),
)
jobs.append(job)
job.start()
if (idx % ncpu == ncpu - 1) or (idx == len(models) - 1):
time.sleep(0.02)
for job in jobs:
job.join()
jobs = []
_, s = elapsed(t0)
logger.info('Numba compiled %d model%s in %s.',
len(models),
'' if len(models) == 1 else 's',
s)
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.
"""
self._init_numba(models)
for mdl in models.values():
# link externals services 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 time constants associated with differential equations
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
# Fixes an issue if the cache was manually built but stale
# after assigning addresses for simulation
# Assigning memory will affect the cache of `v_adders` and `e_adders`.
mdl.cache.refresh()
# ``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`, `Vb` and `Zb` are the system base, bus base values
# `Sn`, `Vn` and `Zn` are the device bases
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)
# store coeffs and bases back in models.
mdl.coeffs = coeffs
mdl.bases = {'Sn': Sn, 'Sb': Sb, 'Vn': Vn, 'Vb': Vb, 'Zn': Zn, 'Zb': Zb}
def l_update_var(self, models: OrderedDict, niter=0, 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, init=False, niter=0):
"""
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, init=init, niter=niter)
def s_update_var(self, models: OrderedDict):
"""