Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Kenneth-T-Moore/510f3be4cad0f1a7858b574d9eb05a9a to your computer and use it in GitHub Desktop.
Save Kenneth-T-Moore/510f3be4cad0f1a7858b574d9eb05a9a to your computer and use it in GitHub Desktop.
CS across nested problem with derivs.
import numpy as np
import openmdao.api as om
from openmdao.test_suite.components.paraboloid import Paraboloid
class SubProblem(om.ExplicitComponent):
def setup(self):
self.add_input('x', val=0.0)
self.add_input('y', val=0.0)
self.add_output('df_dx', val=0.0)
# Setup sub-problem
self._problem = prob = om.Problem()
model = prob.model
model.add_subsystem('sub', Paraboloid(), promotes=['*'])
prob.setup(force_alloc_complex=True)
def compute(self, inputs, outputs):
prob = self._problem
under_cs = self.under_complex_step
if under_cs:
prob.set_complex_step_mode(True)
# Set inputs
prob.set_val('x', inputs['x'])
prob.set_val('y', inputs['y'])
# Run model
prob.run_model()
totals = prob.compute_totals(of=['f_xy'],
wrt=['x'])
# Extract outputs
outputs['df_dx'] = totals['f_xy', 'x']
if under_cs:
prob.set_complex_step_mode(False)
prob = om.Problem()
model = prob.model
model.add_subsystem('comp', SubProblem())
model.approx_totals(method='cs')
prob.setup(force_alloc_complex=True)
prob.run_model()
totals = prob.compute_totals('comp.df_dx', 'comp.x')
# Should be 2.0 (verify by setting to fd). It's 0 because imaginary part is lost when propagated
# through sub-problem's linear vector.
print(totals)
print('done')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment