-
Notifications
You must be signed in to change notification settings - Fork 240
/
driver.py
1574 lines (1324 loc) · 60.5 KB
/
driver.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 a base class for all Drivers in OpenMDAO."""
from itertools import chain
import pprint
import sys
import time
import os
import weakref
import numpy as np
from openmdao.core.group import Group
from openmdao.core.total_jac import _TotalJacInfo
from openmdao.core.constants import INT_DTYPE, _SetupStatus
from openmdao.recorders.recording_manager import RecordingManager
from openmdao.recorders.recording_iteration_stack import Recording
from openmdao.utils.hooks import _setup_hooks
from openmdao.utils.record_util import create_local_meta, check_path, has_match
from openmdao.utils.general_utils import _src_name_iter
from openmdao.utils.mpi import MPI
from openmdao.utils.options_dictionary import OptionsDictionary
import openmdao.utils.coloring as coloring_mod
from openmdao.utils.array_utils import sizes2offsets
from openmdao.vectors.vector import _full_slice, _flat_full_indexer
from openmdao.utils.indexer import indexer
from openmdao.utils.om_warnings import issue_warning, DerivativesWarning, DriverWarning
class Driver(object):
"""
Top-level container for the systems and drivers.
Parameters
----------
**kwargs : dict of keyword arguments
Keyword arguments that will be mapped into the Driver options.
Attributes
----------
fail : bool
Reports whether the driver ran successfully.
iter_count : int
Keep track of iterations for case recording.
options : <OptionsDictionary>
Dictionary with general pyoptsparse options.
recording_options : <OptionsDictionary>
Dictionary with driver recording options.
cite : str
Listing of relevant citations that should be referenced when
publishing work that uses this class.
_problem : weakref to <Problem>
Pointer to the containing problem.
supports : <OptionsDictionary>
Provides a consistent way for drivers to declare what features they support.
_designvars : dict
Contains all design variable info.
_designvars_discrete : list
List of design variables that are discrete.
_dist_driver_vars : dict
Dict of constraints that are distributed outputs. Key is a 'user' variable name,
typically promoted name or an alias. Values are (local indices, local sizes).
_cons : dict
Contains all constraint info.
_objs : dict
Contains all objective info.
_responses : dict
Contains all response info.
_remote_dvs : dict
Dict of design variables that are remote on at least one proc. Values are
(owning rank, size).
_remote_cons : dict
Dict of constraints that are remote on at least one proc. Values are
(owning rank, size).
_remote_objs : dict
Dict of objectives that are remote on at least one proc. Values are
(owning rank, size).
_rec_mgr : <RecordingManager>
Object that manages all recorders added to this driver.
_coloring_info : dict
Metadata pertaining to total coloring.
_total_jac_format : str
Specifies the format of the total jacobian. Allowed values are 'flat_dict', 'dict', and
'array'.
_con_subjacs : dict
Dict of sparse subjacobians for use with certain optimizers, e.g. pyOptSparseDriver.
Keyed by sources and aliases.
_total_jac : _TotalJacInfo or None
Cached total jacobian handling object.
_total_jac_linear : _TotalJacInfo or None
Cached linear total jacobian handling object.
opt_result : dict
Dictionary containing information for use in the optimization report.
_has_scaling : bool
If True, scaling has been set for this driver.
"""
def __init__(self, **kwargs):
"""
Initialize the driver.
"""
self._rec_mgr = RecordingManager()
self._problem = None
self._designvars = None
self._designvars_discrete = []
self._cons = None
self._objs = None
self._responses = None
# Driver options
self.options = OptionsDictionary(parent_name=type(self).__name__)
self.options.declare('debug_print', types=list,
values=['desvars', 'nl_cons', 'ln_cons', 'objs', 'totals'],
desc="List of what type of Driver variables to print at each "
"iteration.",
default=[])
default_desvar_behavior = os.environ.get('OPENMDAO_INVALID_DESVAR_BEHAVIOR', 'warn').lower()
self.options.declare('invalid_desvar_behavior', values=('warn', 'raise', 'ignore'),
desc='Behavior of driver if the initial value of a design '
'variable exceeds its bounds. The default value may be'
'set using the `OPENMDAO_INVALID_DESVAR_BEHAVIOR` environment '
'variable to one of the valid options.',
default=default_desvar_behavior)
# 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 '
'driver level')
self.recording_options.declare('record_responses', types=bool, default=False,
desc='Set True to record constraints and objectives at the '
'driver level')
self.recording_options.declare('record_objectives', types=bool, default=True,
desc='Set to True to record objectives at the driver level')
self.recording_options.declare('record_constraints', types=bool, default=True,
desc='Set to True to record constraints at the '
'driver 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('record_derivatives', types=bool, default=False,
desc='Set to True to record derivatives at the driver '
'level')
self.recording_options.declare('record_inputs', types=bool, default=True,
desc='Set to True to record inputs at the driver level')
self.recording_options.declare('record_outputs', types=bool, default=True,
desc='Set True to record outputs at the '
'driver level.')
self.recording_options.declare('record_residuals', types=bool, default=False,
desc='Set True to record residuals at the '
'driver level.')
# What the driver supports.
self.supports = OptionsDictionary(parent_name=type(self).__name__)
self.supports.declare('optimization', types=bool, default=False)
self.supports.declare('inequality_constraints', types=bool, default=False)
self.supports.declare('equality_constraints', types=bool, default=False)
self.supports.declare('linear_constraints', types=bool, default=False)
self.supports.declare('two_sided_constraints', types=bool, default=False)
self.supports.declare('multiple_objectives', types=bool, default=False)
self.supports.declare('integer_design_vars', types=bool, default=True)
self.supports.declare('gradients', types=bool, default=False)
self.supports.declare('active_set', types=bool, default=False)
self.supports.declare('simultaneous_derivatives', types=bool, default=False)
self.supports.declare('total_jac_sparsity', types=bool, default=False)
self.supports.declare('distributed_design_vars', types=bool, default=True)
self.iter_count = 0
self.cite = ""
self._coloring_info = coloring_mod.ColoringMeta()
self._total_jac_format = 'flat_dict'
self._con_subjacs = {}
self._total_jac = None
self._total_jac_linear = None
self.fail = False
self._declare_options()
self.options.update(kwargs)
self.opt_result = {
'runtime': 0.0,
'iter_count': 0,
'obj_calls': 0,
'deriv_calls': 0,
'exit_status': 'NOT_RUN'
}
self._has_scaling = False
def _get_inst_id(self):
if self._problem is None:
return None
return f"{self._problem()._get_inst_id()}.driver"
@property
def msginfo(self):
"""
Return info to prepend to messages.
Returns
-------
str
Info to prepend to messages.
"""
return type(self).__name__
def add_recorder(self, recorder):
"""
Add a recorder to the driver.
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()
def _declare_options(self):
"""
Declare options before kwargs are processed in the init method.
This is optionally implemented by subclasses of Driver.
"""
pass
def _setup_comm(self, comm):
"""
Perform any driver-specific setup of communicators for the model.
Parameters
----------
comm : MPI.Comm or <FakeComm> or None
The communicator for the Problem.
Returns
-------
MPI.Comm or <FakeComm> or None
The communicator for the Problem model.
"""
return comm
def _set_problem(self, problem):
"""
Set a reference to the containing Problem.
Parameters
----------
problem : <Problem>
Reference to the containing problem.
"""
self._problem = weakref.ref(problem)
def _setup_driver(self, problem):
"""
Prepare the driver for execution.
This is the final thing to run during setup.
Parameters
----------
problem : <Problem>
Pointer to the containing problem.
"""
model = problem.model
self._total_jac = None
# Determine if any design variables are discrete.
self._designvars_discrete = [name for name, meta in self._designvars.items()
if meta['source'] in model._discrete_outputs]
if not self.supports['integer_design_vars'] and len(self._designvars_discrete) > 0:
msg = "Discrete design variables are not supported by this driver: "
msg += '.'.join(self._designvars_discrete)
raise RuntimeError(msg)
self._remote_dvs = remote_dv_dict = {}
self._remote_cons = remote_con_dict = {}
self._dist_driver_vars = dist_dict = {}
self._remote_objs = remote_obj_dict = {}
# Only allow distributed design variables on drivers that support it.
if self.supports['distributed_design_vars'] is False:
dist_vars = []
abs2meta_in = model._var_allprocs_abs2meta['input']
discrete_in = model._var_allprocs_discrete['input']
for dv, meta in self._designvars.items():
# For Auto-ivcs, we need to check the distributed metadata on the target instead.
if meta['source'].startswith('_auto_ivc.'):
for abs_name in model._var_allprocs_prom2abs_list['input'][dv]:
# we can use abs name to check for discrete vars here because
# relative names are absolute names at the model level.
if abs_name in discrete_in:
# Discrete vars aren't distributed.
break
if abs2meta_in[abs_name]['distributed']:
dist_vars.append(dv)
break
elif meta['distributed']:
dist_vars.append(dv)
if dist_vars:
dstr = ', '.join(dist_vars)
msg = "Distributed design variables are not supported by this driver, but the "
msg += f"following variables are distributed: [{dstr}]"
raise RuntimeError(msg)
# Now determine if later we'll need to allgather cons, objs, or desvars.
if model.comm.size > 1:
loc_vars = set(model._outputs._abs_iter())
# some of these lists could have duplicate src names if aliases are used. We'll
# fix that when we convert to sets after the allgather.
remote_dvs = [n for n in _src_name_iter(self._designvars) if n not in loc_vars]
remote_cons = [n for n in _src_name_iter(self._cons) if n not in loc_vars]
remote_objs = [n for n in _src_name_iter(self._objs) if n not in loc_vars]
con_set = set()
obj_set = set()
dv_set = set()
all_remote_vois = model.comm.allgather((remote_dvs, remote_cons, remote_objs))
for rem_dvs, rem_cons, rem_objs in all_remote_vois:
con_set.update(rem_cons)
obj_set.update(rem_objs)
dv_set.update(rem_dvs)
# If we have remote VOIs, pick an owning rank for each and use that
# to bcast to others later
owning_ranks = model._owning_rank
abs2idx = model._var_allprocs_abs2idx
abs2meta_out = model._var_allprocs_abs2meta['output']
sizes = model._var_sizes['output']
rank = model.comm.rank
nprocs = model.comm.size
# Loop over all VOIs.
for vname, voimeta in chain(self._responses.items(), self._designvars.items()):
# vname may be a promoted name or an alias
indices = voimeta['indices']
vsrc = voimeta['source']
meta = abs2meta_out[vsrc]
i = abs2idx[vsrc]
if meta['distributed']:
dist_sizes = sizes[:, i]
tot_size = np.sum(dist_sizes)
# Determine which indices are on our proc.
offsets = sizes2offsets(dist_sizes)
if indices is not None:
indices = indices.shaped_array()
true_sizes = np.zeros(nprocs, dtype=INT_DTYPE)
for irank in range(nprocs):
dist_inds = indices[np.logical_and(indices >= offsets[irank],
indices < (offsets[irank] +
dist_sizes[irank]))]
true_sizes[irank] = dist_inds.size
if irank == rank:
local_indices = dist_inds - offsets[rank]
distrib_indices = dist_inds
ind = indexer(local_indices, src_shape=(tot_size,), flat_src=True)
dist_dict[vname] = (ind, true_sizes, distrib_indices)
else:
dist_dict[vname] = (_flat_full_indexer, dist_sizes,
slice(offsets[rank], offsets[rank] + dist_sizes[rank]))
else:
owner = owning_ranks[vsrc]
sz = sizes[owner, i]
if vsrc in dv_set:
remote_dv_dict[vname] = (owner, sz)
if vsrc in con_set:
remote_con_dict[vname] = (owner, sz)
if vsrc in obj_set:
remote_obj_dict[vname] = (owner, sz)
self._remote_responses = self._remote_cons.copy()
self._remote_responses.update(self._remote_objs)
# set up simultaneous deriv coloring
if coloring_mod._use_total_sparsity:
# reset the coloring
if self._coloring_info.dynamic or self._coloring_info.static is not None:
self._coloring_info.coloring = None
coloring = self._get_static_coloring()
if coloring is not None and self.supports['simultaneous_derivatives']:
if model._owns_approx_jac:
coloring._check_config_partial(model)
else:
coloring._check_config_total(self, model)
if not problem.model._use_derivatives:
issue_warning("Derivatives are turned off. Skipping simul deriv coloring.",
category=DerivativesWarning)
def _check_for_missing_objective(self):
"""
Check for missing objective and raise error if no objectives found.
"""
if len(self._objs) == 0:
msg = "Driver requires objective to be declared"
raise RuntimeError(msg)
def _check_for_invalid_desvar_values(self):
"""
Check for design variable values that exceed their bounds.
This method's behavior is controlled by the OPENMDAO_INVALID_DESVAR environment variable,
which may take on values 'ignore', 'raise'', 'warn'.
- 'ignore' : Proceed without checking desvar bounds.
- 'warn' : Issue a warning if one or more desvar values exceed bounds.
- 'raise' : Raise an exception if one or more desvar values exceed bounds.
These options are case insensitive.
"""
if self.options['invalid_desvar_behavior'] != 'ignore':
invalid_desvar_data = []
for var, meta in self._designvars.items():
_val = self._problem().get_val(var, units=meta['units'], get_remote=True)
val = np.array([_val]) if np.ndim(_val) == 0 else _val # Handle discrete desvars
idxs = meta['indices']() if meta['indices'] else None
flat_idxs = meta['flat_indices']
scaler = meta['scaler'] if meta['scaler'] is not None else 1.
adder = meta['adder'] if meta['adder'] is not None else 0.
lower = meta['lower'] / scaler - adder
upper = meta['upper'] / scaler - adder
flat_val = val.ravel()[idxs] if flat_idxs else val[idxs].ravel()
if (flat_val < lower).any() or (flat_val > upper).any():
invalid_desvar_data.append((var, val, lower, upper))
if invalid_desvar_data:
s = 'The following design variable initial conditions are out of their ' \
'specified bounds:'
for var, val, lower, upper in invalid_desvar_data:
s += f'\n {var}\n val: {val.ravel()}' \
f'\n lower: {lower}\n upper: {upper}'
s += '\nSet the initial value of the design variable to a valid value or set ' \
'the driver option[\'invalid_desvar_behavior\'] to \'ignore\'.'
if self.options['invalid_desvar_behavior'] == 'raise':
raise ValueError(s)
else:
issue_warning(s, category=DriverWarning)
def _get_vars_to_record(self, obj=None):
"""
Get variables to record based on recording options.
Parameters
----------
obj : Problem or Driver
Parent object which has recording options.
Returns
-------
dict
Dictionary containing lists of variables to record.
"""
if obj is None:
obj = self
recording_options = obj.recording_options
problem = self._problem()
model = problem.model
incl = recording_options['includes']
excl = recording_options['excludes']
# includes and excludes for outputs are specified using promoted names
# includes and excludes for inputs are specified using _absolute_ names
abs2prom_output = model._var_allprocs_abs2prom['output']
abs2prom_inputs = model._var_allprocs_abs2prom['input']
# set of promoted output names and absolute input and residual names
# used for matching includes/excludes
match_names = set()
# 1. If record_outputs is True, get the set of outputs
# 2. Filter those using includes and excludes to get the baseline set of variables to record
# 3. Add or remove from that set any desvars, objs, and cons based on the recording
# options of those
# includes and excludes for outputs are specified using _promoted_ names
# vectors are keyed on absolute name, discretes on relative/promoted name
myinputs = myoutputs = myresiduals = []
if recording_options['record_outputs']:
match_names = match_names | set(abs2prom_output.values())
myoutputs = [n for n, prom in abs2prom_output.items() if check_path(prom, incl, excl)]
model_outs = model._outputs
if model._var_discrete['output']:
# if we have discrete outputs then residual name set doesn't match output one
if recording_options['record_residuals']:
myresiduals = [n for n in myoutputs if model_outs._contains_abs(n)]
elif recording_options['record_residuals']:
myresiduals = myoutputs
elif recording_options['record_residuals']:
match_names = match_names | set(model._residuals.keys())
myresiduals = [n for n in model._residuals._abs_iter()
if check_path(abs2prom_output[n], incl, excl)]
myoutputs = set(myoutputs)
if recording_options['record_desvars']:
myoutputs.update(_src_name_iter(self._designvars))
if recording_options['record_objectives'] or recording_options['record_responses']:
myoutputs.update(_src_name_iter(self._objs))
if recording_options['record_constraints'] or recording_options['record_responses']:
myoutputs.update(_src_name_iter(self._cons))
# inputs (if in options). inputs use _absolute_ names for includes/excludes
if 'record_inputs' in recording_options:
if recording_options['record_inputs']:
match_names = match_names | set(abs2prom_inputs.keys())
myinputs = [n for n in abs2prom_inputs if check_path(n, incl, excl)]
# check that all exclude/include globs have at least one matching output or input name
for pattern in excl:
if not has_match(pattern, match_names):
issue_warning(f"{obj.msginfo}: No matches for pattern '{pattern}' in "
"recording_options['excludes'].")
for pattern in incl:
if not has_match(pattern, match_names):
issue_warning(f"{obj.msginfo}: No matches for pattern '{pattern}' in "
"recording_options['includes'].")
# sort lists to ensure that vars are iterated over in the same order on all procs
vars2record = {
'input': sorted(myinputs),
'output': sorted(myoutputs),
'residual': sorted(myresiduals)
}
return vars2record
def _setup_recording(self):
"""
Set up case recording.
"""
self._filtered_vars_to_record = self._get_vars_to_record()
self._rec_mgr.startup(self, self._problem().comm)
def _run(self):
"""
Execute this driver.
This calls the run() method, which should be overriden by the subclass.
Returns
-------
bool
Failure flag; True if failed to converge, False is successful.
"""
problem = self._problem()
model = problem.model
if self.supports['optimization'] and problem.options['group_by_pre_opt_post']:
if model._pre_components:
with model._relevance.nonlinear_active('pre'):
model.run_solve_nonlinear()
with SaveOptResult(self):
with model._relevance.nonlinear_active('iter'):
result = self.run()
if model._post_components:
with model._relevance.nonlinear_active('post'):
model.run_solve_nonlinear()
return result
else:
with SaveOptResult(self):
return self.run()
def _get_voi_val(self, name, meta, remote_vois, driver_scaling=True,
get_remote=True, rank=None):
"""
Get the value of a variable of interest (objective, constraint, or design var).
This will retrieve the value if the VOI is remote.
Parameters
----------
name : str
Name of the variable of interest.
meta : dict
Metadata for the variable of interest.
remote_vois : dict
Dict containing (owning_rank, size) for all remote vois of a particular
type (design var, constraint, or objective).
driver_scaling : bool
When True, return values that are scaled according to either the adder and scaler or
the ref and ref0 values that were specified when add_design_var, add_objective, and
add_constraint were called on the model. Default is True.
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.
rank : int or None
If not None, gather value to this rank only.
Returns
-------
float or ndarray
The value of the named variable of interest.
"""
model = self._problem().model
comm = model.comm
get = model._outputs._abs_get_val
indices = meta['indices']
src_name = meta['source']
if MPI:
distributed = comm.size > 0 and name in self._dist_driver_vars
else:
distributed = False
if name in remote_vois:
owner, size = remote_vois[name]
# if var is distributed or only gathering to one rank
# TODO - support distributed var under a parallel group.
if owner is None or rank is not None:
val = model.get_val(src_name, get_remote=get_remote, rank=rank, flat=True)
if indices is not None:
val = val[indices.flat()]
else:
if owner == comm.rank:
if indices is None:
val = get(src_name, flat=True).copy()
else:
val = get(src_name, flat=True)[indices.as_array()]
else:
if indices is not None:
size = indices.indexed_src_size
val = np.empty(size)
if get_remote:
comm.Bcast(val, root=owner)
elif distributed:
local_val = model.get_val(src_name, get_remote=False, flat=True)
local_indices, sizes, _ = self._dist_driver_vars[name]
if local_indices is not _full_slice:
local_val = local_val[local_indices()]
if get_remote:
local_val = np.ascontiguousarray(local_val)
offsets = np.zeros(sizes.size, dtype=INT_DTYPE)
offsets[1:] = np.cumsum(sizes[:-1])
val = np.zeros(np.sum(sizes))
comm.Allgatherv(local_val, [val, sizes, offsets, MPI.DOUBLE])
else:
val = local_val
else:
if src_name in model._discrete_outputs:
val = model._discrete_outputs[src_name]
if name in self._designvars_discrete:
# At present, only integers are supported by OpenMDAO drivers.
# We check the values here.
if not ((np.isscalar(val) and isinstance(val, (int, np.integer))) or
(isinstance(val, np.ndarray) and np.issubdtype(val[0], np.integer))):
if np.isscalar(val):
suffix = f"A value of type '{type(val).__name__}' was specified."
elif isinstance(val, np.ndarray):
suffix = f"An array of type '{val.dtype.name}' was specified."
else:
suffix = ''
raise ValueError("Only integer scalars or ndarrays are supported as values "
"for discrete variables when used as a design variable. "
+ suffix)
elif indices is None:
val = get(src_name, flat=True).copy()
else:
val = get(src_name, flat=True)[indices.as_array()]
if self._has_scaling and driver_scaling:
# Scale design variable values
adder = meta['total_adder']
if adder is not None:
val += adder
scaler = meta['total_scaler']
if scaler is not None:
val *= scaler
return val
def get_driver_objective_calls(self):
"""
Return number of objective evaluations made during a driver run.
Returns
-------
int
Number of objective evaluations made during a driver run.
"""
return 0
def get_driver_derivative_calls(self):
"""
Return number of derivative evaluations made during a driver run.
Returns
-------
int
Number of derivative evaluations made during a driver run.
"""
return 0
def get_design_var_values(self, get_remote=True, driver_scaling=True):
"""
Return the design variable values.
Parameters
----------
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.
driver_scaling : bool
When True, return values that are scaled according to either the adder and scaler or
the ref and ref0 values that were specified when add_design_var, add_objective, and
add_constraint were called on the model. Default is True.
Returns
-------
dict
Dictionary containing values of each design variable.
"""
return {n: self._get_voi_val(n, dvmeta, self._remote_dvs, get_remote=get_remote,
driver_scaling=driver_scaling)
for n, dvmeta in self._designvars.items()}
def set_design_var(self, name, value, set_remote=True):
"""
Set the value of a design variable.
'name' can be a promoted output name or an alias.
Parameters
----------
name : str
Global pathname of the design variable.
value : float or ndarray
Value for the design variable.
set_remote : bool
If True, set the global value of the variable (value must be of the global size).
If False, set the local value of the variable (value must be of the local size).
"""
problem = self._problem()
meta = self._designvars[name]
src_name = meta['source']
# if the value is not local, don't set the value
if (src_name in self._remote_dvs and
problem.model._owning_rank[src_name] != problem.comm.rank):
return
if name in self._designvars_discrete:
# Note, drivers set values here and generally should know it is setting an integer.
# However, the DOEdriver may pull a non-integer value from its generator, so we
# convert it.
if isinstance(value, float):
value = int(value)
elif isinstance(value, np.ndarray):
if isinstance(problem.model._discrete_outputs[src_name], int):
# Setting an integer value with a 1D array - don't want to convert to array.
value = int(value.item())
else:
value = value.astype(int)
problem.model._discrete_outputs[src_name] = value
elif problem.model._outputs._contains_abs(src_name):
desvar = problem.model._outputs._abs_get_val(src_name)
if name in self._dist_driver_vars:
loc_idxs, _, dist_idxs = self._dist_driver_vars[name]
loc_idxs = loc_idxs() # don't use indexer here
else:
loc_idxs = meta['indices']
if loc_idxs is None:
loc_idxs = _full_slice
else:
loc_idxs = loc_idxs()
dist_idxs = _full_slice
if set_remote:
# provided value is the global value, use indices for this proc
desvar[loc_idxs] = np.atleast_1d(value)[dist_idxs]
else:
# provided value is the local value
desvar[loc_idxs] = np.atleast_1d(value)
# Undo driver scaling when setting design var values into model.
if self._has_scaling:
scaler = meta['total_scaler']
if scaler is not None:
desvar[loc_idxs] *= 1.0 / scaler
adder = meta['total_adder']
if adder is not None:
desvar[loc_idxs] -= adder
def get_objective_values(self, driver_scaling=True):
"""
Return objective values.
Parameters
----------
driver_scaling : bool
When True, return values that are scaled according to either the adder and scaler or
the ref and ref0 values that were specified when add_design_var, add_objective, and
add_constraint were called on the model. Default is True.
Returns
-------
dict
Dictionary containing values of each objective.
"""
return {n: self._get_voi_val(n, obj, self._remote_objs,
driver_scaling=driver_scaling)
for n, obj in self._objs.items()}
def get_constraint_values(self, ctype='all', lintype='all', driver_scaling=True):
"""
Return constraint values.
Parameters
----------
ctype : str
Default is 'all'. Optionally return just the inequality constraints
with 'ineq' or the equality constraints with 'eq'.
lintype : str
Default is 'all'. Optionally return just the linear constraints
with 'linear' or the nonlinear constraints with 'nonlinear'.
driver_scaling : bool
When True, return values that are scaled according to either the adder and scaler or
the ref and ref0 values that were specified when add_design_var, add_objective, and
add_constraint were called on the model. Default is True.
Returns
-------
dict
Dictionary containing values of each constraint.
"""
con_dict = {}
for name, meta in self._cons.items():
if lintype == 'linear' and not meta['linear']:
continue
if lintype == 'nonlinear' and meta['linear']:
continue
if ctype == 'eq' and meta['equals'] is None:
continue
if ctype == 'ineq' and meta['equals'] is not None:
continue
con_dict[name] = self._get_voi_val(name, meta, self._remote_cons,
driver_scaling=driver_scaling)
return con_dict
def _get_ordered_nl_responses(self):
"""
Return the names of nonlinear responses in the order used by the driver.
Default order is objectives followed by nonlinear constraints. This is used for
simultaneous derivative coloring and sparsity determination.
Returns
-------
list of str
The nonlinear response names in order.
"""
order = list(self._objs)
order.extend(n for n, meta in self._cons.items()
if not ('linear' in meta and meta['linear']))
return order
def _update_voi_meta(self, model):
"""
Collect response and design var metadata from the model and size desvars and responses.
Parameters
----------
model : System
The System that represents the entire model.
Returns
-------
int
Total size of responses, with linear constraints excluded.
int
Total size of design vars.
"""
self._objs = objs = {}
self._cons = cons = {}
# driver _responses are keyed by either the alias or the promoted name
response_size = 0
self._responses = resps = model.get_responses(recurse=True, use_prom_ivc=True)
for name, data in resps.items():
if data['type'] == 'con':
cons[name] = data
else:
objs[name] = data
response_size += data['global_size']
# Gather up the information for design vars. _designvars are keyed by the promoted name
self._designvars = designvars = model.get_design_vars(recurse=True, use_prom_ivc=True)
desvar_size = sum(data['global_size'] for data in designvars.values())
self._has_scaling = model._setup_driver_units()
return response_size, desvar_size
def get_exit_status(self):
"""
Return exit status of driver run.
Returns
-------
str
String indicating result of driver run.
"""
return 'FAIL' if self.fail else 'SUCCESS'
def check_relevance(self):
"""
Check if there are constraints that don't depend on any design vars.
This usually indicates something is wrong with the problem formulation.
"""
# relevance not relevant if not using derivatives
if not self.supports['gradients']:
return
if 'singular_jac_behavior' in self.options:
singular_behavior = self.options['singular_jac_behavior']
if singular_behavior == 'ignore':
return
else:
singular_behavior = 'warn'
problem = self._problem()
# Do not perform this check if any subgroup uses approximated partials.
# This causes the relevance graph to be invalid.
for system in problem.model.system_iter(include_self=True, recurse=True, typ=Group):
if system._has_approx:
return
bad = {n for n in self._problem().model._relevance._no_dv_responses
if n not in self._designvars}
if bad:
bad_conns = [m['name'] for m in self._cons.values() if m['source'] in bad]
bad_objs = [m['name'] for m in self._objs.values() if m['source'] in bad]
badmsg = []
if bad_conns:
badmsg.append(f"constraint(s) {bad_conns}")
if bad_objs:
badmsg.append(f"objective(s) {bad_objs}")
bad = ' and '.join(badmsg)
# Note: There is a hack in ScipyOptimizeDriver for older versions of COBYLA that
# implements bounds on design variables by adding them as constraints.