-
Notifications
You must be signed in to change notification settings - Fork 240
/
total_jac.py
1932 lines (1663 loc) · 74 KB
/
total_jac.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
"""
Helper class for total jacobian computation.
"""
from collections import OrderedDict, defaultdict
from itertools import chain
from copy import deepcopy
import os
import pprint
import sys
import time
import numpy as np
from openmdao.core.constants import INT_DTYPE
from openmdao.utils.general_utils import ContainsAll, simple_warning, _prom2ivc_src_dict
from openmdao.utils.mpi import MPI, multi_proc_exception_check
from openmdao.utils.coloring import _initialize_model_approx, Coloring
# Attempt to import petsc4py.
# If OPENMDAO_REQUIRE_MPI is set to a recognized positive value, attempt import
# and raise exception on failure. If set to anything else, no import is attempted.
if 'OPENMDAO_REQUIRE_MPI' in os.environ:
if os.environ['OPENMDAO_REQUIRE_MPI'].lower() in ['always', '1', 'true', 'yes']:
from petsc4py import PETSc
else:
PETSc = None
# If OPENMDAO_REQUIRE_MPI is unset, attempt to import petsc4py, but continue on failure
# with a notification.
else:
try:
from petsc4py import PETSc
except ImportError:
PETSc = None
sys.stdout.write("Unable to import petsc4py. Parallel processing unavailable.\n")
sys.stdout.flush()
_contains_all = ContainsAll()
class _TotalJacInfo(object):
"""
Object to manage computation of total derivatives.
Attributes
----------
comm : MPI.Comm or <FakeComm>
The global communicator.
debug_print : bool
When True, print out debug and timing information for each derivative solved.
has_lin_cons : bool
If True, this total jacobian contains linear constraints.
idx_iter_dict : dict
A dict containing an entry for each outer iteration of the total jacobian computation.
J : ndarray
The dense array form of the total jacobian.
J_dict : dict
Nested or flat dict with views of the jacobian.
J_final : ndarray or dict
If return_format is 'array', Jfinal is J. Otherwise it's either a nested dict (if
return_format is 'dict') or a flat dict (return_format 'flat_dict') with views into
the array jacobian.
lin_sol_cache : dict
Dict of indices keyed to solution vectors.
mode : str
If 'fwd' compute deriv in forward mode, else if 'rev', reverse (adjoint) mode.
model : <System>
The top level System of the System tree.
of_meta : dict
Map of absolute output 'of' var name to tuples of the form
(row/column slice, indices, distrib).
wrt_meta : dict
Map of absolute output 'wrt' var name to tuples of the form
(row/column slice, indices, distrib).
ivc_print_names :dict
Dictionary that maps auto_ivc names back to their promoted input names.
output_list : list of str
List of names of output variables for this total jacobian. In fwd mode, outputs
are responses. In rev mode, outputs are design variables.
output_vec : Dict of vectors keyed by vec_name.
Designated output vectors based on value of fwd.
owning_ranks : dict
Map of absolute var name to the MPI process that owns it.
par_deriv : dict
Cache containing names of desvars or responses for each parallel derivative color.
par_deriv_printnames : dict
Companion to par_deriv cache with auto_ivc names mapped to their promoted inputs.
This is used for debug printing.
return_format : str
Indicates the desired return format of the total jacobian. Can have value of
'array', 'dict', or 'flat_dict'.
simul_coloring : Coloring or None
Contains all data necessary to simultaneously solve for groups of total derivatives.
_dist_driver_vars : dict
Dict of constraints that are distributed outputs. Key is abs variable name, values are
(local indices, local sizes).
"""
def __init__(self, problem, of, wrt, use_abs_names, return_format, approx=False,
debug_print=False, driver_scaling=True, get_remote=True):
"""
Initialize object.
Parameters
----------
problem : <Problem>
Reference to that Problem object that contains this _TotalJacInfo.
of : iter of str
Response names.
wrt : iter of str
Design variable names.
use_abs_names : bool
If True, names in of and wrt are absolute names.
return_format : str
Indicates the desired return format of the total jacobian. Can have value of
'array', 'dict', or 'flat_dict'.
approx : bool
If True, the object will compute approx total jacobians.
debug_print : bool
Set to True to print out debug and timing information for each derivative solved.
driver_scaling : bool
If True (default), scale derivative values by the quantities specified when the desvars
and responses were added. If False, leave them unscaled.
"""
driver = problem.driver
prom2abs = problem.model._var_allprocs_prom2abs_list['output']
prom2abs_in = problem.model._var_allprocs_prom2abs_list['input']
conns = problem.model._conn_global_abs_in2out
self.model = model = problem.model
self.comm = problem.comm
self.mode = problem._mode
self.owning_ranks = problem.model._owning_rank
self.has_scaling = driver._has_scaling and driver_scaling
self.return_format = return_format
self.lin_sol_cache = {}
self.debug_print = debug_print
self.par_deriv = {}
self.par_deriv_printnames = {}
self.get_remote = get_remote
if isinstance(wrt, str):
wrt = [wrt]
if isinstance(of, str):
of = [of]
# convert designvar and response dicts to use src names
# keys will all be absolute names after conversion
design_vars = _prom2ivc_src_dict(driver._designvars)
responses = _prom2ivc_src_dict(driver._responses)
if not model._use_derivatives:
raise RuntimeError("Derivative support has been turned off but compute_totals "
"was called.")
driver_wrt = list(driver._designvars)
driver_of = driver._get_ordered_nl_responses()
# In normal use, of and wrt always contain variable names. However, there are unit tests
# that don't specify them, so we need these here.
if wrt is None:
wrt = driver_wrt
if of is None:
of = driver_of
# Convert 'wrt' names from promoted to absolute
prom_wrt = wrt
wrt = []
self.ivc_print_names = {}
for name in prom_wrt:
if name in prom2abs:
wrt_name = prom2abs[name][0]
elif name in prom2abs_in:
in_abs = prom2abs_in[name][0]
wrt_name = conns[in_abs]
self.ivc_print_names[wrt_name] = name
else:
wrt_name = name
wrt.append(wrt_name)
# Convert 'of' names from promoted to absolute
prom_of = of
of = []
for name in prom_of:
if name in prom2abs:
of_name = prom2abs[name][0]
elif name in prom2abs_in:
# An auto_ivc design var can be used as a response too.
in_abs = prom2abs_in[name][0]
of_name = conns[in_abs]
self.ivc_print_names[of_name] = name
else:
of_name = name
of.append(of_name)
if not get_remote and self.comm.size > 1:
self.remote_vois = frozenset(n for n in chain(of, wrt)
if n not in model._var_abs2meta['output'])
else:
self.remote_vois = frozenset()
# raise an exception if we depend on any discrete outputs
if model._var_allprocs_discrete['output']:
discrete_outs = set(model._var_allprocs_discrete['output'])
inps = of if self.mode == 'rev' else wrt
for inp in inps:
inter = discrete_outs.intersection(model._relevant[inp]['@all'][0]['output'])
if inter:
kind = 'of' if self.mode == 'rev' else 'with respect to'
raise RuntimeError("Total derivative %s '%s' depends upon "
"discrete output variables %s." %
(kind, inp, sorted(inter)))
self.of = of
self.wrt = wrt
self.prom_of = prom_of
self.prom_wrt = prom_wrt
self.input_list = {'fwd': wrt, 'rev': of}
self.output_list = {'fwd': of, 'rev': wrt}
self.input_meta = {'fwd': design_vars, 'rev': responses}
self.output_meta = {'fwd': responses, 'rev': design_vars}
self.input_vec = {'fwd': model._vectors['residual'], 'rev': model._vectors['output']}
self.output_vec = {'fwd': model._vectors['output'], 'rev': model._vectors['residual']}
self._dist_driver_vars = driver._dist_driver_vars
abs2meta_out = model._var_allprocs_abs2meta['output']
constraints = driver._cons
for name in prom_of:
if name in constraints and constraints[name]['linear']:
has_lin_cons = True
self.simul_coloring = None
break
else:
has_lin_cons = False
self.has_lin_cons = has_lin_cons
if approx:
_initialize_model_approx(model, driver, self.of, self.wrt)
modes = ['fwd']
else:
if not has_lin_cons:
self.simul_coloring = driver._coloring_info['coloring']
# if we don't get wrt and of from driver, turn off coloring
if self.simul_coloring is not None and \
(prom_wrt != driver_wrt or prom_of != driver_of):
msg = ("compute_totals called using a different list of design vars and/or "
"responses than those used to define coloring, so coloring will "
"be turned off.\ncoloring design vars: %s, current design vars: "
"%s\ncoloring responses: %s, current responses: %s." %
(driver_wrt, wrt, driver_of, of))
simple_warning(msg)
self.simul_coloring = None
if not isinstance(self.simul_coloring, Coloring):
self.simul_coloring = None
if self.simul_coloring is None:
modes = [self.mode]
else:
modes = self.simul_coloring.modes()
self.in_idx_map = {}
self.in_loc_idxs = {}
self.idx_iter_dict = {}
self.seeds = {}
self.loc_jac_idxs = {}
self.dist_idx_map = {}
self.nondist_loc_map = {}
for mode in modes:
self._create_in_idx_map(mode)
self.of_meta, self.of_size = self._get_tuple_map(of, responses, abs2meta_out)
self.wrt_meta, self.wrt_size = self._get_tuple_map(wrt, design_vars, abs2meta_out)
# always allocate a 2D dense array and we can assign views to dict keys later if
# return format is 'dict' or 'flat_dict'.
self.J = J = np.zeros((self.of_size, self.wrt_size))
if not self.get_remote:
abs2meta = model._var_allprocs_abs2meta['output']
for mode in modes:
# If we're running with only a local total jacobian, then we need to keep
# track of which rows/cols actually exist in our local jac and what the
# mapping is between the global row/col index and our local index.
locs = np.nonzero(self.in_loc_idxs[mode] != -1)[0]
arr = np.full(self.in_loc_idxs[mode].size, -1.0, dtype=INT_DTYPE)
arr[locs] = np.arange(locs.size, dtype=INT_DTYPE)
self.loc_jac_idxs[mode] = arr
# we also need a mapping of which indices correspond to distrib vars so
# we can exclude them from jac scatters
axis = 0 if mode == 'fwd' else 1
self.dist_idx_map[mode] = dist_map = np.zeros(arr.size, dtype=bool)
start = end = 0
for name in self.output_list[mode]:
end += abs2meta[name]['size']
if abs2meta[name]['distributed']:
dist_map[start:end] = True
start = end
# create scratch array for jac scatters
self.jac_scratch = None
if self.comm.size > 1 and self.get_remote:
# need 2 scratch vectors of the same size here
scratch = np.zeros(max(J.shape), dtype=J.dtype)
scratch2 = scratch.copy()
self.jac_scratch = {}
if 'fwd' in modes:
self.jac_scratch['fwd'] = (scratch[:J.shape[0]], scratch2[:J.shape[0]])
if 'rev' in modes:
self.jac_scratch['rev'] = (scratch[:J.shape[1]], scratch2[:J.shape[1]])
if not approx:
self.sol2jac_map = {}
for mode in modes:
self.sol2jac_map[mode] = self._get_sol2jac_map(self.output_list[mode],
self.output_meta[mode],
abs2meta_out, mode)
self.jac_scatters = {}
self.tgt_petsc = {n: {} for n in modes}
self.src_petsc = {n: {} for n in modes}
if 'fwd' in modes:
self._compute_jac_scatters('fwd', J.shape[0], get_remote)
if 'rev' in modes:
self._compute_jac_scatters('rev', J.shape[1], get_remote)
# for dict type return formats, map var names to views of the Jacobian array.
if return_format == 'array':
self.J_final = J
if self.has_scaling or approx:
# for array return format, create a 'dict' view for scaling or FD, since
# our scaling and FD data is by variable.
self.J_dict = self._get_dict_J(J, wrt, prom_wrt, of, prom_of,
self.wrt_meta, self.of_meta, 'dict')
else:
self.J_dict = None
else:
self.J_final = self.J_dict = self._get_dict_J(J, wrt, prom_wrt, of, prom_of,
self.wrt_meta, self.of_meta,
return_format)
if self.has_scaling:
self.prom_design_vars = {prom_wrt[i]: design_vars[dv] for i, dv in enumerate(wrt)}
self.prom_responses = {prom_of[i]: responses[r] for i, r in enumerate(of)}
def _compute_jac_scatters(self, mode, rowcol_size, get_remote):
self.jac_scatters[mode] = jac_scatters = {}
model = self.model
nproc = self.comm.size
if (((mode == 'fwd' and get_remote) or (mode == 'rev' and not get_remote)) and
(nproc > 1 or (model._full_comm is not None and model._full_comm.size > 1))):
myrank = self.comm.rank
if get_remote: # fwd
myoffset = rowcol_size * myrank
else: # rev and not get_remote
# reduce size of vector by not including distrib vars
arr = np.ones(rowcol_size, dtype=bool)
start = end = 0
for name in self.sol2jac_map['rev'][2]: # use names but not the mapping
meta = model._var_abs2meta['output'][name]
end += meta['size']
if meta['distributed']:
arr[start:end] = False
start = end
rowcol_size = np.nonzero(arr)[0].size
if np.all(arr):
arr = slice(None) # save some memory and avoid array copies later
self.nondist_loc_map[mode] = arr
loc_size = np.array([rowcol_size], dtype=INT_DTYPE)
jac_sizes = np.zeros(nproc, dtype=INT_DTYPE)
self.comm.Allgather(loc_size, jac_sizes)
myoffset = np.sum(jac_sizes[:myrank])
tgt_vec = PETSc.Vec().createWithArray(np.zeros(rowcol_size, dtype=float),
comm=self.comm)
self.tgt_petsc[mode] = tgt_vec
src_vec = PETSc.Vec().createWithArray(np.zeros(rowcol_size, dtype=float),
comm=self.comm)
self.src_petsc[mode] = src_vec
_, _, name2jinds = self.sol2jac_map[mode]
owns = self.model._owning_rank
abs2meta_out = self.model._var_allprocs_abs2meta['output']
for vecname in model._lin_vec_names:
sizes = self.model._var_sizes[vecname]['output']
abs2idx = self.model._var_allprocs_abs2idx[vecname]
loc_abs = self.model._var_abs2meta['output']
full_j_tgts = []
full_j_srcs = []
start = end = 0
for name in name2jinds:
if name not in abs2idx:
continue
if name in loc_abs:
end += abs2meta_out[name]['size']
if get_remote and abs2meta_out[name]['distributed']:
srcinds = name2jinds[name]
myinds = srcinds + myoffset
for rank in range(nproc):
if rank != myrank:
offset = rowcol_size * rank # J is same size on all procs
full_j_srcs.append(myinds)
full_j_tgts.append(srcinds + offset)
elif not self.get_remote and not abs2meta_out[name]['distributed']:
var_idx = abs2idx[name]
mysize = sizes[myrank, var_idx]
if mysize > 0:
srcinds = np.arange(start, end, dtype=INT_DTYPE)
myinds = srcinds + myoffset
for rank in range(nproc):
if rank != myrank and sizes[rank, var_idx] > 0:
offset = np.sum(jac_sizes[:rank])
full_j_srcs.append(myinds)
full_j_tgts.append(srcinds + offset)
elif owns[name] == myrank:
srcinds = name2jinds[name]
myinds = srcinds + myoffset
var_idx = abs2idx[name]
for rank in range(nproc):
if rank != myrank and sizes[rank, var_idx] == 0:
offset = rowcol_size * rank # J is same size on all procs
full_j_srcs.append(myinds)
full_j_tgts.append(srcinds + offset)
if name in loc_abs:
start = end
if full_j_srcs:
full_src_inds = np.hstack(full_j_srcs)
full_tgt_inds = np.hstack(full_j_tgts)
else:
full_src_inds = np.zeros(0, dtype=INT_DTYPE)
full_tgt_inds = np.zeros(0, dtype=INT_DTYPE)
src_indexset = PETSc.IS().createGeneral(full_src_inds, comm=self.comm)
tgt_indexset = PETSc.IS().createGeneral(full_tgt_inds, comm=self.comm)
jac_scatters[vecname] = PETSc.Scatter().create(src_vec, src_indexset,
tgt_vec, tgt_indexset)
else:
for vecname in model._lin_vec_names:
jac_scatters[vecname] = None
def _get_dict_J(self, J, wrt, prom_wrt, of, prom_of, wrt_meta, of_meta, return_format):
"""
Create a dict or flat-dict jacobian that maps to views in the given 2D array jacobian.
Parameters
----------
J : ndarray
Array jacobian.
wrt : iter of str
Absolute names of 'with respect to' vars.
prom_wrt : iter of str
Promoted names of 'with respect to' vars.
of : iter of str
Absolute names of output vars.
prom_of : iter of str
Promoted names of output vars.
wrt_meta : dict
Dict mapping absolute 'with respect to' name to array jacobian slice, indices,
and distrib.
of_meta : dict
Dict mapping absolute output name to array jacobian slice, indices, and distrib.
return_format : str
Indicates the desired form of the returned jacobian.
Returns
-------
OrderedDict
Dict form of the total jacobian that contains views of the ndarray jacobian.
"""
J_dict = OrderedDict()
if return_format == 'dict':
for i, out in enumerate(of):
if out in self.remote_vois:
continue
J_dict[prom_of[i]] = outer = OrderedDict()
out_slice = of_meta[out][0]
for j, inp in enumerate(wrt):
if inp not in self.remote_vois:
outer[prom_wrt[j]] = J[out_slice, wrt_meta[inp][0]]
elif return_format == 'flat_dict':
for i, out in enumerate(of):
if out in self.remote_vois:
continue
out_slice = of_meta[out][0]
for j, inp in enumerate(wrt):
if inp not in self.remote_vois:
J_dict[prom_of[i], prom_wrt[j]] = J[out_slice, wrt_meta[inp][0]]
elif return_format == 'flat_dict_structured_key':
# This format is supported by the recorders (specifically the sql recorder), which use
# numpy structured arrays.
for i, out in enumerate(of):
if out in self.remote_vois:
continue
out_slice = of_meta[out][0]
for j, inp in enumerate(wrt):
if inp not in self.remote_vois:
key = "%s!%s" % (prom_of[i], prom_wrt[j])
J_dict[key] = J[out_slice, wrt_meta[inp][0]]
else:
raise ValueError("'%s' is not a valid jacobian return format." % return_format)
return J_dict
def _create_in_idx_map(self, mode):
"""
Create a list that maps a global index to a name, col/row range, and other data.
Parameters
----------
mode : str
Derivative solution direction.
"""
iproc = self.comm.rank
model = self.model
relevant = model._relevant
has_par_deriv_color = False
abs2meta_out = model._var_allprocs_abs2meta['output']
var_sizes = model._var_sizes
var_offsets = model._get_var_offsets()
abs2idx = model._var_allprocs_abs2idx
idx_iter_dict = OrderedDict() # a dict of index iterators
simul_coloring = self.simul_coloring
if simul_coloring:
simul_color_modes = {'fwd': simul_coloring._fwd, 'rev': simul_coloring._rev}
vois = self.input_meta[mode]
input_list = self.input_list[mode]
seed = []
fwd = mode == 'fwd'
loc_idxs = []
idx_map = []
start = 0
end = 0
# If we call compute_totals with any 'wrt' or 'of' that is outside of an existing driver
# var set, then we need to ignore the computed relevancy and perform GS iterations on all
# comps. Note, the inputs are handled individually by direct check vs the relevancy dict,
# so we just bulk check the outputs here.
qoi_i = self.input_meta[mode]
qoi_o = self.output_meta[mode]
if qoi_i and qoi_o:
non_rel_outs = [out for out in self.output_list[mode]
if out not in qoi_i and out not in qoi_o]
else:
non_rel_outs = None
for name in input_list:
rhsname = 'linear'
if name not in abs2meta_out:
# could be promoted input name
abs_in = model._var_allprocs_prom2abs_list['input'][name][0]
name = model._conn_global_abs_in2out[abs_in]
in_var_meta = abs2meta_out[name]
if name in vois:
# if name is in vois, then it has been declared as either a design var or
# a constraint or an objective.
meta = vois[name]
if meta['distributed']:
end += meta['global_size']
else:
end += meta['size']
parallel_deriv_color = meta['parallel_deriv_color']
matmat = meta['vectorize_derivs']
cache_lin_sol = meta['cache_linear_solution']
_check_voi_meta(name, parallel_deriv_color, matmat, simul_coloring)
if matmat or parallel_deriv_color:
rhsname = name
if parallel_deriv_color:
if parallel_deriv_color not in self.par_deriv:
self.par_deriv[parallel_deriv_color] = []
self.par_deriv_printnames[parallel_deriv_color] = []
self.par_deriv[parallel_deriv_color].append(name)
print_name = name
if name in self.ivc_print_names:
print_name = self.ivc_print_names[name]
self.par_deriv_printnames[parallel_deriv_color].append(print_name)
in_idxs = meta['indices'] if 'indices' in meta else None
if in_idxs is None:
# if the var is not distributed, global_size == local size
irange = np.arange(in_var_meta['global_size'], dtype=INT_DTYPE)
else:
irange = in_idxs.copy()
# correct for any negative indices
irange[in_idxs < 0] += in_var_meta['global_size']
else: # name is not a design var or response (should only happen during testing)
end += in_var_meta['global_size']
irange = np.arange(in_var_meta['global_size'], dtype=INT_DTYPE)
in_idxs = parallel_deriv_color = matmat = None
cache_lin_sol = False
in_var_idx = abs2idx[rhsname][name]
sizes = var_sizes[rhsname]['output']
offsets = var_offsets[rhsname]['output']
gstart = np.sum(sizes[:iproc, in_var_idx])
gend = gstart + sizes[iproc, in_var_idx]
if in_var_meta['distributed']:
ndups = 1
else:
# if the var is not distributed, convert the indices to global.
# We don't iterate over the full distributed size in this case.
irange += gstart
if fwd:
ndups = 1
else:
# find the number of duplicate components in rev mode so we can divide
# the seed between 'ndups' procs so that at the end after we do an
# Allreduce, the contributions from all procs will add up properly.
ndups = np.nonzero(sizes[:, in_var_idx])[0].size
# all local idxs that correspond to vars from other procs will be -1
# so each entry of loc_i will either contain a valid local index,
# indicating we should set the local vector entry to 1.0 before running
# solve_linear, or it will contain -1, indicating we should not set any
# value before calling solve_linear.
loc_i = np.full(irange.shape, -1, dtype=INT_DTYPE)
if gend > gstart:
loc = np.nonzero(np.logical_and(irange >= gstart, irange < gend))[0]
if in_idxs is None:
if in_var_meta['distributed']:
loc_i[loc] = np.arange(0, gend - gstart, dtype=INT_DTYPE)
else:
loc_i[loc] = irange[loc] - gstart
else:
loc_i[loc] = irange[loc]
loc_i[loc] -= gstart
loc_offset = offsets[iproc, in_var_idx] - offsets[iproc, 0]
loc_i[loc] += loc_offset
loc_idxs.append(loc_i)
# We apply a -1 here because the derivative of the output is minus the derivative of
# the input
seed.append(np.full(irange.size, -1.0 / ndups, dtype=float))
if parallel_deriv_color:
has_par_deriv_color = True
if parallel_deriv_color not in idx_iter_dict:
if matmat:
it = self.par_deriv_matmat_iter
else:
it = self.par_deriv_iter
imeta = defaultdict(bool)
imeta['par_deriv_color'] = parallel_deriv_color
imeta['matmat'] = matmat
imeta['idx_list'] = [(start, end)]
idx_iter_dict[parallel_deriv_color] = (imeta, it)
else:
imeta, _ = idx_iter_dict[parallel_deriv_color]
if imeta['matmat'] != matmat:
raise RuntimeError('Mixing of vectorized and non-vectorized derivs in '
'the same parallel color group (%s) is not '
'supported.' % parallel_deriv_color)
imeta['idx_list'].append((start, end))
elif matmat:
if name not in idx_iter_dict:
imeta = defaultdict(bool)
imeta['matmat'] = matmat
imeta['idx_list'] = [np.arange(start, end, dtype=INT_DTYPE)]
idx_iter_dict[name] = (imeta, self.matmat_iter)
else:
raise RuntimeError("Variable name '%s' matches a parallel_deriv_color "
"name." % name)
elif not simul_coloring: # plain old single index iteration
imeta = defaultdict(bool)
imeta['idx_list'] = np.arange(start, end, dtype=INT_DTYPE)
idx_iter_dict[name] = (imeta, self.single_index_iter)
if name in relevant and not non_rel_outs:
tup = (rhsname, relevant[name]['@all'][1], cache_lin_sol)
else:
tup = (rhsname, _contains_all, cache_lin_sol)
idx_map.extend([tup] * (end - start))
start = end
if has_par_deriv_color:
_fix_pdc_lengths(idx_iter_dict)
loc_idxs = np.hstack(loc_idxs)
seed = np.hstack(seed)
if simul_coloring and simul_color_modes[mode] is not None:
imeta = defaultdict(bool)
imeta['coloring'] = simul_coloring
all_rel_systems = set()
cache = False
imeta['itermeta'] = itermeta = []
locs = None
for ilist in simul_coloring.color_iter(mode):
for i in ilist:
_, rel_systems, cache_lin_sol = idx_map[i]
_update_rel_systems(all_rel_systems, rel_systems)
cache |= cache_lin_sol
iterdict = defaultdict(bool)
if len(ilist) > 1:
locs = loc_idxs[ilist]
active = locs != -1
iterdict['local_in_idxs'] = locs[active]
iterdict['seeds'] = seed[ilist][active]
iterdict['relevant'] = all_rel_systems
iterdict['cache_lin_solve'] = cache
itermeta.append(iterdict)
idx_iter_dict['@simul_coloring'] = (imeta, self.simul_coloring_iter)
self.in_idx_map[mode] = idx_map
self.in_loc_idxs[mode] = loc_idxs
self.idx_iter_dict[mode] = idx_iter_dict
self.seeds[mode] = seed
def _get_sol2jac_map(self, names, vois, allprocs_abs2meta_out, mode):
"""
Create a dict mapping vecname and direction to an index array into the solution vector.
Using the index array to pull values from the solution vector will give the values
in the order needed by the jacobian.
Parameters
----------
names : iter of str
Names of the variables making up the rows or columns of the jacobian.
vois : dict
Mapping of variable of interest (desvar or response) name to its metadata.
allprocs_abs2meta_out : dict
Mapping of absolute output name to metadata for that var across all procs.
mode : str
Derivative solution direction.
Returns
-------
ndarray
Indices into the solution vector.
ndarray
Indices into a jacobian row or column.
dict
Mapping of var name to jacobian row or column indices.
"""
sol_idxs = {}
jac_idxs = {}
model = self.model
fwd = mode == 'fwd'
myproc = self.comm.rank
name2jinds = {} # map varname to jac row or col idxs that we must scatter to other procs
for vecname in model._lin_vec_names:
inds = []
jac_inds = []
sizes = model._var_sizes[vecname]['output']
ncols = model._vectors['output'][vecname]._ncol
slices = model._vectors['output'][vecname].get_slice_dict()
abs2idx = model._var_allprocs_abs2idx[vecname]
jstart = jend = 0
for name in names:
indices = vois[name]['indices'] if name in vois else None
meta = allprocs_abs2meta_out[name]
if indices is not None:
sz = len(indices)
else:
if self.get_remote:
sz = meta['global_size']
else:
sz = meta['size']
if name in abs2idx and name in slices and name not in self.remote_vois:
var_idx = abs2idx[name]
slc = slices[name]
if MPI and meta['distributed'] and model.comm.size > 1 and self.get_remote:
if indices is not None:
local_idx, sizes_idx, _ = self._dist_driver_vars[name]
dist_offset = np.sum(sizes_idx[:myproc])
full_inds = np.arange(slc.start / ncols, slc.stop / ncols,
dtype=INT_DTYPE)
inds.append(full_inds[local_idx])
jac_inds.append(jstart + dist_offset +
np.arange(len(local_idx), dtype=INT_DTYPE))
if fwd or not self.get_remote:
name2jinds[name] = jac_inds[-1]
else:
dist_offset = np.sum(sizes[:myproc, var_idx])
inds.append(np.arange(slc.start / ncols, slc.stop / ncols,
dtype=INT_DTYPE))
jac_inds.append(np.arange(jstart + dist_offset,
jstart + dist_offset + sizes[myproc, var_idx],
dtype=INT_DTYPE))
if fwd or not self.get_remote:
name2jinds[name] = jac_inds[-1]
else:
idx_array = np.arange(slc.start // ncols, slc.stop // ncols,
dtype=INT_DTYPE)
if indices is not None:
idx_array = idx_array[indices]
inds.append(idx_array)
jac_inds.append(np.arange(jstart, jstart + sz, dtype=INT_DTYPE))
if fwd or not self.get_remote:
name2jinds[name] = jac_inds[-1]
if name not in self.remote_vois:
jend += sz
jstart = jend
if inds:
sol_idxs[vecname] = np.hstack(inds)
jac_idxs[vecname] = np.hstack(jac_inds)
else:
sol_idxs[vecname] = np.zeros(0, dtype=INT_DTYPE)
jac_idxs[vecname] = np.zeros(0, dtype=INT_DTYPE)
return sol_idxs, jac_idxs, name2jinds
def _get_tuple_map(self, names, vois, abs2meta_out):
"""
Create a dict that maps var name to metadata tuple.
The tuple has the form (jacobian row/column slice, indices, distrib)
Parameters
----------
names : iter of str
Names of the variables making up the rows or columns of the jacobian.
vois : dict
Mapping of variable of interest (desvar or response) name to its metadata.
abs2meta_out : dict
Mapping of absolute output var name to metadata for that var.
Returns
-------
dict
Dict of metadata tuples keyed by output name.
int
Total number of rows or columns.
"""
idx_map = {}
start = 0
end = 0
get_remote = self.get_remote
for name in names:
if name in self.remote_vois:
continue
if name in vois:
voi = vois[name]
# this 'size' already takes indices into account
if get_remote and voi['distributed']:
size = voi['global_size']
else:
size = voi['size']
indices = vois[name]['indices']
else:
size = abs2meta_out[name]['global_size']
indices = None
end += size
idx_map[name] = (slice(start, end), indices, abs2meta_out[name]['distributed'])
start = end
return idx_map, end # after the loop, end is the total size
#
# outer loop iteration functions
#
def single_index_iter(self, imeta, mode):
"""
Iterate over single indices for a single variable.
Parameters
----------
imeta : dict
Dictionary of iteration metadata.
mode : str
Direction of derivative solution.
Yields
------
int
Current index.
method
Input setter method.
method
Jac setter method.
"""
for i in imeta['idx_list']:
yield i, self.single_input_setter, self.single_jac_setter, None
def simul_coloring_iter(self, imeta, mode):
"""
Iterate over index lists for the simul coloring case.
Parameters
----------
imeta : dict
Dictionary of iteration metadata.
mode : str
Direction of derivative solution.
Yields
------
list of int or int
Current indices or current index.
method
Input setter method.
method
Jac setter method.
"""
coloring = imeta['coloring']
both = coloring._fwd and coloring._rev
input_setter = self.simul_coloring_input_setter
jac_setter = self.simul_coloring_jac_setter
for color, ilist in enumerate(coloring.color_iter(mode)):
if len(ilist) == 1:
if both:
yield ilist, input_setter, jac_setter, None
else:
yield ilist[0], self.single_input_setter, self.single_jac_setter, None
else:
# yield all indices for a color at once
yield ilist, input_setter, jac_setter, imeta['itermeta'][color]
def par_deriv_iter(self, imeta, mode):
"""
Iterate over index lists for the parallel deriv case.
Parameters
----------
imeta : dict
Dictionary of iteration metadata.
mode : str
Direction of derivative solution.
Yields
------
list of int
Current indices.
method
Input setter method.
method
Jac setter method.
"""
idxs = imeta['idx_list']
for tup in zip(*idxs):
yield tup, self.par_deriv_input_setter, self.par_deriv_jac_setter, None
def matmat_iter(self, imeta, mode):
"""
Iterate over index lists for the matrix matrix case.
Parameters
----------
imeta : dict
Dictionary of iteration metadata.
mode : str
Direction of derivative solution.
Yields
------
list of int
Current indices.
method