Skip to content

Instantly share code, notes, and snippets.

@thearn
Created February 8, 2016 20:53
Show Gist options
  • Save thearn/a553a1264836e853b189 to your computer and use it in GitHub Desktop.
Save thearn/a553a1264836e853b189 to your computer and use it in GitHub Desktop.
working example
from openmdao.api import *
import numpy as np
"""
Test model:
-------------
Find value of state variable "x" such that the line 2*x + 1 has a specific
value of 'y1'
"""
class MyState(Component):
def __init__(self):
super(MyState, self).__init__()
self.add_param("y1", np.pi)
self.add_param("y2", 0.0)
self.add_state("x", 1.0)
def solve_nonlinear(self,p,u,r):
pass
def apply_nonlinear(self, p, u, r):
r['x'] = p['y1'] - p['y2']
def linearize(self, params, unknowns, resids):
J = {}
J['x','y1'] = 1.0
J['x','y2'] = -1.0
J['x', 'x'] = 0.0
return J
class Intercept(Component):
def __init__(self):
super(Intercept, self).__init__()
self.add_param("x", 0.0)
self.add_output("y2", 1.0)
def solve_nonlinear(self, p, u, r):
u['y2'] = 2.0*p['x'] + 1.0
def linearize(self, p, u, r):
return {('y2', 'x') : 2.0}
p = Problem()
p.root = Group()
p.root.add("state", MyState(), promotes=["*"])
p.root.add("intercept", Intercept(), promotes=["*"])
params = (('y1', np.pi),)
p.root.add("param", IndepVarComp(params), promotes=["*"])
p.root.ln_solver = ScipyGMRES()
p.root.ln_solver.options['atol'] = 1e-8
p.root.ln_solver.options['maxiter'] = 100
p.root.ln_solver.options['restart'] = 100
p.root.nl_solver = Newton()
p.root.nl_solver.options['rtol'] = 1.4e-8
p.root.nl_solver.options['maxiter'] = 75
p.root.nl_solver.options['iprint'] = 0
p.setup()
p.run()
print "x, y1, y2:", p['x'], p['y1'], p['y2']
p.check_partial_derivatives()
print
p.check_total_derivatives()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment