-
Notifications
You must be signed in to change notification settings - Fork 240
/
exec_comp.py
1319 lines (1096 loc) · 50.8 KB
/
exec_comp.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 ExecComp class, a component that evaluates an expression."""
import re
import time
from itertools import product
from contextlib import contextmanager
from collections import defaultdict
import numpy as np
from numpy import ndarray, imag, complex128 as npcomplex
from openmdao.core.system import _DEFAULT_COLORING_META
from openmdao.utils.coloring import _ColSparsityJac, _compute_coloring
from openmdao.core.constants import INT_DTYPE
from openmdao.core.explicitcomponent import ExplicitComponent
from openmdao.utils.units import valid_units
from openmdao.utils import cs_safe
from openmdao.utils.om_warnings import issue_warning, DerivativesWarning, SetupWarning
from openmdao.utils.array_utils import get_random_arr
# regex to check for variable names.
VAR_RGX = re.compile(r'([.]*[_a-zA-Z]\w*[ ]*\(?)')
# Names of metadata entries allowed for ExecComp variables.
_allowed_meta = {'value', 'val', 'shape', 'units', 'res_units', 'desc',
'ref', 'ref0', 'res_ref', 'lower', 'upper', 'src_indices',
'flat_src_indices', 'tags', 'shape_by_conn', 'copy_shape', 'compute_shape',
'constant'}
# Names that are not allowed for input or output variables (keywords for options)
_disallowed_names = {'has_diag_partials', 'units', 'shape', 'shape_by_conn', 'run_root_only',
'constant', 'do_coloring'}
def check_option(option, value):
"""
Check option for validity.
Parameters
----------
option : str
The name of the option.
value : any
The value of the option.
Raises
------
ValueError
"""
if option == 'units' and value is not None and not valid_units(value):
raise ValueError("The units '%s' are invalid." % value)
def array_idx_iter(shape):
"""
Return an iterator over the indices into a n-dimensional array.
Parameters
----------
shape : tuple
Shape of the array.
Yields
------
int
"""
for p in product(*[range(s) for s in shape]):
yield p
class ExecComp(ExplicitComponent):
"""
A component defined by an expression string.
Parameters
----------
exprs : str, tuple of str or list of str
An assignment statement or iter of them. These express how the
outputs are calculated based on the inputs. In addition to
standard Python operators, a subset of numpy and scipy functions
is supported.
**kwargs : dict of named args
Initial values of variables can be set by setting a named
arg with the var name. If the value is a dict it is assumed
to contain metadata. To set the initial value in addition to
other metadata, assign the initial value to the 'val' entry
of the dict.
Attributes
----------
_kwargs : dict of named args
Initial values of variables.
_exprs : list
List of expressions.
_codes : list
List of code objects.
_exprs_info : list
List of tuples containing output and inputs for each expression.
complex_stepsize : double
Step size used for complex step which is used for derivatives.
_manual_decl_partials : bool
If True, at least one partial has been declared by the user.
_requires_fd : dict
Contains a mapping of 'of' variables to a tuple of the form (wrts, functs) for those
'of' variables that require finite difference to be used to compute their derivatives.
_constants : dict of dicts
Constants defined in the expressions. The key is the name of the constant and the value
is a dict of metadata.
_coloring_declared : bool
If True, coloring has been declared manually.
_inarray : ndarray or None
If using internal CS, this is a complex array containing input values.
_outarray : ndarray or None
If using internal CS, this is a complex array containing output values.
_indict : dict or None
If using internal CS, this maps input variable views in _inarray to input names.
_viewdict : dict or None
If using internal CS, this maps input, output, and constant names to their corresponding
views/values.
"""
def __init__(self, exprs=[], **kwargs):
r"""
Create a <Component> using only an expression string.
Given a list of assignment statements, this component creates
input and output variables at construction time. All variables
appearing on the left-hand side of an assignment are outputs,
and the rest are inputs. Each variable is assumed to be of
type float unless the initial value for that variable is supplied
in \*\*kwargs. Derivatives are calculated using complex step.
The following functions are available for use in expressions:
========================= ====================================
Function Description
========================= ====================================
abs(x) Absolute value of x
acos(x) Inverse cosine of x
acosh(x) Inverse hyperbolic cosine of x
arange(start, stop, step) Array creation
arccos(x) Inverse cosine of x
arccosh(x) Inverse hyperbolic cosine of x
arcsin(x) Inverse sine of x
arcsinh(x) Inverse hyperbolic sine of x
arctan(x) Inverse tangent of x
arctan2(y, x) 4-quadrant arctangent function of y and x
asin(x) Inverse sine of x
asinh(x) Inverse hyperbolic sine of x
atan(x) Inverse tangent of x
cos(x) Cosine of x
cosh(x) Hyperbolic cosine of x
dot(x, y) Dot product of x and y
e Euler's number
erf(x) Error function
erfc(x) Complementary error function
exp(x) Exponential function
expm1(x) exp(x) - 1
fmax(x, y) Element-wise maximum of x and y
fmin(x, y) Element-wise minimum of x and y
inner(x, y) Inner product of arrays x and y
isinf(x) Element-wise detection of np.inf
isnan(x) Element-wise detection of np.nan
kron(x, y) Kronecker product of arrays x and y
linspace(x, y, N) Numpy linear spaced array creation
log(x) Natural logarithm of x
log10(x) Base-10 logarithm of x
log1p(x) log(1+x)
matmul(x, y) Matrix multiplication of x and y
maximum(x, y) Element-wise maximum of x and y
minimum(x, y) Element-wise minimum of x and y
ones(N) Create an array of ones
outer(x, y) Outer product of x and y
pi Pi
power(x, y) Element-wise x**y
prod(x) The product of all elements in x
sin(x) Sine of x
sinh(x) Hyperbolic sine of x
sum(x) The sum of all elements in x
tan(x) Tangent of x
tanh(x) Hyperbolic tangent of x
tensordot(x, y) Tensor dot product of x and y
zeros(N) Create an array of zeros
========================= ====================================
Notes
-----
If a variable has an initial value that is anything other than 1.0,
either because it has a different type than float or just because its
initial value is != 1.0, you must use a keyword arg
to set the initial value. For example, let's say we have an
ExecComp that takes an array 'x' as input and outputs a float variable
'y' which is the sum of the entries in 'x'.
.. code-block:: python
import numpy
import openmdao.api as om
excomp = om.ExecComp('y=sum(x)', x=numpy.ones(10, dtype=float))
In this example, 'y' would be assumed to be the default type of float
and would be given the default initial value of 1.0, while 'x' would be
initialized with a size 10 float array of ones.
If you want to assign certain metadata for 'x' in addition to its
initial value, you can do it as follows:
.. code-block:: python
excomp = ExecComp('y=sum(x)',
x={'val': numpy.ones(10, dtype=float),
'units': 'ft'})
"""
options = {}
for name in _disallowed_names:
if name in kwargs:
options[name] = kwargs.pop(name)
super().__init__(**options)
# change default coloring values
self._coloring_info['method'] = 'cs'
self._coloring_info['num_full_jacs'] = 2
# if complex step is used for derivatives, this is the stepsize
self.complex_stepsize = 1.e-40
if isinstance(exprs, str):
exprs = [exprs]
self._exprs = exprs[:]
self._exprs_info = []
self._codes = []
self._kwargs = kwargs
self._manual_decl_partials = False
self._no_check_partials = True
self._constants = {}
self._coloring_declared = False
self._inarray = None
self._outarray = None
self._indict = None
self._viewdict = None
def initialize(self):
"""
Declare options.
"""
self.options.declare('has_diag_partials', types=bool, default=False,
desc='If True, treat all array/array partials as diagonal if both '
'arrays have size > 1. All arrays with size > 1 must have the '
'same flattened size or an exception will be raised.')
self.options.declare('units', types=str, allow_none=True, default=None,
desc='Units to be assigned to all variables in this component. '
'Default is None, which means units may be provided for variables'
' individually.',
check_valid=check_option)
self.options.declare('shape', types=(int, tuple, list), allow_none=True, default=None,
desc='Shape to be assigned to all variables in this component. '
'Default is None, which means shape may be provided for variables'
' individually.')
self.options.declare('shape_by_conn', types=bool, default=False,
desc='If True, shape all inputs and outputs based on their '
'connection. Default is False.')
self.options.declare('do_coloring', types=bool, default=True,
desc='If True (the default), compute the partial jacobian '
'coloring for this component.')
@classmethod
def register(cls, name, callable_obj, complex_safe):
"""
Register a callable to be usable within ExecComp expressions.
Parameters
----------
name : str
Name of the callable.
callable_obj : callable
The callable.
complex_safe : bool
If True, the given callable works correctly with complex numbers.
"""
global _expr_dict, _not_complex_safe
if not callable(callable_obj):
raise TypeError(f"{cls.__name__}: '{name}' passed to register() of type "
f"'{type(callable_obj).__name__}' is not callable.")
if name in _expr_dict:
raise NameError(f"{cls.__name__}: '{name}' has already been registered.")
if name in _disallowed_names:
raise NameError(f"{cls.__name__}: cannot register name '{name}' because "
"it's a reserved keyword.")
if '.' in name:
raise NameError(f"{cls.__name__}: cannot register name '{name}' because "
"it contains '.'.")
_expr_dict[name] = callable_obj
if not complex_safe:
_not_complex_safe.add(name)
def setup(self):
"""
Set up variable name and metadata lists.
"""
if self._exprs:
self._setup_expressions()
def _setup_expressions(self):
"""
Set up the expressions.
This is called during setup_procs and after each call to "add_expr" from configure.
"""
global _not_complex_safe
exprs = self._exprs
kwargs = self._kwargs
shape = self.options['shape']
shape_by_conn = self.options['shape_by_conn']
if shape is not None and shape_by_conn:
raise RuntimeError(f"{self.msginfo}: Can't set both shape and shape_by_conn.")
self._exprs_info = exprs_info = []
outs = set()
allvars = set()
constants = set()
self._requires_fd = {}
for expr in exprs:
lhs, _, rhs = expr.partition('=')
onames = self._parse_for_out_vars(lhs)
vnames, fnames = self._parse_for_names(rhs)
constants.update([n for n, val in kwargs.items()
if isinstance(val, dict) and 'constant' in val and val['constant']])
# remove constants
vnames = vnames.difference(constants)
allvars.update(vnames)
outs.update(onames)
if onames.intersection(allvars):
# we have a used-before-calculated output
violators = sorted([n for n in onames if n in allvars])
raise RuntimeError(f"{self.msginfo}: Outputs {violators} are used before "
"being calculated, so this ExecComp is not a valid explicit "
"component.")
exprs_info.append((onames, vnames, fnames))
if _not_complex_safe.intersection(fnames):
for o in onames:
self._requires_fd[o] = (vnames, fnames)
allvars.update(outs)
if self._requires_fd:
inps = []
for out, (rhsvars, funcs) in self._requires_fd.items():
iset = rhsvars.difference(outs)
self._requires_fd[out] = (iset, funcs)
inps.extend(iset)
self._no_check_partials = False
self.set_check_partial_options(wrt=inps, method='fd')
kwargs2 = {}
init_vals = {}
units = self.options['units']
# make sure all kwargs are legit
for varname, val in kwargs.items():
if varname not in allvars and varname not in constants:
msg = f"{self.msginfo}: arg '{varname}' in call to ExecComp() " \
f"does not refer to any variable in the expressions {exprs}"
if varname in ('promotes', 'promotes_inputs', 'promotes_outputs'):
msg += ". Did you intend to promote variables in the 'add_subsystem' call?"
raise RuntimeError(msg)
if isinstance(val, dict):
dct = val
vval = dct.get('val')
vshape = dct.get('shape')
vshape_by_conn = dct.get('shape_by_conn')
vcopy_shape = dct.get('copy_shape')
vcompute_shape = dct.get('compute_shape')
vconstant = dct.get('constant')
vunits = dct.get('units')
if vconstant:
if vval is None:
raise RuntimeError(f"{self.msginfo}: arg '{varname}' in call to ExecComp() "
"is a constant but no value is given")
for ignored_meta in ['units', 'shape']:
if ignored_meta in dct:
issue_warning(f"arg '{varname}' in call to ExecComp() "
f"is a constant. The {ignored_meta} will be ignored",
prefix=self.msginfo, category=SetupWarning)
self._constants[varname] = vval
continue # TODO should still do some checking here!
diff = set(dct.keys()) - _allowed_meta
if diff:
raise RuntimeError("%s: the following metadata names were not "
"recognized for variable '%s': %s" %
(self.msginfo, varname, sorted(diff)))
kwargs2[varname] = dct.copy()
if units is not None:
if vunits is not None and vunits != units:
raise RuntimeError("%s: units of '%s' have been specified for "
"variable '%s', but units of '%s' have been "
"specified for the entire component." %
(self.msginfo, vunits, varname, units))
else:
kwargs2[varname]['units'] = units
if shape is not None:
if vshape is not None and vshape != shape:
raise RuntimeError("%s: shape of %s has been specified for "
"variable '%s', but shape of %s has been "
"specified for the entire component." %
(self.msginfo, vshape, varname, shape))
elif vval is not None and np.atleast_1d(vval).shape != shape:
raise RuntimeError("%s: value of shape %s has been specified for "
"variable '%s', but shape of %s has been "
"specified for the entire component." %
(self.msginfo, np.atleast_1d(vval).shape,
varname, shape))
else:
init_vals[varname] = np.ones(shape)
if vval is not None:
init_vals[varname] = vval
del kwargs2[varname]['val']
if vshape_by_conn or vcopy_shape or vcompute_shape:
if vshape is not None or vval is not None:
raise RuntimeError(f"{self.msginfo}: Can't set 'shape' or 'val' for "
f"variable '{varname}' along with 'copy_shape', "
"compute_shape, or 'shape_by_conn'.")
if vshape is not None:
if varname not in init_vals:
init_vals[varname] = np.ones(vshape)
elif np.atleast_1d(init_vals[varname]).shape != vshape:
raise RuntimeError("%s: shape of %s has been specified for variable "
"'%s', but a value of shape %s has been provided." %
(self.msginfo, str(vshape), varname,
str(np.atleast_1d(init_vals[varname]).shape)))
del kwargs2[varname]['shape']
else:
init_vals[varname] = val
if self._static_mode:
var_rel2meta = self._static_var_rel2meta
else:
var_rel2meta = self._var_rel2meta
for var in sorted(allvars):
meta = kwargs2.get(var, {
'units': units,
'shape': shape,
'shape_by_conn': shape_by_conn})
# if user supplied an initial value, use it, otherwise set to 1.0
if var in init_vals:
val = init_vals[var]
else:
val = 1.0
if var in var_rel2meta:
# Input/Output already exists, but we may be setting defaults for the first time.
# Note that there is only one submitted dictionary of defaults.
current_meta = var_rel2meta[var]
for kname, kvalue in meta.items():
if kvalue is not None:
current_meta[kname] = kvalue
new_val = kwargs[var].get('val')
if new_val is not None:
# val is normally ensured to be a numpy array in add_input/add_output,
# do the same here...
current_meta['val'] = np.atleast_1d(new_val)
else:
# new input and/or output.
if var in outs:
current_meta = self.add_output(var, val, **meta)
else:
if 'constant' in meta:
meta.pop('constant', None)
current_meta = self.add_input(var, val, **meta)
if var not in init_vals:
init_vals[var] = current_meta['val']
self._codes = self._compile_exprs(self._exprs)
def add_expr(self, expr, **kwargs):
"""
Add an expression to the ExecComp.
Parameters
----------
expr : str
An assignment statement that expresses how the outputs are calculated based on the
inputs. In addition to standard Python operators, a subset of numpy and scipy
functions is supported.
**kwargs : dict of named args
Initial values of variables can be set by setting a named arg with the var name. If
the value is a dict it is assumed to contain metadata. To set the initial value in
addition to other metadata, assign the initial value to the 'val' entry of the dict.
Do not include for inputs whose default kwargs have been declared on previous
expressions.
"""
if not isinstance(expr, str):
typ = type(expr).__name__
msg = f"Argument 'expr' must be of type 'str', but type '{typ}' was found."
raise TypeError(msg)
self._exprs.append(expr)
for name in kwargs:
if name in self._kwargs:
raise NameError(f"Defaults for '{name}' have already been defined in a previous "
"expression.")
self._kwargs.update(kwargs)
if not self._static_mode:
self._setup_expressions()
def _compile_exprs(self, exprs):
compiled = []
outputs = set()
for i, expr in enumerate(exprs):
# Quick dupe check.
lhs_name = expr.partition('=')[0].strip()
if lhs_name in outputs:
# Can't add two equations with the same output.
raise RuntimeError(f"{self.msginfo}: The output '{lhs_name}' has already been "
"defined by an expression.")
else:
outputs.add(lhs_name)
try:
compiled.append(compile(expr, expr, 'exec'))
except Exception:
raise RuntimeError("%s: failed to compile expression '%s'." %
(self.msginfo, exprs[i]))
return compiled
def _parse_for_out_vars(self, s):
vnames = set([x.strip() for x in re.findall(VAR_RGX, s)
if not x.endswith('(') and not x.startswith('.')])
for v in vnames:
if v in _expr_dict:
raise NameError("%s: cannot assign to variable '%s' "
"because it's already defined as an internal "
"function or constant." % (self.msginfo, v))
return vnames
def _parse_for_names(self, s):
names = [x.strip() for x in re.findall(VAR_RGX, s) if not x.startswith('.')]
vnames = set()
for n in names:
if n.endswith('('):
continue
vnames.add(n)
fnames = [n[:-1] for n in names if n[-1] == '(']
to_remove = []
for v in vnames:
if v in _disallowed_names:
raise NameError("%s: cannot use variable name '%s' because "
"it's a reserved keyword." % (self.msginfo, v))
if v in _expr_dict:
expvar = _expr_dict[v]
if callable(expvar):
raise NameError("%s: cannot use '%s' as a variable because "
"it's already defined as an internal "
"function or constant." % (self.msginfo, v))
else:
to_remove.append(v)
for f in fnames:
if f not in _expr_dict:
raise NameError(f"{self.msginfo}: can't use '{f}' as a function because "
"it hasn't been registered.")
return vnames.difference(to_remove), fnames
def __getstate__(self):
"""
Return state as a dict.
Returns
-------
dict
State to get.
"""
state = self.__dict__.copy()
del state['_codes']
return state
def __setstate__(self, state):
"""
Restore state from `state`.
Parameters
----------
state : dict
State to restore.
"""
self.__dict__.update(state)
self._codes = self._compile_exprs(self._exprs)
def declare_partials(self, *args, **kwargs):
"""
Declare information about this component's subjacobians.
Parameters
----------
*args : list
Positional args to be passed to base class version of declare_partials.
**kwargs : dict
Keyword args to be passed to base class version of declare_partials.
Returns
-------
dict
Metadata dict for the specified partial(s).
"""
if 'method' not in kwargs or kwargs['method'] not in ('cs', 'fd'):
raise RuntimeError(f"{self.msginfo}: declare_partials must be called with method='cs' "
"or method='fd'.")
if self.options['has_diag_partials']:
raise RuntimeError(f"{self.msginfo}: declare_partials cannot be called manually if "
"has_diag_partials has been set.")
self._manual_decl_partials = True
return super().declare_partials(*args, **kwargs)
def _get_coloring(self):
"""
Get the Coloring for this system.
If necessary, load the Coloring from a file or dynamically generate it.
Returns
-------
Coloring or None
Coloring object, possible loaded from a file or dynamically generated, or None
"""
if self.options['do_coloring']:
return super()._get_coloring()
def _setup_partials(self):
"""
Check that all partials are declared.
"""
has_diag_partials = self.options['has_diag_partials']
if not self._manual_decl_partials:
if self.options['do_coloring'] and not has_diag_partials:
rank = self.comm.rank
sizes = self._var_sizes
if not self._has_distrib_vars and (sum(sizes['input'][rank]) > 1 and
sum(sizes['output'][rank]) > 1):
if not self._coloring_declared:
super().declare_coloring(wrt=None, method='cs')
self._coloring_info['dynamic'] = True
self._manual_decl_partials = False # this gets reset in declare_partials
self._declared_partials = defaultdict(dict)
else:
self.options['do_coloring'] = False
self._coloring_info['dynamic'] = False
meta = self._var_rel2meta
decl_partials = super().declare_partials
for outs, vs, _ in self._exprs_info:
ins = sorted(set(vs).difference(outs))
for out in sorted(outs):
for inp in ins:
if has_diag_partials:
ival = meta[inp]['val']
oval = meta[out]['val']
iarray = isinstance(ival, ndarray) and ival.size > 1
if iarray and isinstance(oval, ndarray) and oval.size > 1:
if oval.size != ival.size:
raise RuntimeError(
"%s: has_diag_partials is True but partial(%s, %s) "
"is not square (shape=(%d, %d))." %
(self.msginfo, out, inp, oval.size, ival.size))
# partial will be declared as diagonal
inds = np.arange(oval.size, dtype=INT_DTYPE)
else:
inds = None
decl_partials(of=out, wrt=inp, rows=inds, cols=inds)
else:
decl_partials(of=out, wrt=inp)
super()._setup_partials()
if self._manual_decl_partials:
undeclared = []
for outs, vs, _ in self._exprs_info:
ins = sorted(set(vs).difference(outs))
for out in sorted(outs):
out = '.'.join((self.pathname, out))
for inp in ins:
inp = '.'.join((self.pathname, inp))
if (out, inp) not in self._subjacs_info:
undeclared.append((out, inp))
if undeclared:
idx = len(self.pathname) + 1
undeclared = ', '.join([' wrt '.join((f"'{of[idx:]}'", f"'{wrt[idx:]}'"))
for of, wrt in undeclared])
issue_warning(f"The following partial derivatives have not been "
f"declared so they are assumed to be zero: [{undeclared}].",
prefix=self.msginfo, category=DerivativesWarning)
def _setup_vectors(self, root_vectors):
"""
Compute all vectors for all vec names.
Parameters
----------
root_vectors : dict of dict of Vector
Root vectors: first key is 'input', 'output', or 'residual'; second key is vec_name.
"""
super()._setup_vectors(root_vectors)
if not self._use_derivatives:
self._manual_decl_partials = True # prevents attempts to use _viewdict in compute
self._iodict = _IODict(self._outputs, self._inputs, self._constants)
self._relcopy = False
if not self._manual_decl_partials:
if self._force_alloc_complex:
# we can use the internal Vector complex arrays
# set complex_step_mode so we'll get the full complex array
self._inputs.set_complex_step_mode(True)
self._outputs.set_complex_step_mode(True)
self._indict = self._inputs._get_local_views()
outdict = self._outputs._get_local_views()
self._inarray = self._inputs.asarray(copy=False)
self._outarray = self._outputs.asarray(copy=False)
self._inputs.set_complex_step_mode(False)
self._outputs.set_complex_step_mode(False)
else:
# we make our own complex 'copy' of the Vector arrays
self._inarray = np.zeros(len(self._inputs), dtype=complex)
self._outarray = np.zeros(len(self._outputs), dtype=complex)
self._indict = self._inputs._get_local_views(self._inarray)
outdict = self._outputs._get_local_views(self._outarray)
self._relcopy = True
# combine lookup dicts for faster exec calls
viewdict = self._indict.copy()
viewdict.update(outdict)
viewdict.update(self._constants)
self._viewdict = _ViewDict(viewdict)
def compute(self, inputs, outputs):
"""
Execute this component's assignment statements.
Parameters
----------
inputs : `Vector`
`Vector` containing inputs.
outputs : `Vector`
`Vector` containing outputs.
"""
if not self._manual_decl_partials:
if self._relcopy:
self._inarray[:] = self._inputs.asarray(copy=False)
self._exec()
outs = outputs.asarray(copy=False)
if outs.dtype == self._outarray.dtype:
outs[:] = self._outarray
else:
outs[:] = self._outarray.real
else:
self._exec()
return
if self._iodict._inputs is not inputs:
self._iodict = _IODict(outputs, inputs, self._constants)
for i, expr in enumerate(self._codes):
try:
# inputs, outputs, and _constants are vectors
exec(expr, _expr_dict, self._iodict) # nosec:
# limited to _expr_dict
except Exception as err:
raise RuntimeError(f"{self.msginfo}: Error occurred evaluating '{self._exprs[i]}':"
f"\n{err}")
def _linearize(self, jac=None, sub_do_ln=False):
"""
Compute jacobian / factorization. The model is assumed to be in a scaled state.
Parameters
----------
jac : Jacobian or None
Ignored.
sub_do_ln : bool
Flag indicating if the children should call linearize on their linear solvers.
"""
if self._requires_fd:
if 'fd' in self._approx_schemes:
fdins = {wrt.rsplit('.', 1)[1] for wrt in self._approx_schemes['fd']._wrt_meta}
else:
fdins = set()
for _, (inps, funcs) in self._requires_fd.items():
diff = inps.difference(fdins)
if diff:
raise RuntimeError(f"{self.msginfo}: expression contains functions "
f"{sorted(funcs)} that are not complex safe. To fix this, "
f"call declare_partials('*', {sorted(diff)}, method='fd') "
f"on this component prior to setup.")
self._requires_fd = False # only need to do this check the first time around
super()._linearize(jac, sub_do_ln)
def declare_coloring(self,
wrt=_DEFAULT_COLORING_META['wrt_patterns'],
method=_DEFAULT_COLORING_META['method'],
form=None,
step=None,
per_instance=_DEFAULT_COLORING_META['per_instance'],
num_full_jacs=_DEFAULT_COLORING_META['num_full_jacs'],
tol=_DEFAULT_COLORING_META['tol'],
orders=_DEFAULT_COLORING_META['orders'],
perturb_size=_DEFAULT_COLORING_META['perturb_size'],
min_improve_pct=_DEFAULT_COLORING_META['min_improve_pct'],
show_summary=_DEFAULT_COLORING_META['show_summary'],
show_sparsity=_DEFAULT_COLORING_META['show_sparsity']):
"""
Set options for deriv coloring of a set of wrt vars matching the given pattern(s).
Parameters
----------
wrt : str or list of str
The name or names of the variables that derivatives are taken with respect to.
This can contain input names, output names, or glob patterns.
method : str
Method used to compute derivative: "fd" for finite difference, "cs" for complex step.
form : str
Finite difference form, can be "forward", "central", or "backward". Leave
undeclared to keep unchanged from previous or default value.
step : float
Step size for finite difference. Leave undeclared to keep unchanged from previous
or default value.
per_instance : bool
If True, a separate coloring will be generated for each instance of a given class.
Otherwise, only one coloring for a given class will be generated and all instances
of that class will use it.
num_full_jacs : int
Number of times to repeat partial jacobian computation when computing sparsity.
tol : float
Tolerance used to determine if an array entry is nonzero during sparsity determination.
orders : int
Number of orders above and below the tolerance to check during the tolerance sweep.
perturb_size : float
Size of input/output perturbation during generation of sparsity.
min_improve_pct : float
If coloring does not improve (decrease) the number of solves more than the given
percentage, coloring will not be used.
show_summary : bool
If True, display summary information after generating coloring.
show_sparsity : bool
If True, display sparsity with coloring info after generating coloring.
"""
super().declare_coloring(wrt, method, form, step, per_instance, num_full_jacs,
tol, orders, perturb_size, min_improve_pct,
show_summary, show_sparsity)
self._coloring_declared = True
self._manual_decl_partials = True
def _exec(self):
for i, expr in enumerate(self._codes):
try:
exec(expr, _expr_dict, self._viewdict) # nosec:
except Exception as err:
raise RuntimeError(f"{self.msginfo}: Error occurred evaluating "
f"'{self._exprs[i]}':\n{err}")
def _compute_coloring(self, recurse=False, **overrides):
"""
Compute a coloring of the partial jacobian.
This assumes that the current System is in a proper state for computing derivatives.
Parameters
----------
recurse : bool
Ignored.
**overrides : dict
Any args that will override either default coloring settings or coloring settings
resulting from an earlier call to declare_coloring.
Returns
-------
list of Coloring
The computed colorings.
"""
if self._manual_decl_partials:
# use framework approx coloring
return super()._compute_coloring(recurse=recurse, **overrides)
info = self._coloring_info
info.update(**overrides)
if isinstance(info['wrt_patterns'], str):
info['wrt_patterns'] = [info['wrt_patterns']]
if not self._coloring_declared and info['method'] is None:
info['method'] = 'cs'
if info['method'] != 'cs':
raise RuntimeError(f"{self.msginfo}: 'method' for coloring must be 'cs' if partials "
"and/or coloring are not declared manually using declare_partials "
"or declare_coloring.")
if info['coloring'] is None and info['static'] is None:
info['dynamic'] = True
# match everything
info['wrt_matches_rel'] = None
info['wrt_matches'] = None
sparsity_start_time = time.perf_counter()
step = self.complex_stepsize * 1j
inv_stepsize = 1.0 / self.complex_stepsize
inarr = self._inarray
oarr = self._outarray
if self.options['has_diag_partials']:
# we should never get here
raise NotImplementedError("has_diag_partials not supported with coloring yet")
# compute perturbations
starting_inputs = self._inputs.asarray(copy=not self._relcopy)
in_offsets = starting_inputs.copy()
in_offsets[in_offsets == 0.0] = 1.0
in_offsets *= info['perturb_size']
# use special sparse jacobian to collect sparsity info
jac = _ColSparsityJac(self, info)
for i in range(info['num_full_jacs']):
inarr[:] = starting_inputs + in_offsets * get_random_arr(in_offsets.size, self.comm)
for i in range(inarr.size):
inarr[i] += step
self._exec()
jac.set_col(self, i, imag(oarr * inv_stepsize))
inarr[i] -= step
if not self._relcopy:
self._inputs.set_val(starting_inputs)
sparsity, sp_info = jac.get_sparsity(self)
sparsity_time = time.perf_counter() - sparsity_start_time
coloring = _compute_coloring(sparsity, 'fwd')
if not self._finalize_coloring(coloring, info, sp_info, sparsity_time):
return [None]
# compute mapping of col index to wrt varname
self._col_idx2name = idxnames = [None] * len(self._inputs)
plen = len(self.pathname) + 1
for name, slc in self._inputs.get_slice_dict().items():
name = name[plen:]