-
Notifications
You must be signed in to change notification settings - Fork 240
/
component.py
1580 lines (1349 loc) · 68.7 KB
/
component.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 Component class."""
from collections import OrderedDict, Counter, defaultdict
from collections.abc import Iterable
from itertools import product
import numpy as np
from numpy import ndarray, isscalar, atleast_1d, atleast_2d, promote_types
from scipy.sparse import issparse
from openmdao.core.system import System, _supported_methods, _DEFAULT_COLORING_META, \
global_meta_names
from openmdao.core.constants import INT_DTYPE
from openmdao.jacobians.dictionary_jacobian import DictionaryJacobian
from openmdao.vectors.vector import _full_slice
from openmdao.utils.array_utils import shape_to_len
from openmdao.utils.units import valid_units, simplify_unit
from openmdao.utils.name_maps import rel_key2abs_key, abs_key2rel_key, rel_name2abs_name
from openmdao.utils.mpi import MPI
from openmdao.utils.general_utils import format_as_float_or_array, ensure_compatible, \
find_matches, simple_warning, make_set, _is_slicer_op, warn_deprecation, convert_src_inds, \
_slice_indices
import openmdao.utils.coloring as coloring_mod
_forbidden_chars = ['.', '*', '?', '!', '[', ']']
_whitespace = set([' ', '\t', '\r', '\n'])
def _valid_var_name(name):
"""
Determine if the proposed name is a valid variable name.
Leading and trailing whitespace is illegal, and a specific list of characters
are illegal anywhere in the string.
Parameters
----------
name : str
Proposed name.
Returns
-------
bool
True if the proposed name is a valid variable name, else False.
"""
global _forbidden_chars, _whitespace
if not name:
return False
for char in _forbidden_chars:
if char in name:
return False
return name[0] not in _whitespace and name[-1] not in _whitespace
class Component(System):
"""
Base Component class; not to be directly instantiated.
Attributes
----------
_approx_schemes : OrderedDict
A mapping of approximation types to the associated ApproximationScheme.
_var_rel2meta : dict
Dictionary mapping relative names to metadata.
This is only needed while adding inputs and outputs. During setup, these are used to
build the dictionaries of metadata.
_static_var_rel2meta : dict
Static version of above - stores data for variables added outside of setup.
_var_rel_names : {'input': [str, ...], 'output': [str, ...]}
List of relative names of owned variables existing on current proc.
This is only needed while adding inputs and outputs. During setup, these are used to
determine the list of absolute names.
_static_var_rel_names : dict
Static version of above - stores names of variables added outside of setup.
_declared_partials : dict
Cached storage of user-declared partials.
_declared_partial_checks : list
Cached storage of user-declared check partial options.
_no_check_partials : bool
If True, the check_partials function will ignore this component.
"""
def __init__(self, **kwargs):
"""
Initialize all attributes.
Parameters
----------
**kwargs : dict of keyword arguments
available here and in all descendants of this system.
"""
super().__init__(**kwargs)
self._var_rel_names = {'input': [], 'output': []}
self._var_rel2meta = {}
self._static_var_rel_names = {'input': [], 'output': []}
self._static_var_rel2meta = {}
self._declared_partials = defaultdict(dict)
self._declared_partial_checks = []
self._no_check_partials = False
def _declare_options(self):
"""
Declare options before kwargs are processed in the init method.
"""
super()._declare_options()
self.options.declare('distributed', types=bool, default=False,
desc='True if the component has variables that are distributed '
'across multiple processes.')
def setup(self):
"""
Declare inputs and outputs.
Available attributes:
name
pathname
comm
options
"""
pass
def _setup_procs(self, pathname, comm, mode, prob_meta):
"""
Execute first phase of the setup process.
Distribute processors, assign pathnames, and call setup on the component.
Parameters
----------
pathname : str
Global name of the system, including the path.
comm : MPI.Comm or <FakeComm>
MPI communicator object.
mode : str
Derivatives calculation mode, 'fwd' for forward, and 'rev' for
reverse (adjoint). Default is 'rev'.
prob_meta : dict
Problem level metadata.
"""
super()._setup_procs(pathname, comm, mode, prob_meta)
orig_comm = comm
if self._num_par_fd > 1:
if comm.size > 1:
comm = self._setup_par_fd_procs(comm)
elif not MPI:
msg = ("%s: MPI is not active but num_par_fd = %d. No parallel finite difference "
"will be performed." % (self.msginfo, self._num_par_fd))
simple_warning(msg)
self.comm = comm
# Clear out old variable information so that we can call setup on the component.
self._var_rel_names = {'input': [], 'output': []}
self._var_rel2meta = {}
# reset shape if any dynamic shape parameters are set in case this is a resetup
# NOTE: this is necessary because we allow variables to be added in __init__.
for meta in self._static_var_rel2meta.values():
if 'shape_by_conn' in meta and (meta['shape_by_conn'] or
meta['copy_shape'] is not None):
meta['shape'] = None
if not np.isscalar(meta['value']):
if meta['value'].size > 0:
meta['value'] = meta['value'].flatten()[0]
else:
meta['value'] = 1.0
self._var_rel2meta.update(self._static_var_rel2meta)
for io in ['input', 'output']:
self._var_rel_names[io].extend(self._static_var_rel_names[io])
self.setup()
self._set_vector_class()
def _set_vector_class(self):
if self.options['distributed']:
dist_vec_class = self._problem_meta['distributed_vector_class']
if dist_vec_class is not None:
self._vector_class = dist_vec_class
else:
simple_warning("The 'distributed' option is set to True for Component %s, "
"but there is no distributed vector implementation (MPI/PETSc) "
"available. The default non-distributed vectors will be used."
% self.pathname)
self._vector_class = self._problem_meta['local_vector_class']
else:
self._vector_class = self._problem_meta['local_vector_class']
def _configure_check(self):
"""
Do any error checking on i/o configuration.
"""
# check here if declare_coloring was called during setup but declare_partials
# wasn't. If declare partials wasn't called, call it with of='*' and wrt='*' so we'll
# have something to color.
if self._coloring_info['coloring'] is not None:
for key, meta in self._declared_partials.items():
if 'method' in meta and meta['method'] is not None:
break
else:
method = self._coloring_info['method']
simple_warning("%s: declare_coloring or use_fixed_coloring was called but no approx"
" partials were declared. Declaring all partials as approximated "
"using default metadata and method='%s'." % (self.msginfo, method))
self.declare_partials('*', '*', method=method)
super()._configure_check()
def _setup_var_data(self):
"""
Compute the list of abs var names, abs/prom name maps, and metadata dictionaries.
"""
global global_meta_names
super()._setup_var_data()
allprocs_prom2abs_list = self._var_allprocs_prom2abs_list
abs2prom = self._var_allprocs_abs2prom = self._var_abs2prom
# Compute the prefix for turning rel/prom names into abs names
prefix = self.pathname + '.' if self.pathname else ''
iproc = self.comm.rank
for io in ['input', 'output']:
abs2meta = self._var_abs2meta[io]
allprocs_abs2meta = self._var_allprocs_abs2meta[io]
is_input = io == 'input'
for i, prom_name in enumerate(self._var_rel_names[io]):
abs_name = prefix + prom_name
abs2meta[abs_name] = metadata = self._var_rel2meta[prom_name]
# Compute allprocs_prom2abs_list, abs2prom
allprocs_prom2abs_list[io][prom_name] = [abs_name]
abs2prom[io][abs_name] = prom_name
allprocs_abs2meta[abs_name] = {
meta_name: metadata[meta_name]
for meta_name in global_meta_names[io]
}
if is_input and 'src_indices' in metadata:
allprocs_abs2meta[abs_name]['has_src_indices'] = \
metadata['src_indices'] is not None
# ensure that if src_indices is a slice we reset it to that instead of
# the converted array value (in case this is a re-setup), so that we can
# re-convert using potentially different sizing information.
if metadata['src_slice'] is not None:
metadata['src_indices'] = metadata['src_slice']
for prom_name, val in self._var_discrete[io].items():
abs_name = prefix + prom_name
# Compute allprocs_prom2abs_list, abs2prom
allprocs_prom2abs_list[io][prom_name] = [abs_name]
abs2prom[io][abs_name] = prom_name
# Compute allprocs_discrete (metadata for discrete vars)
self._var_allprocs_discrete[io][abs_name] = v = val.copy()
del v['value']
if self._var_discrete['input'] or self._var_discrete['output']:
self._discrete_inputs = _DictValues(self._var_discrete['input'])
self._discrete_outputs = _DictValues(self._var_discrete['output'])
else:
self._discrete_inputs = self._discrete_outputs = ()
def _setup_var_sizes(self):
"""
Compute the arrays of variable sizes for all variables/procs on this system.
"""
iproc = self.comm.rank
for io in ('input', 'output'):
sizes = self._var_sizes['nonlinear'][io] = np.zeros((self.comm.size,
len(self._var_rel_names[io])),
dtype=INT_DTYPE)
for i, (name, metadata) in enumerate(self._var_allprocs_abs2meta[io].items()):
sizes[iproc, i] = metadata['size']
if self.comm.size > 1:
my_sizes = sizes[iproc, :].copy()
self.comm.Allgather(my_sizes, sizes)
# all names are relevant for the 'nonlinear' and 'linear' vectors. We
# can then use them to compute the size arrays of for all other vectors
# based on the nonlinear size array.
nl_allprocs_relnames = self._var_allprocs_relevant_names['nonlinear']
nl_relnames = self._var_relevant_names['nonlinear']
for io in ('input', 'output'):
nl_allprocs_relnames[io] = list(self._var_allprocs_abs2meta[io])
nl_relnames[io] = list(self._var_abs2meta[io])
self._setup_var_index_maps('nonlinear')
self._owned_sizes = self._var_sizes['nonlinear']['output']
if self._use_derivatives:
sizes = self._var_sizes
nl_sizes = sizes['nonlinear']
nl_abs2idx = self._var_allprocs_abs2idx['nonlinear']
sizes['linear'] = nl_sizes
self._var_allprocs_relevant_names['linear'] = nl_allprocs_relnames
self._var_relevant_names['linear'] = nl_relnames
self._var_allprocs_abs2idx['linear'] = nl_abs2idx
# Initialize size arrays for other linear vecs besides 'linear'
# (which is the same as 'nonlinear')
for vec_name in self._lin_rel_vec_name_list[1:]:
# at component level, _var_allprocs_* is the same as var_* since all vars exist in
# all procs for a given component, so we don't have to mess with figuring out what
# vars are local.
relnames = self._var_allprocs_relevant_names[vec_name]
sizes[vec_name] = {}
for io in ('input', 'output'):
sizes[vec_name][io] = sz = np.zeros((self.comm.size, len(relnames[io])),
dtype=INT_DTYPE)
# Variables for this vec_name are a subset of those for nonlinear, so just
# take columns of the nonlinear sizes array
for idx, abs_name in enumerate(relnames[io]):
sz[:, idx] = nl_sizes[io][:, nl_abs2idx[abs_name]]
self._setup_var_index_maps(vec_name)
def _setup_partials(self):
"""
Process all partials and approximations that the user declared.
"""
self._subjacs_info = {}
self._jacobian = DictionaryJacobian(system=self)
self.setup_partials() # hook for component writers to specify sparsity patterns
# check to make sure that if num_par_fd > 1 that this system is actually doing FD.
# Unfortunately we have to do this check after system setup has been called because that's
# when declare_partials generally happens, so we raise an exception here instead of just
# resetting the value of num_par_fd (because the comm has already been split and possibly
# used by the system setup).
orig_comm = self._full_comm if self._full_comm is not None else self.comm
if self._num_par_fd > 1 and orig_comm.size > 1 and not (self._owns_approx_jac or
self._approx_schemes):
raise RuntimeError("%s: num_par_fd is > 1 but no FD is active." % self.msginfo)
for key, dct in self._declared_partials.items():
of, wrt = key
self._declare_partials(of, wrt, dct)
def setup_partials(self):
"""
Declare partials.
This is meant to be overridden by component classes. All partials should be
declared here since this is called after all size/shape information is known for
all variables.
"""
pass
def _update_wrt_matches(self, info):
"""
Determine the list of wrt variables that match the wildcard(s) given in declare_coloring.
Parameters
----------
info : dict
Coloring metadata dict.
"""
ofs, allwrt = self._get_partials_varlists()
wrt_patterns = info['wrt_patterns']
matches_prom = set()
for w in wrt_patterns:
matches_prom.update(find_matches(w, allwrt))
# error if nothing matched
if not matches_prom:
raise ValueError("{}: Invalid 'wrt' variable(s) specified for colored approx partial "
"options: {}.".format(self.msginfo, wrt_patterns))
info['wrt_matches_prom'] = matches_prom
info['wrt_matches'] = [rel_name2abs_name(self, n) for n in matches_prom]
def _update_subjac_sparsity(self, sparsity):
"""
Update subjac sparsity info based on the given coloring.
The sparsity of the partial derivatives in this component will be used when computing
the sparsity of the total jacobian for the entire model. Without this, all of this
component's partials would be treated as dense, resulting in an overly conservative
coloring of the total jacobian.
Parameters
----------
sparsity : dict
A nested dict of the form dct[of][wrt] = (rows, cols, shape)
"""
# sparsity uses relative names, so we need to convert to absolute
pathname = self.pathname
for of, sub in sparsity.items():
of_abs = '.'.join((pathname, of)) if pathname else of
for wrt, tup in sub.items():
wrt_abs = '.'.join((pathname, wrt)) if pathname else wrt
abs_key = (of_abs, wrt_abs)
if abs_key in self._subjacs_info:
# add sparsity info to existing partial info
self._subjacs_info[abs_key]['sparsity'] = tup
def add_input(self, name, val=1.0, shape=None, src_indices=None, flat_src_indices=None,
units=None, desc='', tags=None, shape_by_conn=False, copy_shape=None):
"""
Add an input variable to the component.
Parameters
----------
name : str
name of the variable in this component's namespace.
val : float or list or tuple or ndarray or Iterable
The initial value of the variable being added in user-defined units.
Default is 1.0.
shape : int or tuple or list or None
Shape of this variable, only required if src_indices not provided and
val is not an array. Default is None.
src_indices : int or list of ints or tuple of ints or int ndarray or Iterable or None
The global indices of the source variable to transfer data from.
A value of None implies this input depends on all entries of source.
Default is None. The shapes of the target and src_indices must match,
and form of the entries within is determined by the value of 'flat_src_indices'.
flat_src_indices : bool
If True, each entry of src_indices is assumed to be an index into the
flattened source. Otherwise each entry must be a tuple or list of size equal
to the number of dimensions of the source.
units : str or None
Units in which this input variable will be provided to the component
during execution. Default is None, which means it is unitless.
desc : str
description of the variable
tags : str or list of strs
User defined tags that can be used to filter what gets listed when calling
list_inputs and list_outputs.
shape_by_conn : bool
If True, shape this input to match its connected output.
copy_shape : str or None
If a str, that str is the name of a variable. Shape this input to match that of
the named variable.
Returns
-------
dict
metadata for added variable
"""
# First, type check all arguments
if not isinstance(name, str):
raise TypeError('%s: The name argument should be a string.' % self.msginfo)
if not _valid_var_name(name):
raise NameError("%s: '%s' is not a valid input name." % (self.msginfo, name))
if not isscalar(val) and not isinstance(val, (list, tuple, ndarray, Iterable)):
raise TypeError('%s: The val argument should be a float, list, tuple, ndarray or '
'Iterable' % self.msginfo)
if shape is not None and not isinstance(shape, (int, tuple, list, np.integer)):
raise TypeError("%s: The shape argument should be an int, tuple, or list but "
"a '%s' was given" % (self.msginfo, type(shape)))
if src_indices is not None and not isinstance(src_indices, (int, list, tuple,
ndarray, Iterable)):
raise TypeError('%s: The src_indices argument should be an int, list, '
'tuple, ndarray or Iterable' % self.msginfo)
if units is not None:
if not isinstance(units, str):
raise TypeError('%s: The units argument should be a str or None.' % self.msginfo)
if not valid_units(units):
raise ValueError("%s: The units '%s' are invalid." % (self.msginfo, units))
units = simplify_unit(units)
if tags is not None and not isinstance(tags, (str, list)):
raise TypeError('The tags argument should be a str or list')
if (shape_by_conn or copy_shape):
if shape is not None or not isscalar(val):
raise ValueError("%s: If shape is to be set dynamically using 'shape_by_conn' or "
"'copy_shape', 'shape' and 'val' should be a scalar, "
"but shape of '%s' and val of '%s' was given for variable '%s'."
% (self.msginfo, shape, val, name))
if src_indices is not None:
raise ValueError("%s: Setting of 'src_indices' along with 'shape_by_conn' or "
"'copy_shape' for variable '%s' is currently unsupported." %
(self.msginfo, name))
src_slice = None
if not (shape_by_conn or copy_shape):
if src_indices is not None:
if _is_slicer_op(src_indices):
src_slice = src_indices
if flat_src_indices is not None:
simple_warning(f"{self.msginfo}: Input '{name}' was added with slice "
"src_indices, so flat_src_indices is ignored.")
else:
src_indices = np.asarray(src_indices, dtype=INT_DTYPE)
# value, shape: based on args, making sure they are compatible
val, shape, src_indices = ensure_compatible(name, val, shape, src_indices)
if src_indices is not None and src_slice is None and src_indices.ndim == 1:
flat_src_indices = True
if src_indices is not None:
warn_deprecation(f"{self.msginfo}: Passing `src_indices` as an arg to `add_input` is"
"deprecated and will become an error in a future release. Add "
"`src_indices` to a `promotes` or `connect` call instead.")
metadata = {
'value': val,
'shape': shape,
'size': shape_to_len(shape),
'src_indices': src_indices, # these will ultimately be converted to a flat index array
'flat_src_indices': flat_src_indices,
'add_input_src_indices': src_indices is not None,
'src_slice': src_slice, # store slice def here, if any. This is never overwritten
'units': units,
'desc': desc,
'distributed': self.options['distributed'],
'tags': make_set(tags),
'shape_by_conn': shape_by_conn,
'copy_shape': copy_shape,
}
if self._static_mode:
var_rel2meta = self._static_var_rel2meta
var_rel_names = self._static_var_rel_names
else:
var_rel2meta = self._var_rel2meta
var_rel_names = self._var_rel_names
# Disallow dupes
if name in var_rel2meta:
raise ValueError("{}: Variable name '{}' already exists.".format(self.msginfo, name))
var_rel2meta[name] = metadata
var_rel_names['input'].append(name)
self._var_added(name)
return metadata
def add_discrete_input(self, name, val, desc='', tags=None):
"""
Add a discrete input variable to the component.
Parameters
----------
name : str
name of the variable in this component's namespace.
val : a picklable object
The initial value of the variable being added.
desc : str
description of the variable
tags : str or list of strs
User defined tags that can be used to filter what gets listed when calling
list_inputs and list_outputs.
Returns
-------
dict
metadata for added variable
"""
# First, type check all arguments
if not isinstance(name, str):
raise TypeError('%s: The name argument should be a string.' % self.msginfo)
if not _valid_var_name(name):
raise NameError("%s: '%s' is not a valid input name." % (self.msginfo, name))
if tags is not None and not isinstance(tags, (str, list)):
raise TypeError('%s: The tags argument should be a str or list' % self.msginfo)
metadata = {
'value': val,
'type': type(val),
'desc': desc,
'tags': make_set(tags),
}
if metadata['type'] == np.ndarray:
metadata.update({'shape': val.shape})
if self._static_mode:
var_rel2meta = self._static_var_rel2meta
else:
var_rel2meta = self._var_rel2meta
# Disallow dupes
if name in var_rel2meta:
raise ValueError("{}: Variable name '{}' already exists.".format(self.msginfo, name))
var_rel2meta[name] = self._var_discrete['input'][name] = metadata
self._var_added(name)
return metadata
def add_output(self, name, val=1.0, shape=None, units=None, res_units=None, desc='',
lower=None, upper=None, ref=1.0, ref0=0.0, res_ref=1.0, tags=None,
shape_by_conn=False, copy_shape=None):
"""
Add an output variable to the component.
Parameters
----------
name : str
name of the variable in this component's namespace.
val : float or list or tuple or ndarray
The initial value of the variable being added in user-defined units. Default is 1.0.
shape : int or tuple or list or None
Shape of this variable, only required if val is not an array.
Default is None.
units : str or None
Units in which the output variables will be provided to the component during execution.
Default is None, which means it has no units.
res_units : str or None
Units in which the residuals of this output will be given to the user when requested.
Default is None, which means it has no units.
desc : str
description of the variable.
lower : float or list or tuple or ndarray or Iterable or None
lower bound(s) in user-defined units. It can be (1) a float, (2) an array_like
consistent with the shape arg (if given), or (3) an array_like matching the shape of
val, if val is array_like. A value of None means this output has no lower bound.
Default is None.
upper : float or list or tuple or ndarray or or Iterable None
upper bound(s) in user-defined units. It can be (1) a float, (2) an array_like
consistent with the shape arg (if given), or (3) an array_like matching the shape of
val, if val is array_like. A value of None means this output has no upper bound.
Default is None.
ref : float or ndarray
Scaling parameter. The value in the user-defined units of this output variable when
the scaled value is 1. Default is 1.
ref0 : float or ndarray
Scaling parameter. The value in the user-defined units of this output variable when
the scaled value is 0. Default is 0.
res_ref : float or ndarray
Scaling parameter. The value in the user-defined res_units of this output's residual
when the scaled value is 1. Default is 1.
tags : str or list of strs or set of strs
User defined tags that can be used to filter what gets listed when calling
list_inputs and list_outputs.
shape_by_conn : bool
If True, shape this output to match its connected input(s).
copy_shape : str or None
If a str, that str is the name of a variable. Shape this output to match that of
the named variable.
Returns
-------
dict
metadata for added variable
"""
# First, type check all arguments
if (shape_by_conn or copy_shape) and (shape is not None or not isscalar(val)):
raise ValueError("%s: If shape is to be set dynamically using 'shape_by_conn' or "
"'copy_shape', 'shape' and 'val' should be scalar, "
"but shape of '%s' and val of '%s' was given for variable '%s'."
% (self.msginfo, shape, val, name))
if not isinstance(name, str):
raise TypeError('%s: The name argument should be a string.' % self.msginfo)
if not _valid_var_name(name):
raise NameError("%s: '%s' is not a valid output name." % (self.msginfo, name))
if not (copy_shape or shape_by_conn):
if not isscalar(val) and not isinstance(val, (list, tuple, ndarray, Iterable)):
msg = '%s: The val argument should be a float, list, tuple, ndarray or Iterable'
raise TypeError(msg % self.msginfo)
if not isscalar(ref) and not isinstance(val, (list, tuple, ndarray, Iterable)):
msg = '%s: The ref argument should be a float, list, tuple, ndarray or Iterable'
raise TypeError(msg % self.msginfo)
if not isscalar(ref0) and not isinstance(val, (list, tuple, ndarray, Iterable)):
msg = '%s: The ref0 argument should be a float, list, tuple, ndarray or Iterable'
raise TypeError(msg % self.msginfo)
if not isscalar(res_ref) and not isinstance(val, (list, tuple, ndarray, Iterable)):
msg = '%s: The res_ref argument should be a float, list, tuple, ndarray or Iterable'
raise TypeError(msg % self.msginfo)
if shape is not None and not isinstance(shape, (int, tuple, list, np.integer)):
raise TypeError("%s: The shape argument should be an int, tuple, or list but "
"a '%s' was given" % (self.msginfo, type(shape)))
if res_units is not None:
if not isinstance(res_units, str):
msg = '%s: The res_units argument should be a str or None' % self.msginfo
raise TypeError(msg)
if not valid_units(res_units):
raise ValueError("%s: The res_units '%s' are invalid" % (self.msginfo, res_units))
res_units = simplify_unit(res_units)
if units is not None:
if not isinstance(units, str):
raise TypeError('%s: The units argument should be a str or None' % self.msginfo)
if not valid_units(units):
raise ValueError("%s: The units '%s' are invalid" % (self.msginfo, units))
units = simplify_unit(units)
if tags is not None and not isinstance(tags, (str, set, list)):
raise TypeError('The tags argument should be a str, set, or list')
if not (copy_shape or shape_by_conn):
# value, shape: based on args, making sure they are compatible
val, shape, _ = ensure_compatible(name, val, shape)
if lower is not None:
lower = ensure_compatible(name, lower, shape)[0]
self._has_bounds = True
if upper is not None:
upper = ensure_compatible(name, upper, shape)[0]
self._has_bounds = True
# All refs: check the shape if necessary
for item, item_name in zip([ref, ref0, res_ref], ['ref', 'ref0', 'res_ref']):
if not isscalar(item):
it = atleast_1d(item)
if it.shape != shape:
raise ValueError("{}: When adding output '{}', expected shape {} but got "
"shape {} for argument '{}'.".format(self.msginfo, name,
shape, it.shape,
item_name))
if isscalar(ref):
self._has_output_scaling |= ref != 1.0
else:
self._has_output_scaling |= np.any(ref != 1.0)
if isscalar(ref0):
self._has_output_scaling |= ref0 != 0.0
else:
self._has_output_scaling |= np.any(ref0)
if isscalar(res_ref):
self._has_resid_scaling |= res_ref != 1.0
else:
self._has_resid_scaling |= np.any(res_ref != 1.0)
metadata = {
'value': val,
'shape': shape,
'size': shape_to_len(shape),
'units': units,
'res_units': res_units,
'desc': desc,
'distributed': self.options['distributed'],
'tags': make_set(tags),
'ref': format_as_float_or_array('ref', ref, flatten=True),
'ref0': format_as_float_or_array('ref0', ref0, flatten=True),
'res_ref': format_as_float_or_array('res_ref', res_ref, flatten=True),
'lower': lower,
'upper': upper,
'shape_by_conn': shape_by_conn,
'copy_shape': copy_shape
}
# We may not know the pathname yet, so we have to use name for now, instead of abs_name.
if self._static_mode:
var_rel2meta = self._static_var_rel2meta
var_rel_names = self._static_var_rel_names
else:
var_rel2meta = self._var_rel2meta
var_rel_names = self._var_rel_names
# Disallow dupes
if name in var_rel2meta:
raise ValueError("{}: Variable name '{}' already exists.".format(self.msginfo, name))
var_rel2meta[name] = metadata
var_rel_names['output'].append(name)
self._var_added(name)
return metadata
def add_discrete_output(self, name, val, desc='', tags=None):
"""
Add an output variable to the component.
Parameters
----------
name : str
name of the variable in this component's namespace.
val : a picklable object
The initial value of the variable being added.
desc : str
description of the variable.
tags : str or list of strs or set of strs
User defined tags that can be used to filter what gets listed when calling
list_inputs and list_outputs.
Returns
-------
dict
metadata for added variable
"""
if not isinstance(name, str):
raise TypeError('%s: The name argument should be a string.' % self.msginfo)
if not _valid_var_name(name):
raise NameError("%s: '%s' is not a valid output name." % (self.msginfo, name))
if tags is not None and not isinstance(tags, (str, set, list)):
raise TypeError('%s: The tags argument should be a str, set, or list' % self.msginfo)
metadata = {
'value': val,
'type': type(val),
'desc': desc,
'tags': make_set(tags)
}
if metadata['type'] == np.ndarray:
metadata.update({'shape': val.shape})
if self._static_mode:
var_rel2meta = self._static_var_rel2meta
else:
var_rel2meta = self._var_rel2meta
# Disallow dupes
if name in var_rel2meta:
raise ValueError("{}: Variable name '{}' already exists.".format(self.msginfo, name))
var_rel2meta[name] = self._var_discrete['output'][name] = metadata
self._var_added(name)
return metadata
def _var_added(self, name):
"""
Notify config that a variable has been added to this Component.
Parameters
----------
name : str
Name of the added variable.
"""
if self._problem_meta is not None and self._problem_meta['config_info'] is not None:
self._problem_meta['config_info']._var_added(self.pathname, name)
def _update_dist_src_indices(self, abs_in2out, all_abs2meta, all_abs2idx, all_sizes):
"""
Set default src_indices on distributed components for any inputs where they aren't set.
Parameters
----------
abs_in2out : dict
Mapping of connected inputs to their source. Names are absolute.
all_abs2meta : dict
Mapping of absolute names to metadata for all variables in the model.
all_abs2idx : dict
Dictionary mapping an absolute name to its allprocs variable index.
all_sizes : dict
Mapping of vec_names and types to sizes of each variable in all procs.
Returns
-------
set
Names of inputs where src_indices were added.
"""
if not self.options['distributed'] or self.comm.size == 1:
return set()
iproc = self.comm.rank
abs2meta_in = self._var_abs2meta['input']
all_abs2meta_in = all_abs2meta['input']
all_abs2meta_out = all_abs2meta['output']
sizes_in = self._var_sizes['nonlinear']['input']
sizes_out = all_sizes['nonlinear']['output']
added_src_inds = set()
for i, iname in enumerate(self._var_allprocs_abs2meta['input']):
if iname in abs2meta_in and abs2meta_in[iname]['src_indices'] is None:
meta_in = abs2meta_in[iname]
src = abs_in2out[iname]
out_i = all_abs2idx[src]
nzs = np.nonzero(sizes_out[:, out_i])[0]
if (all_abs2meta_out[src]['global_size'] ==
all_abs2meta_in[iname]['global_size'] or nzs.size == self.comm.size):
# This offset assumes a 'full' distributed output
offset = np.sum(sizes_in[:iproc, i])
end = offset + sizes_in[iproc, i]
else: # distributed output (may have some zero size entries)
if nzs.size == 1:
offset = 0
end = sizes_out[nzs[0], out_i]
else:
# total sizes differ and output is distributed, so can't determine mapping
raise RuntimeError(f"{self.msginfo}: Can't determine src_indices "
f"automatically for input '{iname}'. They must be "
"supplied manually.")
inds = np.arange(offset, end, dtype=INT_DTYPE)
if meta_in['shape'] != inds.shape:
inds = inds.reshape(meta_in['shape'])
meta_in['src_indices'] = inds
meta_in['flat_src_indices'] = True
all_abs2meta_in[iname]['has_src_indices'] = True
added_src_inds.add(iname)
simple_warning(f"{self.msginfo}: Component is distributed but input '{iname}' was "
"added without src_indices. Setting src_indices to "
f"np.arange({offset}, {end}, dtype=int).reshape({inds.shape}).")
return added_src_inds
def _approx_partials(self, of, wrt, method='fd', **kwargs):
"""
Inform the framework that the specified derivatives are to be approximated.
Parameters
----------
of : str or list of str
The name of the residual(s) that derivatives are being computed for.
May also contain a glob pattern.
wrt : str or list of str
The name of the variables that derivatives are taken with respect to.
This can contain the name of any input or output variable.
May also contain a glob pattern.
method : str
The type of approximation that should be used. Valid options include:
- 'fd': Finite Difference
**kwargs : dict
Keyword arguments for controlling the behavior of the approximation.
"""
pattern_matches = self._find_partial_matches(of, wrt)
self._has_approx = True
for of_bundle, wrt_bundle in product(*pattern_matches):
of_pattern, of_matches = of_bundle
wrt_pattern, wrt_matches = wrt_bundle
if not of_matches:
raise ValueError('{}: No matches were found for of="{}"'.format(self.msginfo,
of_pattern))
if not wrt_matches:
raise ValueError('{}: No matches were found for wrt="{}"'.format(self.msginfo,
wrt_pattern))
info = self._subjacs_info
for rel_key in product(of_matches, wrt_matches):
abs_key = rel_key2abs_key(self, rel_key)
meta = info[abs_key]
meta['method'] = method
meta.update(kwargs)
info[abs_key] = meta
def declare_partials(self, of, wrt, dependent=True, rows=None, cols=None, val=None,
method='exact', step=None, form=None, step_calc=None):
"""
Declare information about this component's subjacobians.
Parameters
----------
of : str or list of str
The name of the residual(s) that derivatives are being computed for.
May also contain a glob pattern.
wrt : str or list of str
The name of the variables that derivatives are taken with respect to.
This can contain the name of any input or output variable.
May also contain a glob pattern.
dependent : bool(True)
If False, specifies no dependence between the output(s) and the
input(s). This is only necessary in the case of a sparse global
jacobian, because if 'dependent=False' is not specified and
declare_partials is not called for a given pair, then a dense
matrix of zeros will be allocated in the sparse global jacobian
for that pair. In the case of a dense global jacobian it doesn't
matter because the space for a dense subjac will always be
allocated for every pair.
rows : ndarray of int or None
Row indices for each nonzero entry. For sparse subjacobians only.
cols : ndarray of int or None
Column indices for each nonzero entry. For sparse subjacobians only.
val : float or ndarray of float or scipy.sparse
Value of subjacobian. If rows and cols are not None, this will
contain the values found at each (row, col) location in the subjac.
method : str
The type of approximation that should be used. Valid options include:
'fd': Finite Difference, 'cs': Complex Step, 'exact': use the component
defined analytic derivatives. Default is 'exact'.
step : float
Step size for approximation. Defaults to None, in which case the approximation
method provides its default value.
form : string
Form for finite difference, can be 'forward', 'backward', or 'central'. Defaults
to None, in which case the approximation method provides its default value.
step_calc : string
Step type for finite difference, can be 'abs' for absolute', or 'rel' for
relative. Defaults to None, in which case the approximation method provides
its default value.
Returns