-
Notifications
You must be signed in to change notification settings - Fork 240
/
balance_comp.py
345 lines (287 loc) · 14.3 KB
/
balance_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
"""Define the BalanceComp class."""
from types import FunctionType
from numbers import Number
import numpy as np
from openmdao.core.implicitcomponent import ImplicitComponent
from openmdao.utils import cs_safe
from openmdao.utils.array_utils import shape_to_len
class BalanceComp(ImplicitComponent):
"""
A simple equation balance for solving implicit equations.
Parameters
----------
name : str
The name of the state variable to be created.
eq_units : str or None
Units for the left-hand-side and right-hand-side of the equation to be balanced.
lhs_name : str or None
Optional name for the LHS variable associated with the implicit state variable. If
None, the default will be used: 'lhs:{name}'.
rhs_name : str or None
Optional name for the RHS variable associated with the implicit state variable. If
None, the default will be used: 'rhs:{name}'.
rhs_val : int, float, or np.array
Default value for the RHS of the given state. Must be compatible
with the shape (optionally) given by the val or shape option in kwargs.
use_mult : bool
Specifies whether the LHS multiplier is to be used. If True, then an additional
input `mult_name` is created, with the default value given by `mult_val`, that
multiplies lhs. Default is False.
mult_name : str or None
Optional name for the LHS multiplier variable associated with the implicit state
variable. If None, the default will be used: 'mult:{name}'.
mult_val : int, float, or np.array
Default value for the LHS multiplier of the given state. Must be compatible
with the shape (optionally) given by the val or shape option in kwargs.
normalize : bool
Specifies whether or not the resulting residual should be normalized by a quadratic
function of the RHS.
val : float, int, or np.ndarray
Set initial value for the state.
**kwargs : dict
Additional arguments to be passed for the creation of the implicit state variable.
(see `add_output` method).
Attributes
----------
_state_vars : dict
Cache the data provided during `add_balance`
so everything can be saved until setup is called.
"""
def initialize(self):
"""
Declare options.
"""
self.options.declare('guess_func', types=FunctionType, allow_none=True, default=None,
recordable=False, desc='A callable function in the form '
'f(inputs, outputs, residuals) that can provide an initial "guess" '
'value of the state variable(s) based on the inputs, outputs and '
'residuals.')
def __init__(self, name=None, eq_units=None, lhs_name=None, rhs_name=None, rhs_val=0.0,
use_mult=False, mult_name=None, mult_val=1.0, normalize=True, val=None, **kwargs):
r"""
Initialize a BalanceComp, optionally creating a new implicit state variable.
The BalanceComp allows for the creation of one or more implicit state variables,
and computes the residuals for those variables based on the following equation.
.. math::
\mathcal{R}_{name} =
\frac{f_{mult}(x,...) \times f_{lhs}(x,...) - f_{rhs}(x,...)}{f_{norm}(f_{rhs}(x,...))}
Where :math:`f_{lhs}` represents the left-hand-side of the equation,
:math:`f_{rhs}` represents the right-hand-side, and :math:`f_{mult}`
is an optional multiplier on the left hand side. At least one of these
quantities should be a function of the associated state variable. If
use_mult is True the default value of the multiplier is 1. The optional normalization
function :math:`f_{norm}(f_{rhs}(x,...))` is computed as:
.. math::
f_{norm}(f_{rhs}(x,...)) =
\begin{cases}
\left| f_{rhs} \right|, & \text{if normalize and } \left| f_{rhs} \right| \geq 2 \\
0.25 f_{rhs}^2 + 1, & \text{if normalize and } \left| f_{rhs} \right| < 2 \\
1, & \text{if not normalize}
\end{cases}
New state variables, and their associated residuals are created by
calling `add_balance`. As an example, solving the equation
:math:`x**2 = 2` implicitly can be be accomplished as follows:
.. code-block:: python
prob = Problem()
bal = BalanceComp()
bal.add_balance('x', val=1.0)
exec_comp = ExecComp('y=x**2')
prob.model.add_subsystem(name='exec', subsys=exec_comp)
prob.model.add_subsystem(name='balance', subsys=bal)
prob.model.connect('balance.x', 'exec.x')
prob.model.connect('exec.y', 'balance.lhs:x')
prob.model.linear_solver = DirectSolver()
prob.model.nonlinear_solver = NewtonSolver(solve_subsystems=False)
prob.setup()
prob.set_val('exec.x', 2)
prob.run_model()
The arguments to add_balance can be provided on initialization to provide a balance
with a one state/residual without the need to call `add_balance`:
.. code-block:: python
prob = Problem()
bal = BalanceComp('x', val=1.0)
exec_comp = ExecComp('y=x**2')
prob.model.add_subsystem(name='exec', subsys=exec_comp)
prob.model.add_subsystem(name='balance', subsys=bal)
prob.model.connect('balance.x', 'exec.x')
prob.model.connect('exec.y', 'balance.lhs:x')
prob.model.linear_solver = DirectSolver()
prob.model.nonlinear_solver = NewtonSolver(solve_subsystems=False)
prob.setup()
prob.set_val('exec.x', 2)
prob.run_model()
"""
if 'guess_func' in kwargs:
super().__init__(guess_func=kwargs['guess_func'])
kwargs.pop('guess_func')
else:
super().__init__()
self._state_vars = {}
if name is not None:
self.add_balance(name, eq_units, lhs_name, rhs_name, rhs_val,
use_mult, mult_name, mult_val, normalize, val, **kwargs)
self._no_check_partials = True
def apply_nonlinear(self, inputs, outputs, residuals):
"""
Calculate the residual for each balance.
Parameters
----------
inputs : Vector
Unscaled, dimensional input variables read via inputs[key].
outputs : Vector
Unscaled, dimensional output variables read via outputs[key].
residuals : Vector
Unscaled, dimensional residuals written to via residuals[key].
"""
for name, options in self._state_vars.items():
lhs = inputs[options['lhs_name']]
rhs = inputs[options['rhs_name']]
_scale_factor = np.ones((rhs.shape))
if options['normalize']:
# Indices where the rhs is near zero or not near zero
idxs_nz = np.where(cs_safe.abs(rhs) < 2)
idxs_nnz = np.where(cs_safe.abs(rhs) >= 2)
# Compute scaling factors
# scale factor that normalizes by the rhs, except near 0
_scale_factor[idxs_nnz] = 1.0 / cs_safe.abs(rhs[idxs_nnz])
_scale_factor[idxs_nz] = 1.0 / (.25 * rhs[idxs_nz] ** 2 + 1)
if options['use_mult']:
residuals[name] = (inputs[options['mult_name']] * lhs - rhs) * _scale_factor
else:
residuals[name] = (lhs - rhs) * _scale_factor
def linearize(self, inputs, outputs, jacobian):
"""
Calculate the partials of the residual for each balance.
Parameters
----------
inputs : Vector
Unscaled, dimensional input variables read via inputs[key].
outputs : Vector
Unscaled, dimensional output variables read via outputs[key].
jacobian : Jacobian
Sub-jac components written to jacobian[output_name, input_name].
"""
for name, options in self._state_vars.items():
lhs_name = options['lhs_name']
rhs_name = options['rhs_name']
lhs = inputs[lhs_name]
rhs = inputs[rhs_name]
_scale_factor = np.ones((rhs.shape))
_dscale_drhs = np.zeros((rhs.shape))
if options['normalize']:
# Indices where the rhs is near zero or not near zero
idxs_nz = np.where(cs_safe.abs(rhs) < 2)[0]
idxs_nnz = np.where(cs_safe.abs(rhs) >= 2)[0]
# scale factor that normalizes by the rhs, except near 0
_scale_factor[idxs_nnz] = 1.0 / cs_safe.abs(rhs[idxs_nnz])
_scale_factor[idxs_nz] = 1.0 / (.25 * rhs[idxs_nz] ** 2 + 1)
_dscale_drhs[idxs_nnz] = -np.sign(rhs[idxs_nnz]) / rhs[idxs_nnz]**2
_dscale_drhs[idxs_nz] = -.5 * rhs[idxs_nz] / (.25 * rhs[idxs_nz] ** 2 + 1) ** 2
if options['use_mult']:
mult_name = options['mult_name']
mult = inputs[mult_name]
# Partials of residual wrt mult
deriv = lhs * _scale_factor
jacobian[name, mult_name] = deriv.flatten()
else:
mult = 1.0
# Partials of residual wrt rhs
deriv = (mult * lhs - rhs) * _dscale_drhs - _scale_factor
jacobian[name, rhs_name] = deriv.flatten()
# Partials of residual wrt lhs
deriv = mult * _scale_factor
jacobian[name, lhs_name] = deriv.flatten()
def guess_nonlinear(self, inputs, outputs, residuals):
"""
Provide initial guess for states.
Override this method to set the initial guess for states.
Parameters
----------
inputs : Vector
Unscaled, dimensional input variables read via inputs[key].
outputs : Vector
Unscaled, dimensional output variables read via outputs[key].
residuals : Vector
Unscaled, dimensional residuals written to via residuals[key].
"""
if self.options['guess_func'] is not None:
self.options['guess_func'](inputs, outputs, residuals)
def add_balance(self, name, eq_units=None, lhs_name=None, rhs_name=None, rhs_val=0.0,
use_mult=False, mult_name=None, mult_val=1.0, normalize=True, val=None,
**kwargs):
"""
Add a new state variable and associated equation to be balanced.
This will create new inputs `lhs:name`, `rhs:name`, and `mult:name` that will
define the left and right sides of the equation to be balanced, and a
multiplier for the left-hand-side.
Parameters
----------
name : str
The name of the state variable to be created.
eq_units : str or None
Units for the left-hand-side and right-hand-side of the equation to be balanced.
lhs_name : str or None
Optional name for the LHS variable associated with the implicit state variable. If
None, the default will be used: 'lhs:{name}'.
rhs_name : str or None
Optional name for the RHS variable associated with the implicit state variable. If
None, the default will be used: 'rhs:{name}'.
rhs_val : int, float, or np.array
Default value for the RHS. Must be compatible with the shape (optionally)
given by the val or shape option in kwargs.
use_mult : bool
Specifies whether the LHS multiplier is to be used. If True, then an additional
input `mult_name` is created, with the default value given by `mult_val`, that
multiplies lhs. Default is False.
mult_name : str or None
Optional name for the LHS multiplier variable associated with the implicit state
variable. If None, the default will be used: 'mult:{name}'.
mult_val : int, float, or np.array
Default value for the LHS multiplier. Must be compatible with the shape (optionally)
given by the val or shape option in kwargs.
normalize : bool
Specifies whether or not the resulting residual should be normalized by a quadratic
function of the RHS.
val : float, int, or np.ndarray
Set initial value for the state.
**kwargs : dict
Additional arguments to be passed for the creation of the implicit state variable.
(see `add_output` method).
"""
options = {'kwargs': kwargs,
'eq_units': eq_units,
'lhs_name': lhs_name,
'rhs_name': rhs_name,
'rhs_val': rhs_val,
'use_mult': use_mult,
'mult_name': mult_name,
'mult_val': mult_val,
'normalize': normalize}
self._state_vars[name] = options
if val is None:
# If user doesn't specify initial guess for val, we can size problem from initial
# rhs_val.
if 'shape' not in kwargs and np.ndim(rhs_val) > 0:
kwargs['shape'] = rhs_val.shape
else:
options['kwargs']['val'] = val
meta = self.add_output(name, **options['kwargs'])
shape = meta['shape']
for s in ('lhs', 'rhs', 'mult'):
if options['{0}_name'.format(s)] is None:
options['{0}_name'.format(s)] = '{0}:{1}'.format(s, name)
self.add_input(options['lhs_name'],
val=np.ones(shape),
units=options['eq_units'])
self.add_input(options['rhs_name'],
val=options['rhs_val'] * np.ones(shape),
units=options['eq_units'])
if options['use_mult']:
self.add_input(options['mult_name'],
val=options['mult_val'] * np.ones(shape),
units=None)
ar = np.arange(shape_to_len(shape))
self.declare_partials(of=name, wrt=options['lhs_name'], rows=ar, cols=ar, val=1.0)
self.declare_partials(of=name, wrt=options['rhs_name'], rows=ar, cols=ar, val=1.0)
if options['use_mult']:
self.declare_partials(of=name, wrt=options['mult_name'], rows=ar, cols=ar, val=1.0)