/
system.py
2957 lines (2520 loc) · 115 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
"""Define the base System class."""
from __future__ import division
from contextlib import contextmanager
from collections import OrderedDict, Iterable, defaultdict
from fnmatch import fnmatchcase
import sys
from numbers import Integral
from six import iteritems, string_types
import numpy as np
import openmdao
from openmdao.jacobians.assembled_jacobian import DenseJacobian, CSCJacobian
from openmdao.utils.general_utils import determine_adder_scaler, \
format_as_float_or_array, warn_deprecation, ContainsAll
from openmdao.recorders.recording_manager import RecordingManager
from openmdao.vectors.vector import INT_DTYPE
from openmdao.utils.mpi import MPI
from openmdao.utils.options_dictionary import OptionsDictionary
from openmdao.utils.record_util import create_local_meta, check_path
from openmdao.utils.write_outputs import write_outputs
from openmdao.utils.array_utils import evenly_distrib_idxs
# Use this as a special value to be able to tell if the caller set a value for the optional
# out_stream argument. We run into problems running testflo if we use a default of sys.stdout.
_DEFAULT_OUT_STREAM = object()
_empty_frozen_set = frozenset()
_asm_jac_types = {
'csc': CSCJacobian,
'dense': DenseJacobian,
}
class System(object):
"""
Base class for all systems in OpenMDAO.
Never instantiated; subclassed by <Group> or <Component>.
All subclasses have their attributes defined here.
In attribute names:
abs / abs_name : absolute, unpromoted variable name, seen from root (unique).
rel / rel_name : relative, unpromoted variable name, seen from current system (unique).
prom / prom_name : relative, promoted variable name, seen from current system (non-unique).
idx : global variable index among variables on all procs (I/O indices separate).
my_idx : index among variables in this system, on this processor (I/O indices separate).
io : indicates explicitly that input and output variables are combined in the same dict.
Attributes
----------
name : str
Name of the system, must be different from siblings.
pathname : str
Global name of the system, including the path.
comm : MPI.Comm or <FakeComm>
MPI communicator object.
options : OptionsDictionary
options dictionary
recording_options : OptionsDictionary
Recording options dictionary
under_complex_step : bool
When True, this system is undergoing complex step.
force_alloc_complex : bool
When True, the vectors have been allocated for checking with complex step.
iter_count : int
Int that holds the number of times this system has iterated
in a recording run.
cite : str
Listing of relevant citations that should be referenced when
publishing work that uses this class.
_full_comm : MPI.Comm or None
MPI communicator object used when System's comm is split for parallel FD.
_subsystems_allprocs : [<System>, ...]
List of all subsystems (children of this system).
_subsystems_myproc : [<System>, ...]
List of local subsystems that exist on this proc.
_subsystems_myproc_inds : [int, ...]
List of indices of subsystems on this proc among all of this system's subsystems
(i.e. among _subsystems_allprocs).
_subsystems_proc_range : (int, int)
List of ranges of each myproc subsystem's processors relative to those of this system.
_var_promotes : { 'any': [], 'input': [], 'output': [] }
Dictionary of lists of variable names/wildcards specifying promotion
(used to calculate promoted names)
_var_allprocs_abs_names : {'input': [str, ...], 'output': [str, ...]}
List of absolute names of this system's variables on all procs.
_var_abs_names : {'input': [str, ...], 'output': [str, ...]}
List of absolute names of this system's variables existing on current proc.
_var_allprocs_prom2abs_list : {'input': dict, 'output': dict}
Dictionary mapping promoted names to list of all absolute names.
For outputs, the list will have length one since promoted output names are unique.
_var_abs2prom : {'input': dict, 'output': dict}
Dictionary mapping absolute names to promoted names, on current proc.
_var_allprocs_abs2meta : dict
Dictionary mapping absolute names to metadata dictionaries for allprocs variables.
The keys are
('units', 'shape', 'size') for inputs and
('units', 'shape', 'size', 'ref', 'ref0', 'res_ref', 'distributed') for outputs.
_var_abs2meta : dict
Dictionary mapping absolute names to metadata dictionaries for myproc variables.
_var_discrete : dict
Dictionary of discrete var metadata and values local to this process.
_var_allprocs_discrete : dict
Dictionary of discrete var metadata and values for all processes.
_discrete_inputs : dict-like or None
Storage for discrete input values.
_discrete_outputs : dict-like or None
Storage for discrete output values.
_var_allprocs_abs2idx : dict
Dictionary mapping absolute names to their indices among this system's allprocs variables.
Therefore, the indices range from 0 to the total number of this system's variables.
_var_sizes : {'input': ndarray, 'output': ndarray}
Array of local sizes of this system's allprocs variables.
The array has size nproc x num_var where nproc is the number of processors
owned by this system and num_var is the number of allprocs variables.
_var_offsets : {'input': dict of ndarray, 'output': dict of ndarray} or None
Dict of distributed offsets, keyed by var name. Offsets are stored in an array
of size nproc x num_var where nproc is the number of processors
in this System's communicator and num_var is the number of allprocs variables
in the given system. This is only defined in a Group that owns one or more interprocess
connections or a top level Group or System that is used to compute total derivatives
across multiple processes.
_ext_num_vars : {'input': (int, int), 'output': (int, int)}
Total number of allprocs variables in system before/after this one.
_ext_sizes : {'input': (int, int), 'output': (int, int)}
Total size of allprocs variables in system before/after this one.
_vec_names : [str, ...]
List of names of all vectors, including the nonlinear vector.
_lin_vec_names : [str, ...]
List of names of the linear vectors (i.e., the right-hand sides).
_vectors : {'input': dict, 'output': dict, 'residual': dict}
Dictionaries of vectors keyed by vec_name.
_inputs : <Vector>
The inputs vector; points to _vectors['input']['nonlinear'].
_outputs : <Vector>
The outputs vector; points to _vectors['output']['nonlinear'].
_residuals : <Vector>
The residuals vector; points to _vectors['residual']['nonlinear'].
_lower_bounds : <Vector>
Vector of lower bounds, scaled and dimensionless.
_upper_bounds : <Vector>
Vector of upper bounds, scaled and dimensionless.
_nonlinear_solver : <NonlinearSolver>
Nonlinear solver to be used for solve_nonlinear.
_linear_solver : <LinearSolver>
Linear solver to be used for solve_linear; not the Newton system.
_solver_info : SolverInfo
A stack-like object shared by all Solvers in the model.
_approx_schemes : OrderedDict
A mapping of approximation types to the associated ApproximationScheme.
_jacobian : <Jacobian>
<Jacobian> object to be used in apply_linear.
_owns_approx_jac : bool
If True, this system approximated its Jacobian
_owns_approx_jac_meta : dict
Stores approximation metadata (e.g., step_size) from calls to approx_totals
_owns_approx_of : set or None
Overrides aproximation outputs. This is set when calculating system derivatives, and serves
as a way to communicate the driver's output quantities to the approximation objects so that
we only take derivatives of variables that the driver needs.
_owns_approx_of_idx : dict
Index for override 'of' approximations if declared. When the user calls `add_objective`
or `add_constraint`, they may optionally specify an "indices" argument. This argument must
also be communicated to the approximations when they are set up so that 1) the Jacobian is
the correct size, and 2) we don't perform any extra unnecessary calculations.
_owns_approx_wrt : set or None
Overrides aproximation inputs. This is set when calculating system derivatives, and serves
as a way to communicate the driver's input quantities to the approximation objects so that
we only take derivatives with respect to variables that the driver needs.
_owns_approx_wrt_idx : dict
Index for override 'wrt' approximations if declared. When the user calls `add_designvar`
they may optionally specify an "indices" argument. This argument must also be communicated
to the approximations when they are set up so that 1) the Jacobian is the correct size, and
2) we don't perform any extra unnecessary calculations.
_subjacs_info : dict of dict
Sub-jacobian metadata for each (output, input) pair added using
declare_partials. Members of each pair may be glob patterns.
_design_vars : dict of dict
dict of all driver design vars added to the system.
_responses : dict of dict
dict of all driver responses added to the system.
_rec_mgr : <RecordingManager>
object that manages all recorders added to this system.
_static_mode : bool
If true, we are outside of setup.
In this case, add_input, add_output, and add_subsystem all add to the
'_static' versions of the respective data structures.
These data structures are never reset during reconfiguration.
_static_subsystems_allprocs : [<System>, ...]
List of subsystems that stores all subsystems added outside of setup.
_static_design_vars : dict of dict
Driver design variables added outside of setup.
_static_responses : dict of dict
Driver responses added outside of setup.
_reconfigured : bool
If True, this system has reconfigured, and the immediate parent should update.
supports_multivecs : bool
If True, this system overrides compute_multi_jacvec_product (if an ExplicitComponent),
or solve_multi_linear/apply_multi_linear (if an ImplicitComponent).
matrix_free : Bool
This is set to True if the component overrides the appropriate function with a user-defined
matrix vector product with the Jacobian or any of its subsystems do.
_relevant : dict
Mapping of a VOI to a tuple containing dependent inputs, dependent outputs,
and dependent systems.
_vois : dict
Either design vars or responses metadata, depending on the direction of
derivatives.
_mode : str
Indicates derivative direction for the model, either 'fwd' or 'rev'.
_scope_cache : dict
Cache for variables in the scope of various mat-vec products.
_has_guess : bool
True if this system has or contains a system with a `guess_nonlinear` method defined.
_has_output_scaling : bool
True if this system has output scaling.
_has_resid_scaling : bool
True if this system has resid scaling.
_has_input_scaling : bool
True if this system has input scaling.
_owning_rank : dict
Dict mapping var name to the lowest rank where that variable is local.
_filtered_vars_to_record: Dict
Dict of list of var names to record
_vector_class : class
Class to use for data vectors. After setup will contain the value of either
_distributed_vector_class or _local_vector_class.
_distributed_vector_class : class
Class to use for distributed data vectors.
_local_vector_class : class
Class to use for local data vectors.
_assembled_jac : AssembledJacobian or None
If not None, this is the AssembledJacobian owned by this system's linear_solver.
_num_par_fd : int
If FD is active, and the value is > 1, turns on parallel FD and specifies the number of
concurrent FD solves.
_par_fd_id : int
ID used to determine which columns in the jacobian will be computed when using parallel FD.
_use_derivatives : bool
If True, perform any memory allocations necessary for derivative computation.
"""
def __init__(self, num_par_fd=1, **kwargs):
"""
Initialize all attributes.
Parameters
----------
num_par_fd : int
If FD is active, number of concurrent FD solves.
**kwargs : dict of keyword arguments
Keyword arguments that will be mapped into the System options.
"""
self.name = ''
self.pathname = ''
self.comm = None
# System options
self.options = OptionsDictionary()
self.options.declare('assembled_jac_type', values=['csc', 'dense'], default='csc',
desc='Linear solver(s) in this group, if using an assembled '
'jacobian, will use this type.')
# Case recording options
self.recording_options = OptionsDictionary()
self.recording_options.declare('record_inputs', types=bool, default=True,
desc='Set to True to record inputs at the system level')
self.recording_options.declare('record_outputs', types=bool, default=True,
desc='Set to True to record outputs at the system level')
self.recording_options.declare('record_residuals', types=bool, default=True,
desc='Set to True to record residuals at the system level')
self.recording_options.declare('record_metadata', types=bool,
desc='Record metadata for this system', default=True)
self.recording_options.declare('record_model_metadata', types=bool,
desc='Record metadata for all sub systems in the model',
default=True)
self.recording_options.declare('includes', types=list, default=['*'],
desc='Patterns for variables to include in recording')
self.recording_options.declare('excludes', types=list, default=[],
desc='Patterns for vars to exclude in recording '
'(processed post-includes)')
self.recording_options.declare('options_excludes', types=list, default=[],
desc='User-defined metadata to exclude in recording')
# Case recording related
self.iter_count = 0
self.cite = ""
self._subsystems_allprocs = []
self._subsystems_myproc = []
self._subsystems_myproc_inds = []
self._subsystems_proc_range = []
self._var_promotes = {'input': [], 'output': [], 'any': []}
self._var_allprocs_abs_names = {'input': [], 'output': []}
self._var_abs_names = {'input': [], 'output': []}
self._var_allprocs_prom2abs_list = None
self._var_abs2prom = {'input': {}, 'output': {}}
self._var_allprocs_abs2meta = {}
self._var_abs2meta = {}
self._var_discrete = {'input': {}, 'output': {}}
self._var_allprocs_discrete = {'input': {}, 'output': {}}
self._var_allprocs_abs2idx = {}
self._var_sizes = None
self._var_offsets = None
self._full_comm = None
self._ext_num_vars = {'input': (0, 0), 'output': (0, 0)}
self._ext_sizes = {'input': (0, 0), 'output': (0, 0)}
self._vectors = {'input': {}, 'output': {}, 'residual': {}}
self._inputs = None
self._outputs = None
self._residuals = None
self._lower_bounds = None
self._upper_bounds = None
self._nonlinear_solver = None
self._linear_solver = None
self._jacobian = None
self._approx_schemes = OrderedDict()
self._subjacs_info = {}
self.matrix_free = False
self._owns_approx_jac = False
self._owns_approx_jac_meta = {}
self._owns_approx_wrt = None
self._owns_approx_of = None
self._owns_approx_wrt_idx = {}
self._owns_approx_of_idx = {}
self.under_complex_step = False
self.force_alloc_complex = False
self._design_vars = OrderedDict()
self._responses = OrderedDict()
self._rec_mgr = RecordingManager()
self._static_mode = True
self._static_subsystems_allprocs = []
self._static_design_vars = OrderedDict()
self._static_responses = OrderedDict()
self._reconfigured = False
self.supports_multivecs = False
self._relevant = None
self._vec_names = None
self._vois = None
self._mode = None
self._scope_cache = {}
self._num_par_fd = num_par_fd
self._declare_options()
self.initialize()
self.options.update(kwargs)
self._has_guess = False
self._has_output_scaling = False
self._has_resid_scaling = False
self._has_input_scaling = False
self._vector_class = None
self._local_vector_class = None
self._distributed_vector_class = None
self._use_derivatives = True
self._assembled_jac = None
self._par_fd_id = 0
self._filtered_vars_to_record = {}
self._owning_rank = {}
self._lin_vec_names = []
def _declare_options(self):
"""
Declare options before kwargs are processed in the init method.
This is optionally implemented by subclasses of Component or Group
that themselves are intended to be subclassed by the end user. The
options of the intermediate class are declared here leaving the
`initialize` method available for user-defined options.
"""
pass
def _check_reconf(self):
"""
Check if this systems wants to reconfigure and if so, perform the reconfiguration.
"""
reconf = self.reconfigure()
if reconf:
with self._unscaled_context_all():
# Backup input values
old = {'input': self._inputs, 'output': self._outputs}
# Perform reconfiguration
self.resetup('reconf')
new = {'input': self._inputs, 'output': self._outputs}
# Reload input and output values where possible
for type_ in ['input', 'output']:
for abs_name, old_view in iteritems(old[type_]._views_flat):
if abs_name in new[type_]._views_flat:
new_view = new[type_]._views_flat[abs_name]
if len(old_view) == len(new_view):
new_view[:] = old_view
self._reconfigured = True
def _check_reconf_update(self):
"""
Check if any subsystem has reconfigured and if so, perform the necessary update setup.
"""
self._reconfigured = False
def reconfigure(self):
"""
Perform reconfiguration.
Returns
-------
bool
If True, reconfiguration is to be performed.
"""
return False
def initialize(self):
"""
Perform any one-time initialization run at instantiation.
"""
pass
def _configure(self):
"""
Configure this system to assign children settings.
"""
pass
def _get_initial_global(self, initial):
"""
Get initial values for _ext_num_vars, _ext_sizes.
Parameters
----------
initial : bool
Whether we are reconfiguring - i.e., the model has been previously setup.
Returns
-------
_ext_num_vars : {'input': (int, int), 'output': (int, int)}
Total number of allprocs variables in system before/after this one.
_ext_sizes : {'input': (int, int), 'output': (int, int)}
Total size of allprocs variables in system before/after this one.
"""
if not initial:
return (self._ext_num_vars, self._ext_sizes)
else:
ext_num_vars = {}
ext_sizes = {}
vec_names = self._lin_rel_vec_name_list if self._use_derivatives else self._vec_names
for vec_name in vec_names:
ext_num_vars[vec_name] = {}
ext_sizes[vec_name] = {}
for type_ in ['input', 'output']:
ext_num_vars[vec_name][type_] = (0, 0)
ext_sizes[vec_name][type_] = (0, 0)
if self._use_derivatives:
ext_num_vars['nonlinear'] = ext_num_vars['linear']
ext_sizes['nonlinear'] = ext_sizes['linear']
return ext_num_vars, ext_sizes
def _get_root_vectors(self, initial, force_alloc_complex=False):
"""
Get the root vectors for the nonlinear and linear vectors for the model.
Parameters
----------
initial : bool
Whether we are reconfiguring - i.e., whether the model has been previously setup.
force_alloc_complex : bool
Force allocation of imaginary part in nonlinear vectors. OpenMDAO can generally
detect when you need to do this, but in some cases (e.g., complex step is used
after a reconfiguration) you may need to set this to True.
Returns
-------
dict of dict of Vector
Root vectors: first key is 'input', 'output', or 'residual'; second key is vec_name.
"""
# save root vecs as an attribute so that we can reuse the nonlinear scaling vecs in the
# linear root vec
self._root_vecs = root_vectors = {'input': OrderedDict(),
'output': OrderedDict(),
'residual': OrderedDict()}
if initial:
relevant = self._relevant
vec_names = self._rel_vec_name_list if self._use_derivatives else self._vec_names
vois = self._vois
abs2idx = self._var_allprocs_abs2idx
# Check for complex step to set vectors up appropriately.
# If any subsystem needs complex step, then we need to allocate it everywhere.
nl_alloc_complex = force_alloc_complex
for sub in self.system_iter(include_self=True, recurse=True):
nl_alloc_complex |= 'cs' in sub._approx_schemes
if nl_alloc_complex:
break
# Linear vectors allocated complex only if subsolvers require derivatives.
if nl_alloc_complex:
from openmdao.error_checking.check_config import check_allocate_complex_ln
ln_alloc_complex = check_allocate_complex_ln(self, force_alloc_complex)
else:
ln_alloc_complex = False
if self._has_input_scaling or self._has_output_scaling or self._has_resid_scaling:
self._scale_factors = self._compute_root_scale_factors()
else:
self._scale_factors = {}
vector_class = self._vector_class
for vec_name in vec_names:
sizes = self._var_sizes[vec_name]['output']
ncol = 1
rel = None
if vec_name == 'nonlinear':
alloc_complex = nl_alloc_complex
else:
alloc_complex = ln_alloc_complex
if vec_name != 'linear':
voi = vois[vec_name]
if voi['vectorize_derivs']:
if 'size' in voi:
ncol = voi['size']
else:
owner = self._owning_rank[vec_name]
ncol = sizes[owner, abs2idx[vec_name][vec_name]]
rdct, _ = relevant[vec_name]['@all']
rel = rdct['output']
for key in ['input', 'output', 'residual']:
root_vectors[key][vec_name] = vector_class(vec_name, key, self,
alloc_complex=alloc_complex,
ncol=ncol, relevant=rel)
else:
for key, vardict in iteritems(self._vectors):
for vec_name, vec in iteritems(vardict):
root_vectors[key][vec_name] = vec._root_vector
return root_vectors
def _get_bounds_root_vectors(self, vector_class, initial):
"""
Get the root vectors for the lower and upper bounds vectors.
Parameters
----------
vector_class : Vector
The Vector class used to instantiate the root vectors.
initial : bool
Whether we are reconfiguring - i.e., whether the model has been previously setup.
Returns
-------
Vector
Root vector for the lower bounds vector.
Vector
Root vector for the upper bounds vector.
"""
if not initial:
lower = self._lower_bounds._root_vector
upper = self._upper_bounds._root_vector
else:
lower = vector_class('nonlinear', 'output', self)
upper = vector_class('nonlinear', 'output', self)
return lower, upper
def resetup(self, setup_mode='full'):
"""
Public wrapper for _setup that reconfigures after an initial setup has been performed.
Parameters
----------
setup_mode : str
Must be one of 'full', 'reconf', or 'update'.
"""
self._setup(self.comm, setup_mode=setup_mode, mode=self._mode,
distributed_vector_class=self._distributed_vector_class,
local_vector_class=self._local_vector_class,
use_derivatives=self._use_derivatives)
self._final_setup(self.comm, setup_mode=setup_mode,
force_alloc_complex=self._outputs._alloc_complex)
def _setup(self, comm, setup_mode, mode, distributed_vector_class, local_vector_class,
use_derivatives):
"""
Perform setup for this system and its descendant systems.
There are three modes of setup:
1. 'full': wipe everything and setup this and all descendant systems from scratch
2. 'reconf': don't wipe everything, but reconfigure this and all descendant systems
3. 'update': update after one or more immediate systems has done a 'reconf' or 'update'
Parameters
----------
comm : MPI.Comm or <FakeComm> or None
The global communicator.
setup_mode : str
Must be one of 'full', 'reconf', or 'update'.
mode : str
Derivative direction, either 'fwd', or 'rev', or 'auto'
distributed_vector_class : type
Reference to the <Vector> class or factory function used to instantiate vectors
and associated transfers involved in interprocess communication.
local_vector_class : type
Reference to the <Vector> class or factory function used to instantiate vectors
and associated transfers involved in intraprocess communication.
use_derivatives : bool
If True, perform any memory allocations necessary for derivative computation.
"""
# 1. Full setup that must be called in the root system.
if setup_mode == 'full':
recurse = True
self.pathname = ''
self.comm = comm
self._relevant = None
self._distributed_vector_class = distributed_vector_class
self._local_vector_class = local_vector_class
self._use_derivatives = use_derivatives
# 2. Partial setup called in the system initiating the reconfiguration.
elif setup_mode == 'reconf':
recurse = True
# 3. Update-mode setup called in all ancestors of the system initiating the reconf.
elif setup_mode == 'update':
recurse = False
self._mode = mode
# If we're only updating and not recursing, processors don't need to be redistributed.
if recurse:
# Besides setting up the processors, this method also builds the model hierarchy.
self._setup_procs(self.pathname, comm, mode)
# Recurse model from the bottom to the top for configuring.
self._configure()
# For updating variable and connection data, setup needs to be performed only
# in the current system, by gathering data from immediate subsystems,
# and no recursion is necessary.
self._setup_var_data(recurse=recurse)
self._setup_vec_names(mode, self._vec_names, self._vois)
self._setup_global_connections(recurse=recurse)
self._setup_relevance(mode, self._relevant)
self._setup_var_index_ranges(recurse=recurse)
self._setup_var_index_maps(recurse=recurse)
self._setup_var_sizes(recurse=recurse)
self._setup_connections(recurse=recurse)
def _setup_par_fd_procs(self, comm):
"""
Split up the comm for use in parallel FD.
Parameters
----------
comm : MPI.Comm or <FakeComm>
MPI communicator object.
Returns
-------
MPI.Comm or <FakeComm>
MPI communicator object.
"""
num_par_fd = self._num_par_fd
if comm.size < num_par_fd:
raise ValueError("'%s': num_par_fd must be <= communicator size (%d)" %
(self.pathname, comm.size))
self._full_comm = comm
if num_par_fd > 1:
sizes, offsets = evenly_distrib_idxs(num_par_fd, comm.size)
# a 'color' is assigned to each subsystem, with
# an entry for each processor it will be given
# e.g. [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
color = np.empty(comm.size, dtype=int)
for i in range(num_par_fd):
color[offsets[i]:offsets[i] + sizes[i]] = i
self._par_fd_id = color[comm.rank]
comm = self._full_comm.Split(self._par_fd_id)
return comm
def _setup_recording(self, recurse=True):
myinputs = myoutputs = myresiduals = set()
incl = self.recording_options['includes']
excl = self.recording_options['excludes']
if self.recording_options['record_inputs']:
if self._inputs:
myinputs = {n for n in self._inputs._names
if check_path(n, incl, excl)}
if self.recording_options['record_outputs']:
if self._outputs:
myoutputs = {n for n in self._outputs._names
if check_path(n, incl, excl)}
if self.recording_options['record_residuals']:
myresiduals = myoutputs # outputs and residuals have same names
elif self.recording_options['record_residuals']:
if self._residuals:
myresiduals = {n for n in self._residuals._names
if check_path(n, incl, excl)}
self._filtered_vars_to_record = {
'i': myinputs,
'o': myoutputs,
'r': myresiduals
}
self._rec_mgr.startup(self)
# Recursion
if recurse:
for subsys in self._subsystems_myproc:
subsys._setup_recording(recurse)
def _final_setup(self, comm, setup_mode, force_alloc_complex=False):
"""
Perform final setup for this system and its descendant systems.
This part of setup is called automatically at the start of run_model or run_driver.
There are three modes of setup:
1. 'full': wipe everything and setup this and all descendant systems from scratch
2. 'reconf': don't wipe everything, but reconfigure this and all descendant systems
3. 'update': update after one or more immediate systems has done a 'reconf' or 'update'
Parameters
----------
comm : MPI.Comm or <FakeComm> or None
The global communicator.
setup_mode : str
Must be one of 'full', 'reconf', or 'update'.
force_alloc_complex : bool
Force allocation of imaginary part in nonlinear vectors. OpenMDAO can generally
detect when you need to do this, but in some cases (e.g., complex step is used
after a reconfiguration) you may need to set this to True.
"""
# 1. Full setup that must be called in the root system.
if setup_mode == 'full':
initial = True
recurse = True
resize = False
# 2. Partial setup called in the system initiating the reconfiguration.
elif setup_mode == 'reconf':
initial = False
recurse = True
resize = True
# 3. Update-mode setup called in all ancestors of the system initiating the reconf.
elif setup_mode == 'update':
initial = False
recurse = False
resize = False
# For vector-related, setup, recursion is always necessary, even for updating.
# For reconfiguration setup, we resize the vectors once, only in the current system.
ext_num_vars, ext_sizes = self._get_initial_global(initial)
self._setup_global(ext_num_vars, ext_sizes)
root_vectors = self._get_root_vectors(initial, force_alloc_complex=force_alloc_complex)
self._setup_vectors(root_vectors, resize=resize)
self._setup_bounds(*self._get_bounds_root_vectors(self._local_vector_class, initial),
resize=resize)
# Transfers do not require recursion, but they have to be set up after the vector setup.
self._setup_transfers(recurse=recurse)
# Same situation with solvers, partials, and Jacobians.
# If we're updating, we just need to re-run setup on these, but no recursion necessary.
self._setup_solvers(recurse=recurse)
if self._use_derivatives:
self._setup_partials(recurse=recurse)
self._setup_jacobians(recurse=recurse)
self._setup_recording(recurse=recurse)
# If full or reconf setup, reset this system's variables to initial values.
if setup_mode in ('full', 'reconf'):
self.set_initial_values()
# Tell all subsystems to record their metadata if they have recorders attached
for sub in self.system_iter(recurse=True, include_self=True):
if sub.recording_options['record_metadata']:
sub._rec_mgr.record_metadata(sub)
# Also, optionally, record to the recorders attached to this System,
# the system metadata for all the subsystems
if self.recording_options['record_model_metadata']:
for sub in self.system_iter(recurse=True, include_self=True):
self._rec_mgr.record_metadata(sub)
def _setup_var_index_ranges(self, recurse=True):
"""
Compute the division of variables by subsystem.
Parameters
----------
recurse : bool
Whether to call this method in subsystems.
"""
pass
def _setup_var_data(self, recurse=True):
"""
Compute the list of abs var names, abs/prom name maps, and metadata dictionaries.
Parameters
----------
recurse : bool
Whether to call this method in subsystems.
"""
self._var_allprocs_abs_names = {'input': [], 'output': []}
self._var_abs_names = {'input': [], 'output': []}
self._var_allprocs_prom2abs_list = {'input': OrderedDict(), 'output': OrderedDict()}
self._var_abs2prom = {'input': {}, 'output': {}}
self._var_allprocs_abs2meta = {}
self._var_abs2meta = {}
def _setup_var_index_maps(self, recurse=True):
"""
Compute maps from abs var names to their index among allprocs variables in this system.
Parameters
----------
recurse : bool
Whether to call this method in subsystems.
"""
self._var_allprocs_abs2idx = abs2idx = {}
vec_names = self._lin_rel_vec_name_list if self._use_derivatives else self._vec_names
for vec_name in vec_names:
abs2idx[vec_name] = abs2idx_t = {}
for type_ in ['input', 'output']:
for i, abs_name in enumerate(self._var_allprocs_relevant_names[vec_name][type_]):
abs2idx_t[abs_name] = i
if self._use_derivatives:
abs2idx['nonlinear'] = abs2idx['linear']
# Recursion
if recurse:
for subsys in self._subsystems_myproc:
subsys._setup_var_index_maps(recurse)
def _setup_var_sizes(self, recurse=True):
"""
Compute the arrays of local variable sizes for all variables/procs on this system.
Parameters
----------
recurse : bool
Whether to call this method in subsystems.
"""
self._var_sizes = {}
self._owning_rank = defaultdict(int)
def _setup_global_shapes(self):
"""
Compute the global size and shape of all variables on this system.
"""
meta = self._var_allprocs_abs2meta
# now set global sizes and shapes into metadata for distributed outputs
sizes = self._var_sizes['nonlinear']['output']
for idx, abs_name in enumerate(self._var_allprocs_abs_names['output']):
mymeta = meta[abs_name]
local_shape = mymeta['shape']
if not mymeta['distributed']:
# not distributed, just use local shape and size
mymeta['global_size'] = mymeta['size']
mymeta['global_shape'] = local_shape
continue
global_size = np.sum(sizes[:, idx])
mymeta['global_size'] = global_size
# assume that all but the first dimension of the shape of a
# distributed output is the same on all procs
high_dims = local_shape[1:]
if high_dims:
high_size = np.prod(high_dims)
dim1 = global_size // high_size
if global_size % high_size != 0:
raise RuntimeError("Global size of output '%s' (%s) does not agree "
"with local shape %s" % (abs_name, global_size,
local_shape))
global_shape = tuple([dim1] + list(high_dims))
else:
high_size = 1
global_shape = (global_size,)
mymeta['global_shape'] = global_shape
def _setup_global_connections(self, recurse=True, conns=None):
"""
Compute dict of all connections between this system's inputs and outputs.
The connections come from 4 sources:
1. Implicit connections owned by the current system
2. Explicit connections declared by the current system
3. Explicit connections declared by parent systems
4. Implicit / explicit from subsystems
Parameters
----------
recurse : bool
Whether to call this method in subsystems.
conns : dict
Dictionary of connections passed down from parent group.
"""
pass
def _setup_vec_names(self, mode, vec_names=None, vois=None):
"""
Return the list of vec_names and the vois dict.
Parameters
----------
mode : str
Derivative direction, either 'fwd' or 'rev'.
vec_names : list of str or None
The list of names of vectors. Depends on the value of mode.
vois : dict
Dictionary of either design vars or responses, depending on the value
of mode.
"""
def _filter_names(voi_dict):
return set(voi for voi, data in iteritems(voi_dict)
if data['parallel_deriv_color'] is not None
or data['vectorize_derivs'])
self._vois = vois
if vec_names is None: # should only occur at top level on full setup
if self._use_derivatives:
vec_names = ['nonlinear', 'linear']
if mode == 'fwd':
desvars = self.get_design_vars(recurse=True, get_sizes=False)
vec_names.extend(sorted(_filter_names(desvars)))
self._vois = vois = desvars
else: # rev
responses = self.get_responses(recurse=True, get_sizes=False)
vec_names.extend(sorted(_filter_names(responses)))
self._vois = vois = responses
else:
vec_names = ['nonlinear']
self._vois = {}
self._vec_names = vec_names
self._lin_vec_names = vec_names[1:] # only linear vec names
for s in self.system_iter():
s._vec_names = vec_names
s._lin_vec_names = self._lin_vec_names
def _init_relevance(self, mode):
"""
Create the relevance dictionary.
Parameters
----------