/
group.py
3039 lines (2587 loc) · 133 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 os
from collections import Counter, OrderedDict, defaultdict
from collections.abc import Iterable
from itertools import product, chain
from numbers import Number
import inspect
from fnmatch import fnmatchcase
import copy
import numpy as np
import networkx as nx
from openmdao.jacobians.dictionary_jacobian import DictionaryJacobian
from openmdao.core.system import System, INT_DTYPE
from openmdao.core.component import Component, _DictValues, _full_slice
from openmdao.core.constants import _UNDEFINED
from openmdao.proc_allocators.default_allocator import DefaultAllocator, ProcAllocationError
from openmdao.jacobians.jacobian import SUBJAC_META_DEFAULTS
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.utils.array_utils import convert_neg, array_connection_compatible, \
_flatten_src_indices
from openmdao.utils.general_utils import ContainsAll, all_ancestors, simple_warning, \
common_subpath, conditional_error, _is_slicer_op, _slice_indices
from openmdao.utils.units import is_compatible, unit_conversion, _has_val_mismatch
from openmdao.utils.mpi import MPI, check_mpi_exceptions, multi_proc_exception_check
from openmdao.utils.coloring import Coloring, _STD_COLORING_FNAME
import openmdao.utils.coloring as coloring_mod
from openmdao.core.constants import _SetupStatus
# regex to check for valid names.
import re
namecheck_rgx = re.compile('[a-zA-Z][_a-zA-Z0-9]*')
class Group(System):
"""
Class used to group systems together; instantiate or inherit.
Attributes
----------
_mpi_proc_allocator : ProcAllocator
Object used to allocate MPI processes to subsystems.
_proc_info : dict of subsys_name: (min_procs, max_procs, weight)
Information used to determine MPI process allocation to subsystems.
_subgroups_myproc : list
List of local subgroups.
_subsystems_proc_range : (int, int)
List of ranges of each myproc subsystem's processors relative to those of this system.
_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 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 the vec_name, second key is (mode, isub) where
mode is 'fwd' or 'rev' and isub is the subsystem index among allprocs subsystems
or isub 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.
_loc_subsys_map : dict
Mapping of local subsystem names to their corresponding System.
_approx_subjac_keys : list
List of subjacobian keys used for approximated derivatives.
_setup_procs_finished : bool
Flag to check if setup_procs is complete
_has_distrib_vars : bool
If True, this Group contains distributed variables. Only used to determine if a parallel
group or distributed component is below a DirectSolver so that we can raise an exception.
_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.
_raise_connection_errors : bool
Flag indicating whether connection errors are raised as an Exception.
_order_set : bool
Flag to check if set_order has been called.
"""
def __init__(self, **kwargs):
"""
Set the solvers to nonlinear and linear block Gauss--Seidel by default.
Parameters
----------
**kwargs : dict
dict of arguments available here and in all descendants of this
Group.
"""
self._mpi_proc_allocator = DefaultAllocator()
self._proc_info = {}
super(Group, self).__init__(**kwargs)
self._subgroups_myproc = None
self._subsystems_proc_range = []
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._approx_subjac_keys = None
self._setup_procs_finished = False
self._has_distrib_vars = False
self._contains_parallel_group = False
self._raise_connection_errors = True
self._order_set = False
# 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()
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):
"""
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.
"""
meta = {'prom': name}
if val is not _UNDEFINED:
meta['value'] = val
if units is not None:
meta['units'] = units
if self._static_mode:
dct = self._static_group_inputs
else:
dct = self._group_inputs
if name in dct:
old = dct[name][0]
overlap = sorted(set(old).intersection(meta))
if overlap:
simple_warning(f"{self.msginfo}: Setting input defaults for input '{name}' which "
f"override previously set defaults for {overlap}.")
old.update(meta)
else:
dct[name] = [meta]
def _get_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.
"""
try:
return self._scope_cache[excl_sub]
except KeyError:
pass
if excl_sub is None:
# All outputs
scope_out = frozenset(self._var_allprocs_abs_names['output'])
# All inputs connected to an output in this system
scope_in = frozenset(self._conn_global_abs_in2out).intersection(
self._var_allprocs_abs_names['input'])
else:
# Empty for the excl_sub
scope_out = frozenset()
# All inputs connected to an output in this system but not in excl_sub
scope_in = set()
for abs_in in self._var_allprocs_abs_names['input']:
if abs_in in self._conn_global_abs_in2out:
abs_out = self._conn_global_abs_in2out[abs_in]
if abs_out not in excl_sub._var_allprocs_abs2idx['linear']:
scope_in.add(abs_in)
scope_in = frozenset(scope_in)
self._scope_cache[excl_sub] = (scope_out, scope_in)
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.
"""
scale_factors = super(Group, self)._compute_root_scale_factors()
if self._has_input_scaling:
abs2meta_in = self._var_abs2meta
allprocs_meta_out = self._var_allprocs_abs2meta
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.isscalar(ref) and np.isscalar(ref0)):
# 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 src_indices.ndim != 1:
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
else:
factor, offset = unit_conversion(units_out, units_in)
a0 = (ref0 + offset) * factor
a1 = (ref - ref0) * factor
scale_factors[abs_in] = {
('input', 'phys'): (a0, a1),
('input', 'norm'): (-a0 / a1, 1.0 / a1)
}
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()
for subsys in self._subsystems_myproc:
subsys._configure()
subsys._setup_var_data()
self._has_guess |= subsys._has_guess
self._has_bounds |= subsys._has_bounds
self.matrix_free |= subsys.matrix_free
conf_info = self._problem_meta['config_info']
conf_info._reset()
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).
for s in conf_info._modified_system_iter(self):
s._setup_var_data()
def _setup_procs(self, pathname, comm, mode, 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.
mode : string
Derivatives calculation mode, 'fwd' for forward, and 'rev' for
reverse (adjoint). Default is 'rev'.
prob_meta : dict
Problem level metadata.
"""
super(Group, self)._setup_procs(pathname, comm, mode, prob_meta)
self._setup_procs_finished = False
self._vectors = {}
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 = ("%s: MPI is not active but num_par_fd = %d. No parallel finite difference "
"will be performed." % (self.msginfo, self._num_par_fd))
simple_warning(msg)
self.comm = comm
self._approx_subjac_keys = None
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()
# 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:
proc_info = [self._proc_info[s.name] for s in self._subsystems_allprocs]
# Call the load balancing algorithm
try:
sub_inds, sub_comm, sub_proc_range = self._mpi_proc_allocator(
proc_info, len(self._subsystems_allprocs), comm)
except ProcAllocationError as err:
subs = self._subsystems_allprocs
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,
[subs[i].name for i in err.sub_inds]))
self._subsystems_myproc = [self._subsystems_allprocs[ind] for ind in sub_inds]
# Define local subsystems
if 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 rank, inds in enumerate(gathered):
for ind in inds:
if ind not in seen:
new_allsubs.append(self._subsystems_allprocs[ind])
seen.add(ind)
self._subsystems_allprocs = new_allsubs
else:
sub_comm = comm
self._subsystems_myproc = self._subsystems_allprocs
sub_proc_range = (0, 1)
# Compute _subsystems_proc_range
self._subsystems_proc_range = [sub_proc_range] * len(self._subsystems_myproc)
self._subsystems_inds = inds = {}
# need to set pathname correctly even for non-local subsystems
for i, s in enumerate(self._subsystems_allprocs):
inds[s.name] = i
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, mode, 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)]
self._loc_subsys_map = {s.name: s for s in self._subsystems_myproc}
if MPI and nproc > 1:
if 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(Group, self)._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._subsystems_myproc:
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:
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 _get_all_promotes(self, remote_systems):
"""
Create the top level mapping of all promoted names to absolute names.
This includes all buried promoted names.
Parameters
----------
remote_systems : dict
Mapping of system pathname to owning rank. Includes only systems that are
remote in at least one MPI process.
Returns
-------
dict
Mapping of all promoted names to absolute names.
"""
myrank = self.comm.rank
mysys = set(n for n, rank in remote_systems.items() if rank == myrank)
iotypes = ('input', 'output')
if self.comm.size > 1:
prom2abs = {'input': defaultdict(set), 'output': defaultdict(set)}
for s in self.system_iter(recurse=True):
if s.pathname in mysys: # we 'own' this system
prefix = s.pathname + '.' if s.pathname else ''
for typ in iotypes:
# use abs2prom to determine locality since prom2abs is for allprocs
sys_abs2prom = s._var_abs2prom[typ]
t_prom2abs = prom2abs[typ]
for prom, alist in s._var_allprocs_prom2abs_list[typ].items():
t_prom2abs[prefix + prom].update(n for n in alist if n in sys_abs2prom)
all_proms = self.comm.gather(prom2abs, root=0)
if myrank == 0:
prom2abs = {'input': defaultdict(list), 'output': defaultdict(list)}
for typ in iotypes:
t_prom2abs = prom2abs[typ]
for rankproms in all_proms:
for prom, absnames in rankproms[typ].items():
t_prom2abs[prom].extend(absnames)
t_prom2abs = prom2abs['input']
for prom, absnames in t_prom2abs.items():
t_prom2abs[prom] = sorted(absnames) # sort to keep order the same on all procs
self.comm.bcast(prom2abs, root=0)
else:
prom2abs = self.comm.bcast(prom2abs, root=0)
else: # serial
prom2abs = {'input': defaultdict(list), 'output': defaultdict(list)}
for s in self.system_iter(recurse=True):
prefix = s.pathname + '.' if s.pathname else ''
for typ in iotypes:
t_prom2abs = prom2abs[typ]
for prom, abslist in s._var_allprocs_prom2abs_list[typ].items():
t_prom2abs[prefix + prom] = abslist
return prom2abs
def _top_level_setup(self, mode):
self._problem_meta['connections'] = conns = self._conn_global_abs_in2out
self._problem_meta['all_meta'] = self._var_allprocs_abs2meta
self._problem_meta['meta'] = self._var_abs2meta
rsystems = self._find_remote_sys_owners()
self._problem_meta['remote_vars'] = self._find_remote_var_owners(rsystems)
self._problem_meta['prom2abs'] = self._get_all_promotes(rsystems)
self._resolve_group_input_defaults()
auto_ivc = self._setup_auto_ivcs(mode)
self._check_prom_masking()
def _check_prom_masking(self):
"""
Raise exception if any promoted variable name masks an absolute variable name.
"""
prom2abs_in = self._var_allprocs_prom2abs_list['input']
prom2abs_out = self._var_allprocs_prom2abs_list['output']
abs2meta = self._problem_meta['all_meta']
for absname in abs2meta:
if absname in prom2abs_in:
for name in prom2abs_in[absname]:
if name != absname:
raise RuntimeError(f"{self.msginfo}: Absolute variable name '{absname}'"
" is masked by a matching promoted name. Try"
" promoting to a different name. This can be caused"
" by promoting '*' at group level or promoting using"
" dotted names.")
elif absname in prom2abs_out:
if absname != prom2abs_out[absname][0]:
raise RuntimeError(f"{self.msginfo}: Absolute variable name '{absname}' is"
" masked by a matching promoted name. Try"
" promoting to a different name. This can be caused"
" by promoting '*' at group level or promoting using"
" dotted names.")
def _top_level_setup2(self):
self._resolve_ambiguous_input_meta()
if self.comm.size > 1:
abs2meta = self._var_abs2meta
abs2idx = self._var_allprocs_abs2idx['nonlinear']
all_abs2meta = self._var_allprocs_abs2meta
conns = self._conn_global_abs_in2out
# the code below is to handle the case where src_indices were not specified
# for a distributed input. This update can't happen until sizes are known.
dist_ins = [n for n in self._var_allprocs_abs_names['input']
if all_abs2meta[n]['distributed']]
dcomp_names = set(d.rsplit('.', 1)[0] for d in dist_ins)
if dcomp_names:
added_src_inds = set()
for comp in self.system_iter(recurse=True, typ=Component):
if comp.pathname in dcomp_names:
added_src_inds.update(
comp._update_dist_src_indices(conns, all_abs2meta, abs2idx,
self._var_sizes))
all_added = set()
for a in self.comm.allgather(added_src_inds):
all_added.update(a)
for a in all_added:
all_abs2meta[a]['has_src_indices'] = True
if a in conns:
src = conns[a]
if src.startswith('_auto_ivc.'):
all_abs2meta[src]['distributed'] = True
def _setup_var_index_ranges(self):
"""
Compute the division of variables by subsystem.
"""
nsub_allprocs = len(self._subsystems_allprocs)
subsystems_var_range = self._subsystems_var_range = {}
vec_names = self._lin_rel_vec_name_list if self._use_derivatives else self._vec_names
# First compute these on one processor for each subsystem
for vec_name in vec_names:
# Here, we count the number of variables in each subsystem.
# We do this so that we can compute the offset when we recurse into each subsystem.
allprocs_counters = {}
for type_ in ['input', 'output']:
allprocs_counters[type_] = np.zeros(nsub_allprocs, INT_DTYPE)
for subsys in self._subsystems_myproc:
if vec_name in subsys._rel_vec_names:
comm = subsys.comm if subsys._full_comm is None else subsys._full_comm
if comm.rank == 0:
isub = self._subsystems_inds[subsys.name]
allprocs_counters[type_][isub] = \
len(subsys._var_allprocs_relevant_names[vec_name][type_])
# If running in parallel, allgather
if self.comm.size > 1:
gathered = self.comm.allgather(allprocs_counters)
allprocs_counters = {
type_: np.zeros(nsub_allprocs, INT_DTYPE) for type_ in ['input', 'output']
}
for myproc_counters in gathered:
for type_ in ['input', 'output']:
allprocs_counters[type_] += myproc_counters[type_]
# Compute _subsystems_var_range
subsystems_var_range[vec_name] = {}
for type_ in ['input', 'output']:
subsystems_var_range[vec_name][type_] = {}
for subsys in self._subsystems_myproc:
if vec_name not in subsys._rel_vec_names:
continue
isub = self._subsystems_inds[subsys.name]
start = np.sum(allprocs_counters[type_][:isub])
subsystems_var_range[vec_name][type_][subsys.name] = (
start, start + allprocs_counters[type_][isub]
)
if self._use_derivatives:
subsystems_var_range['nonlinear'] = subsystems_var_range['linear']
self._setup_var_index_maps()
for subsys in self._subsystems_myproc:
subsys._setup_var_index_ranges()
def _setup_var_data(self):
"""
Compute the list of abs var names, abs/prom name maps, and metadata dictionaries.
"""
if self._var_allprocs_prom2abs_list is None:
old_prom2abs = {}
else:
old_prom2abs = self._var_allprocs_prom2abs_list['input']
super(Group, self)._setup_var_data()
abs_names = self._var_abs_names
abs_names_discrete = self._var_abs_names_discrete
allprocs_abs_names = self._var_allprocs_abs_names
allprocs_abs_names_discrete = self._var_allprocs_abs_names_discrete
var_discrete = self._var_discrete
allprocs_discrete = self._var_allprocs_discrete
abs2meta = self._var_abs2meta
abs2prom = self._var_abs2prom
allprocs_abs2meta = self._var_allprocs_abs2meta
allprocs_abs2prom = self._var_allprocs_abs2prom
allprocs_prom2abs_list = self._var_allprocs_prom2abs_list
gatherable = self._gatherable_vars
for n, lst in self._group_inputs.items():
lst[0]['path'] = self.pathname # used for error reporting
self._group_inputs[n] = lst.copy() # must copy the list manually
for subsys in self._subsystems_myproc:
self._has_output_scaling |= subsys._has_output_scaling
self._has_resid_scaling |= subsys._has_resid_scaling
var_maps = subsys._get_maps(subsys._var_allprocs_prom2abs_list)
# Assemble allprocs_abs2meta and abs2meta
allprocs_abs2meta.update(subsys._var_allprocs_abs2meta)
abs2meta.update(subsys._var_abs2meta)
gatherable.update(subsys._gatherable_vars)
sub_prefix = subsys.name + '.'
for type_ in ['input', 'output']:
subprom2prom = var_maps[type_]
# Assemble abs_names and allprocs_abs_names
allprocs_abs_names[type_].extend(
subsys._var_allprocs_abs_names[type_])
allprocs_abs_names_discrete[type_].extend(
subsys._var_allprocs_abs_names_discrete[type_])
abs_names[type_].extend(subsys._var_abs_names[type_])
abs_names_discrete[type_].extend(subsys._var_abs_names_discrete[type_])
allprocs_discrete[type_].update(subsys._var_allprocs_discrete[type_])
var_discrete[type_].update({sub_prefix + k: v for k, v in
subsys._var_discrete[type_].items()})
# Assemble allprocs_prom2abs_list and abs2prom
sub_loc_proms = subsys._var_abs2prom[type_]
for sub_prom, sub_abs in subsys._var_allprocs_prom2abs_list[type_].items():
prom_name = subprom2prom[sub_prom]
if prom_name not in allprocs_prom2abs_list[type_]:
allprocs_prom2abs_list[type_][prom_name] = []
allprocs_prom2abs_list[type_][prom_name].extend(sub_abs)
for abs_name in sub_abs:
if abs_name in sub_loc_proms:
abs2prom[type_][abs_name] = prom_name
allprocs_abs2prom[type_][abs_name] = prom_name
if isinstance(subsys, Group):
subprom2prom = var_maps['input']
for sub_prom, metalist in subsys._group_inputs.items():
key = subprom2prom[sub_prom]
if key not in self._group_inputs:
self._group_inputs[key] = []
self._group_inputs[key].extend(metalist)
# If running in parallel, allgather
if self.comm.size > 1 and self._mpi_proc_allocator.parallel:
mysub = self._subsystems_myproc[0] if self._subsystems_myproc else False
if (mysub and mysub.comm.rank == 0 and (mysub._full_comm is None or
mysub._full_comm.rank == 0)):
raw = (allprocs_abs_names, allprocs_abs_names_discrete, allprocs_discrete,
allprocs_prom2abs_list, allprocs_abs2prom, allprocs_abs2meta,
self._has_output_scaling, self._has_resid_scaling, self._group_inputs)
else:
raw = (
{'input': [], 'output': []},
{'input': [], 'output': []},
{'input': {}, 'output': {}},
{'input': {}, 'output': {}},
{'input': {}, 'output': {}},
{},
False,
False,
{}
)
gathered = self.comm.allgather(raw)
for type_ in ['input', 'output']:
allprocs_abs_names[type_] = []
allprocs_abs_names_discrete[type_] = []
allprocs_abs2prom[type_] = {}
allprocs_prom2abs_list[type_] = OrderedDict()
myrank = self.comm.rank
for rank, (myproc_abs_names, myproc_abs_names_discrete, myproc_discrete,
myproc_prom2abs_list, all_abs2prom, myproc_abs2meta, oscale,
rscale, ginputs) in enumerate(gathered):
self._has_output_scaling |= oscale
self._has_resid_scaling |= rscale
if rank != myrank:
for p, mlist in ginputs.items():
if p not in self._group_inputs:
self._group_inputs[p] = []
self._group_inputs[p].extend(mlist)
# Assemble in parallel allprocs_abs2meta
for n in myproc_abs2meta:
if n not in allprocs_abs2meta:
allprocs_abs2meta[n] = myproc_abs2meta[n]
for type_ in ['input', 'output']:
# Assemble in parallel allprocs_abs_names
allprocs_abs_names[type_].extend(myproc_abs_names[type_])
allprocs_abs_names_discrete[type_].extend(myproc_abs_names_discrete[type_])
allprocs_discrete[type_].update(myproc_discrete[type_])
allprocs_abs2prom[type_].update(all_abs2prom[type_])
# Assemble in parallel allprocs_prom2abs_list
for prom_name, abs_names_list in myproc_prom2abs_list[type_].items():
if prom_name not in allprocs_prom2abs_list[type_]:
allprocs_prom2abs_list[type_][prom_name] = []
allprocs_prom2abs_list[type_][prom_name].extend(abs_names_list)
# determine 'gatherable' vars, i.e., vars that are remote somewhere in the comm
locs = {}
locs_disc = {}
for type_ in ('input', 'output'):
locs[type_] = np.array([n in abs2meta and abs2meta[n]['size'] > 0
for n in allprocs_abs_names[type_]], dtype=bool)
locs_disc[type_] = np.array([
n in abs2prom[type_] for n in allprocs_abs_names_discrete[type_]
], dtype=bool)
raw_locs = (locs, locs_disc)
allprocs_raw_locs = self.comm.allgather(raw_locs)
for type_ in ('input', 'output'):
all_locs = np.ones(len(allprocs_abs_names[type_]), dtype=bool)
all_locs_disc = np.ones(len(allprocs_abs_names_discrete[type_]), dtype=bool)
for rank, (loc, loc_disc) in enumerate(allprocs_raw_locs):
all_locs &= loc[type_]
all_locs_disc &= loc_disc[type_]
for i, n in enumerate(allprocs_abs_names[type_]):
if not all_locs[i]:
gatherable.add(n)
for i, n in enumerate(allprocs_abs_names_discrete[type_]):
if not all_locs_disc[i]:
gatherable.add(n)
for prom_name, abs_list in allprocs_prom2abs_list['output'].items():
if len(abs_list) > 1:
raise RuntimeError("{}: Output name '{}' refers to "
"multiple outputs: {}.".format(self.msginfo, prom_name,
sorted(abs_list)))
if self._group_inputs:
p2abs_in = self._var_allprocs_prom2abs_list['input']
extra = [gin for gin in self._group_inputs if gin not in p2abs_in]
if extra:
# make sure that we don't have a leftover group input default entry from a previous
# execution of _setup_var_data before promoted names were updated.
ex = set()
for e in extra:
if e in old_prom2abs:
del self._group_inputs[e] # clean up old key using old promoted name
else:
ex.add(e)
if ex:
raise RuntimeError(f"{self.msginfo}: The following group inputs, passed to "
f"set_input_defaults(), could not be found: {sorted(ex)}.")
if self._var_discrete['input'] or self._var_discrete['output']:
self._discrete_inputs = _DictValues(self._var_discrete['input'])
self._discrete_outputs = _DictValues(self._var_discrete['output'])
else:
self._discrete_inputs = self._discrete_outputs = ()
def _resolve_group_input_defaults(self):
"""
Resolve any ambiguities in group input defaults throughout the model.
"""
skip = set(('path', 'use_tgt', 'prom'))
prom2abs_in = self._var_allprocs_prom2abs_list['input']
for prom, metalist in self._group_inputs.items():
top_origin = metalist[0]['path']
top_prom = metalist[0]['prom']
allmeta = set()
for meta in metalist:
allmeta.update(meta)
fullmeta = {n: _UNDEFINED for n in allmeta - skip}
for key in sorted(fullmeta):
for i, submeta in enumerate(metalist):
if key in submeta:
if fullmeta[key] is _UNDEFINED:
origin = submeta['path']
origin_prom = submeta['prom']
val = fullmeta[key] = submeta[key]
if origin != top_origin:
simple_warning(f"Group '{top_origin}' did not set a default "
f"'{key}' for input '{top_prom}', so the value of "
f"({val}) from group '{origin}' will be used.")
else:
eq = submeta[key] == val
if isinstance(eq, np.ndarray):
eq = np.all(eq)
if not eq:
# first, see if origin is an ancestor
if not origin or submeta['path'].startswith(origin + '.'):
simple_warning(f"Groups '{origin}' and '{submeta['path']}' "
f"called set_input_defaults for the input "
f"'{origin_prom}' with conflicting '{key}'. "
f"The value ({val}) from '{origin}' will be "
"used.")
else: # origin is not an ancestor, so we have an ambiguity
if origin_prom != submeta['prom']:
prm = f"('{origin_prom}' / '{submeta['prom']}')"
else:
prm = f"'{origin_prom}'"
common = common_subpath((origin, submeta['path']))
if common:
sub = self._get_subsystem(common)
if sub is not None:
for a in prom2abs_in[prom]:
if a in sub._var_abs2prom['input']:
prom = sub._var_abs2prom['input'][a]
break
gname = f"Group named '{common}'" if common else 'model'
conditional_error(f"{self.msginfo}: The subsystems {origin} "
f"and {submeta['path']} called "
f"set_input_defaults for promoted input "
f"{prm} with conflicting values for "
f"'{key}'. Call <group>.set_input_defaults("
f"'{prom}', {key}=?), where <group> is the "
f"{gname} to remove the ambiguity.")
# update all metadata dicts with any missing metadata that was filled in elsewhere
for meta in metalist:
meta.update(fullmeta)
def _setup_var_sizes(self):
"""
Compute the arrays of local variable sizes for all variables/procs on this system.
"""
super(Group, self)._setup_var_sizes()
self._var_offsets = None
iproc = self.comm.rank
nproc = self.comm.size