/
problem.py
3545 lines (3002 loc) · 152 KB
/
problem.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 Problem class and a FakeComm class for non-MPI users."""
import __main__
import shutil
import sys
import pprint
import os
import weakref
import pathlib
import textwrap
import traceback
from collections import defaultdict, namedtuple
from itertools import product
from io import StringIO, TextIOBase
import numpy as np
import scipy.sparse as sparse
from openmdao.core.constants import _SetupStatus
from openmdao.core.component import Component
from openmdao.core.driver import Driver, record_iteration, SaveOptResult
from openmdao.core.explicitcomponent import ExplicitComponent
from openmdao.core.system import System, _OptStatus
from openmdao.core.group import Group
from openmdao.core.total_jac import _TotalJacInfo
from openmdao.core.constants import _DEFAULT_OUT_STREAM, _UNDEFINED
from openmdao.jacobians.dictionary_jacobian import _CheckingJacobian
from openmdao.approximation_schemes.complex_step import ComplexStep
from openmdao.approximation_schemes.finite_difference import FiniteDifference
from openmdao.solvers.solver import SolverInfo
from openmdao.vectors.default_vector import DefaultVector
from openmdao.error_checking.check_config import _default_checks, _all_checks, \
_all_non_redundant_checks
from openmdao.recorders.recording_iteration_stack import _RecIteration
from openmdao.recorders.recording_manager import RecordingManager, record_viewer_data, \
record_model_options
from openmdao.utils.mpi import MPI, FakeComm, multi_proc_exception_check, check_mpi_env
from openmdao.utils.name_maps import name2abs_names
from openmdao.utils.options_dictionary import OptionsDictionary
from openmdao.utils.units import simplify_unit
from openmdao.utils.name_maps import abs_key2rel_key
from openmdao.utils.logger_utils import get_logger, TestLogger
from openmdao.utils.hooks import _setup_hooks, _reset_all_hooks
from openmdao.utils.record_util import create_local_meta
from openmdao.utils.array_utils import scatter_dist_to_local
from openmdao.utils.class_util import overrides_method
from openmdao.utils.reports_system import get_reports_to_activate, activate_reports, \
clear_reports, get_reports_dir, _load_report_plugins
from openmdao.utils.general_utils import pad_name, LocalRangeIterable, \
_find_dict_meta, env_truthy, add_border, match_includes_excludes, inconsistent_across_procs
from openmdao.utils.om_warnings import issue_warning, DerivativesWarning, warn_deprecation, \
OMInvalidCheckDerivativesOptionsWarning
import openmdao.utils.coloring as coloring_mod
from openmdao.visualization.tables.table_builder import generate_table
try:
from openmdao.vectors.petsc_vector import PETScVector
except ImportError:
PETScVector = None
from openmdao.utils.name_maps import rel_key2abs_key, rel_name2abs_name
CITATION = """@article{openmdao_2019,
Author={Justin S. Gray and John T. Hwang and Joaquim R. R. A.
Martins and Kenneth T. Moore and Bret A. Naylor},
Title="{OpenMDAO: An Open-Source Framework for Multidisciplinary
Design, Analysis, and Optimization}",
Journal="{Structural and Multidisciplinary Optimization}",
Year={2019},
Publisher={Springer},
pdf={http://openmdao.org/pubs/openmdao_overview_2019.pdf},
note= {In Press}
}"""
# Used for naming Problems when no explicit name is given
# Also handles sub problems
_problem_names = []
# Used to keep track of the current Problem tree if there are any subproblems
_prob_setup_stack = []
def _clear_problem_names():
global _problem_names
_problem_names = []
_reset_all_hooks()
def _get_top_script():
"""
Return the absolute pathname of the top level script.
Returns
-------
Path or None
The absolute path, or None if it can't be resolved.
"""
try:
return pathlib.Path(__main__.__file__).resolve()
except Exception:
# this will error out in some cases, e.g. inside of a jupyter notebook, so just
# return None in that case.
pass
def _default_prob_name():
"""
Return the default problem name.
Returns
-------
str
The default problem name.
"""
def_prob_name = os.environ.get('OPENMDAO_DEFAULT_PROBLEM', '')
if def_prob_name:
return def_prob_name
name = _get_top_script()
if name is None or env_truthy('TESTFLO_RUNNING'):
return 'problem'
return name.stem
class Problem(object):
"""
Top-level container for the systems and drivers.
Parameters
----------
model : <System> or None
The top-level <System>. If not specified, an empty <Group> will be created.
driver : <Driver> or None
The driver for the problem. If not specified, a simple "Run Once" driver will be used.
comm : MPI.Comm or <FakeComm> or None
The MPI communicator for this Problem. If not specified, comm will be MPI.COMM_WORLD if
MPI is active, else it will be None.
name : str
Problem name. Can be used to specify a Problem instance when multiple Problems
exist.
reports : str, bool, None, _UNDEFINED
If _UNDEFINED, the OPENMDAO_REPORTS variable is used. Defaults to _UNDEFINED.
If given, reports overrides OPENMDAO_REPORTS. If boolean, enable/disable all reports.
Since none is acceptable in the environment variable, a value of reports=None
is equivalent to reports=False. Otherwise, reports may be a sequence of
strings giving the names of the reports to run.
**options : named args
All remaining named args are converted to options.
Attributes
----------
model : <System>
Pointer to the top-level <System> object (root node in the tree).
comm : MPI.Comm or <FakeComm>
The global communicator.
_driver : <Driver>
Slot for the driver. The default driver is `Driver`, which just runs
the model once.
_mode : 'fwd' or 'rev'
Derivatives calculation mode, 'fwd' for forward, and 'rev' for
reverse (adjoint).
_orig_mode : 'fwd', 'rev', or 'auto'
Derivatives calculation mode assigned by the user. If set to 'auto', _mode will be
automatically assigned to 'fwd' or 'rev' based on relative sizes of design variables vs.
responses.
cite : str
Listing of relevant citations that should be referenced when
publishing work that uses this class.
options : <OptionsDictionary>
Dictionary with general options for the problem.
model_options : dict
A dictionary of options to be passed to subsystems in the problem's model during
the setup process.
This dictionary is keyed by a path pattern string, and the associated value for each path
pattern is a dictionary of {option_name: option_val}. Those subsystems within the
hierarchy which match the path pattern and that have an option of the given name, will
have the value of that option overridden by value given in the dictionary.
recording_options : <OptionsDictionary>
Dictionary with problem recording options.
_rec_mgr : <RecordingManager>
Object that manages all recorders added to this problem.
_reports : list of str
Names of reports to activate for this Problem.
_check : bool
If True, call check_config at the end of final_setup.
_filtered_vars_to_record : dict
Dictionary of lists of design vars, constraints, etc. to record.
_logger : object or None
Object for logging config checks if _check is True.
_name : str
Problem name. If no name given, a default name of the form 'problemN', where N is an
integer, will be given to the problem so it can be referenced in command line tools
that have an optional problem name argument
_metadata : dict
Problem level metadata.
_run_counter : int
The number of times run_driver or run_model has been called.
_warned : bool
Bool to check if `value` deprecation warning has occured yet
_computing_coloring : bool
When True, we are computing coloring.
"""
def __init__(self, model=None, driver=None, comm=None, name=None, reports=_UNDEFINED,
**options):
"""
Initialize attributes.
"""
global _problem_names
# this function doesn't do anything after the first call
_load_report_plugins()
self._driver = None
self._reports = get_reports_to_activate(reports)
self.cite = CITATION
self._warned = False
self._computing_coloring = False
# Set the Problem name so that it can be referenced from command line tools (e.g. check)
# that accept a Problem argument, and to name the corresponding reports subdirectory.
if name: # if name hasn't been used yet, use it. Otherwise, error
if name not in _problem_names:
self._name = name
else:
raise ValueError(f"The problem name '{name}' already exists")
else: # No name given: look for a name, of the form, 'problemN', that hasn't been used
problem_counter = len(_problem_names) + 1 if _problem_names else ''
base = _default_prob_name()
_name = f"{base}{problem_counter}"
if _name in _problem_names: # need to make it unique so append string of form '.N'
i = 1
while True:
_name = f"{base}{problem_counter}.{i}"
if _name not in _problem_names:
break
i += 1
self._name = _name
_problem_names.append(self._name)
if comm is None:
use_mpi = check_mpi_env()
if use_mpi is False:
comm = FakeComm()
else:
try:
from mpi4py import MPI
comm = MPI.COMM_WORLD
except ImportError:
comm = FakeComm()
if model is None:
self.model = Group()
elif isinstance(model, Group):
from openmdao.core.parallel_group import ParallelGroup
if isinstance(model, ParallelGroup):
raise TypeError(f"{self.msginfo}: The value provided for 'model' "
"cannot be a ParallelGroup.")
self.model = model
else:
raise TypeError(self.msginfo +
": The value provided for 'model' is not a Group.")
if driver is None:
driver = Driver()
elif not isinstance(driver, Driver):
raise TypeError(self.msginfo +
": The value provided for 'driver' is not a valid Driver.")
self._update_reports(driver)
# can't use driver property here without causing a lint error, so just do it manually
self._driver = driver
self.comm = comm
self._mode = None # mode is assigned in setup()
self._metadata = None
self._run_counter = -1
self._rec_mgr = RecordingManager()
# General options
self.options = OptionsDictionary(parent_name=type(self).__name__)
self.options.declare('coloring_dir', types=str,
default=os.path.join(os.getcwd(), 'coloring_files'),
desc='Directory containing coloring files (if any) for this Problem.')
self.options.declare('group_by_pre_opt_post', types=bool,
default=False,
desc="If True, group subsystems of the top level model into "
"pre-optimization, optimization, and post-optimization, and only "
"iterate over the optimization subsystems during optimization. This "
"applies only when the top level nonlinear solver is of type"
"NonlinearRunOnce.")
self.options.declare('allow_post_setup_reorder', types=bool,
default=True,
desc="If True, the execution order of direct subsystems of any group "
"that sets its 'auto_order' option to True will be automatically "
"ordered according to data dependencies. If this option is False, the "
"'auto_order' option will be ignored and a warning will be issued for "
"each group that has set it to True. Note that subsystems of a Group "
"that form a cycle will never be reordered, regardless of the value of"
" the 'auto_order' option.")
self.options.update(options)
# Options passed to models
self.model_options = {}
# Case recording options
self.recording_options = OptionsDictionary(parent_name=type(self).__name__)
self.recording_options.declare('record_desvars', types=bool, default=True,
desc='Set to True to record design variables at the '
'problem level')
self.recording_options.declare('record_objectives', types=bool, default=True,
desc='Set to True to record objectives at the problem level')
self.recording_options.declare('record_constraints', types=bool, default=True,
desc='Set to True to record constraints at the '
'problem level')
self.recording_options.declare('record_responses', types=bool, default=False,
desc='Set True to record constraints and objectives at the '
'problem level.')
self.recording_options.declare('record_inputs', types=bool, default=False,
desc='Set True to record inputs at the '
'problem level.')
self.recording_options.declare('record_outputs', types=bool, default=True,
desc='Set True to record outputs at the '
'problem level.')
self.recording_options.declare('record_residuals', types=bool, default=False,
desc='Set True to record residuals at the '
'problem level.')
self.recording_options.declare('record_derivatives', types=bool, default=False,
desc='Set to True to record derivatives for the problem '
'level')
self.recording_options.declare('record_abs_error', types=bool, default=True,
desc='Set to True to record absolute error of '
'model nonlinear solver')
self.recording_options.declare('record_rel_error', types=bool, default=True,
desc='Set to True to record relative error of model \
nonlinear solver')
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')
# Start a run by deleting any existing reports so that the files
# that are in that directory are all from this run and not a previous run
reports_dirpath = pathlib.Path(get_reports_dir()).joinpath(f'{self._name}')
if self.comm.rank == 0:
if os.path.isdir(reports_dirpath):
shutil.rmtree(reports_dirpath)
# register hooks for any reports
activate_reports(self._reports, self)
# So Problem and driver can have hooks attached to their methods
_setup_hooks(self)
def _has_active_report(self, name):
"""
Return True if named report is active for this Problem.
Parameters
----------
name : str
Name of the report.
Returns
-------
bool
True if the named report is active for this Problem.
"""
return name in self._reports
def _get_var_abs_name(self, name):
if name in self.model._var_allprocs_abs2meta:
return name
elif name in self.model._var_allprocs_prom2abs_list['output']:
return self.model._var_allprocs_prom2abs_list['output'][name][0]
elif name in self.model._var_allprocs_prom2abs_list['input']:
abs_names = self.model._var_allprocs_prom2abs_list['input'][name]
if len(abs_names) == 1:
return abs_names[0]
else:
raise KeyError(f"{self.msginfo}: Using promoted name `{name}' is ambiguous and "
f"matches unconnected inputs {sorted(abs_names)}. Use absolute name "
"to disambiguate.")
raise KeyError(f'{self.msginfo}: Variable "{name}" not found.')
@property
def driver(self):
"""
Get the Driver for this Problem.
"""
return self._driver
def _update_reports(self, driver):
if self._driver is not None:
# remove any reports on previous driver
clear_reports(self._driver)
driver._set_problem(self)
activate_reports(self._reports, driver)
_setup_hooks(driver)
@driver.setter
def driver(self, driver):
"""
Set this Problem's Driver.
Parameters
----------
driver : <Driver>
Driver to be set to our _driver attribute.
"""
self._update_reports(driver)
self._driver = driver
@property
def msginfo(self):
"""
Return info to prepend to messages.
Returns
-------
str
Info to prepend to messages.
"""
if self._name is None:
return type(self).__name__
return f'{type(self).__name__} {self._name}'
def _get_inst_id(self):
return self._name
def is_local(self, name):
"""
Return True if the named variable or system is local to the current process.
Parameters
----------
name : str
Name of a variable or system.
Returns
-------
bool
True if the named system or variable is local to this process.
"""
if self._metadata is None:
raise RuntimeError(f"{self.msginfo}: is_local('{name}') was called before setup() "
"completed.")
try:
abs_name = self._get_var_abs_name(name)
except KeyError:
sub = self.model._get_subsystem(name)
return sub is not None and sub._is_local
# variable exists, but may be remote
return abs_name in self.model._var_abs2meta['input'] or \
abs_name in self.model._var_abs2meta['output']
@property
def _recording_iter(self):
return self._metadata['recording_iter']
def __getitem__(self, name):
"""
Get an output/input variable.
Parameters
----------
name : str
Promoted or relative variable name in the root system's namespace.
Returns
-------
float or ndarray or any python object
the requested output/input variable.
"""
return self.get_val(name, get_remote=None)
def get_val(self, name, units=None, indices=None, get_remote=False):
"""
Get an output/input variable.
Function is used if you want to specify display units.
Parameters
----------
name : str
Promoted or relative variable name in the root system's namespace.
units : str, optional
Units to convert to before return.
indices : int or list of ints or tuple of ints or int ndarray or Iterable or None, optional
Indices or slice to return.
get_remote : bool or None
If True, retrieve the value even if it is on a remote process. Note that if the
variable is remote on ANY process, this function must be called on EVERY process
in the Problem's MPI communicator.
If False, only retrieve the value if it is on the current process, or only the part
of the value that's on the current process for a distributed variable.
If None and the variable is remote or distributed, a RuntimeError will be raised.
Returns
-------
object
The value of the requested output/input variable.
"""
if self._metadata['setup_status'] == _SetupStatus.POST_SETUP:
abs_names = name2abs_names(self.model, name)
if abs_names:
val = self.model._get_cached_val(name, abs_names, get_remote=get_remote)
if val is not _UNDEFINED:
if indices is not None:
val = val[indices]
if units is not None:
val = self.model.convert2units(name, val, simplify_unit(units))
else:
raise KeyError(f'{self.model.msginfo}: Variable "{name}" not found.')
else:
val = self.model.get_val(name, units=units, indices=indices, get_remote=get_remote,
from_src=True)
if val is _UNDEFINED:
if get_remote:
raise KeyError(f'{self.msginfo}: Variable name "{name}" not found.')
else:
raise RuntimeError(f"{self.model.msginfo}: Variable '{name}' is not local to "
f"rank {self.comm.rank}. You can retrieve values from "
"other processes using `get_val(<name>, get_remote=True)`.")
return val
def __setitem__(self, name, value):
"""
Set an output/input variable.
Parameters
----------
name : str
Promoted or relative variable name in the root system's namespace.
value : float or ndarray or any python object
value to set this variable to.
"""
self.set_val(name, value)
def set_val(self, name, val=None, units=None, indices=None):
"""
Set an output/input variable.
Function is used if you want to set a value using a different unit.
Parameters
----------
name : str
Promoted or relative variable name in the root system's namespace.
val : object
Value to set this variable to.
units : str, optional
Units that value is defined in.
indices : int or list of ints or tuple of ints or int ndarray or Iterable or None, optional
Indices or slice to set to specified value.
"""
if self._metadata is None:
raise RuntimeError(f"{self.msginfo}: '{name}' Cannot call set_val before setup.")
self.model.set_val(name, val, units=units, indices=indices)
def _set_initial_conditions(self):
"""
Set all initial conditions that have been saved in cache after setup.
"""
for value, set_units, pathname, name in self.model._initial_condition_cache.values():
if pathname:
system = self.model._get_subsystem(pathname)
if system is None:
self.model.set_val(pathname + '.' + name, value, units=set_units)
else:
system.set_val(name, value, units=set_units)
else:
self.model.set_val(name, value, units=set_units)
# Clean up cache
self.model._initial_condition_cache = {}
def _check_collected_errors(self):
"""
If any collected errors are found, raise an exception containing all of them.
"""
if self._metadata['saved_errors'] is None:
return
unique_errors = self._get_unique_saved_errors()
# set the errors to None so that all future calls will immediately raise an exception.
self._metadata['saved_errors'] = None
if unique_errors:
final_msg = [f"\nCollected errors for problem '{self._name}':"]
for _, msg, exc_type, tback in unique_errors:
final_msg.append(f" {msg}")
# if there's only one error, include its traceback if it exists.
if len(unique_errors) == 1:
if isinstance(tback, str):
final_msg.append('Traceback (most recent call last):')
final_msg.append(tback)
else:
raise exc_type('\n'.join(final_msg)).with_traceback(tback)
raise RuntimeError('\n'.join(final_msg))
def run_model(self, case_prefix=None, reset_iter_counts=True):
"""
Run the model by calling the root system's solve_nonlinear.
Parameters
----------
case_prefix : str or None
Prefix to prepend to coordinates when recording. None means keep the preexisting
prefix.
reset_iter_counts : bool
If True and model has been run previously, reset all iteration counters.
"""
if not self.model._have_output_solver_options_been_applied():
raise RuntimeError(self.msginfo +
": Before calling `run_model`, the `setup` method must be called "
"if set_output_solver_options has been called.")
if self._mode is None:
raise RuntimeError(self.msginfo +
": The `setup` method must be called before `run_model`.")
old_prefix = self._recording_iter.prefix
if case_prefix is not None:
if not isinstance(case_prefix, str):
raise TypeError(self.msginfo + ": The 'case_prefix' argument should be a string.")
self._recording_iter.prefix = case_prefix
try:
if self.model.iter_count > 0 and reset_iter_counts:
self.driver.iter_count = 0
self.model._reset_iter_counts()
self.final_setup()
self._run_counter += 1
record_model_options(self, self._run_counter)
self.model._clear_iprint()
self.model.run_solve_nonlinear()
finally:
self._recording_iter.prefix = old_prefix
def _set_opt_status(self, status):
self._metadata['opt_status'] = status
def run_driver(self, case_prefix=None, reset_iter_counts=True):
"""
Run the driver on the model.
Parameters
----------
case_prefix : str or None
Prefix to prepend to coordinates when recording. None means keep the preexisting
prefix.
reset_iter_counts : bool
If True and model has been run previously, reset all iteration counters.
Returns
-------
bool
Failure flag; True if failed to converge, False is successful.
"""
model = self.model
driver = self.driver
if self._mode is None:
raise RuntimeError(self.msginfo +
": The `setup` method must be called before `run_driver`.")
if not model._have_output_solver_options_been_applied():
raise RuntimeError(self.msginfo +
": Before calling `run_driver`, the `setup` method must be called "
"if set_output_solver_options has been called.")
if 'singular_jac_behavior' in driver.options:
self._metadata['singular_jac_behavior'] = driver.options['singular_jac_behavior']
old_prefix = self._recording_iter.prefix
if case_prefix is not None:
if not isinstance(case_prefix, str):
raise TypeError(self.msginfo + ": The 'case_prefix' argument should be a string.")
self._recording_iter.prefix = case_prefix
try:
if model.iter_count > 0 and reset_iter_counts:
driver.iter_count = 0
model._reset_iter_counts()
self.final_setup()
# for optimizing drivers, check that constraints are affected by design vars
if driver.supports['optimization'] and self._metadata['use_derivatives']:
driver.check_relevance()
self._run_counter += 1
record_model_options(self, self._run_counter)
model._clear_iprint()
if self.options['group_by_pre_opt_post'] and driver.supports['optimization']:
if model._run_on_opt[_OptStatus.PRE]:
self._set_opt_status(_OptStatus.PRE)
model.run_solve_nonlinear()
with SaveOptResult(driver):
self._set_opt_status(_OptStatus.OPTIMIZING)
result = driver.run()
if model._run_on_opt[_OptStatus.POST]:
self._set_opt_status(_OptStatus.POST)
model.run_solve_nonlinear()
return result
else:
with SaveOptResult(driver):
return driver.run()
finally:
self._recording_iter.prefix = old_prefix
self._set_opt_status(None)
def compute_jacvec_product(self, of, wrt, mode, seed):
"""
Given a seed and 'of' and 'wrt' variables, compute the total jacobian vector product.
Parameters
----------
of : list of str
Variables whose derivatives will be computed.
wrt : list of str
Derivatives will be computed with respect to these variables.
mode : str
Derivative direction ('fwd' or 'rev').
seed : dict or list
Either a dict keyed by 'wrt' varnames (fwd) or 'of' varnames (rev), containing
dresidual (fwd) or doutput (rev) values, OR a list of dresidual or doutput
values that matches the corresponding 'wrt' (fwd) or 'of' (rev) varname list.
Returns
-------
dict
The total jacobian vector product, keyed by variable name.
"""
if mode == 'fwd':
if len(wrt) != len(seed):
raise RuntimeError(self.msginfo +
": seed and 'wrt' list must be the same length in fwd mode.")
lnames, rnames = of, wrt
lkind, rkind = 'output', 'residual'
else: # rev
if len(of) != len(seed):
raise RuntimeError(self.msginfo +
": seed and 'of' list must be the same length in rev mode.")
lnames, rnames = wrt, of
lkind, rkind = 'residual', 'output'
rvec = self.model._vectors[rkind]['linear']
lvec = self.model._vectors[lkind]['linear']
rvec.set_val(0.)
conns = self.model._conn_global_abs_in2out
# set seed values into dresids (fwd) or doutputs (rev)
# seed may have keys that are inputs and must be converted into auto_ivcs
try:
seed[rnames[0]]
except (IndexError, TypeError):
for i, name in enumerate(rnames):
if name in conns:
rvec[conns[name]] = seed[i]
else:
rvec[name] = seed[i]
else:
for name in rnames:
if name in conns:
rvec[conns[name]] = seed[name]
else:
rvec[name] = seed[name]
# We apply a -1 here because the derivative of the output is minus the derivative of
# the residual in openmdao.
data = rvec.asarray()
data *= -1.
self.model.run_solve_linear(mode)
if mode == 'fwd':
return {n: lvec[n].copy() for n in lnames}
else:
# may need to convert some lnames to auto_ivc names
return {n: lvec[conns[n] if n in conns else n].copy() for n in lnames}
def _setup_recording(self):
"""
Set up case recording.
"""
if self._rec_mgr.has_recorders():
self._filtered_vars_to_record = self.driver._get_vars_to_record(self)
self._rec_mgr.startup(self, self.comm)
def add_recorder(self, recorder):
"""
Add a recorder to the problem.
Parameters
----------
recorder : CaseRecorder
A recorder instance.
"""
self._rec_mgr.append(recorder)
def cleanup(self):
"""
Clean up resources prior to exit.
"""
# shut down all recorders
self._rec_mgr.shutdown()
# clean up driver and model resources
self.driver.cleanup()
for system in self.model.system_iter(include_self=True, recurse=True):
system.cleanup()
def record(self, case_name):
"""
Record the variables at the Problem level.
Must be called after `final_setup` has been called. This can either
happen automatically through `run_driver` or `run_model`, or it can be
called manually.
Parameters
----------
case_name : str
Name used to identify this Problem case.
"""
if self._metadata['setup_status'] < _SetupStatus.POST_FINAL_SETUP:
raise RuntimeError(f"{self.msginfo}: Problem.record() cannot be called before "
"`Problem.run_model()`, `Problem.run_driver()`, or "
"`Problem.final_setup()`.")
else:
record_iteration(self, self, case_name)
def _get_recorder_metadata(self, case_name):
"""
Return metadata from the latest iteration for use in the recorder.
Parameters
----------
case_name : str
Name of current case.
Returns
-------
dict
Metadata dictionary for the recorder.
"""
return create_local_meta(case_name)
def setup(self, check=False, logger=None, mode='auto', force_alloc_complex=False,
distributed_vector_class=PETScVector, local_vector_class=DefaultVector,
derivatives=True):
"""
Set up the model hierarchy.
When `setup` is called, the model hierarchy is assembled, the processors are allocated
(for MPI), and variables and connections are all assigned. This method traverses down
the model hierarchy to call `setup` on each subsystem, and then traverses up the model
hierarchy to call `configure` on each subsystem.
Parameters
----------
check : None, bool, list of str, or the strs ‘all’
Determines what config checks, if any, are run after setup is complete.
If None or False, no checks are run
If True, the default checks ('out_of_order', 'system', 'solvers', 'dup_inputs',
'missing_recorders', 'unserializable_options', 'comp_has_no_outputs',
'auto_ivc_warnings') are run
If list of str, run those config checks
If ‘all’, all the checks ('auto_ivc_warnings', 'comp_has_no_outputs', 'cycles',
'dup_inputs', 'missing_recorders', 'all_unserializable_options', 'out_of_order',
'promotions', 'solvers', 'system', 'unconnected_inputs') are run.
logger : object
Object for logging config checks if check is True.
mode : str
Derivatives calculation mode, 'fwd' for forward, and 'rev' for
reverse (adjoint). Default is 'auto', which will pick 'fwd' or 'rev' based on
the direction resulting in the smallest number of linear solves required to
compute derivatives.
force_alloc_complex : bool
If True, sufficient memory will be allocated to allow nonlinear vectors to store
complex values while operating under complex step.
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.
derivatives : bool
If True, perform any memory allocations necessary for derivative computation.
Returns
-------
<Problem>
This enables the user to instantiate and setup in one line.
"""
model = self.model
comm = self.comm
if not isinstance(self.model, Group):
raise TypeError("The model for this Problem is of type "
f"'{self.model.__class__.__name__}'. "
"The model must be a Group or a sub-class of Group.")
# A distributed vector type is required for MPI
if comm.size > 1:
if distributed_vector_class is PETScVector and PETScVector is None:
raise ValueError(f"{self.msginfo}: Attempting to run in parallel under MPI but "
"PETScVector could not be imported.")
elif not distributed_vector_class.distributed:
raise ValueError(f"{self.msginfo}: The `distributed_vector_class` argument must be "
"a distributed vector class like `PETScVector` when running in "
f"parallel under MPI but '{distributed_vector_class.__name__}' "
"was specified which is not distributed.")
if mode not in ['fwd', 'rev', 'auto']:
msg = f"{self.msginfo}: Unsupported mode: '{mode}'. Use either 'fwd' or 'rev'."
raise ValueError(msg)
self._mode = self._orig_mode = mode
model_comm = self.driver._setup_comm(comm)
# this metadata will be shared by all Systems/Solvers in the system tree
self._metadata = {
'name': self._name, # the name of this Problem
'pathname': None, # the pathname of this Problem in the current tree of Problems
'comm': comm,
'coloring_dir': self.options['coloring_dir'], # directory for coloring files
'recording_iter': _RecIteration(comm.rank), # manager of recorder iterations
'local_vector_class': local_vector_class,
'distributed_vector_class': distributed_vector_class,
'solver_info': SolverInfo(),
'use_derivatives': derivatives,
'force_alloc_complex': force_alloc_complex, # forces allocation of complex vectors
'vars_to_gather': {}, # vars that are remote somewhere. does not include distrib vars
'prom2abs': {'input': {}, 'output': {}}, # includes ALL promotes including buried ones
'static_mode': False, # used to determine where various 'static'
# and 'dynamic' data structures are stored.
# Dynamic ones are added during System
# setup/configure. They are wiped out and re-created during
# each Problem setup. Static ones are added outside of
# Problem setup and they are never wiped out or re-created.
'config_info': None, # used during config to determine if additional updates required
'parallel_groups': [], # list of pathnames of parallel groups in this model (all procs)
'setup_status': _SetupStatus.PRE_SETUP,
'model_ref': weakref.ref(model), # ref to the model (needed to get out-of-scope
# src data for inputs)
'has_par_deriv_color': False, # True if any dvs/responses have parallel deriv colors
'mode': mode, # mode (derivative direction) set by the user. 'auto' by default
'abs_in2prom_info': {}, # map of abs input name to list of length = sys tree height
# down to var location, to allow quick resolution of local
# src_shape/src_indices due to promotes. For example,
# for abs_in of a.b.c.d, dict entry would be
# [None, None, None], corresponding to levels
# a, a.b, and a.b.c, with one of the Nones replaced
# by promotes info. Dict entries are only created if
# src_indices are applied to the variable somewhere.
'reports_dir': self.get_reports_dir(), # directory where reports will be written
'saved_errors': [], # store setup errors here until after final_setup
'checking': False, # True if check_totals or check_partials is running