-
Notifications
You must be signed in to change notification settings - Fork 240
/
component.py
1791 lines (1533 loc) · 77.9 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."""
import sys
import types
from collections import defaultdict
from collections.abc import Iterable
from itertools import product
from numbers import Integral
import numpy as np
from numpy import ndarray, isscalar, ndim, atleast_1d, atleast_2d, promote_types
from scipy.sparse import issparse, coo_matrix
from openmdao.core.system import System, _supported_methods, _DEFAULT_COLORING_META, \
global_meta_names, collect_errors
from openmdao.core.constants import INT_DTYPE
from openmdao.jacobians.dictionary_jacobian import DictionaryJacobian
from openmdao.utils.array_utils import shape_to_len
from openmdao.utils.units import simplify_unit
from openmdao.utils.name_maps import abs_key_iter, 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, make_set, inconsistent_across_procs
from openmdao.utils.indexer import Indexer, indexer
import openmdao.utils.coloring as coloring_mod
from openmdao.utils.om_warnings import issue_warning, MPIWarning, DistributedComponentWarning, \
DerivativesWarning, warn_deprecation
_forbidden_chars = {'.', '*', '?', '!', '[', ']'}
_whitespace = {' ', '\t', '\r', '\n'}
_allowed_types = (list, tuple, ndarray, Iterable)
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
if _forbidden_chars.intersection(name):
return False
return name is name.strip()
class Component(System):
"""
Base Component class; not to be directly instantiated.
Parameters
----------
**kwargs : dict of keyword arguments
Available here and in all descendants of this system.
Attributes
----------
_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_patterns : dict
Dictionary of declared partials patterns. Each key is a tuple of the form
(of, wrt) where of and wrt may be glob patterns.
_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.
_has_distrib_outputs : bool
If True, this component has at least one distributed output.
"""
def __init__(self, **kwargs):
"""
Initialize all attributes.
"""
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_patterns = {}
self._declared_partial_checks = []
self._no_check_partials = False
self._has_distrib_outputs = 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='If True, set all variables in this component as distributed '
'across multiple processes')
self.options.declare('run_root_only', types=bool, default=False,
desc='If True, call compute, compute_partials, linearize, '
'apply_linear, apply_nonlinear, and compute_jacvec_product '
'only on rank 0 and broadcast the results to the other ranks.')
self.options.declare('always_opt', types=bool, default=False,
desc='If True, force nonlinear operations on this component to be '
'included in the optimization loop even if this component is not '
'relevant to the design variables and responses.')
def _check_matfree_deprecation(self):
# check for mixed distributed variables
has_dist_ins = has_nd_ins = has_dist_outs = has_nd_outs = False
for name in self._var_rel_names['input']:
meta = self._var_rel2meta[name]
if meta['distributed']:
has_dist_ins = True
else:
has_nd_ins = True
for name in self._var_rel_names['output']:
meta = self._var_rel2meta[name]
if meta['distributed']:
has_dist_outs = True
else:
has_nd_outs = True
if (has_nd_ins and has_dist_outs) or (has_dist_ins and has_nd_outs):
warn_deprecation(f"{self.msginfo}: It appears this component mixes "
"distributed/non-distributed inputs and outputs, so it may break "
"starting with OpenMDAO 3.25, where the convention "
"used when passing data between distributed and non-distributed "
"inputs and outputs within a matrix free component will change. "
"See https://github.com/OpenMDAO/POEMs/blob/master/POEM_075.md for "
"details.")
def setup(self):
"""
Declare inputs and outputs.
Available attributes:
name
pathname
comm
options
"""
pass
def _setup_procs(self, pathname, comm, 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.
prob_meta : dict
Problem level metadata.
"""
super()._setup_procs(pathname, comm, prob_meta)
if self._num_par_fd > 1:
if comm.size > 1:
comm = self._setup_par_fd_procs(comm)
elif not MPI:
issue_warning(f"MPI is not active but num_par_fd = {self._num_par_fd}. No parallel "
"finite difference will be performed.",
prefix=self.msginfo, category=MPIWarning)
self._num_par_fd = 1
self.comm = comm
nprocs = comm.size
# Clear out old variable information so that we can call setup on the component.
self._var_rel_names = {'input': [], 'output': []}
self._var_rel2meta = {}
if comm.size == 1:
self._has_distrib_vars = self._has_distrib_outputs = False
for meta in self._static_var_rel2meta.values():
# 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__.
if 'shape_by_conn' in meta and (meta['shape_by_conn'] or
meta['compute_shape'] is not None):
meta['shape'] = None
if not isscalar(meta['val']):
if meta['val'].size > 0:
meta['val'] = meta['val'].flatten()[0]
else:
meta['val'] = 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._setup_check()
self._set_vector_class()
def _set_vector_class(self):
if self._has_distrib_vars:
dist_vec_class = self._problem_meta['distributed_vector_class']
if dist_vec_class is not None:
self._vector_class = dist_vec_class
else:
issue_warning("Component contains distributed variables, "
"but there is no distributed vector implementation (MPI/PETSc) "
"available. The default non-distributed vectors will be used.",
prefix=self.msginfo, category=DistributedComponentWarning)
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 meta in self._declared_partials_patterns.values():
if 'method' in meta and meta['method'] is not None:
break
else:
method = self._coloring_info.method
issue_warning("declare_coloring or use_fixed_coloring was called but no approx"
" partials were declared. Declaring all partials as approximated "
f"using default metadata and method='{method}'.", prefix=self.msginfo,
category=DerivativesWarning)
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 + '.'
for io in ['input', 'output']:
abs2meta = self._var_abs2meta[io]
allprocs_abs2meta = self._var_allprocs_abs2meta[io]
is_input = io == 'input'
for prom_name in 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
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['val']
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 = ()
self._serial_idxs = None
self._inconsistent_keys = set()
@collect_errors
def _setup_var_sizes(self):
"""
Compute the arrays of variable sizes for all variables/procs on this system.
"""
iproc = self.comm.rank
abs2idx = self._var_allprocs_abs2idx = {}
for io in ('input', 'output'):
sizes = self._var_sizes[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()):
sz = metadata['size']
sizes[iproc, i] = 0 if sz is None else sz
abs2idx[name] = i
if self.comm.size > 1:
my_sizes = sizes[iproc, :].copy()
self.comm.Allgather(my_sizes, sizes)
self._owned_sizes = self._var_sizes['output']
def _setup_partials(self):
"""
Process all partials and approximations that the user declared.
"""
self._subjacs_info = {}
if not self.matrix_free:
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, pattern_meta in self._declared_partials_patterns.items():
of, wrt = key
self._resolve_partials_patterns(of, wrt, pattern_meta)
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 _declared_partials_iter(self):
"""
Iterate over all declared partials.
Yields
------
key : tuple (of, wrt)
Subjacobian key.
"""
yield from self._subjacs_info.keys()
def _get_missing_partials(self, missing):
"""
Provide (of, wrt) tuples for which derivatives have not been declared in the component.
Parameters
----------
missing : dict
Dictionary containing set of missing derivatives keyed by system pathname.
"""
if ('*', '*') in self._declared_partials_patterns or \
(('*',), ('*',)) in self._declared_partials_patterns:
return
# keep old default behavior where matrix free components are assumed to have
# 'dense' whole variable to whole variable partials if no partials are declared.
if self.matrix_free and not self._declared_partials_patterns:
return
keyset = self._subjacs_info
mset = set()
for of in self._var_allprocs_abs2meta['output']:
for wrt in self._var_allprocs_abs2meta['input']:
if (of, wrt) not in keyset:
mset.add((of, wrt))
if mset:
missing[self.pathname] = mset
@property
def checking(self):
"""
Return True if check_partials or check_totals is executing.
Returns
-------
bool
True if we're running within check_partials or check_totals.
"""
return self._problem_meta is not None and self._problem_meta['checking']
def _run_root_only(self):
"""
Return the value of the run_root_only option and check for possible errors.
Returns
-------
bool
True if run_root_only is active.
"""
if self.options['run_root_only']:
if self.comm.size > 1 or (self._full_comm is not None and self._full_comm.size > 1):
if self._has_distrib_vars:
raise RuntimeError(f"{self.msginfo}: Can't set 'run_root_only' option when "
"a component has distributed variables.")
if self._num_par_fd > 1:
raise RuntimeError(f"{self.msginfo}: Can't set 'run_root_only' option when "
"using parallel FD.")
if self._problem_meta['has_par_deriv_color']:
raise RuntimeError(f"{self.msginfo}: Can't set 'run_root_only' option when "
"using parallel_deriv_color.")
return True
return False
def _promoted_wrt_iter(self):
_, wrts = self._get_partials_varlists()
yield from wrts
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
prefix = self.pathname + '.'
for of, sub in sparsity.items():
of = prefix + of
for wrt, tup in sub.items():
wrt = prefix + wrt
abs_key = (of, wrt)
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, units=None, desc='', tags=None,
shape_by_conn=False, copy_shape=None, compute_shape=None, distributed=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 val is not an array. Default is None.
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.
compute_shape : function
A function taking a dict arg containing names and shapes of this component's outputs
and returning the shape of this input.
distributed : bool
If True, this variable is a distributed variable, so it can have different sizes/values
across MPI processes.
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, _allowed_types):
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, (Integral, tuple, list)):
raise TypeError("%s: The shape argument should be an int, tuple, or list but "
"a '%s' was given" % (self.msginfo, type(shape)))
if units is not None:
if not isinstance(units, str):
raise TypeError('%s: The units argument should be a str or None.' % self.msginfo)
units = simplify_unit(units, msginfo=self.msginfo)
if tags is not None and not isinstance(tags, (str, list, set)):
raise TypeError('The tags argument should be a str, set, or list')
if copy_shape and compute_shape:
raise ValueError(f"{self.msginfo}: Only one of 'copy_shape' or 'compute_shape' can "
"be specified.")
if copy_shape and not isinstance(copy_shape, str):
raise TypeError(f"{self.msginfo}: The copy_shape argument should be a str or None but "
f"a '{type(copy_shape).__name__}' was given.")
if compute_shape and not isinstance(compute_shape, types.FunctionType):
raise TypeError(f"{self.msginfo}: The compute_shape argument should be a function but "
f"a '{type(compute_shape).__name__}' was given.")
if (shape_by_conn or copy_shape or compute_shape):
if shape is not None or ndim(val) > 0:
raise ValueError("%s: If shape is to be set dynamically using 'shape_by_conn', "
"'copy_shape', or 'compute_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))
else:
# value, shape: based on args, making sure they are compatible
val, shape = ensure_compatible(name, val, shape)
# until we get rid of component level distributed option, handle the case where
# component distributed has been set to True but variable distributed has been set
# to False by the caller.
if distributed is not False:
if distributed is None:
distributed = False
# using ._dict below to avoid tons of deprecation warnings
distributed = distributed or self.options._dict['distributed']['val']
metadata = {}
metadata.update({
'val': val,
'shape': shape,
'size': shape_to_len(shape),
'src_indices': None,
'flat_src_indices': None,
'units': units,
'desc': desc,
'distributed': distributed,
'tags': make_set(tags),
'shape_by_conn': shape_by_conn,
'compute_shape': compute_shape,
'copy_shape': copy_shape,
})
# this will get reset later if comm size is 1
self._has_distrib_vars |= metadata['distributed']
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 = {}
metadata.update({
'val': 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=None, tags=None,
shape_by_conn=False, copy_shape=None, compute_shape=None, distributed=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.
compute_shape : function
A function taking a dict arg containing names and shapes of this component's inputs
and returning the shape of this output.
distributed : bool
If True, this variable is a distributed variable, so it can have different sizes/values
across MPI processes.
Returns
-------
dict
Metadata for added variable.
"""
global _allowed_types
# First, type check all arguments
if (shape_by_conn or copy_shape or compute_shape) and (shape is not None or ndim(val) > 0):
raise ValueError("%s: If shape is to be set dynamically using 'shape_by_conn', "
"'copy_shape', or 'compute_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 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)
res_units = simplify_unit(res_units, msginfo=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)
units = simplify_unit(units, msginfo=self.msginfo)
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 or compute_shape):
if not isscalar(val) and not isinstance(val, _allowed_types):
msg = '%s: The val argument should be a float, list, tuple, ndarray or Iterable'
raise TypeError(msg % self.msginfo)
# 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 item is not None and not isscalar(item):
if not isinstance(item, _allowed_types):
raise TypeError(f'{self.msginfo}: The {item_name} argument should be a '
'float, list, tuple, ndarray or Iterable')
it = atleast_1d(item)
if it.shape != shape:
raise ValueError(f"{self.msginfo}: When adding output '{name}', expected "
f"shape {shape} but got shape {it.shape} for argument "
f"'{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
self._has_output_adder |= ref0 != 0.0
else:
self._has_output_scaling |= np.any(ref0)
self._has_output_adder |= 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)
# until we get rid of component level distributed option, handle the case where
# component distributed has been set to True but variable distributed has been set
# to False by the caller.
if distributed is not False:
if distributed is None:
distributed = False
# using ._dict below to avoid tons of deprecation warnings
distributed = distributed or self.options._dict['distributed']['val']
if copy_shape and compute_shape:
raise ValueError(f"{self.msginfo}: Only one of 'copy_shape' or 'compute_shape' can "
"be specified.")
if copy_shape and not isinstance(copy_shape, str):
raise TypeError(f"{self.msginfo}: The copy_shape argument should be a str or None but "
f"a '{type(copy_shape).__name__}' was given.")
if compute_shape and not isinstance(compute_shape, types.FunctionType):
raise TypeError(f"{self.msginfo}: The compute_shape argument should be a function but "
f"a '{type(compute_shape).__name__}' was given.")
metadata = {}
metadata.update({
'val': val,
'shape': shape,
'size': shape_to_len(shape),
'units': units,
'res_units': res_units,
'desc': desc,
'distributed': 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, val_if_none=None),
'lower': lower,
'upper': upper,
'shape_by_conn': shape_by_conn,
'compute_shape': compute_shape,
'copy_shape': copy_shape,
})
# this will get reset later if comm size is 1
self._has_distrib_vars |= metadata['distributed']
self._has_distrib_outputs |= metadata['distributed']
# 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 = {}
metadata.update({
'val': 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 for any distributed 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 types to sizes of each variable in all procs.
Returns
-------
list
Names of inputs where src_indices were added.
"""
iproc = self.comm.rank
abs2meta_in = self._var_abs2meta['input']
all_abs2meta_in = all_abs2meta['input']
all_abs2meta_out = all_abs2meta['output']
abs_in2prom_info = self._problem_meta['abs_in2prom_info']
sizes_in = self._var_sizes['input']
sizes_out = all_sizes['output']
added_src_inds = []
# loop over continuous inputs
for i, (iname, meta_in) in enumerate(abs2meta_in.items()):
if meta_in['src_indices'] is None and iname not in abs_in2prom_info:
src = abs_in2out[iname]
dist_in = meta_in['distributed']
dist_out = all_abs2meta_out[src]['distributed']
if dist_in or dist_out:
gsize_out = all_abs2meta_out[src]['global_size']
gsize_in = all_abs2meta_in[iname]['global_size']
vout_sizes = sizes_out[:, all_abs2idx[src]]
offset = None
if gsize_out == gsize_in or (not dist_out and np.sum(vout_sizes)
== gsize_in):
# This assumes one of:
# 1) a distributed output with total size matching the total size of a
# distributed input
# 2) a non-distributed output with local size matching the total size of a
# distributed input
# 3) a non-distributed output with total size matching the total size of a
# distributed input
if dist_in:
offset = np.sum(sizes_in[:iproc, i])
end = offset + sizes_in[iproc, i]
# total sizes differ and output is distributed, so can't determine mapping
if offset is None:
self._collect_error(f"{self.msginfo}: Can't determine src_indices "
f"automatically for input '{iname}'. They must be "
"supplied manually.", ident=(self.pathname, iname))
continue
if dist_in and not dist_out:
src_shape = self._get_full_dist_shape(src, all_abs2meta_out[src]['shape'])
else:
src_shape = all_abs2meta_out[src]['global_shape']
if offset == end:
idx = np.zeros(0, dtype=INT_DTYPE)
else:
idx = slice(offset, end)
meta_in['src_indices'] = indexer(idx, flat_src=True, src_shape=src_shape)
meta_in['flat_src_indices'] = True
added_src_inds.append(iname)
return added_src_inds