-
Notifications
You must be signed in to change notification settings - Fork 240
/
system.py
4237 lines (3602 loc) · 168 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
import sys
import os
from contextlib import contextmanager
from collections import OrderedDict, defaultdict
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from fnmatch import fnmatchcase
import sys
import os
import time
from numbers import Integral
import itertools
from six import iteritems, itervalues, string_types
import numpy as np
import networkx as nx
import openmdao
from openmdao.jacobians.assembled_jacobian import DenseJacobian, CSCJacobian
from openmdao.jacobians.dictionary_jacobian import DictionaryJacobian
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.variable_table import write_var_table
from openmdao.utils.array_utils import evenly_distrib_idxs, sizes2offsets
from openmdao.utils.general_utils import make_set, var_name_match_includes_excludes, simple_warning
from openmdao.utils.graph_utils import all_connected_nodes
from openmdao.utils.name_maps import rel_name2abs_name
from openmdao.utils.coloring import _compute_coloring, Coloring, \
_STD_COLORING_FNAME, _DEF_COMP_SPARSITY_ARGS
import openmdao.utils.coloring as coloring_mod
from openmdao.utils.general_utils import determine_adder_scaler, find_matches, \
format_as_float_or_array, warn_deprecation, ContainsAll, all_ancestors, \
simple_warning
from openmdao.approximation_schemes.complex_step import ComplexStep
from openmdao.approximation_schemes.finite_difference import FiniteDifference
# 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,
}
# Suppored methods for derivatives
_supported_methods = {
'fd': FiniteDifference,
'cs': ComplexStep,
'exact': None
}
_DEFAULT_COLORING_META = {
'wrt_patterns': ('*',), # patterns used to match wrt variables
'method': 'fd', # finite differencing method ('fd' or 'cs')
'wrt_matches': None, # where matched wrt names are stored
'per_instance': True, # assume each instance can have a different coloring
'coloring': None, # this will contain the actual Coloring object
'dynamic': False, # True if dynamic coloring is being used
'static': None, # either _STD_COLORING_FNAME, a filename, or a Coloring object
# if use_fixed_coloring was called
}
_DEFAULT_COLORING_META.update(_DEF_COMP_SPARSITY_ARGS)
_full_slice = slice(None)
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
_problem_options : OptionsDictionary
Problem level options.
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_abs_names_discrete : {'input': [str, ...], 'output': [str, ...]}
List of absolute names of this system's discrete variables on all procs.
_var_abs_names_discrete : {'input': [str, ...], 'output': [str, ...]}
List of absolute names of this system's discrete 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_abs2prom : {'input': dict, 'output': dict}
Dictionary mapping absolute names to promoted names, on all procs.
_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 : {<vecname>: {'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.
_owned_sizes : ndarray
Array of local sizes for 'owned' or distributed vars only.
_nodup_out_ranges : dict
Range of each output/resid in the global non-duplicated array.
_nodup2local_out_inds : ndarray
Indices that map values from the global non-duplicated array into the local output/resids.
_var_offsets : {<vecname>: {'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.
_conn_global_abs_in2out : {'abs_in': 'abs_out'}
Dictionary containing all explicit & implicit connections owned by this system
or any descendant system. The data is the same across all processors.
_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 : list 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 : list 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.
_has_bounds: bool
True if this system has upper or lower bounds on outputs.
_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.
_has_approx : bool
If True, this system or its descendent has declared approximated partial or semi-total
derivatives.
_coloring_info : tuple
Metadata that defines how to perform coloring of this System's approx jacobian. Not
used if this System does no partial or semi-total coloring.
_first_call_to_linearize : bool
If True, this is the first call to _linearize.
_nodup_out_ranges : OrderedDict
Tuples of the form (start, end) keyed on variable name.
_nodup2local_out_inds : ndarray
Index array mapping global non-dup outputs/resids to local outputs/resids.
_local2owned_inds : ndarray
Index array mapping local outputs/resids to owned local outputs/resids.
_noncontig_dis_inds : ndarray
Index array mapping global stacked (rank order) array to global array where
distrib vars are contiguous and all vars appear in global execution order.
Execution order is meaningless for systems in ParallelGroups, but for purposes
of global ordering, the declared execution order, which is the same across all
ranks, is used.
"""
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 = None
self.comm = None
# System options
self.options = OptionsDictionary(parent_name=type(self).__name__)
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(parent_name=type(self).__name__)
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')
self._problem_options = None
# 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_abs_names_discrete = {'input': [], 'output': []}
self._var_abs_names_discrete = {'input': [], 'output': []}
self._var_allprocs_prom2abs_list = None
self._var_abs2prom = {'input': {}, 'output': {}}
self._var_allprocs_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._owned_sizes = None
self._var_offsets = None
self._nodup_out_ranges = None
self._nodup2local_out_inds = 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._discrete_inputs = None
self._discrete_outputs = 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._conn_global_abs_in2out = {}
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._has_bounds = False
self._vector_class = None
self._local_vector_class = None
self._distributed_vector_class = None
self._use_derivatives = True
self._has_approx = False
self._assembled_jac = None
self._par_fd_id = 0
self._filtered_vars_to_record = {}
self._owning_rank = None
self._lin_vec_names = []
self._coloring_info = _DEFAULT_COLORING_META.copy()
self._first_call_to_linearize = True # will check in first call to _linearize
@property
def msginfo(self):
"""
Our instance pathname, if available, or our class name. For use in error messages.
Returns
-------
str
Either our instance pathname or class name.
"""
if self.pathname == '':
return '{} (<model>)'.format(type(self).__name__)
if self.pathname is not None:
return '{} ({})'.format(type(self).__name__, self.pathname)
if self.name:
return '{} ({})'.format(type(self).__name__, self.name)
return type(self).__name__
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_self_reconf(self):
"""
Check if this systems wants to reconfigure and if so, perform the reconfiguration.
"""
if self.reconfigure():
with self._unscaled_context_all():
# Backup input values
old_in = self._inputs
old_out = self._outputs
# Perform reconfiguration
self.resetup('reconf')
new_in = self._inputs
new_out = self._outputs
# Reload input and output values where possible
for vold, vnew in [(old_in, new_in), (old_out, new_out)]:
for abs_name, old_view in iteritems(vold._views_flat):
if abs_name in vnew._views_flat:
new_view = vnew._views_flat[abs_name]
if len(old_view) == len(new_view):
new_view[:] = old_view
self._reconfigured = True
def _check_child_reconf(self, subsys=None):
"""
Check if any subsystem has reconfigured and if so, perform the necessary update setup.
Parameters
----------
subsys : System or None
ignored
"""
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 = {}
if self._vector_class is None:
self._vector_class = self._local_vector_class
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
lower, upper = self._get_bounds_root_vectors(self._local_vector_class, initial)
root_vectors['lower'] = lower
root_vectors['upper'] = upper
return root_vectors
def _get_approx_scheme(self, method):
"""
Return the approximation scheme associated with the given method, creating one if needed.
Parameters
----------
method : str
Name of the type of approxmation scheme.
Returns
-------
ApproximationScheme
The ApproximationScheme associated with the given method.
"""
if method == 'exact':
return None
if method not in _supported_methods:
msg = '{}: Method "{}" is not supported, method must be one of {}'
raise ValueError(msg.format(self.msginfo, method,
[m for m in _supported_methods if m != 'exact']))
if method not in self._approx_schemes:
self._approx_schemes[method] = _supported_methods[method]()
return self._approx_schemes[method]
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:
return self._lower_bounds._root_vector, self._upper_bounds._root_vector
else:
lower = vector_class('nonlinear', 'output', self)
upper = vector_class('nonlinear', 'output', self)
lower._data[:] = -np.inf
upper._data[:] = np.inf
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,
prob_options=self._problem_options)
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, prob_options=None):
"""
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.
prob_options : OptionsDictionary
Problem level options dictionary.
"""
# save a ref to the problem level options.
self._problem_options = prob_options
# 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
# 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, self._problem_options)
# 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_sizes(recurse=recurse)
self._setup_connections(recurse=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)
# 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()
rec_model_meta = self.recording_options['record_model_metadata']
# 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 rec_model_meta:
self._rec_mgr.record_metadata(sub)
def use_fixed_coloring(self, coloring=_STD_COLORING_FNAME, recurse=True):
"""
Use a precomputed coloring for this System.
Parameters
----------
coloring : str
A coloring filename. If no arg is passed, filename will be determined
automatically.
recurse : bool
If True, set fixed coloring in all subsystems that declare a coloring. Ignored
if a specific coloring is passed in.
"""
if coloring_mod._force_dyn_coloring and coloring is _STD_COLORING_FNAME:
self._coloring_info['dynamic'] = True
return # don't use static this time
self._coloring_info['static'] = coloring
self._coloring_info['dynamic'] = False
if coloring is not _STD_COLORING_FNAME:
if recurse:
simple_warning("%s: recurse was passed to use_fixed_coloring but a specific "
"coloring was set, so recurse was ignored." % self.pathname)
if isinstance(coloring, Coloring):
approx = self._get_approx_scheme(coloring._meta['method'])
# force regen of approx groups on next call to compute_approximations
approx._reset()
return
if recurse:
for s in self._subsystems_myproc:
s.use_fixed_coloring(coloring, recurse)
def declare_coloring(self,
wrt=_DEFAULT_COLORING_META['wrt_patterns'],
method=_DEFAULT_COLORING_META['method'],
form=None,
step=None,
per_instance=_DEFAULT_COLORING_META['per_instance'],
num_full_jacs=_DEFAULT_COLORING_META['num_full_jacs'],
tol=_DEFAULT_COLORING_META['tol'],
orders=_DEFAULT_COLORING_META['orders'],
perturb_size=_DEFAULT_COLORING_META['perturb_size'],
min_improve_pct=_DEFAULT_COLORING_META['min_improve_pct'],
show_summary=_DEFAULT_COLORING_META['show_summary'],
show_sparsity=_DEFAULT_COLORING_META['show_sparsity']):
"""
Set options for deriv coloring of a set of wrt vars matching the given pattern(s).
Parameters
----------
wrt : str or list of str
The name or names of the variables that derivatives are taken with respect to.
This can contain input names, output names, or glob patterns.
method : str
Method used to compute derivative: "fd" for finite difference, "cs" for complex step.
form : str
Finite difference form, can be "forward", "central", or "backward". Leave
undeclared to keep unchanged from previous or default value.
step : float
Step size for finite difference. Leave undeclared to keep unchanged from previous
or default value.
per_instance : bool
If True, a separate coloring will be generated for each instance of a given class.
Otherwise, only one coloring for a given class will be generated and all instances
of that class will use it.
num_full_jacs : int
Number of times to repeat partial jacobian computation when computing sparsity.
tol : float
Tolerance used to determine if an array entry is nonzero during sparsity determination.
orders : int
Number of orders above and below the tolerance to check during the tolerance sweep.
perturb_size : float
Size of input/output perturbation during generation of sparsity.
min_improve_pct : float
If coloring does not improve (decrease) the number of solves more than the given
percentage, coloring will not be used.
show_summary : bool
If True, display summary information after generating coloring.
show_sparsity : bool