/
test_jacobian_features.py
642 lines (496 loc) · 23.4 KB
/
test_jacobian_features.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
from __future__ import print_function, division
import unittest
import numpy as np
import scipy as sp
import itertools
from six import iteritems
from parameterized import parameterized
from openmdao.api import IndepVarComp, Group, Problem, ExplicitComponent, \
COOJacobian, ScipyIterativeSolver, DirectSolver, DenseJacobian
from openmdao.devtools.testutil import assert_rel_error
class SimpleComp(ExplicitComponent):
def setup(self):
self.add_input('x', shape=1)
self.add_input('y1', shape=2)
self.add_input('y2', shape=2)
self.add_input('y3', shape=2)
self.add_input('z', shape=(2, 2))
self.add_output('f', shape=1)
self.add_output('g', shape=(2, 2))
def compute(self, inputs, outputs):
outputs['f'] = np.sum(inputs['z']) + inputs['x']
outputs['g'] = (np.outer(inputs['y1'] + inputs['y3'], np.ones(2))
+ np.outer(np.ones(2), inputs['y2'])
+ inputs['x']*np.eye(2))
def compute_partials(self, inputs, partials):
partials['f', 'x'] = 1.
partials['f', 'z'] = np.ones((1, 4))
partials['g', 'y1'] = np.array([[1, 0], [1, 0], [0, 1], [0, 1]])
partials['g', 'y2'] = np.array([[1, 0], [0, 1], [1, 0], [0, 1]])
partials['g', 'y3'] = np.array([[1, 0], [1, 0], [0, 1], [0, 1]])
partials['g', 'x'] = np.eye(2)
class SimpleCompDependence(SimpleComp):
def setup(self):
self.add_input('x', shape=1)
self.add_input('y1', shape=2)
self.add_input('y2', shape=2)
self.add_input('y3', shape=2)
self.add_input('z', shape=(2, 2))
self.add_output('f', shape=1)
self.add_output('g', shape=(2, 2))
self.declare_partials('f', 'y1', dependent=False)
self.declare_partials('f', 'y2', dependent=False)
self.declare_partials('f', 'y3', dependent=False)
self.declare_partials('g', 'z', dependent=False)
class SimpleCompGlob(SimpleComp):
def setup(self):
self.add_input('x', shape=1)
self.add_input('y1', shape=2)
self.add_input('y2', shape=2)
self.add_input('y3', shape=2)
self.add_input('z', shape=(2, 2))
self.add_output('f', shape=1)
self.add_output('g', shape=(2, 2))
# This matches y1, y2, and y3.
self.declare_partials('f', 'y*', dependent=False)
# This matches y1 and y3.
self.declare_partials('g', 'y[13]', val=[[1, 0], [1, 0], [0, 1], [0, 1]])
class SimpleCompConst(ExplicitComponent):
def setup(self):
self.add_input('x', shape=1)
self.add_input('y1', shape=2)
self.add_input('y2', shape=2)
self.add_input('y3', shape=2)
self.add_input('z', shape=(2, 2))
self.add_output('f', shape=1)
self.add_output('g', shape=(2, 2))
# Declare derivatives
self.declare_partials('f', ['y1', 'y2', 'y3'], dependent=False)
self.declare_partials('g', 'z', dependent=False)
self.declare_partials('f', 'x', val=1.)
self.declare_partials('f', 'z', val=np.ones((1, 4)))
self.declare_partials('g', 'y[13]', val=[[1, 0], [1, 0], [0, 1], [0, 1]])
self.declare_partials('g', 'y2', val=[1., 1., 1., 1.], cols=[0, 0, 1, 1], rows=[0, 2, 1, 3])
self.declare_partials('g', 'x', val=sp.sparse.coo_matrix(((1., 1.), ((0, 3), (0, 0)))))
def compute(self, inputs, outputs):
outputs['f'] = np.sum(inputs['z']) + inputs['x']
outputs['g'] = np.outer(inputs['y1'] + inputs['y3'], inputs['y2']) + inputs['x'] * np.eye(2)
def compute_partials(self, inputs, partials):
pass
class SimpleCompFD(SimpleComp):
def __init__(self, **kwargs):
super(SimpleCompFD, self).__init__()
self.kwargs = kwargs
def setup(self):
super(SimpleCompFD, self).setup()
self.declare_partials('f', ['y1', 'y2', 'y3'], dependent=False)
self.declare_partials('g', 'z', dependent=False)
self.approx_partials('*', '*', **self.kwargs)
def compute_partials(self, inputs, partials):
pass
class SimpleCompMixedFD(SimpleComp):
def __init__(self, **kwargs):
super(SimpleCompMixedFD, self).__init__()
self.kwargs = kwargs
def setup(self):
super(SimpleCompMixedFD, self).setup()
self.declare_partials('f', ['y1', 'y2', 'y3'], dependent=False)
self.declare_partials('g', 'z', dependent=False)
self.approx_partials('g', 'x', **self.kwargs)
self.approx_partials('g', 'y2', **self.kwargs)
def compute_partials(self, inputs, partials):
partials['f', 'x'] = 1.
partials['f', 'z'] = np.ones((1, 4))
partials['g', 'y1'] = np.array([[1, 0], [1, 0], [0, 1], [0, 1]])
partials['g', 'y3'] = np.array([[1, 0], [1, 0], [0, 1], [0, 1]])
# dg/dx and dg/dy2 are FD'd
class SimpleCompKwarg(SimpleComp):
def __init__(self, partial_kwargs):
self.partial_kwargs = partial_kwargs
super(SimpleCompKwarg, self).__init__()
def setup(self):
super(SimpleCompKwarg, self).setup()
self.declare_partials(**self.partial_kwargs)
def compute_partials(self, inputs, partials):
pass
class TestJacobianFeatures(unittest.TestCase):
def setUp(self):
self.model = model = Group()
comp = IndepVarComp()
variables = (
('x', 1.),
('y1', np.ones(2)),
('y2', np.ones(2)),
('y3', np.ones(2)),
('z', np.ones((2, 2))),
)
for name, val in variables:
comp.add_output(name, val)
model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z'])
self.problem = Problem(model=model)
self.problem.set_solver_print(level=0)
model.linear_solver = ScipyIterativeSolver()
model.jacobian = COOJacobian()
def test_dependence(self):
problem = self.problem
model = problem.model
model.add_subsystem('simple', SimpleCompConst(),
promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
problem.setup(check=False)
problem.run_model()
# Note: since this test is looking for something not user-facing, it is inherently fragile
# w.r.t. internal implementations.
model._linearize()
jac = model._jacobian._int_mtx._matrix
# Testing dependence by examining the number of entries in the Jacobian. If non-zeros are
# removed during array creation (e.g. `eliminate_zeros` function on scipy.sparse matrices),
# then this test will fail since there are zero entries in the sub-Jacobians.
# 16 for outputs w.r.t. themselves
# 1 for df/dx
# 4 for df/dz
# 8 for dg/dy1
# 4 for dg/dy2
# 8 for dg/dy3
# 2 for dg/dx
expected_nnz = 16 + 1 + 4 + 8 + 4 + 8 + 2
self.assertEqual(jac.nnz, expected_nnz)
@parameterized.expand([
({'of': 'f', 'wrt': 'z', 'val': np.ones((1, 5))},
'simple: d\(f\)/d\(z\): Expected 1x4 but val is 1x5'),
({'of': 'f', 'wrt': 'z', 'rows': [0, -1, 4], 'cols': [0, 0, 0]},
'simple: d\(f\)/d\(z\): row indices must be non-negative'),
({'of': 'f', 'wrt': 'z', 'rows': [0, 0, 0], 'cols': [0, -1, 4]},
'simple: d\(f\)/d\(z\): col indices must be non-negative'),
({'of': 'f', 'wrt': 'z', 'rows': [0, 0], 'cols': [0, 4]},
'simple: d\(f\)/d\(z\): Expected 1x4 but declared at least 1x5'),
({'of': 'f', 'wrt': 'z', 'rows': [0, 10]},
'If one of rows/cols is specified, then both must be specified'),
({'of': 'f', 'wrt': 'z', 'cols': [0, 10]},
'If one of rows/cols is specified, then both must be specified'),
({'of': 'f', 'wrt': 'z', 'rows': [0], 'cols': [0, 3]},
'rows and cols must have the same shape, rows: \(1L?,\), cols: \(2L?,\)'),
({'of': 'f', 'wrt': 'z', 'rows': [0, 0, 0], 'cols': [0, 1, 3], 'val': [0, 1]},
'If rows and cols are specified, val must be a scalar or have the same shape, '
'val: \(2L?,\), rows/cols: \(3L?,\)'),
])
def test_bad_sizes(self, partials_kwargs, error_msg):
comp = SimpleCompKwarg(partials_kwargs)
problem = self.problem
model = problem.model
model.add_subsystem('simple', comp, promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
with self.assertRaises(ValueError) as ex:
problem.setup(check=False)
self.assertRegexpMatches(str(ex.exception), error_msg)
@parameterized.expand([
({'of': 'q', 'wrt': 'z'}, 'No matches were found for of="q"'),
({'of': 'f?', 'wrt': 'x'}, 'No matches were found for of="f?"'),
({'of': 'f', 'wrt': 'q'}, 'No matches were found for wrt="q"'),
({'of': 'f', 'wrt': 'x?'}, 'No matches were found for wrt="x?"'),
])
def test_bad_names(self, partials_kwargs, error_msg):
comp = SimpleCompKwarg(partials_kwargs)
problem = self.problem
model = problem.model
model.add_subsystem('simple', comp, promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
with self.assertRaises(ValueError) as ex:
problem.setup(check=False)
self.assertEquals(str(ex.exception), error_msg)
def test_const_jacobian(self):
model = Group()
comp = IndepVarComp()
for name, val in (('x', 1.), ('y1', np.ones(2)), ('y2', np.ones(2)),
('y3', np.ones(2)), ('z', np.ones((2, 2)))):
comp.add_output(name, val)
model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z'])
problem = Problem(model=model)
problem.set_solver_print(level=0)
model.linear_solver = ScipyIterativeSolver()
model.jacobian = COOJacobian()
model.add_subsystem('simple', SimpleCompConst(),
promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
problem.setup(check=False)
problem.run_model()
totals = problem.compute_total_derivs(['f', 'g'],
['x', 'y1', 'y2', 'y3', 'z'])
jacobian = {}
jacobian['f', 'x'] = [[1.]]
jacobian['f', 'z'] = np.ones((1, 4))
jacobian['f', 'y1'] = np.zeros((1, 2))
jacobian['f', 'y2'] = np.zeros((1, 2))
jacobian['f', 'y3'] = np.zeros((1, 2))
jacobian['g', 'y1'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'y2'] = [[1, 0], [0, 1], [1, 0], [0, 1]]
jacobian['g', 'y3'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'x'] = [[1], [0], [0], [1]]
jacobian['g', 'z'] = np.zeros((4, 4))
assert_rel_error(self, totals, jacobian)
@parameterized.expand(
itertools.product([1e-6, 1e-8], # Step size
['forward', 'central', 'backward'], # FD Form
['rel', 'abs'], # Step calc
)
)
def test_fd(self, step, form, step_calc):
comp = SimpleCompFD(step=step, form=form, step_calc=step_calc)
problem = self.problem
model = problem.model
model.add_subsystem('simple', comp, promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
problem.setup(check=True)
problem.run_model()
totals = problem.compute_total_derivs(['f', 'g'],
['x', 'y1', 'y2', 'y3', 'z'])
jacobian = {}
jacobian['f', 'x'] = [[1.]]
jacobian['f', 'z'] = np.ones((1, 4))
jacobian['f', 'y1'] = np.zeros((1, 2))
jacobian['f', 'y2'] = np.zeros((1, 2))
jacobian['f', 'y3'] = np.zeros((1, 2))
jacobian['g', 'y1'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'y2'] = [[1, 0], [0, 1], [1, 0], [0, 1]]
jacobian['g', 'y3'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'x'] = [[1], [0], [0], [1]]
jacobian['g', 'z'] = np.zeros((4, 4))
assert_rel_error(self, totals, jacobian, 1e-6)
def test_mixed_fd(self):
comp = SimpleCompMixedFD()
problem = self.problem
model = problem.model
model.add_subsystem('simple', comp, promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
problem.setup(check=True)
problem.run_model()
totals = problem.compute_total_derivs(['f', 'g'],
['x', 'y1', 'y2', 'y3', 'z'])
jacobian = {}
jacobian['f', 'x'] = [[1.]]
jacobian['f', 'z'] = np.ones((1, 4))
jacobian['f', 'y1'] = np.zeros((1, 2))
jacobian['f', 'y2'] = np.zeros((1, 2))
jacobian['f', 'y3'] = np.zeros((1, 2))
jacobian['g', 'y1'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'y2'] = [[1, 0], [0, 1], [1, 0], [0, 1]]
jacobian['g', 'y3'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'x'] = [[1], [0], [0], [1]]
jacobian['g', 'z'] = np.zeros((4, 4))
assert_rel_error(self, totals, jacobian, 1e-6)
def test_units_fd(self):
class UnitCompBase(ExplicitComponent):
def setup(self):
self.add_input('T', val=284., units="degR", desc="Temperature")
self.add_input('P', val=1., units='lbf/inch**2', desc="Pressure")
self.add_output('flow:T', val=284., units="degR", desc="Temperature")
self.add_output('flow:P', val=1., units='lbf/inch**2', desc="Pressure")
self.approx_partials(of='*', wrt='*')
def compute(self, inputs, outputs):
outputs['flow:T'] = inputs['T']
outputs['flow:P'] = inputs['P']
p = Problem()
model = p.model = Group()
indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*'])
indep.add_output('T', val=100., units='degK')
indep.add_output('P', val=1., units='bar')
units = model.add_subsystem('units', UnitCompBase(), promotes=['*'])
p.setup()
p.run_model()
totals = p.compute_total_derivs(['flow:T', 'flow:P'], ['T', 'P'])
expected_totals = {
('flow:T', 'T'): [[9/5]],
('flow:P', 'T'): [[0.]],
('flow:T', 'P'): [[0.]],
('flow:P', 'P'): [[14.50377]],
}
assert_rel_error(self, totals, expected_totals, 1e-6)
expected_subjacs = {
('units.flow:T', 'units.T'): [[-1.]],
('units.flow:P', 'units.T'): [[0.]],
('units.flow:T', 'units.P'): [[0.]],
('units.flow:P', 'units.P'): [[-1.]],
}
jac = units._jacobian._subjacs
for deriv, val in iteritems(expected_subjacs):
assert_rel_error(self, jac[deriv], val, 1e-6)
def test_reference(self):
class TmpComp(ExplicitComponent):
def initialize(self):
self.A = np.ones((3, 3))
def setup(self):
self.add_output('y', shape=(3,))
self.add_output('z', shape=(3,))
self.add_input('x', shape=(3,), units='degF')
def compute_partials(self, inputs, partials):
partials['y', 'x'] = self.A
partials['z', 'x'] = self.A
p = Problem()
model = p.model = Group()
indep = model.add_subsystem('indep', IndepVarComp(), promotes=['*'])
indep.add_output('x', val=100., shape=(3,), units='degK')
model.add_subsystem('comp', TmpComp(), promotes=['*'])
p.setup()
p.run_model()
totals = p.compute_total_derivs(['y', 'z'], ['x'])
expected_totals = {
('y', 'x'): 9/5 * np.ones((3, 3)),
('z', 'x'): 9/5 * np.ones((3, 3)),
}
assert_rel_error(self, totals, expected_totals, 1e-6)
class TestJacobianForDocs(unittest.TestCase):
def test_const_jacobian(self):
model = Group()
comp = IndepVarComp()
for name, val in (('x', 1.), ('y1', np.ones(2)), ('y2', np.ones(2)),
('y3', np.ones(2)), ('z', np.ones((2, 2)))):
comp.add_output(name, val)
model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z'])
problem = Problem(model=model)
model.suppress_solver_output = True
model.linear_solver = DirectSolver()
model.jacobian = DenseJacobian()
model.add_subsystem('simple', SimpleCompConst(),
promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
problem.setup(check=False)
problem.run_model()
totals = problem.compute_total_derivs(['f', 'g'],
['x', 'y1', 'y2', 'y3', 'z'])
assert_rel_error(self, totals['f', 'x'], [[1.]])
assert_rel_error(self, totals['f', 'z'], np.ones((1, 4)))
assert_rel_error(self, totals['f', 'y1'], np.zeros((1, 2)))
assert_rel_error(self, totals['f', 'y2'], np.zeros((1, 2)))
assert_rel_error(self, totals['f', 'y3'], np.zeros((1, 2)))
assert_rel_error(self, totals['g', 'x'], [[1], [0], [0], [1]])
assert_rel_error(self, totals['g', 'z'], np.zeros((4, 4)))
assert_rel_error(self, totals['g', 'y1'], [[1, 0], [1, 0], [0, 1], [0, 1]])
assert_rel_error(self, totals['g', 'y2'], [[1, 0], [0, 1], [1, 0], [0, 1]])
assert_rel_error(self, totals['g', 'y3'], [[1, 0], [1, 0], [0, 1], [0, 1]])
def test_sparse_jacobian_in_place(self):
class SparsePartialComp(ExplicitComponent):
def setup(self):
self.add_input('x', shape=(4,))
self.add_output('f', shape=(2,))
self.declare_partials(of='f', wrt='x', rows=[0,1,1,1], cols=[0,1,2,3])
def compute_partials(self, inputs, partials):
pd = partials['f', 'x']
# Corresponds to the (0, 0) entry
pd[0] = 1.
# (1,1) entry
pd[1] = 2.
# (1, 2) entry
pd[2] = 3.
# (1, 3) entry
pd[3] = 4
model = Group()
comp = IndepVarComp()
comp.add_output('x', np.ones(4))
model.add_subsystem('input', comp)
model.add_subsystem('example', SparsePartialComp())
model.connect('input.x', 'example.x')
problem = Problem(model=model)
problem.setup(check=False)
problem.run_model()
totals = problem.compute_total_derivs(['example.f'], ['input.x'])
assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]])
def test_sparse_jacobian(self):
class SparsePartialComp(ExplicitComponent):
def setup(self):
self.add_input('x', shape=(4,))
self.add_output('f', shape=(2,))
self.declare_partials(of='f', wrt='x', rows=[0, 1, 1, 1], cols=[0, 1, 2, 3])
def compute_partials(self, inputs, partials):
# Corresponds to the [(0,0), (1,1), (1,2), (1,3)] entries.
partials['f', 'x'] = [1., 2., 3., 4.]
model = Group()
comp = IndepVarComp()
comp.add_output('x', np.ones(4))
model.add_subsystem('input', comp)
model.add_subsystem('example', SparsePartialComp())
model.connect('input.x', 'example.x')
problem = Problem(model=model)
problem.setup(check=False)
problem.run_model()
totals = problem.compute_total_derivs(['example.f'], ['input.x'])
assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]])
def test_sparse_jacobian_const(self):
class SparsePartialComp(ExplicitComponent):
def setup(self):
self.add_input('x', shape=(4,))
self.add_input('y', shape=(2,))
self.add_output('f', shape=(2,))
self.declare_partials(of='f', wrt='x', rows=[0,1,1,1], cols=[0,1,2,3],
val=[1. , 2., 3., 4.])
self.declare_partials(of='f', wrt='y', val=sp.sparse.eye(2, format='csc'))
def compute_partials(self, inputs, partials):
pass
model = Group()
comp = IndepVarComp()
comp.add_output('x', np.ones(4))
comp.add_output('y', np.ones(2))
model.add_subsystem('input', comp)
model.add_subsystem('example', SparsePartialComp())
model.connect('input.x', 'example.x')
model.connect('input.y', 'example.y')
problem = Problem(model=model)
problem.setup(check=False)
problem.run_model()
totals = problem.compute_total_derivs(['example.f'], ['input.x', 'input.y'])
assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]])
assert_rel_error(self, totals['example.f', 'input.y'], [[1., 0.], [0., 1.]])
def test_fd_glob(self):
class FDPartialComp(ExplicitComponent):
def setup(self):
self.add_input('x', shape=(4,))
self.add_input('y', shape=(2,))
self.add_input('y2', shape=(2,))
self.add_output('f', shape=(2,))
self.approx_partials('f', 'y*')
self.approx_partials('f', 'x')
def compute(self, inputs, outputs):
f = outputs['f']
x = inputs['x']
y = inputs['y']
f[0] = x[0] + y[0]
f[1] = np.dot([0, 2, 3, 4], x) + y[1]
model = Group()
comp = IndepVarComp()
comp.add_output('x', np.ones(4))
comp.add_output('y', np.ones(2))
model.add_subsystem('input', comp)
model.add_subsystem('example', FDPartialComp())
model.connect('input.x', 'example.x')
model.connect('input.y', 'example.y')
problem = Problem(model=model)
problem.setup(check=False)
problem.run_model()
totals = problem.compute_total_derivs(['example.f'], ['input.x', 'input.y'])
assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]],
tolerance=1e-8)
assert_rel_error(self, totals['example.f', 'input.y'], [[1., 0.], [0., 1.]], tolerance=1e-8)
def test_fd_options(self):
class FDPartialComp(ExplicitComponent):
def setup(self):
self.add_input('x', shape=(4,))
self.add_input('y', shape=(2,))
self.add_input('y2', shape=(2,))
self.add_output('f', shape=(2,))
self.approx_partials('f', 'y*', method='fd', form='backward', step=1e-6)
self.approx_partials('f', 'x', method='fd', form='central', step=1e-4)
def compute(self, inputs, outputs):
f = outputs['f']
x = inputs['x']
y = inputs['y']
f[0] = x[0] + y[0]
f[1] = np.dot([0, 2, 3, 4], x) + y[1]
model = Group()
comp = IndepVarComp()
comp.add_output('x', np.ones(4))
comp.add_output('y', np.ones(2))
model.add_subsystem('input', comp)
model.add_subsystem('example', FDPartialComp())
model.connect('input.x', 'example.x')
model.connect('input.y', 'example.y')
problem = Problem(model=model)
problem.setup(check=False)
problem.run_model()
totals = problem.compute_total_derivs(['example.f'], ['input.x', 'input.y'])
assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]],
tolerance=1e-8)
assert_rel_error(self, totals['example.f', 'input.y'], [[1., 0.], [0., 1.]], tolerance=1e-8)
if __name__ == '__main__':
unittest.main()