/
system.py
6266 lines (5392 loc) · 255 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 hashlib
import time
import functools
from contextlib import contextmanager
from collections import defaultdict
from itertools import chain
from enum import IntEnum
from fnmatch import fnmatchcase
from numbers import Integral
import numpy as np
from openmdao.core.constants import _DEFAULT_OUT_STREAM, _UNDEFINED, INT_DTYPE, INF_BOUND, \
_SetupStatus
from openmdao.jacobians.jacobian import Jacobian
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, multi_proc_exception_check
from openmdao.utils.options_dictionary import OptionsDictionary
from openmdao.utils.record_util import create_local_meta, check_path, has_match
from openmdao.utils.units import is_compatible, unit_conversion, simplify_unit
from openmdao.utils.variable_table import write_var_table
from openmdao.utils.array_utils import evenly_distrib_idxs, shape_to_len
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, _ColSparsityJac
import openmdao.utils.coloring as coloring_mod
from openmdao.utils.indexer import indexer
from openmdao.utils.om_warnings import issue_warning, \
DerivativesWarning, PromotionWarning, UnusedOptionWarning, UnitsWarning
from openmdao.utils.general_utils import determine_adder_scaler, \
format_as_float_or_array, all_ancestors, make_set, match_prom_or_abs, \
ensure_compatible, env_truthy, make_traceback, _is_slicer_op
from openmdao.approximation_schemes.complex_step import ComplexStep
from openmdao.approximation_schemes.finite_difference import FiniteDifference
from openmdao.core.total_jac import _TotalJacInfo
_empty_frozen_set = frozenset()
_asm_jac_types = {
'csc': CSCJacobian,
'dense': DenseJacobian,
}
# Suppored methods for derivatives
_supported_methods = {
'fd': FiniteDifference,
'cs': ComplexStep,
'exact': None,
'jax': 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',
'compute_shape', 'copy_shape'),
'output': ('units', 'shape', 'size', 'desc',
'ref', 'ref0', 'res_ref', 'distributed', 'lower', 'upper', 'tags', 'shape_by_conn',
'compute_shape', 'copy_shape'),
}
allowed_meta_names = {
'val',
'global_shape',
'global_size',
'src_indices',
'flat_src_indices',
'type',
'res_units',
}
allowed_meta_names.update(global_meta_names['input'])
allowed_meta_names.update(global_meta_names['output'])
resp_size_checks = {
'con': ['ref', 'ref0', 'scaler', 'adder', 'upper', 'lower', 'equals'],
'obj': ['ref', 'ref0', 'scaler', 'adder']
}
resp_types = {'con': 'constraint', 'obj': 'objective'}
class _MatchType(IntEnum):
"""
Class used to define different types of promoted name matches.
Attributes
----------
NAME : int
Literal name match.
RENAME : int
Rename match.
PATTERN : int
Glob pattern match.
"""
NAME = 0
RENAME = 1
PATTERN = 2
class _OptStatus(IntEnum):
"""
Class used to define different states during the optimization process.
Attributes
----------
PRE : int
Before the optimization.
OPTIMIZING : int
During the optimization.
POST : int
After the optimization.
"""
PRE = 0
OPTIMIZING = 1
POST = 2
def collect_errors(method):
"""
Decorate a method so that it will collect any exceptions for later display.
Parameters
----------
method : method
The method to be decorated.
Returns
-------
method
The wrapped method.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except Exception:
if env_truthy('OPENMDAO_FAIL_FAST'):
raise
type_exc, exc, tb = sys.exc_info()
if isinstance(exc, KeyError) and self._get_saved_errors():
# it's likely the result of an earlier error, so ignore it
return
self._collect_error(str(exc), exc_type=type_exc, tback=tb)
return wrapper
class System(object):
"""
Base class for all systems in OpenMDAO.
Never instantiated; subclassed by <Group> or <Component>.
In attribute names:
abs: absolute, unpromoted variable name, seen from root (unique).
rel: relative, unpromoted variable name, seen from current system (unique).
prom: relative, promoted variable name, seen from current system (non-unique for inputs).
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.
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_finite_difference : bool
When True, this system is undergoing finite differencing.
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 not 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 : dict
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_prom2inds : dict
Maps promoted name to src_indices in scope of system.
_var_allprocs_prom2abs_list : {'input': dict, 'output': dict}
Dictionary mapping promoted names (continuous and discrete) 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. Contains continuous
and discrete variables.
_var_allprocs_abs2prom : {'input': dict, 'output': dict}
Dictionary mapping absolute names to promoted names, on all procs. Contains continuous
and discrete variables.
_var_allprocs_abs2meta : dict
Dictionary mapping absolute names to metadata dictionaries for allprocs continuous
variables.
_var_abs2meta : dict
Dictionary mapping absolute names to metadata dictionaries for myproc continuous 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.
_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 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
_conn_global_abs_in2out : {'abs_in': 'abs_out'}
Dictionary containing all explicit & implicit connections (continuous and discrete)
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 nonlinear inputs vector.
_outputs : <Vector>
The nonlinear outputs vector.
_residuals : <Vector>
The nonlinear residuals vector.
_dinputs : <Vector>
The linear inputs vector.
_doutputs : <Vector>
The linear outputs vector.
_dresiduals : <Vector>
The linear residuals vector.
_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 : dict
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_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.
_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.
_approx_subjac_keys : list
List of subjacobian keys used for approximated derivatives.
_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 : dict
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.
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. Note that the framework
will not set the matrix_free flag correctly for Component instances having a matrix vector
product function that is added dynamically (not declared as part of the class) and in that
case the matrix_free flag must be set manually to True.
_relevant : dict
Mapping of a VOI to a tuple containing dependent inputs, dependent outputs,
and dependent systems.
_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_output_adder : bool
True if this system has scaling that includes an adder term.
_has_resid_scaling : bool
True if this system has resid scaling.
_has_input_scaling : bool
True if this system has input scaling.
_has_input_adder : bool
True if this system has scaling that includes an adder term.
_has_bounds : bool
True if this system has upper or lower bounds on outputs.
_has_distrib_vars : bool
If True, this System contains at least one distributed variable. Used to determine if a
parallel group or distributed component is below a DirectSolver so that we can raise an
exception.
_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.
_tot_jac : __TotalJacInfo or None
If a total jacobian is being computed and this is the top level System, this will
be a reference to the _TotalJacInfo object.
_saved_errors : list
Temporary storage for any saved errors that occur before this System is assigned
a parent Problem.
_output_solver_options : dict or None
Solver output options if set_output_solver_options has been called.
_promotion_tree : dict
Mapping of system path to promotion info indicating all subsystems where variables
were promoted.
_run_on_opt: list of bool
Indicates whether this system should run before, during, or after the optimization process
(if there is an optimization process at all).
_during_sparsity : bool
If True, we're doing a sparsity computation and uncolored approxs need to be restricted
to only colored columns.
"""
def __init__(self, num_par_fd=1, **kwargs):
"""
Initialize all attributes.
"""
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 or implicit component, '
'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('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._var_promotes = {'input': [], 'output': [], 'any': []}
self._var_allprocs_prom2abs_list = None
self._var_prom2inds = {}
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 = {}
self._inputs = None
self._outputs = None
self._residuals = None
self._dinputs = None
self._doutputs = None
self._dresiduals = None
self._discrete_inputs = None
self._discrete_outputs = None
self._nonlinear_solver = None
self._linear_solver = None
self._jacobian = None
self._approx_schemes = {}
self._subjacs_info = {}
self._approx_subjac_keys = None
self.matrix_free = _UNDEFINED
self._owns_approx_jac = False
self._owns_approx_jac_meta = {}
self._owns_approx_wrt = None
self._owns_approx_of = None
self.under_complex_step = False
self.under_finite_difference = False
self._design_vars = {}
self._responses = {}
self._rec_mgr = RecordingManager()
self._conn_global_abs_in2out = {}
self._static_subsystems_allprocs = {}
self._static_design_vars = {}
self._static_responses = {}
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_output_adder = False
self._has_resid_scaling = False
self._has_input_scaling = False
self._has_input_adder = False
self._has_bounds = False
self._has_distrib_vars = False
self._has_approx = False
self._vector_class = None
self._assembled_jac = None
self._par_fd_id = 0
self._filtered_vars_to_record = {}
self._owning_rank = None
self._coloring_info = coloring_mod._Partial_ColoringMeta()
self._first_call_to_linearize = True # will check in first call to _linearize
self._tot_jac = None
self._saved_errors = None if env_truthy('OPENMDAO_FAIL_FAST') else []
self._output_solver_options = {}
self._promotion_tree = None
# need separate values for [PRE, OPTIMIZE, POST] since a Group may participate in
# multiple phases because some of its subsystems may be in one phase and some in another.
self._run_on_opt = [False, True, False]
self._during_sparsity = False
@property
def under_approx(self):
"""
Return True if under complex step or finite difference.
Returns
-------
bool
True if under CS or FD.
"""
return self.under_complex_step or self.under_finite_difference
@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 is not None:
if self.pathname == '':
return f"<model> <class {type(self).__name__}>"
return f"'{self.pathname}' <class {type(self).__name__}>"
if self.name:
return f"'{self.name}' <class {type(self).__name__}>"
return f"<class {type(self).__name__}>"
def _get_inst_id(self):
return self.pathname if self.pathname is not None else ''
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.
Yields
------
str
"""
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 _jac_of_iter(self):
"""
Iterate over (name, offset, end, slice, dist_sizes) for each 'of' (row) var in the jacobian.
The slice is internal to the given variable in the result, and this is always a full
slice except when indices are defined for the 'of' variable.
Yields
------
str
Name of 'of' variable.
int
Starting index.
int
Ending index.
slice or ndarray
A full slice or indices for the 'of' variable.
ndarray or None
Distributed sizes if var is distributed else None
"""
toidx = self._var_allprocs_abs2idx
sizes = self._var_sizes['output']
total = self.pathname == ''
szname = 'global_size' if total else 'size'
start = end = 0
for of, meta in self._var_abs2meta['output'].items():
end += meta[szname]
yield of, start, end, _full_slice, sizes[:, toidx[of]] if meta['distributed'] else None
start = end
def _jac_wrt_iter(self, wrt_matches=None):
"""
Iterate over (name, offset, end, vec, slc, dist_sizes) for each column var in the jacobian.
Parameters
----------
wrt_matches : set or None
Only include row vars that are contained in this set. This will determine what
the actual offsets are, i.e. the offsets will be into a reduced jacobian
containing only the matching columns.
Yields
------
str
Name of 'wrt' variable.
int
Starting index.
int
Ending index.
Vector or None
Either the _outputs or _inputs vector if var is local else None.
slice
A full slice.
ndarray or None
Distributed sizes if var is distributed else None
"""
toidx = self._var_allprocs_abs2idx
sizes_in = self._var_sizes['input']
tometa_in = self._var_allprocs_abs2meta['input']
local_ins = self._var_abs2meta['input']
local_outs = self._var_abs2meta['output']
total = self.pathname == ''
szname = 'global_size' if total else 'size'
start = end = 0
for of, _start, _end, _, dist_sizes in self._jac_of_iter():
if wrt_matches is None or of in wrt_matches:
end += (_end - _start)
vec = self._outputs if of in local_outs else None
yield of, start, end, vec, _full_slice, dist_sizes
start = end
for wrt, meta in self._var_abs2meta['input'].items():
if wrt_matches is None or wrt in wrt_matches:
end += meta[szname]
vec = self._inputs if wrt in local_ins else None
dist_sizes = sizes_in[:, toidx[wrt]] if tometa_in[wrt]['distributed'] else None
yield wrt, start, end, vec, _full_slice, dist_sizes
start = end
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 _have_output_solver_options_been_applied(self):
"""
Check to see if the cached output solver options were applied.
"""
for subsys in self.system_iter(include_self=True, recurse=True):
if subsys._output_solver_options: # If options dict not empty, has not been applied
return False # No need to look for more
return True
def set_output_solver_options(self, name, lower=_UNDEFINED, upper=_UNDEFINED,
ref=_UNDEFINED, ref0=_UNDEFINED, res_ref=_UNDEFINED):
"""
Set solver output options.
Allows the user to set output solver options after the output has been defined and
metadata set using the add_ouput method.
Parameters
----------
name : str
Name of the variable in this system's namespace.
lower : float or list or tuple or ndarray or None
Lower bound(s) in user-defined units. It can be (1) a float, (2) an array_like
consistent with the shape arg (if given), or (3) an array_like matching the shape of
val, if val is array_like. A value of None means this output has no lower bound.
Default is None.
upper : float or list or tuple or ndarray or None
Upper bound(s) in user-defined units. It can be (1) a float, (2) an array_like
consistent with the shape arg (if given), or (3) an array_like matching the shape of
val, if val is array_like. A value of None means this output has no upper bound.
Default is None.
ref : float
Scaling parameter. The value in the user-defined units of this output variable when
the scaled value is 1. Default is 1.
ref0 : float
Scaling parameter. The value in the user-defined units of this output variable when
the scaled value is 0. Default is 0.
res_ref : float
Scaling parameter. The value in the user-defined res_units of this output's residual
when the scaled value is 1. Default is None, which means residual scaling matches
output scaling.
"""
# Cache the solver options for use later in the setup process.
# Since this can be called before setup, there is no way to update the
# self._var_allprocs_abs2meta['output'] values since those have not been setup yet.
# These values are applied in the System._apply_output_solver_options method
# which is called in System._setup. That method is only called by the top model.
output_solver_options = {}
if lower is not _UNDEFINED:
output_solver_options['lower'] = lower
if upper is not _UNDEFINED:
output_solver_options['upper'] = upper
if ref is not _UNDEFINED:
output_solver_options['ref'] = ref
if ref0 is not _UNDEFINED:
output_solver_options['ref0'] = ref0
if res_ref is not _UNDEFINED:
output_solver_options['res_ref'] = res_ref
self._output_solver_options[name] = output_solver_options
return
def _apply_output_solver_options(self):
"""
Apply the cached output solver options.
Solver options can be set using the System.set_output_solver_options method.
These cannot be set immediately when that method is called because not
all the variables have been setup at the time a user could potentially want to call it.
So they are cached so that they can be applied later in the setup process.
They are applied in System._setup using this method.
"""
# Loop through the output solver options that have been set on this System
prefix = self.pathname + '.' if self.pathname else ''
for name, options in self._output_solver_options.items():
subsys_path = name.rpartition('.')[0]
subsys = self._get_subsystem(subsys_path) if subsys_path else self
abs_name = prefix + name
# Will need to set both of these dicts to keep them both up-to-date
# _var_allprocs_abs2meta is a partial copy of _var_abs2meta
abs2meta = subsys._var_abs2meta['output']
allprocs_abs2meta = subsys._var_allprocs_abs2meta['output']
if abs_name not in abs2meta:
raise RuntimeError(
f"Output solver options set using System.set_output_solver_options for "
f"non-existent variable '{abs_name}' in System '{self.pathname}'.")
metadatadict_abs2meta = abs2meta[abs_name]
metadatadict_allprocs_abs2meta = allprocs_abs2meta[abs_name]
# Update the metadata that was set
for meta_key in options:
if options[meta_key] is None:
val_as_float_or_array_or_none = None
else:
shape = metadatadict_abs2meta['shape']
val = ensure_compatible(name, options[meta_key], shape)[0]
val_as_float_or_array_or_none = format_as_float_or_array(meta_key, val,
flatten=True)
# Setting both here because the copying of _var_abs2meta to
# _var_allprocs_abs2meta happens before this. Need to keep both up to date
metadatadict_abs2meta.update({
meta_key: val_as_float_or_array_or_none,
})
metadatadict_allprocs_abs2meta.update({
meta_key: val_as_float_or_array_or_none,
})
# recalculate the _has scaling and bounds vars (_has_output_scaling, _has_output_adder,
# _has_resid_scaling, _has_bounds ) across all outputs.
# Since you are allowed to reference multiple subsystems from set_output_solver_options,
# need to loop over all of the ones that got modified by those calls.
# Loop over all the options set. Each one of these could be referencing a different
# subsystem since the name could be a path
for name, options in self._output_solver_options.items():
subsys_path = name.rpartition('.')[0]
subsys = self._get_subsystem(subsys_path) if subsys_path else self
# Now that we know which subsystem was affected. We have to recalculate
# _has_output_scaling, _has_output_adder, _has_resid_scaling, _has_bounds
# across all the outputs of that subsystem, since the changes might have
# affected their values
subsys._has_output_scaling = False
subsys._has_output_adder = False
subsys._has_resid_scaling = False
subsys._has_bounds = False
abs2meta = subsys._var_abs2meta['output']
for abs_name, metadata in abs2meta.items(): # Loop over all outputs for that subsystem
ref = metadata['ref']
if np.isscalar(ref):
subsys._has_output_scaling |= ref != 1.0
else:
subsys._has_output_scaling |= np.any(ref != 1.0)
ref0 = metadata['ref0']
if np.isscalar(ref0):
subsys._has_output_scaling |= ref0 != 0.0
subsys._has_output_adder |= ref0 != 0.0
else:
subsys._has_output_scaling |= np.any(ref0)
subsys._has_output_adder |= np.any(ref0)
res_ref = metadata['res_ref']
if np.isscalar(res_ref):
subsys._has_resid_scaling |= res_ref != 1.0
else:
subsys._has_resid_scaling |= np.any(res_ref != 1.0)
if metadata['lower'] is not None or metadata['upper'] is not None:
subsys._has_bounds = True
# Clear the cached to indicate that the cached values have been applied
self._output_solver_options = {}
def set_design_var_options(self, name,
lower=_UNDEFINED, upper=_UNDEFINED,
scaler=_UNDEFINED, adder=_UNDEFINED,
ref=_UNDEFINED, ref0=_UNDEFINED):
"""
Set options for design vars in the model.
Can be used to set the options outside of setting them when calling add_design_var
Parameters
----------
name : str
Name of the variable in this system's namespace.
lower : float or ndarray, optional
Lower boundary for the input.
upper : upper or ndarray, optional
Upper boundary for the input.
scaler : float or ndarray, optional
Value to multiply the model value to get the scaled value for the driver. scaler
is second in precedence. adder and scaler are an alterantive to using ref
and ref0.
adder : float or ndarray, optional
Value to add to the model value to get the scaled value for the driver. adder
is first in precedence. adder and scaler are an alterantive to using ref
and ref0.
ref : float or ndarray, optional
Value of design var that scales to 1.0 in the driver.
ref0 : float or ndarray, optional
Value of design var that scales to 0.0 in the driver.
"""
# Check inputs
# Name must be a string
if not isinstance(name, str):
raise TypeError('{}: The name argument should be a string, got {}'.format(self.msginfo,
name))
are_new_bounds = lower is not _UNDEFINED or upper is not _UNDEFINED
are_new_scaling = scaler is not _UNDEFINED or adder is not _UNDEFINED or ref is not \
_UNDEFINED or ref0 is not _UNDEFINED
# Must set at least one argument for this function to do something
if not are_new_scaling and not are_new_bounds:
raise RuntimeError(
'Must set a value for at least one argument in call to set_design_var_options.')
if self._static_mode:
design_vars = self._static_design_vars
else:
design_vars = self._design_vars
if name not in design_vars:
msg = "{}: set_design_var_options called with design variable '{}' that does not exist."
raise RuntimeError(msg.format(self.msginfo, name))
existing_dv_meta = design_vars[name]
are_existing_scaling = existing_dv_meta['scaler'] is not None or \
existing_dv_meta['adder'] is not None or \
existing_dv_meta['ref'] is not None or \
existing_dv_meta['ref0'] is not None
are_existing_bounds = existing_dv_meta['lower'] is not None or \
existing_dv_meta['upper'] is not None
# figure out the bounds (lower, upper) based on what is passed to this
# method and what were the existing bounds
if are_new_bounds:
# wipe out all the bounds and only use what is set by the arguments to this call
if lower is _UNDEFINED:
lower = None
if upper is _UNDEFINED:
upper = None
else:
lower = existing_dv_meta['lower']
upper = existing_dv_meta['upper']
if are_new_scaling and are_existing_scaling and are_existing_bounds and not are_new_bounds:
# need to unscale bounds using the existing scaling so the new scaling can
# be applied. But if no new bounds, no need to
if lower is not None:
lower = lower / existing_dv_meta['scaler'] - existing_dv_meta['adder']
if upper is not None:
upper = upper / existing_dv_meta['scaler'] - existing_dv_meta['adder']
# Now figure out scaling
if are_new_scaling:
if scaler is _UNDEFINED:
scaler = None
if adder is _UNDEFINED:
adder = None
if ref is _UNDEFINED:
ref = None
if ref0 is _UNDEFINED:
ref0 = None
else:
scaler = existing_dv_meta['scaler']
adder = existing_dv_meta['adder']
ref = existing_dv_meta['ref']
ref0 = existing_dv_meta['ref0']
# Convert ref/ref0 to ndarray/float as necessary
ref = format_as_float_or_array('ref', ref, val_if_none=None, flatten=True)
ref0 = format_as_float_or_array('ref0', ref0, val_if_none=None, flatten=True)
# determine adder and scaler based on args
adder, scaler = determine_adder_scaler(ref0, ref, adder, scaler)
if lower is None:
# if not set, set lower to -INF_BOUND and don't apply adder/scaler
lower = -INF_BOUND
else:
# Convert lower to ndarray/float as necessary
lower = format_as_float_or_array('lower', lower, flatten=True)
# Apply scaler/adder
lower = (lower + adder) * scaler
if upper is None:
# if not set, set upper to INF_BOUND and don't apply adder/scaler
upper = INF_BOUND
else:
# Convert upper to ndarray/float as necessary
upper = format_as_float_or_array('upper', upper, flatten=True)
# Apply scaler/adder
upper = (upper + adder) * scaler
if isinstance(scaler, np.ndarray):
if np.all(scaler == 1.0):
scaler = None