/
group.py
5203 lines (4427 loc) · 226 KB
/
group.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
"""Define the Group class."""
import sys
from collections import Counter, defaultdict
from collections.abc import Iterable
from itertools import product, chain
from numbers import Number
import inspect
from difflib import get_close_matches
import numpy as np
import networkx as nx
from openmdao.core.configinfo import _ConfigInfo
from openmdao.core.system import System, collect_errors
from openmdao.core.component import Component, _DictValues
from openmdao.core.constants import _UNDEFINED, INT_DTYPE, _SetupStatus
from openmdao.vectors.vector import _full_slice
from openmdao.proc_allocators.default_allocator import DefaultAllocator, ProcAllocationError
from openmdao.jacobians.jacobian import SUBJAC_META_DEFAULTS
from openmdao.jacobians.dictionary_jacobian import DictionaryJacobian
from openmdao.recorders.recording_iteration_stack import Recording
from openmdao.solvers.nonlinear.nonlinear_runonce import NonlinearRunOnce
from openmdao.solvers.linear.linear_runonce import LinearRunOnce
from openmdao.solvers.linear.direct import DirectSolver
from openmdao.utils.array_utils import array_connection_compatible, _flatten_src_indices, \
shape_to_len, ValueRepeater
from openmdao.utils.general_utils import common_subpath, all_ancestors, \
convert_src_inds, shape2tuple, get_connection_owner, ensure_compatible, \
meta2src_iter, get_rev_conns, _contains_all
from openmdao.utils.units import is_compatible, unit_conversion, _has_val_mismatch, _find_unit, \
_is_unitless, simplify_unit
from openmdao.utils.graph_utils import get_out_of_order_nodes
from openmdao.utils.mpi import MPI, check_mpi_exceptions, multi_proc_exception_check
import openmdao.utils.coloring as coloring_mod
from openmdao.utils.indexer import indexer, Indexer
from openmdao.utils.relevance import get_relevance
from openmdao.utils.om_warnings import issue_warning, UnitsWarning, UnusedOptionWarning, \
PromotionWarning, MPIWarning, DerivativesWarning
from openmdao.utils.class_util import overrides_method
# regex to check for valid names.
import re
namecheck_rgx = re.compile('[a-zA-Z][_a-zA-Z0-9]*')
# use a class with slots instead of a namedtuple so that we can
# change index after creation if needed.
class _SysInfo(object):
__slots__ = ['system', 'index']
def __init__(self, system, index):
self.system = system
self.index = index
def __iter__(self):
yield self.system
yield self.index
class _PromotesInfo(object):
__slots__ = ['src_indices', 'flat', 'src_shape', 'promoted_from', 'prom']
def __init__(self, src_indices=None, flat=None, src_shape=None, promoted_from='', prom=None):
self.flat = flat
self.src_shape = src_shape
if src_indices is not None:
if isinstance(src_indices, Indexer):
self.src_indices = src_indices
self.src_indices.set_src_shape(self.src_shape)
else:
self.src_indices = indexer(src_indices, src_shape=self.src_shape, flat_src=flat)
else:
self.src_indices = None
self.promoted_from = promoted_from # pathname of promoting system
self.prom = prom # local promoted name of input
def __iter__(self):
yield self.src_indices
yield self.flat
yield self.src_shape
def __repr__(self): # pragma no cover
return (f"_PromotesInfo(src_indices={self.src_indices}, flat={self.flat}, "
f"src_shape={self.src_shape}, promoted_from={self.promoted_from}, "
f"prom={self.prom})")
def prom_path(self):
if self.promoted_from is None or self.prom is None:
return ''
return '.'.join((self.promoted_from, self.prom)) if self.promoted_from else self.prom
def copy(self):
return _PromotesInfo(self.src_indices.copy(), self.flat, self.src_shape, self.promoted_from,
self.prom)
def set_src_shape(self, shape):
if self.src_indices is not None:
self.src_indices.set_src_shape(shape)
self.src_shape = shape
def compare(self, other):
"""
Compare attributes in the two objects.
Two attributes are considered mismatched only if neither is None and their values
are unequal.
Returns
-------
list
List of unequal atrribute names.
"""
mismatches = []
if self.flat != other.flat:
if self.flat is not None and other.flat is not None:
mismatches.append('flat_src_indices')
if self.src_shape != other.src_shape:
if self.src_shape is not None and other.src_shape is not None:
mismatches.append('src_shape')
self_srcinds = None if self.src_indices is None else self.src_indices.as_array()
other_srcinds = None if other.src_indices is None else other.src_indices.as_array()
if isinstance(self_srcinds, np.ndarray) and isinstance(other_srcinds, np.ndarray):
if (self_srcinds.shape != other_srcinds.shape or
not np.all(self_srcinds == other_srcinds)):
mismatches.append('src_indices')
return mismatches
class Group(System):
"""
Class used to group systems together; instantiate or inherit.
Parameters
----------
**kwargs : dict
Dict of arguments available here and in all descendants of this Group.
Attributes
----------
_mpi_proc_allocator : ProcAllocator
Object used to allocate MPI processes to subsystems.
_proc_info : dict of subsys_name: (min_procs, max_procs, weight, proc_group)
Information used to determine MPI process allocation to subsystems.
_subgroups_myproc : list
List of local subgroups, (sorted by name if Problem option allow_post_setup_reorder is
True).
_manual_connections : dict
Dictionary of input_name: (output_name, src_indices) connections.
_group_inputs : dict
Mapping of promoted names to certain metadata (src_indices, units).
_static_group_inputs : dict
Group inputs added outside of setup/configure.
_pre_config_group_inputs : dict
Group inputs added inside of setup but before configure.
_static_manual_connections : dict
Dictionary that stores all explicit connections added outside of setup.
_conn_abs_in2out : {'abs_in': 'abs_out'}
Dictionary containing all explicit & implicit continuous var connections owned
by this system only. The data is the same across all processors.
_conn_discrete_in2out : {'abs_in': 'abs_out'}
Dictionary containing all explicit & implicit discrete var connections owned
by this system only. The data is the same across all processors.
_transfers : dict of dict of Transfers
First key is mode, second is subname where
mode is 'fwd' or 'rev' and subname is the subsystem name
or subname can be None for the full, simultaneous transfer.
_discrete_transfers : dict of discrete transfer metadata
Key is system pathname or None for the full, simultaneous transfer.
_setup_procs_finished : bool
Flag to check if setup_procs is complete
_contains_parallel_group : bool
If True, this Group contains a ParallelGroup. Only used to determine if a parallel
group or distributed component is below a DirectSolver so that we can raise an exception.
_order_set : bool
Flag to check if set_order has been called.
_auto_ivc_warnings : list
List of Auto IVC warnings to be raised later.
_shapes_graph : nx.Graph
Dynamic shape dependency graph, or None.
_pre_components : set of str or None
Set of pathnames of components that are executed prior to the optimization loop. Empty
unless the 'group_by_pre_opt_post' option is True in the Problem.
_post_components : set of str or None
Set of pathnames of components that are executed after the optimization loop. Empty
unless the 'group_by_pre_opt_post' option is True in the Problem.
_iterated_components : set of str or ContainsAll
Set of pathnames of components that are executed in the optimization loop if
'group_by_pre_opt_post' is True in the Problem.
_fd_rev_xfer_correction_dist : dict
If this group is using finite difference to compute derivatives,
this is the set of inputs that are upstream of a distributed response
within this group, keyed by active response. These determine if contributions
from all ranks will be added together to get the correct input values when derivatives
in the larger model are being solved using reverse mode.
"""
def __init__(self, **kwargs):
"""
Set the solvers to nonlinear and linear block Gauss--Seidel by default.
"""
self._mpi_proc_allocator = DefaultAllocator()
self._proc_info = {}
super().__init__(**kwargs)
self._subgroups_myproc = None
self._manual_connections = {}
self._group_inputs = {}
self._pre_config_group_inputs = {}
self._static_group_inputs = {}
self._static_manual_connections = {}
self._conn_abs_in2out = {}
self._conn_discrete_in2out = {}
self._transfers = {}
self._discrete_transfers = {}
self._setup_procs_finished = False
self._contains_parallel_group = False
self._order_set = False
self._shapes_graph = None
self._pre_components = None
self._post_components = None
self._iterated_components = None
self._fd_rev_xfer_correction_dist = {}
# TODO: we cannot set the solvers with property setters at the moment
# because our lint check thinks that we are defining new attributes
# called nonlinear_solver and linear_solver without documenting them.
if not self._nonlinear_solver:
self._nonlinear_solver = NonlinearRunOnce()
if not self._linear_solver:
self._linear_solver = LinearRunOnce()
self.options.declare('auto_order', types=bool, default=False,
desc='If True the order of subsystems is determined automatically '
'based on the dependency graph. It will not break or reorder '
'cycles.')
def setup(self):
"""
Build this group.
This method should be overidden by your Group's method. The reason for using this
method to add subsystem is to save memory and setup time when using your Group
while running under MPI. This avoids the creation of systems that will not be
used in the current process.
You may call 'add_subsystem' to add systems to this group. You may also issue connections,
and set the linear and nonlinear solvers for this group level. You cannot safely change
anything on children systems; use the 'configure' method instead.
Available attributes:
name
pathname
comm
options
"""
pass
def configure(self):
"""
Configure this group to assign children settings.
This method may optionally be overidden by your Group's method.
You may only use this method to change settings on your children subsystems. This includes
setting solvers in cases where you want to override the defaults.
You can assume that the full hierarchy below your level has been instantiated and has
already called its own configure methods.
Available attributes:
name
pathname
comm
options
system hieararchy with attribute access
"""
pass
def set_input_defaults(self, name, val=_UNDEFINED, units=None, src_shape=None):
"""
Specify metadata to be assumed when multiple inputs are promoted to the same name.
Parameters
----------
name : str
Promoted input name.
val : object
Value to assume for the promoted input.
units : str or None
Units to assume for the promoted input.
src_shape : int or tuple
Assumed shape of any connected source or higher level promoted input.
"""
meta = {'prom': name, 'auto': False}
if val is _UNDEFINED:
src_shape = shape2tuple(src_shape)
else:
if src_shape is not None:
# make sure value and src_shape are compatible
val, src_shape = ensure_compatible(name, val, src_shape)
elif isinstance(val, np.ndarray):
src_shape = val.shape
elif isinstance(val, Number):
src_shape = (1,)
meta['val'] = val
if units is not None:
if not isinstance(units, str):
raise TypeError('%s: The units argument should be a str or None' % self.msginfo)
meta['units'] = simplify_unit(units, msginfo=self.msginfo)
if src_shape is not None:
meta['src_shape'] = src_shape
if self._static_mode:
dct = self._static_group_inputs
else:
dct = self._group_inputs
if name in dct:
old = dct[name][0]
overlap = set(old).intersection(meta)
if overlap:
issue_warning(f"Setting input defaults for input '{name}' which "
f"override previously set defaults for {sorted(overlap)}.",
prefix=self.msginfo, category=PromotionWarning)
old.update(meta)
else:
dct[name] = [meta]
def _get_matvec_scope(self, excl_sub=None):
"""
Find the input and output variables that are needed for a particular matvec product.
Parameters
----------
excl_sub : <System>
A subsystem whose variables should be excluded from the matvec product.
Returns
-------
(set, set)
Sets of output and input variables.
"""
if excl_sub is None:
cache_key = None
else:
cache_key = excl_sub.pathname
try:
iovars, excl = self._scope_cache[cache_key]
# Make sure they're the same subsystem instance before returning
if excl is excl_sub:
return iovars
except KeyError:
pass
if excl_sub is None:
# A value of None will be interpreted as 'all outputs'.
scope_out = None
# All inputs connected to an output in this system
scope_in = frozenset(self._conn_global_abs_in2out).intersection(
self._var_allprocs_abs2meta['input'])
else:
# Empty for the excl_sub
scope_out = frozenset()
# All inputs connected to an output in this system but not in excl_sub
# allins is used to filter out discrete variables that might be found in
# self._conn_global_abs_in2out.
allins = self._var_allprocs_abs2meta['input']
exvars = excl_sub._var_allprocs_abs2idx
scope_in = frozenset(abs_in for abs_in, abs_out in self._conn_global_abs_in2out.items()
if abs_out not in exvars and abs_in in allins)
# Use the pathname as the dict key instead of the object itself. When
# the object is used as the key, memory leaks result from multiple
# calls to setup().
self._scope_cache[cache_key] = ((scope_out, scope_in), excl_sub)
return scope_out, scope_in
def _compute_root_scale_factors(self):
"""
Compute scale factors for all variables.
Returns
-------
dict
Mapping of each absolute var name to its corresponding scaling factor tuple.
"""
# make this a defaultdict to handle the case of access using unconnected inputs
scale_factors = defaultdict(lambda: {
'input': (0.0, 1.0),
})
for abs_name, meta in self._var_allprocs_abs2meta['output'].items():
ref0 = meta['ref0']
res_ref = meta['res_ref']
a0 = ref0
a1 = meta['ref'] - ref0
scale_factors[abs_name] = {
'output': (a0, a1),
'residual': (0.0, 1.0 if res_ref is None else res_ref),
}
# Input scaling for connected inputs is added here.
# This is a combined scale factor that includes the scaling of the connected source
# and the unit conversion between the source output and each target input.
if self._has_input_scaling:
abs2meta_in = self._var_abs2meta['input']
allprocs_meta_out = self._var_allprocs_abs2meta['output']
for abs_in, abs_out in self._conn_global_abs_in2out.items():
if abs_in not in abs2meta_in:
# we only perform scaling on local, non-discrete arrays, so skip
continue
meta_in = abs2meta_in[abs_in]
meta_out = allprocs_meta_out[abs_out]
ref = meta_out['ref']
ref0 = meta_out['ref0']
src_indices = meta_in['src_indices']
if src_indices is not None:
if not (np.ndim(ref) == 0 and np.ndim(ref0) == 0):
# TODO: if either ref or ref0 are not scalar and the output is
# distributed, we need to do a scatter
# to obtain the values needed due to global src_indices
if meta_out['distributed']:
raise RuntimeError("{}: vector scalers with distrib vars "
"not supported yet.".format(self.msginfo))
if not src_indices._flat_src:
src_indices = _flatten_src_indices(src_indices, meta_in['shape'],
meta_out['global_shape'],
meta_out['global_size'])
ref = ref[src_indices]
ref0 = ref0[src_indices]
# Compute scaling arrays for inputs using a0 and a1
# Example:
# Let x, x_src, x_tgt be the dimensionless variable,
# variable in source units, and variable in target units, resp.
# x_src = a0 + a1 x
# x_tgt = b0 + b1 x
# x_tgt = g(x_src) = d0 + d1 x_src
# b0 + b1 x = d0 + d1 a0 + d1 a1 x
# b0 = d0 + d1 a0
# b0 = g(a0)
# b1 = d0 + d1 a1 - d0
# b1 = g(a1) - g(0)
units_in = meta_in['units']
units_out = meta_out['units']
if units_in is None or units_out is None or units_in == units_out:
a0 = ref0
a1 = ref - ref0
# No unit conversion, only scaling. Just send the scale factors.
scale_factors[abs_in] = {
'input': (a0, a1),
}
else:
factor, offset = unit_conversion(units_out, units_in)
a0 = ref0
a1 = ref - ref0
# Send both unit scaling and solver scaling. Linear input vectors need to
# treat them differently in reverse mode.
scale_factors[abs_in] = {
'input': (a0, a1, factor, offset),
}
# For adder allocation check.
a0 = (ref0 + offset) * factor
# Check whether we need to allocate an adder for the input vector.
if np.any(np.asarray(a0)):
self._has_input_adder = True
return scale_factors
def _configure(self):
"""
Configure our model recursively to assign any children settings.
Highest system's settings take precedence.
"""
# reset group_inputs back to what it was just after self.setup() in case _configure
# is called multiple times.
self._group_inputs = self._pre_config_group_inputs.copy()
for n, lst in self._group_inputs.items():
self._group_inputs[n] = lst.copy()
self.matrix_free = False
self._has_guess = overrides_method('guess_nonlinear', self, Group)
for subsys in self._sorted_sys_iter():
subsys._configure()
subsys._setup_var_data()
self._has_guess |= subsys._has_guess
self._has_bounds |= subsys._has_bounds
self.matrix_free |= subsys.matrix_free
self._problem_meta['setup_status'] = _SetupStatus.POST_CONFIGURE
self.configure()
# if our configure() has added or promoted any variables, we have to call
# _setup_var_data again on any modified systems and their ancestors (only those that
# are our descendents).
self._problem_meta['config_info']._update_modified_systems(self)
def _reset_setup_vars(self):
"""
Reset all the stuff that gets initialized in setup.
"""
super()._reset_setup_vars()
self._setup_procs_finished = False
def _setup_procs(self, pathname, comm, prob_meta):
"""
Execute first phase of the setup process.
Distribute processors, assign pathnames, and call setup on the group. This method recurses
downward through the model.
Parameters
----------
pathname : str
Global name of the system, including the path.
comm : MPI.Comm or <FakeComm>
MPI communicator object.
prob_meta : dict
Problem level metadata.
"""
super()._setup_procs(pathname, comm, prob_meta)
nproc = comm.size
if self._num_par_fd > 1:
info = self._coloring_info
if comm.size > 1:
# if approx_totals has been declared, or there is an approx coloring, setup par FD
if self._owns_approx_jac or info.dynamic or info.static is not None:
comm = self._setup_par_fd_procs(comm)
else:
msg = "%s: num_par_fd = %d but FD is not active." % (self.msginfo,
self._num_par_fd)
raise RuntimeError(msg)
elif not MPI:
msg = f"MPI is not active but num_par_fd = {self._num_par_fd}. No parallel " \
f"finite difference will be performed."
issue_warning(msg, prefix=self.msginfo, category=MPIWarning)
self.comm = comm
self._subsystems_allprocs = self._static_subsystems_allprocs.copy()
self._manual_connections = self._static_manual_connections.copy()
self._group_inputs = self._static_group_inputs.copy()
# copy doesn't copy the internal list so we have to do it manually (we don't want
# a full deepcopy either because we want the internal metadata dicts to be shared)
for n, lst in self._group_inputs.items():
self._group_inputs[n] = lst.copy()
# Call setup function for this group.
self.setup()
self._setup_check()
# need to save these because _setup_var_data can be called multiple times
# during the config process and we don't want to wipe out any group_inputs
# that were added during self.setup()
self._pre_config_group_inputs = self._group_inputs.copy()
for n, lst in self._pre_config_group_inputs.items():
self._pre_config_group_inputs[n] = lst.copy()
if MPI:
allsubs = list(self._subsystems_allprocs.values())
proc_info = [self._proc_info[s.name] for s, _ in allsubs]
# Call the load balancing algorithm
try:
sub_inds, sub_comm = self._mpi_proc_allocator(proc_info, len(allsubs), comm)
except ProcAllocationError as err:
if err.sub_inds is None:
raise RuntimeError("%s: %s" % (self.msginfo, err.msg))
else:
raise RuntimeError("%s: MPI process allocation failed: %s for the following "
"subsystems: %s" %
(self.msginfo, err.msg,
[allsubs[i].system.name for i in err.sub_inds]))
self._subsystems_myproc = [allsubs[ind].system for ind in sub_inds]
# Define local subsystems
if (self._mpi_proc_allocator.parallel and
not (np.sum([minp for minp, _, _, _ in proc_info]) <= comm.size)):
# reorder the subsystems_allprocs based on which procs they live on. If we don't
# do this, we can get ordering mismatches in some of our data structures.
new_allsubs = {}
seen = set()
gathered = self.comm.allgather(sub_inds)
for inds in gathered:
for ind in inds:
if ind not in seen:
sinfo = allsubs[ind]
sinfo.index = len(new_allsubs)
new_allsubs[sinfo.system.name] = sinfo
seen.add(ind)
self._subsystems_allprocs = new_allsubs
else:
sub_comm = comm
self._subsystems_myproc = [s for s, _ in self._subsystems_allprocs.values()]
# need to set pathname correctly even for non-local subsystems
for s, _ in self._subsystems_allprocs.values():
s.pathname = '.'.join((self.pathname, s.name)) if self.pathname else s.name
# Perform recursion
for subsys in self._subsystems_myproc:
subsys._setup_procs(subsys.pathname, sub_comm, prob_meta)
# build a list of local subgroups to speed up later loops
self._subgroups_myproc = [s for s in self._subsystems_myproc if isinstance(s, Group)]
if prob_meta['allow_post_setup_reorder']:
self._subgroups_myproc.sort(key=lambda x: x.name)
if nproc > 1 and self._mpi_proc_allocator.parallel:
self._problem_meta['parallel_groups'].append(self.pathname)
allpars = self.comm.allgather(self._problem_meta['parallel_groups'])
full = set()
for p in allpars:
full.update(p)
self._problem_meta['parallel_groups'] = sorted(full)
if self._problem_meta['parallel_groups']:
prefix = self.pathname + '.' if self.pathname else ''
for par in self._problem_meta['parallel_groups']:
if par.startswith(prefix) and par != prefix:
self._contains_parallel_group = True
break
self._setup_procs_finished = True
def _configure_check(self):
"""
Do any error checking on i/o and connections.
"""
for subsys in self._subsystems_myproc:
subsys._configure_check()
super()._configure_check()
def _list_states(self):
"""
Return list of all local states at and below this system.
Returns
-------
list
List of all states.
"""
states = []
for subsys in self._sorted_sys_iter():
states.extend(subsys._list_states())
return sorted(states)
def _list_states_allprocs(self):
"""
Return list of all states at and below this system across all procs.
Returns
-------
list
List of all states.
"""
if MPI and self.comm.size > 1:
all_states = set()
byproc = self.comm.allgather(self._list_states())
for proc_states in byproc:
all_states.update(proc_states)
return sorted(all_states)
else:
return self._list_states()
def _setup(self, comm, prob_meta):
"""
Perform setup for this system and its descendant systems.
This is only called on the top-level model.
Parameters
----------
comm : MPI.Comm or <FakeComm> or None
The global communicator.
prob_meta : dict
Problem level metadata dictionary.
"""
# save a ref to the problem level options.
self._problem_meta = prob_meta
self._initial_condition_cache = {}
# reset any coloring if a Coloring object was not set explicitly
if self._coloring_info.dynamic or self._coloring_info.static is not None:
self._coloring_info.coloring = None
self.pathname = ''
self.comm = comm
self._pre_components = None
self._post_components = None
# Besides setting up the processors, this method also builds the model hierarchy.
self._setup_procs(self.pathname, comm, self._problem_meta)
prob_meta['config_info'] = _ConfigInfo()
try:
# Recurse model from the bottom to the top for configuring.
self._configure()
finally:
prob_meta['config_info'] = None
prob_meta['setup_status'] = _SetupStatus.POST_CONFIGURE
self._configure_check()
self._setup_var_data()
# have to do this again because we are passed the point in _setup_var_data when this happens
self._has_output_scaling = False
self._has_output_adder = False
self._has_resid_scaling = False
self._has_bounds = False
for subsys in self.system_iter(include_self=True, recurse=True):
subsys._apply_output_solver_options()
self._has_output_scaling |= subsys._has_output_scaling
self._has_output_adder |= subsys._has_output_adder
self._has_resid_scaling |= subsys._has_resid_scaling
self._has_bounds |= subsys._has_bounds
# promoted names must be known to determine implicit connections so this must be
# called after _setup_var_data, and _setup_var_data will have to be partially redone
# after auto_ivcs have been added, but auto_ivcs can't be added until after we know all of
# the connections.
self._setup_global_connections()
self._setup_dynamic_shapes()
self._top_level_post_connections()
self._setup_var_sizes()
self._top_level_post_sizes()
# determine which connections are managed by which group, and check validity of connections
self._setup_connections()
def _get_dataflow_graph(self):
"""
Return a graph of all variables and components in the model.
Each component is connected to each of its input and output variables, and those variables
are connected to other variables based on the connections in the model.
This results in a smaller graph (fewer edges) than would be the case for a pure variable
graph where all inputs to a particular component would have to be connected to all outputs
from that component.
This should only be called on the top level Group.
Returns
-------
networkx.DiGraph
Graph of all variables and components in the model.
"""
assert self.pathname == '', "call _get_dataflow_graph on the top level Group only."
graph = nx.DiGraph()
comp_seen = set()
# locate any components that don't have any inputs or outputs and add them to the graph
for subsys in self.system_iter(recurse=True, typ=Component):
if not subsys._var_abs2meta['input'] and not subsys._var_abs2meta['output']:
graph.add_node(subsys.pathname, local=True)
comp_seen.add(subsys.pathname)
if self.comm.size > 1:
allemptycomps = self.comm.allgather(comp_seen)
for compset in allemptycomps:
for comp in compset:
if comp not in comp_seen:
graph.add_node(comp, local=False)
comp_seen.add(comp)
for direction in ('input', 'output'):
isout = direction == 'output'
allvmeta = self._var_allprocs_abs2meta[direction]
vmeta = self._var_abs2meta[direction]
for vname in self._var_allprocs_abs2prom[direction]:
if vname in allvmeta:
local = vname in vmeta
else: # var is discrete
local = vname in self._var_discrete[direction]
graph.add_node(vname, type_=direction, local=local)
comp = vname.rpartition('.')[0]
if comp not in comp_seen:
graph.add_node(comp, local=local)
comp_seen.add(comp)
if isout:
graph.add_edge(comp, vname)
else:
graph.add_edge(vname, comp)
for tgt, src in self._conn_global_abs_in2out.items():
# connect the variables src and tgt
graph.add_edge(src, tgt)
return graph
def _check_alias_overlaps(self, responses):
"""
Check for overlapping indices in aliased responses.
If the responses contain aliases, the returned response dict will
be a copy with the alias keys removed and any missing alias sources
added.
This may only be called on the top level Group.
Parameters
----------
responses : dict
Dictionary of response metadata. Keys don't matter.
Returns
-------
dict
Dictionary of response metadata with alias keys removed.
"""
assert self.pathname == '', "call _check_alias_overlaps on the top level System only."
aliases = set()
srcdict = {}
discrete_outs = self._var_allprocs_discrete['output']
# group all aliases by source so we can compute overlaps for each source individually
for meta in responses.values():
src = meta['source']
if src not in discrete_outs:
if meta['alias']:
aliases.add(meta['alias'])
if src in srcdict:
srcdict[src].append(meta)
else:
srcdict[src] = [meta]
abs2meta_out = self._var_allprocs_abs2meta['output']
# loop over any sources having multiple aliases to ensure no overlap of indices
for src, metalist in srcdict.items():
if len(metalist) == 1:
continue
size = abs2meta_out[src]['global_size']
shape = abs2meta_out[src]['global_shape']
mat = np.zeros(size, dtype=np.ushort)
for meta in metalist:
indices = meta['indices']
if indices is None:
mat[:] += 1
else:
indices.set_src_shape(shape)
mat[indices.flat()] += 1
if np.any(mat > 1):
matching_aliases = sorted(m['alias'] for m in metalist if m['alias'])
raise RuntimeError(f"{self.msginfo}: Indices for aliases {matching_aliases} are "
f"overlapping constraint/objective '{src}'.")
return responses
def _get_var_offsets(self):
"""
Compute global offsets for variables.
Returns
-------
dict
Arrays of global offsets keyed by vec_name and deriv direction.
"""
if self._var_offsets is None:
offsets = self._var_offsets = {}
for type_ in ['input', 'output']:
vsizes = self._var_sizes[type_]
if vsizes.size > 0:
csum = np.empty(vsizes.size, dtype=INT_DTYPE)
csum[0] = 0
csum[1:] = np.cumsum(vsizes)[:-1]
offsets[type_] = csum.reshape(vsizes.shape)
else:
offsets[type_] = np.zeros(0, dtype=INT_DTYPE).reshape((1, 0))
return self._var_offsets
def _get_jac_col_scatter(self):
"""
Return source and target indices for a scatter from output vector to total jacobian column.
If the transfer involves remote or distributed variables, the indices will be global.
Otherwise they will be converted to local.
This is only called on the top level system.
Returns
-------
ndarray
Source indices.
ndarray
Target indices.
int
Size of jacobian column.
bool
True if remote or distributed vars are present.
"""
myrank = self.comm.rank
nranks = self.comm.size
owns = self._owning_rank
abs2idx = self._var_allprocs_abs2idx
abs2meta = self._var_abs2meta['output']
sizes = self._var_sizes['output']
global_offsets = self._get_var_offsets()['output']
oflist = list(self._jac_of_iter())
tsize = oflist[-1][2]
toffset = myrank * tsize
has_dist_data = False
sinds = []
tinds = []
for name, tstart, tend, jinds, dist_sizes in oflist:
vind = abs2idx[name]
if dist_sizes is None:
if name in abs2meta:
owner = myrank
else:
owner = owns[name]
has_dist_data |= nranks > 1
voff = global_offsets[owner, vind]
if jinds is _full_slice:
vsize = sizes[owner, vind]
sinds.append(range(voff, voff + vsize))
else:
sinds.append(jinds + voff)
tinds.append(range(tstart + toffset, tend + toffset))
assert len(sinds[-1]) == len(tinds[-1])
else: # 'name' refers to a distributed variable
has_dist_data |= nranks > 1
dtstart = dtend = tstart
dsstart = dsend = 0
for rnk, sz in enumerate(dist_sizes):
dsend += sz
if sz > 0:
voff = global_offsets[rnk, vind]
if jinds is _full_slice:
dtend += sz
sinds.append(range(voff, voff + sz))
tinds.append(range(toffset + dtstart, toffset + dtend))
elif jinds.size > 0: # jinds is a flat array
subinds = jinds[jinds >= dsstart]
subinds = subinds[subinds < dsend]
if subinds.size > 0:
dtend += subinds.size
sinds.append(subinds + (voff - dsstart))
tinds.append(range(toffset + dtstart, toffset + dtend))
dtstart = dtend
dsstart = dsend