def test_double_arraycomp(self): # Mainly testing a bug in the array return for multiple arrays group = Group() group.add('x_param1', ParamComp('x1', np.ones((2))), promotes=['*']) group.add('x_param2', ParamComp('x2', np.ones((2))), promotes=['*']) group.add('mycomp', DoubleArrayComp(), promotes=['*']) prob = Problem(impl=impl) prob.root = group prob.root.ln_solver = PetscKSP() prob.setup(check=False) prob.run() Jbase = group.mycomp.JJ J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fwd', return_format='array') diff = np.linalg.norm(J - Jbase) assert_rel_error(self, diff, 0.0, 1e-8) J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fd', return_format='array') diff = np.linalg.norm(J - Jbase) assert_rel_error(self, diff, 0.0, 1e-8) J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='rev', return_format='array') diff = np.linalg.norm(J - Jbase) assert_rel_error(self, diff, 0.0, 1e-8)
def test_simple_paraboloid_equality(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 50.0), promotes=['*']) root.add('p2', ParamComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('con', ExecComp('c = 15.0 - x + y'), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_param('y', low=-50.0, high=50.0) prob.driver.add_objective('f_xy') prob.driver.add_constraint('c', ctype='ineq') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob['x'], 7.16667, 1e-6) assert_rel_error(self, prob['y'], -7.833334, 1e-6)
def __init__(self): super(SellarStateConnection, self).__init__() self.add('px', ParamComp('x', 1.0), promotes=['*']) self.add('pz', ParamComp('z', np.array([5.0, 2.0])), promotes=['*']) self.add('state_eq', StateConnection()) self.add('d1', SellarDis1(), promotes=['x', 'z', 'y1']) self.add('d2', SellarDis2(), promotes=['z', 'y1']) self.connect('state_eq.y2_command', 'd1.y2') self.connect('d2.y2', 'state_eq.y2_actual') self.add('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0, d1=0.0, d2=0.0), promotes=['x', 'z', 'y1', 'obj']) self.connect('d2.y2', 'obj_cmp.y2') self.add('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['*']) self.add('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2']) self.connect('d2.y2', 'con_cmp2.y2') self.nl_solver = Newton()
def test_fd_skip_keys(self): prob = Problem() root = prob.root = Group() comp = Component() comp.add_param('x', 0.) comp.add_param('y', 0.) comp.add_output('z', 0.) comp.solve_nonlinear = lambda p, u, r: u.__setitem__('z', 1.) comp._get_fd_params = lambda: ['x'] comp.jacobian = lambda a, b, c: {('z', 'x'): 0.} root.add('comp', comp, promotes=['x', 'y']) root.add('px', ParamComp('x', 0.), promotes=['*']) root.add('py', ParamComp('y', 0.), promotes=['*']) prob.setup(check=False) prob.run() try: prob.check_partial_derivatives(out_stream=None) except KeyError as err: self.fail('KeyError raised: {0}'.format(str(err)))
def test_simple(self): prob = Problem(Group(), impl=impl) size = 5 A1 = prob.root.add('A1', ParamComp('a', np.zeros(size, float))) B1 = prob.root.add('B1', ParamComp('b', np.zeros(size, float))) B2 = prob.root.add('B2', ParamComp('b', np.zeros(size, float))) S1 = prob.root.add('S1', ParamComp('s', '')) L1 = prob.root.add('L1', ParamComp('l', [])) C1 = prob.root.add('C1', ABCDArrayComp(size)) C2 = prob.root.add('C2', ABCDArrayComp(size)) prob.root.connect('A1.a', 'C1.a') prob.root.connect('B1.b', 'C1.b') # prob.root.connect('S1:s', 'C1.in_string') # prob.root.connect('L1:l', 'C1.in_list') prob.root.connect('C1.c', 'C2.a') prob.root.connect('B2.b', 'C2.b') # prob.root.connect('C1.out_string', 'C2.in_string') # prob.root.connect('C1.out_list', 'C2.in_list') prob.setup(check=False) prob['A1.a'] = np.ones(size, float) * 3.0 prob['B1.b'] = np.ones(size, float) * 7.0 prob['B2.b'] = np.ones(size, float) * 5.0 prob.run() self.assertTrue(all(prob['C2.a'] == np.ones(size, float) * 10.)) self.assertTrue(all(prob['C2.b'] == np.ones(size, float) * 5.)) self.assertTrue(all(prob['C2.c'] == np.ones(size, float) * 15.)) self.assertTrue(all(prob['C2.d'] == np.ones(size, float) * 5.))
def __init__(self): super(FanIn, self).__init__() self.add('p1', ParamComp('x1', 1.0)) self.add('p2', ParamComp('x2', 1.0)) self.add('comp1', ExecComp(['y=-2.0*x'])) self.add('comp2', ExecComp(['y=5.0*x'])) self.add('comp3', ExecComp(['y=3.0*x1+7.0*x2'])) self.connect("comp1.y", "comp3.x1") self.connect("comp2.y", "comp3.x2") self.connect("p1.x1", "comp1.x") self.connect("p2.x2", "comp2.x")
def __init__(self): super(ConvergeDivergeGroups, self).__init__() self.add('p', ParamComp('x', 2.0)) sub1 = self.add('sub1', Group()) sub1.add('comp1', Comp1()) sub2 = sub1.add('sub2', Group()) sub2.add('comp2', Comp2()) sub2.add('comp3', Comp3()) sub1.add('comp4', Comp4()) sub3 = self.add('sub3', Group()) sub3.add('comp5', Comp5()) sub3.add('comp6', Comp6()) self.add('comp7', Comp7()) self.connect("p.x", "sub1.comp1.x1") self.connect('sub1.comp1.y1', 'sub1.sub2.comp2.x1') self.connect('sub1.comp1.y2', 'sub1.sub2.comp3.x1') self.connect('sub1.sub2.comp2.y1', 'sub1.comp4.x1') self.connect('sub1.sub2.comp3.y1', 'sub1.comp4.x2') self.connect('sub1.comp4.y1', 'sub3.comp5.x1') self.connect('sub1.comp4.y2', 'sub3.comp6.x1') self.connect('sub3.comp5.y1', 'comp7.x1') self.connect('sub3.comp6.y1', 'comp7.x2')
def test_simple_array_comp2D(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', np.zeros((2, 2))), promotes=['*']) root.add('comp', ArrayComp2D(), promotes=['*']) root.add('con', ExecComp('c = y - 20.0', c=np.zeros((2, 2)), y=np.zeros((2, 2))), promotes=['*']) root.add('obj', ExecComp('o = y[0, 0]', y=np.zeros((2, 2))), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_objective('o') prob.driver.add_constraint('c', ctype='eq') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() obj = prob['o'] assert_rel_error(self, obj, 20.0, 1e-6)
def test_array_values(self): prob = Problem() prob.root = Group() prob.root.add('pc', ParamComp('x', np.zeros((2, 3)), units='degC'), promotes=['x']) prob.root.add('uc', UnitComp(shape=(2, 3), param_name='x', out_name='x_out', units='degF'), promotes=['x', 'x_out']) prob.setup(check=False) prob.run() assert_rel_error(self, prob['x_out'], np.array([[32., 32., 32.], [32., 32., 32.]]), 1e-6) param_list = ['x'] unknown_list = ['x_out'] # Forward Mode J = prob.calc_gradient(param_list, unknown_list, mode='fwd', return_format='dict') assert_rel_error(self, J['x_out']['x'], 1.8 * np.eye(6), 1e-6) # Reverse Mode J = prob.calc_gradient(param_list, unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J['x_out']['x'], 1.8 * np.eye(6), 1e-6)
def test_parallel_diamond(self): size = 3 prob = Problem(Group(), impl=impl) root = prob.root root.add('P1', ParamComp('x', np.ones(size, float) * 1.1)) G1 = root.add('G1', ParallelGroup()) G1.add('C1', ABCDArrayComp(size)) G1.add('C2', ABCDArrayComp(size)) root.add('C3', ABCDArrayComp(size)) root.connect('P1.x', 'G1.C1.a') root.connect('P1.x', 'G1.C2.b') root.connect('G1.C1.c', 'C3.a') root.connect('G1.C2.d', 'C3.b') prob.setup(check=False) prob.run() if not MPI or self.comm.rank == 0: assert_rel_error(self, prob.root.G1.C1.unknowns['c'], np.ones(size) * 2.1, 1.e-10) assert_rel_error(self, prob.root.G1.C1.unknowns['d'], np.ones(size) * .1, 1.e-10) assert_rel_error(self, prob.root.C3.params['a'], np.ones(size) * 2.1, 1.e-10) assert_rel_error(self, prob.root.C3.params['b'], np.ones(size) * -.1, 1.e-10) if not MPI or self.comm.rank == 1: assert_rel_error(self, prob.root.G1.C2.unknowns['c'], np.ones(size) * 2.1, 1.e-10) assert_rel_error(self, prob.root.G1.C2.unknowns['d'], np.ones(size) * -.1, 1.e-10)
def test_index_error_messages_con(self): prob = Problem() prob.root = Group() prob.root.fd_options['force_fd'] = True prob.root.ln_solver.options['mode'] = 'auto' prob.root.add('myparams', ParamComp('x', np.zeros(4))) prob.root.add('rosen', Rosenbrock(4)) prob.root.connect('myparams.x', 'rosen.x') prob.driver = MySimpleDriver() prob.driver.add_param('myparams.x') prob.driver.add_constraint('rosen.xxx', indices=[4]) prob.setup(check=False) # Make sure we can't do this with self.assertRaises(IndexError) as cm: prob.run() msg = "Index for constraint 'rosen.xxx' is out of bounds. " msg += "Requested index: [4], " msg += "Parameter shape: (4,)." raised_error = str(cm.exception) raised_error = raised_error.replace('(4L,', '(4,') self.assertEqual(msg, raised_error)
def test_conflicting_promotions(self): # verify we get an error if we have conflicting promotions root = Group() # promoting G1.x will create an implicit connection to G3.x # this is a conflict because G3.x (aka G3.C4.x) is already connected # to G3.C3.x G2 = root.add('G2', Group()) G2.add('C1', ParamComp('x', 5.), promotes=['x']) G1 = G2.add('G1', Group(), promotes=['x']) G1.add('C2', ExecComp('y=x*2.0'), promotes=['x']) G3 = root.add('G3', Group(), promotes=['x']) G3.add('C3', ExecComp('y=x*2.0'), promotes=['y']) # promoting y G3.add('C4', ExecComp('y=x*2.0'), promotes=['x', 'y']) # promoting y again.. BAD prob = Problem(root) try: prob.setup(check=False) except Exception as error: msg = "Promoted name 'G3.y' matches multiple unknowns: ['G3.C3.y', 'G3.C4.y']" self.assertEqual(text_type(error), msg) else: self.fail("Error expected")
def test_conflicting_connections(self): # verify we get an error if we have conflicting implicit and explicit connections root = Group() # promoting G1.x will create an implicit connection to G3.x # this is a conflict because G3.x (aka G3.C4.x) is already connected # to G3.C3.x G2 = root.add('G2', Group(), promotes=['x']) # BAD PROMOTE G2.add('C1', ParamComp('x', 5.), promotes=['x']) G1 = G2.add('G1', Group(), promotes=['x']) G1.add('C2', ExecComp('y=x*2.0'), promotes=['x']) G3 = root.add('G3', Group(), promotes=['x']) G3.add('C3', ExecComp('y=x*2.0')) G3.add('C4', ExecComp('y=x*2.0'), promotes=['x']) root.connect('G2.G1.C2.y', 'G3.C3.x') G3.connect('C3.y', 'x') prob = Problem(root) try: prob.setup(check=False) except Exception as error: msg = "Target 'G3.C4.x' is connected to multiple unknowns: ['G2.C1.x', 'G3.C3.y']" self.assertEqual(text_type(error), msg) else: self.fail("Error expected")
def test_simple_matvec(self): class VerificationComp(SimpleCompDerivMatVec): def jacobian(self, params, unknowns, resids): raise RuntimeError( "Derivative functions on this comp should not run.") def apply_linear(self, params, unknowns, dparams, dunknowns, dresids, mode): raise RuntimeError( "Derivative functions on this comp should not run.") sub = Group() sub.add('mycomp', VerificationComp()) prob = Problem() prob.root = Group() prob.root.add('sub', sub) prob.root.add('x_param', ParamComp('x', 1.0)) prob.root.connect('x_param.x', "sub.mycomp.x") sub.fd_options['force_fd'] = True prob.setup(check=False) prob.run() J = prob.calc_gradient(['x_param.x'], ['sub.mycomp.y'], mode='fwd', return_format='dict') assert_rel_error(self, J['sub.mycomp.y']['x_param.x'][0][0], 2.0, 1e-6) J = prob.calc_gradient(['x_param.x'], ['sub.mycomp.y'], mode='rev', return_format='dict') assert_rel_error(self, J['sub.mycomp.y']['x_param.x'][0][0], 2.0, 1e-6)
def test_auto_order(self): # this tests the auto ordering when we have a cycle that is smaller # than the full graph. p = Problem(root=Group()) root = p.root C5 = root.add("C5", ExecComp('y=x*2.0')) C6 = root.add("C6", ExecComp('y=x*2.0')) C1 = root.add("C1", ExecComp('y=x*2.0')) C2 = root.add("C2", ExecComp('y=x*2.0')) C3 = root.add("C3", ExecComp(['y=x*2.0', 'y2=x2+1.0'])) C4 = root.add("C4", ExecComp(['y=x*2.0', 'y2=x2+1.0'])) P1 = root.add("P1", ParamComp('x', 1.0)) root.connect('P1.x', 'C1.x') root.connect('C1.y', 'C2.x') root.connect('C2.y', 'C4.x') root.connect('C4.y', 'C5.x') root.connect('C5.y', 'C6.x') root.connect('C5.y', 'C3.x2') root.connect('C6.y', 'C3.x') root.connect('C3.y', 'C4.x2') p.setup(check=False) self.assertEqual(p.root.list_auto_order(), ['P1', 'C1', 'C2', 'C4', 'C5', 'C6', 'C3'])
def test_inp_inp_promoted_w_explicit_src(self): p = Problem(root=Group()) root = p.root G1 = root.add("G1", Group()) G2 = G1.add("G2", Group(), promotes=['x']) C1 = G2.add("C1", ExecComp('y=x*2.0')) C2 = G2.add("C2", ParamComp('x', 1.0), promotes=['x']) G3 = root.add("G3", Group()) G4 = G3.add("G4", Group(), promotes=['x']) C3 = G4.add("C3", ExecComp('y=x*2.0'), promotes=['x']) C4 = G4.add("C4", ExecComp('y=x*2.0'), promotes=['x']) p.root.connect('G1.x', 'G3.x') p.setup(check=False) self.assertEqual(p._dangling['G1.G2.C1.x'], set(['G1.G2.C1.x'])) self.assertEqual(len(p._dangling), 1) # setting promoted name will set the value into the unknowns, but will # not propagate it to the params. That will happen during run(). p['G1.x'] = 999. self.assertEqual(p.root.G3.G4.C3.params['x'], 0.) self.assertEqual(p.root.G3.G4.C4.params['x'], 0.) p.run() self.assertEqual(p.root.G3.G4.C3.params['x'], 999.) self.assertEqual(p.root.G3.G4.C4.params['x'], 999.)
def test_bad_size(self): class BadComp(SimpleArrayComp): def jacobian(self, params, unknowns, resids): """Analytical derivatives""" J = {} J[('y', 'x')] = np.zeros((3, 3)) return J prob = Problem() prob.root = Group() prob.root.add('comp', BadComp()) prob.root.add('p1', ParamComp('x', np.ones([2]))) prob.root.connect('p1.x', 'comp.x') prob.setup(check=False) prob.run() try: data = prob.check_partial_derivatives(out_stream=None) except Exception as err: msg = "Jacobian in component 'comp' between the" + \ " variables 'x' and 'y' is the wrong size. " + \ "It should be 2 by 2" self.assertEqual(str(err), msg) else: self.fail("Error expected")
def test_bad_init1(self): try: p = ParamComp('P') except Exception as err: self.assertEqual( str(err), "ParamComp init: a value must be provided as the second arg.")
def test_simple_array_comp(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', np.zeros([2])), promotes=['*']) root.add('comp', SimpleArrayComp(), promotes=['*']) root.add('con', ExecComp('c = y - 20.0', c=np.array([0.0, 0.0]), y=np.array([0.0, 0.0])), promotes=['*']) root.add('obj', ExecComp('o = y[0]', y=np.array([0.0, 0.0])), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_objective('o') prob.driver.add_constraint('c', ctype='eq') prob.setup(check=False) prob.run() obj = prob['o'] assert_rel_error(self, obj, 20.0, 1e-6)
def __init__(self): super(SellarDerivatives, self).__init__() self.add('px', ParamComp('x', 1.0), promotes=['*']) self.add('pz', ParamComp('z', np.array([5.0, 2.0])), promotes=['*']) self.add('d1', SellarDis1withDerivatives(), promotes=['*']) self.add('d2', SellarDis2withDerivatives(), promotes=['*']) self.add('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0, d1=0.0, d2=0.0), promotes=['*']) self.add('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['*']) self.add('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['*']) self.nl_solver = NLGaussSeidel()
def test_bad_init6(self): try: p = ParamComp([('x', )]) except Exception as err: self.assertEqual( str(err), "ParamComp init: arg ('x',) must be a tuple of the form (name, value) or (name, value, keyword_dict)." )
def test_bad_init5(self): try: p = ParamComp(1.0) except Exception as err: self.assertEqual( str(err), "first argument to ParamComp init must be either of type `str` or an iterable of tuples of the form (name, value) or (name, value, keyword_dict)." )
def test_check_matrix_matrix(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('a', 1.0), promotes=['*']) root.add('p2', ParamComp('b', 1.0), promotes=['*']) sub1 = root.add('sub1', Group(), promotes=['*']) sub2 = sub1.add('sub2', Group(), promotes=['*']) sub2.add('comp', ExecComp(['x = 2.0*a + 3.0*b', 'y=4.0*a - 1.0*b']), promotes=['*']) prob.setup(check=False) prob.run() # NOTE: this call won't actually calculate mode because default ln_solver # is ScipyGMRES and its default mode is 'fwd', not 'auto'. mode = prob._check_for_matrix_matrix(['a'], ['x']) root.ln_solver.options['mode'] = 'rev' sub1.ln_solver.options['mode'] = 'rev' try: mode = prob._check_for_matrix_matrix(['a'], ['x']) except Exception as err: msg = "Group 'sub2' has mode 'fwd' but the root group has mode 'rev'. Modes must match to use Matrix Matrix." self.assertEqual(text_type(err), msg) else: self.fail('Exception expected') sub1.ln_solver.options['mode'] = 'fwd' sub2.ln_solver.options['mode'] = 'rev' try: mode = prob._check_for_matrix_matrix(['a'], ['x']) except Exception as err: msg = "Group 'sub1' has mode 'fwd' but the root group has mode 'rev'. Modes must match to use Matrix Matrix." self.assertEqual(text_type(err), msg) else: self.fail('Exception expected') sub1.ln_solver.options['mode'] = 'rev' mode = prob._check_for_matrix_matrix(['a'], ['x'])
def test_nested_conn(self): # tests a self contained connection under a Group nested at least 3 levels # down from the Problem prob = Problem(root=Group()) root = prob.root G1 = root.add('G1', Group()) G2 = G1.add('G2', Group()) C1 = G2.add('C1', ParamComp('x', 5.)) C2 = G2.add('C2', ExecComp('y=x*2.0')) G2.connect('C1.x', 'C2.x') prob.setup(check=False)
def __init__(self): super(FanOut, self).__init__() self.add('p', ParamComp('x', 1.0)) self.add('comp1', ExecComp(['y=3.0*x'])) self.add('comp2', ExecComp(['y=-2.0*x'])) self.add('comp3', ExecComp(['y=5.0*x'])) self.connect("comp1.y", "comp2.x") self.connect("comp1.y", "comp3.x") self.connect("p.x", "comp1.x")
def __init__(self): super(SellarDerivativesGrouped, self).__init__() self.add('px', ParamComp('x', 1.0), promotes=['*']) self.add('pz', ParamComp('z', np.array([5.0, 2.0])), promotes=['*']) sub = self.add('mda', Group(), promotes=['*']) sub.add('d1', SellarDis1withDerivatives(), promotes=['*']) sub.add('d2', SellarDis2withDerivatives(), promotes=['*']) self.add('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['*']) self.add('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['*']) self.add('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['*']) sub.nl_solver = NLGaussSeidel() sub.d1.fd_options['force_fd'] = True sub.d2.fd_options['force_fd'] = True
def test_fan_out(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 1.0)) root.add('p2', ParamComp('x', 1.0)) root.add('comp1', ExecComp('y = 3.0*x')) root.add('comp2', ExecComp('y = 5.0*x')) root.add('obj', ExecComp('o = i1 + i2')) root.add('con1', ExecComp('c = 15.0 - x')) root.add('con2', ExecComp('c = 15.0 - x')) # hook up non explicitly root.connect('p1.x', 'comp1.x') root.connect('p2.x', 'comp2.x') root.connect('comp1.y', 'obj.i1') root.connect('comp2.y', 'obj.i2') root.connect('comp1.y', 'con1.x') root.connect('comp2.y', 'con2.x') prob.driver = pyOptSparseDriver() prob.driver.add_param('p1.x', low=-50.0, high=50.0) prob.driver.add_param('p2.x', low=-50.0, high=50.0) prob.driver.add_objective('obj.o') prob.driver.add_constraint('con1.c', ctype='eq') prob.driver.add_constraint('con2.c', ctype='eq') prob.setup(check=False) prob.run() obj = prob['obj.o'] assert_rel_error(self, obj, 30.0, 1e-6) # Verify that pyOpt has the correct wrt names con1 = prob.driver.pyopt_solution.constraints['con1.c'] self.assertEqual(con1.wrt, ['p1.x']) con2 = prob.driver.pyopt_solution.constraints['con2.c'] self.assertEqual(con2.wrt, ['p2.x'])
def test_indices(self): asize = 3 prob = Problem(root=Group(), impl=impl) root = prob.root root.ln_solver = LinearGaussSeidel() root.ln_solver.options['mode'] = 'rev' p = root.add('p', ParamComp('x', np.arange(asize, dtype=float) + 1.0)) G1 = root.add('G1', ParallelGroup()) G1.ln_solver = LinearGaussSeidel() G1.ln_solver.options['mode'] = 'rev' c2 = G1.add( 'c2', ExecComp4Test('y = x * 2.0', x=np.zeros(asize), y=np.zeros(asize))) c3 = G1.add( 'c3', ExecComp4Test('y = numpy.ones(3).T*x.dot(numpy.arange(3.,6.))', x=np.zeros(asize), y=np.zeros(asize))) c4 = root.add( 'c4', ExecComp4Test('y = x * 4.0', x=np.zeros(asize), y=np.zeros(asize))) c5 = root.add( 'c5', ExecComp4Test('y = x * 5.0', x=np.zeros(asize), y=np.zeros(asize))) prob.driver.add_param('p.x', indices=[1, 2]) prob.driver.add_constraint('c4.y', indices=[1]) prob.driver.add_constraint('c5.y', indices=[2]) prob.driver.parallel_derivs(['c4.y', 'c5.y']) root.connect('p.x', 'G1.c2.x') root.connect('p.x', 'G1.c3.x') root.connect('G1.c2.y', 'c4.x') root.connect('G1.c3.y', 'c5.x') prob.setup(check=False) prob.run() J = prob.calc_gradient(['p.x'], ['c4.y', 'c5.y'], mode='fwd', return_format='dict') assert_rel_error(self, J['c5.y']['p.x'][0], np.array([20., 25.]), 1e-6) assert_rel_error(self, J['c4.y']['p.x'][0], np.array([8., 0.]), 1e-6) J = prob.calc_gradient(['p.x'], ['c4.y', 'c5.y'], mode='rev', return_format='dict') assert_rel_error(self, J['c5.y']['p.x'][0], np.array([20., 25.]), 1e-6) assert_rel_error(self, J['c4.y']['p.x'][0], np.array([8., 0.]), 1e-6)
def test_scaler_adder(self): class ScaleAddDriver(Driver): def run(self, problem): """ Save away scaled info.""" params = self.get_params() param_meta = self.get_param_metadata() self.set_param('x', 0.5) problem.root.solve_nonlinear() objective = self.get_objectives() constraint = self.get_constraints() # Stuff we saved should be in the scaled coordinates. self.param = params['x'] self.obj_scaled = objective['f_xy'] self.con_scaled = constraint['con'] self.param_high = param_meta['x']['high'] self.param_low = param_meta['x']['low'] prob = Problem() root = prob.root = Group() driver = prob.driver = ScaleAddDriver() root.add('p1', ParamComp([('x', 60000.0, { 'desc': 'my x' }), ('y', 60000.0, { 'desc': 'my y' })]), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('constraint', ExecComp('con=f_xy + x + y'), promotes=['*']) driver.add_param('x', low=59000.0, high=61000.0, adder=-60000.0, scaler=1 / 1000.0) driver.add_objective('f_xy', adder=-10890367002.0, scaler=1.0 / 20) driver.add_constraint('con', adder=-10890487502.0, scaler=1.0 / 20) prob.setup(check=False) prob.run() self.assertEqual(driver.param_high, 1.0) self.assertEqual(driver.param_low, -1.0) self.assertEqual(driver.param, 0.0) self.assertEqual(prob['x'], 60500.0) self.assertEqual(driver.obj_scaled[0], 1.0) self.assertEqual(driver.con_scaled[0], 1.0)
def setUp(self): self.p = Problem(root=Group()) root = self.p.root self.G1 = root.add("G1", Group()) self.G2 = self.G1.add("G2", Group()) self.C1 = self.G2.add("C1", ExecComp('y=x*2.0')) self.C2 = self.G2.add("C2", ParamComp('x', 1.0)) self.G3 = root.add("G3", Group()) self.G4 = self.G3.add("G4", Group()) self.C3 = self.G4.add("C3", ExecComp('y=x*2.0')) self.C4 = self.G4.add("C4", ExecComp('y=x*2.0'))