-
Notifications
You must be signed in to change notification settings - Fork 240
/
system.py
4973 lines (4259 loc) · 203 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."""
import sys
import os
import time
from contextlib import contextmanager
from collections import OrderedDict, defaultdict
from collections.abc import Iterable
from itertools import chain
import re
from fnmatch import fnmatchcase
from numbers import Integral
import numpy as np
import networkx as nx
import openmdao
from openmdao.core.configinfo import _ConfigInfo
from openmdao.core.constants import _DEFAULT_OUT_STREAM, _UNDEFINED, INT_DTYPE
from openmdao.jacobians.assembled_jacobian import DenseJacobian, CSCJacobian
from openmdao.recorders.recording_manager import RecordingManager
from openmdao.vectors.vector import _full_slice
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.units import is_compatible, unit_conversion
from openmdao.utils.variable_table import write_var_table
from openmdao.utils.array_utils import evenly_distrib_idxs
from openmdao.utils.graph_utils import all_connected_nodes
from openmdao.utils.name_maps import name2abs_name, name2abs_names
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, \
format_as_float_or_array, ContainsAll, all_ancestors, _slice_indices, \
simple_warning, make_set, ensure_compatible, match_prom_or_abs, _is_slicer_op
from openmdao.approximation_schemes.complex_step import ComplexStep
from openmdao.approximation_schemes.finite_difference import FiniteDifference
from openmdao.utils.units import unit_conversion
_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)
_recordable_funcs = frozenset(['_apply_linear', '_apply_nonlinear', '_solve_linear',
'_solve_nonlinear'])
# the following are local metadata that will also be accessible for vars on all procs
global_meta_names = {
'input': ('units', 'shape', 'size', 'distributed', 'tags', 'desc', 'shape_by_conn',
'copy_shape'),
'output': ('units', 'shape', 'size', 'desc',
'ref', 'ref0', 'res_ref', 'distributed', 'lower', 'upper', 'tags', 'shape_by_conn',
'copy_shape'),
}
allowed_meta_names = {
'value',
'global_shape',
'global_size',
'src_indices',
'src_slice',
'flat_src_indices',
'type',
'res_units',
}
allowed_meta_names.update(global_meta_names['input'])
allowed_meta_names.update(global_meta_names['output'])
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_meta : dict
Problem level metadata.
under_complex_step : bool
When True, this system is undergoing complex step.
under_approx : bool
When True, this system is undergoing approximation.
iter_count : int
Counts the number of times this system has called _solve_nonlinear. This also
corresponds to the number of times that the system's outputs are recorded if a recorder
is present.
iter_count_apply : int
Counts the number of times the system has called _apply_nonlinear. For ExplicitComponent,
calls to apply_nonlinear also call compute, so number of executions can be found by adding
this and iter_count together. Recorders do no record calls to apply_nonlinear.
iter_count_without_approx : int
Counts the number of times the system has iterated but excludes any that occur during
approximation of derivatives.
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.
_solver_print_cache : list
Allows solver iprints to be set to requested values after setup calls.
_subsystems_allprocs : OrderedDict
Dict mapping subsystem name to SysInfo(system, index) for children of this system.
_subsystems_myproc : [<System>, ...]
List of local subsystems that exist on this proc.
_var_promotes : { 'any': [], 'input': [], 'output': [] }
Dictionary of lists of variable names/wildcards specifying promotion
(used to calculate promoted names)
_var_promotes_src_indices : dict
Dictionary mapping promoted input names/wildcards to (src_indices, flat_src_indices)
_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.
_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.
_vars_to_gather : dict
Contains names of non-distributed variables that are remote on at least one proc in the comm
_dist_var_locality : dict
Contains names of distrib vars mapped to the ranks in the comm where they are local.
_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.
_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'].
_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.
_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_subsystems_allprocs : OrderedDict
Dict of SysInfo(subsys, index) 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.
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
_problem_meta['distributed_vector_class'] or _problem_meta['local_vector_class'].
_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.
_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.
_is_local : bool
If True, this system is local to this mpi process.
"""
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
self._is_local = False
# 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='Deprecated. Recording of metadata will always be done',
default=True,
deprecation="The recording option, record_metadata, "
"on System is "
"deprecated. Recording of metadata will always be done")
self.recording_options.declare('record_model_metadata', types=bool,
desc='Deprecated. Recording of model metadata will always '
'be done',
deprecation="The recording option, record_model_metadata, "
"on System is deprecated. Recording of model metadata will "
"always be done",
default=True)
self.recording_options.declare('includes', types=list, default=['*'],
desc='Patterns for variables to include in recording. \
Uses fnmatch wildcards')
self.recording_options.declare('excludes', types=list, default=[],
desc='Patterns for vars to exclude in recording '
'(processed post-includes). Uses fnmatch wildcards')
self.recording_options.declare('options_excludes', types=list, default=[],
desc='User-defined metadata to exclude in recording')
self._problem_meta = None
# Counting iterations.
self.iter_count = 0
self.iter_count_apply = 0
self.iter_count_without_approx = 0
self.cite = ""
self._solver_print_cache = []
self._subsystems_allprocs = {}
self._subsystems_myproc = []
self._vars_to_gather = {}
self._dist_var_locality = {}
self._var_promotes = {'input': [], 'output': [], 'any': []}
self._var_promotes_src_indices = {}
self._var_allprocs_prom2abs_list = None
self._var_abs2prom = {'input': {}, 'output': {}}
self._var_allprocs_abs2prom = {'input': {}, 'output': {}}
self._var_allprocs_abs2meta = {'input': {}, 'output': {}}
self._var_abs2meta = {'input': {}, 'output': {}}
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._full_comm = None
self._vectors = {'input': {}, 'output': {}, 'residual': {}}
self._inputs = None
self._outputs = None
self._residuals = None
self._discrete_inputs = None
self._discrete_outputs = None
self._nonlinear_solver = None
self._linear_solver = None
self._jacobian = None
self._approx_schemes = OrderedDict()
self._subjacs_info = {}
self.matrix_free = False
self.under_approx = 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._design_vars = OrderedDict()
self._responses = OrderedDict()
self._rec_mgr = RecordingManager()
self._conn_global_abs_in2out = {}
self._static_subsystems_allprocs = {}
self._static_design_vars = OrderedDict()
self._static_responses = OrderedDict()
self.supports_multivecs = False
self._relevant = 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._has_approx = False
self._assembled_jac = None
self._par_fd_id = 0
self._filtered_vars_to_record = {}
self._owning_rank = None
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> <class {}>'.format(type(self).__name__)
if self.pathname is not None:
return "'{}' <class {}>".format(self.pathname, type(self).__name__)
if self.name:
return "'{}' <class {}>".format(self.name, type(self).__name__)
return type(self).__name__
def _get_inst_id(self):
return self.pathname
def abs_name_iter(self, iotype, local=True, cont=True, discrete=False):
"""
Iterate over absolute variable names for this System.
By setting appropriate values for 'cont' and 'discrete', yielded variable
names can be continuous only, discrete only, or both.
Parameters
----------
iotype : str
Either 'input' or 'output'.
local : bool
If True, include only names of local variables. Default is True.
cont : bool
If True, include names of continuous variables. Default is True.
discrete : bool
If True, include names of discrete variables. Default is False.
"""
if cont:
if local:
yield from self._var_abs2meta[iotype]
else:
yield from self._var_allprocs_abs2meta[iotype]
if discrete:
if local:
prefix = self.pathname + '.' if self.pathname else ''
for name in self._var_discrete[iotype]:
yield prefix + name
else:
yield from self._var_allprocs_discrete[iotype]
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 initialize(self):
"""
Perform any one-time initialization run at instantiation.
"""
pass
def _configure(self):
"""
Configure this system to assign children settings.
"""
pass
def _get_root_vectors(self):
"""
Get the root vectors for the nonlinear and linear vectors for the model.
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()}
relevant = self._relevant
vec_names = self._rel_vec_name_list if self._use_derivatives else self._vec_names
vectorized_vois = self._problem_meta['vectorized_vois']
force_alloc_complex = self._problem_meta['force_alloc_complex']
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
for vec_name in vec_names:
sizes = self._var_sizes[vec_name]['output']
ncol = 1
if vec_name == 'nonlinear':
alloc_complex = nl_alloc_complex
else:
alloc_complex = ln_alloc_complex
if vec_name != 'linear':
if vec_name in vectorized_vois:
voi = vectorized_vois[vec_name]
if 'size' in voi:
ncol = voi['size']
else:
owner = self._owning_rank[vec_name]
ncol = sizes[owner, abs2idx[vec_name][vec_name]]
for key in ['input', 'output', 'residual']:
root_vectors[key][vec_name] = self._vector_class(vec_name, key, self,
alloc_complex=alloc_complex,
ncol=ncol)
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_source(self, name):
"""
Return the source variable connected to the given named variable.
The name can be a promoted name or an absolute name.
If the given variable is an input, the absolute name of the connected source will
be returned. If the given variable itself is a source, its own absolute name will
be returned.
Parameters
----------
name : str
Absolute or promoted name of the variable.
Returns
-------
str
The absolute name of the source variable.
"""
if self._problem_meta is None or 'prom2abs' not in self._problem_meta:
raise RuntimeError(f"{self.msginfo}: get_source cannot be called for variable {name} "
"before Problem.setup is complete.")
model = self._problem_meta['model_ref']()
prom2abs = self._problem_meta['prom2abs']
if name in prom2abs['input']:
name = prom2abs['input'][name][0]
elif name in prom2abs['output']:
return prom2abs['output'][name][0]
if name in model._conn_global_abs_in2out:
return model._conn_global_abs_in2out[name]
return name
def _setup(self, comm, mode, prob_meta):
"""
Perform setup for this system and its descendant systems.
Parameters
----------
comm : MPI.Comm or <FakeComm> or None
The global communicator.
mode : str
Derivative direction, either 'fwd', or 'rev', or 'auto'
prob_meta : dict
Problem level metadata dictionary.
"""
# save a ref to the problem level options.
self._problem_meta = prob_meta
# reset any coloring if a Coloring object was not set explicitly
if self._coloring_info['dynamic'] or self._coloring_info['static'] is not None:
self._coloring_info['coloring'] = None
self.pathname = ''
self.comm = comm
self._relevant = None
self._mode = mode
# Besides setting up the processors, this method also builds the model hierarchy.
self._setup_procs(self.pathname, comm, mode, self._problem_meta)
prob_meta['config_info'] = _ConfigInfo()
try:
# Recurse model from the bottom to the top for configuring.
self._configure()
finally:
prob_meta['config_info'] = None
self._configure_check()
self._setup_var_data()
self._setup_vec_names(mode)
# promoted names must be known to determine implicit connections so this must be
# called after _setup_var_data, and _setup_var_data will have to be partially redone
# after auto_ivcs have been added, but auto_ivcs can't be added until after we know all of
# the connections.
self._setup_global_connections()
self._setup_dynamic_shapes()
self._top_level_post_connections(mode)
# Now that connections are setup, we need to convert relevant vector names into their
# auto_ivc source where applicable.
conns = self._conn_global_abs_in2out
new_names = [conns[v] if v in conns else v for v in self._vec_names]
self._problem_meta['vec_names'] = new_names
self._problem_meta['lin_vec_names'] = new_names[1:]
self._setup_relevance(mode)
self._setup_var_sizes()
self._top_level_post_sizes()
# determine which connections are managed by which group, and check validity of connections
self._setup_connections()
def _top_level_post_connections(self, mode):
# this runs after all connections are known
pass
def _top_level_post_sizes(self):
# this runs after the variable sizes are known
self._setup_global_shapes()
def _configure_check(self):
"""
Do any error checking on i/o and connections.
"""
pass
def _setup_dynamic_shapes(self):
pass
def _final_setup(self, comm):
"""
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.
Parameters
----------
comm : MPI.Comm or <FakeComm> or None
The global communicator.
"""
if self._use_derivatives:
# must call this before vector setup because it determines if we need to alloc commplex
self._setup_partials()
self._setup_vectors(self._get_root_vectors())
# Transfers do not require recursion, but they have to be set up after the vector setup.
self._setup_transfers()
# 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()
self._setup_solver_print()
if self._use_derivatives:
self._setup_jacobians()
self._setup_recording()
self.set_initial_values()
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
If True, display sparsity with coloring info after generating coloring.
"""
if method not in ('fd', 'cs'):
raise RuntimeError("{}: method must be one of ['fd', 'cs'].".format(self.msginfo))
self._has_approx = True
approx = self._get_approx_scheme(method)
# start with defaults
options = _DEFAULT_COLORING_META.copy()
options.update(approx.DEFAULT_OPTIONS)
if self._coloring_info['static'] is None:
options['dynamic'] = True
else:
options['dynamic'] = False
options['static'] = self._coloring_info['static']
options['wrt_patterns'] = [wrt] if isinstance(wrt, str) else wrt
options['method'] = method
options['per_instance'] = per_instance
options['repeat'] = num_full_jacs
options['tol'] = tol
options['orders'] = orders
options['perturb_size'] = perturb_size
options['min_improve_pct'] = min_improve_pct
options['show_summary'] = show_summary
options['show_sparsity'] = show_sparsity
options['coloring'] = self._coloring_info['coloring']
if form is not None:
options['form'] = form
if step is not None:
options['step'] = step
self._coloring_info = options
def _compute_approx_coloring(self, recurse=False, **overrides):
"""
Compute a coloring of the approximated derivatives.
This assumes that the current System is in a proper state for computing approximated
derivatives.
Parameters
----------
recurse : bool
If True, recurse from this system down the system hierarchy. Whenever a group
is encountered that has specified its coloring metadata, we don't recurse below
that group unless that group has a subsystem that has a nonlinear solver that uses
gradients.
**overrides : dict
Any args that will override either default coloring settings or coloring settings
resulting from an earlier call to declare_coloring.
Returns
-------
list of Coloring
The computed colorings.
"""
if recurse:
colorings = []
my_coloring = self._coloring_info['coloring']
grad_systems = self._get_gradient_nl_solver_systems()
for s in self.system_iter(include_self=True, recurse=True):
if my_coloring is None or s in grad_systems:
if s._coloring_info['coloring'] is not None:
coloring = s._compute_approx_coloring(recurse=False, **overrides)[0]
colorings.append(coloring)
if coloring is not None:
coloring._meta['pathname'] = s.pathname
coloring._meta['class'] = type(s).__name__
return [c for c in colorings if c is not None] or [None]
# don't override metadata if it's already declared
info = self._coloring_info
info.update(**overrides)
if isinstance(info['wrt_patterns'], str):
info['wrt_patterns'] = [info['wrt_patterns']]
if info['method'] is None and self._approx_schemes:
info['method'] = list(self._approx_schemes)[0]
if self._coloring_info['coloring'] is None:
# check to see if any approx derivs have been declared
for meta in self._subjacs_info.values():
if 'method' in meta and meta['method']:
break
else: # no approx derivs found
simple_warning("%s: No approx partials found but coloring was requested. "
"Declaring ALL partials as approx (method='%s')" %
(self.msginfo, self._coloring_info['method']))
try:
self.declare_partials('*', '*', method=self._coloring_info['method'])
except AttributeError: # this system must be a group
from openmdao.core.component import Component
for s in self.system_iter(recurse=True, typ=Component):
s.declare_partials('*', '*', method=self._coloring_info['method'])
self._setup_partials()
approx_scheme = self._get_approx_scheme(self._coloring_info['method'])
if self._coloring_info['coloring'] is None and self._coloring_info['static'] is None:
self._coloring_info['dynamic'] = True
coloring_fname = self.get_approx_coloring_fname()
# if we find a previously computed class coloring for our class, just use that
# instead of regenerating a coloring.
if not info['per_instance'] and coloring_fname in coloring_mod._CLASS_COLORINGS:
info['coloring'] = coloring = coloring_mod._CLASS_COLORINGS[coloring_fname]
if coloring is None:
print("\nClass coloring for class '{}' wasn't good enough, "
"so skipping for '{}'".format(type(self).__name__, self.pathname))
info['static'] = None
else:
print("\n{} using class coloring for class '{}'".format(self.pathname,
type(self).__name__))
info.update(coloring._meta)
# force regen of approx groups during next compute_approximations
approx_scheme._reset()
return [coloring]
from openmdao.core.group import Group
is_total = isinstance(self, Group)
# compute perturbations
starting_inputs = self._inputs.asarray(copy=True)
in_offsets = starting_inputs.copy()
in_offsets[in_offsets == 0.0] = 1.0
in_offsets *= info['perturb_size']
starting_outputs = self._outputs.asarray(copy=True)
out_offsets = starting_outputs.copy()
out_offsets[out_offsets == 0.0] = 1.0
out_offsets *= info['perturb_size']
starting_resids = self._residuals.asarray(copy=True)
# for groups, this does some setup of approximations
self._setup_approx_coloring()