def test_request(self): logging.debug('') logging.debug('test_request') assembly = Assembly() comp1 = assembly.add('comp1', ExtCode()) comp2 = assembly.add('comp2', ExtCode()) sub = assembly.add('sub', Assembly()) comp3 = sub.add('comp3', ExtCode()) comp1.resources = dict(min_cpus=10, max_cpus=10, resource_limits=dict(virtual_memory=100, cpu_time=120), rerunnable=True, accounting_id='frobozz', queue_name='debug', job_category='MPI') comp2.resources = dict(max_cpus=2, resource_limits=dict(wallclock_time=1000000)) comp3.resources = dict(min_cpus=200, resource_limits=dict(virtual_memory=20, cpu_time=1000, wallclock_time=500), rerunnable=True, accounting_id='frobozz', queue_name='debug', job_category='MPI') req = RAM.max_request(assembly) expected = dict(min_cpus=200, max_cpus=200, resource_limits=dict(virtual_memory=100, cpu_time=1000, wallclock_time=1000000)) logging.debug('req: %r', req) logging.debug('exp: %r', expected) self.assertEqual(req, expected) req = RAM.total_request(assembly) expected = dict(min_cpus=200, max_cpus=200, resource_limits=dict(virtual_memory=100, cpu_time=1120, wallclock_time=1000500), rerunnable=True, accounting_id='frobozz', queue_name='debug', job_category='MPI') logging.debug('req: %r', req) logging.debug('exp: %r', expected) self.assertEqual(req, expected) comp3.resources['accounting_id'] = 'xyzzy' assert_raises(self, 'RAM.total_request(assembly)', globals(), locals(), ValueError, "Incompatible settings for 'accounting_id':" " 'xyzzy' vs. 'frobozz'")
def test_vtree(self): top = Assembly() sub = top.add('sub', Assembly()) sub.add('comp', LoadsComp()) sub.driver.workflow.add('comp') sub.create_passthrough('comp.loads_in') sub.create_passthrough('comp.loads_out') top.driver.workflow.add('sub') jsonfile = os.path.join(self.tempdir, 'test_vtree.json') old_json_file = os.path.join(os.path.dirname(__file__), 'vtree.json') top.recorders = [JSONCaseRecorder(jsonfile)] loads = Loads() loads.Fx = [1, 2, 3] loads.Fy = [4, 5, 6] loads.Fz = [7, 8, 9] arr = LoadsArray() arr.loads = [loads] top.sub.loads_in = arr top.run() cdsnew = CaseDataset(jsonfile, 'json') cdsold = CaseDataset(old_json_file, 'json') cdsold.data.vars('sub.comp.loads_out').fetch()[0][0]['loads'][0]['Fx'] == cdsnew.data.vars('sub.comp.loads_out').fetch()[0][0]['loads'][0]['Fx'] cdsold.data.vars('sub.comp.loads_out').fetch()[1][0]['loads'][0]['Fz'] == cdsnew.data.vars('sub.comp.loads_out').fetch()[1][0]['loads'][0]['Fz']
def test_vtree(self): top = Assembly() sub = top.add('sub', Assembly()) sub.add('comp', LoadsComp()) sub.driver.workflow.add('comp') sub.create_passthrough('comp.loads_in') sub.create_passthrough('comp.loads_out') top.driver.workflow.add('sub') sout = StringIO() top.recorders = [JSONCaseRecorder(sout)] loads = Loads() loads.Fx = [1, 2, 3] loads.Fy = [4, 5, 6] loads.Fz = [7, 8, 9] arr = LoadsArray() arr.loads = [loads] top.sub.loads_in = arr top.run() # with open('vtree.new', 'w') as out: # out.write(sout.getvalue()) self.verify(sout, 'vtree.json')
def configure_blade(): top = Assembly() configure_bladesurface(top, os.path.join(PATH, 'data/DTU_10MW_RWT_blade_axis_prebend.dat'), planform_nC=6) # load the planform file top.blade_length = 86.366 top.span_ni = 5 b = top.blade_surface # distribute 200 points evenly along the airfoil sections b.chord_ni = 40 # load the airfoil shapes defining the blade for f in [os.path.join(PATH, 'data/ffaw3241.dat'), os.path.join(PATH, 'data/ffaw3301.dat'), os.path.join(PATH, 'data/ffaw3360.dat'), os.path.join(PATH, 'data/ffaw3480.dat') , os.path.join(PATH, 'data/cylinder.dat')]: b.base_airfoils.append(np.loadtxt(f)) b.blend_var = np.array([0.241, 0.301, 0.36, 0.48, 1.]) return top
def lofted_blade_shape_example(): top = Assembly() configure_bladesurface(top, 'data/DTU_10MW_RWT_blade_axis_prebend.dat', planform_nC=6) # load the planform file top.blade_length = 86.366 top.span_ni = 50 print 'planform variables: ', top.pf_splines.pfOut.list_vars() b = top.blade_surface # distribute 200 points evenly along the airfoil sections b.chord_ni = 200 # load the airfoil shapes defining the blade for f in ['data/ffaw3241.dat', 'data/ffaw3301.dat', 'data/ffaw3360.dat', 'data/ffaw3480.dat' , 'data/tc72.dat' , 'data/cylinder.dat']: b.base_airfoils.append(np.loadtxt(f)) b.blend_var = np.array([0.241, 0.301, 0.36, 0.48, 0.72, 1.]) top.run() pf = top.pf_splines.pfOut plt.figure() plt.title('chord') plt.plot(pf.s, pf.chord) plt.savefig('chord.eps') plt.figure() plt.title('twist') plt.plot(pf.s, pf.rot_z) plt.savefig('twist.eps') plt.figure() plt.title('relative thickness') plt.plot(pf.s, pf.rthick) plt.savefig('rthick.eps') plt.figure() plt.title('pitch axis aft leading edge') plt.plot(pf.s, pf.p_le) plt.savefig('p_le.eps') plt.figure() plt.axis('equal') for i in range(b.span_ni): plt.plot(b.surfout.surface[:, i, 0], b.surfout.surface[:, i, 1]) plt.savefig('lofted_blade.eps') plt.savefig('lofted_blade.png') return top
def test_linearGS_simul_element_and_full_connection(self): # Added because of a bug with array slices for Linear GS top = Assembly() top.add('comp1', ArrayComp2D()) top.add('comp2', ArrayComp2D()) top.add('driver', SimpleDriver()) top.driver.workflow.add(['comp1', 'comp2']) top.connect('comp1.y', 'comp2.x') top.driver.add_parameter('comp1.x[0][0]', low=-10, high=10) top.driver.add_objective('comp1.y[0][0]') top.driver.add_constraint('comp2.y[0][1] < 0') top.driver.gradient_options.lin_solver = 'linear_gs' top.driver.gradient_options.maxiter = 1 top.run() J = top.driver.calc_gradient(mode='forward') assert_rel_error(self, J[0, 0], 2.0, .000001) assert_rel_error(self, J[1, 0], 39.0, .000001) J = top.driver.calc_gradient(mode='adjoint') assert_rel_error(self, J[0, 0], 2.0, .000001) assert_rel_error(self, J[1, 0], 39.0, .000001)
def test_scaler_array_expression(self): model = Assembly() model.add('sub', SubAsmb()) model.driver.workflow.add('sub') model.run() J = model.driver.workflow.calc_gradient(inputs=['sub.x', 'sub.y'], outputs=['sub.z']) assert_rel_error(self, J[0,0], 10.0, .001) assert_rel_error(self, J[0,1], 10.0, .001) assert_rel_error(self, J[0,2], 20.0, .001)
def test_invalid_input(self): model = Assembly() model.add("driver", DistributionCaseDriver()) model.add("driven", SimpleComponent()) model.driver.workflow.add("driven") model.driver.distribution_generator = FiniteDifferenceGenerator(model.driver) try: model.driver.add_parameter("driven.invalid", low=-10.0, high=10.0, fd_step=0.1) except AttributeError as err: self.assertEqual(str(err), "driver: Can't add parameter 'driven.invalid' because it doesn't exist.")
class GeomTestCase(unittest.TestCase): def setUp(self): """this setup function will be called before each test in this class""" self.top = Assembly() self.top.add('g1', GeoSource()) self.top.add('g2', GeoSink()) self.top.connect('g1.g_out', 'g2.g_inp') self.top.driver.workflow.add(['g1', 'g2']) def tearDown(self): """this teardown function will be called after each test""" self.top = None def testGeom(self): self.top.run() self.assertEqual(1, self.top.g2.g_inp.get_tessellation()) try: self.top.g2.g_extra = "hey" except TypeError as err: msg = "g2 (1-2): g_extra must provide interface 'IStaticGeometry'" self.assertEqual(str(err), msg) else: self.fail("exception expected")
def test_invalid_case_outputs(self): model = Assembly() model.add('driver', DistributionCaseDriver()) model.add('driven', SimpleComponent()) model.driver.workflow.add('driven') model.driver.distribution_generator = FiniteDifferenceGenerator(model.driver) try: model.driver.add_response('driven.invalid') except ValueError as err: self.assertEqual(str(err), "driver: Can't add response " "'driven.invalid' because of invalid variables" " 'driven.invalid'") else: self.fail('Expected ValueError')
def test_comp_error(self): a = Assembly() a.add('m',MetaModel()) a.m.default_surrogate = KrigingSurrogate() a.m.model = DummyError() a.m.train_next = True a.driver.workflow.add('m') try: a.run() except RuntimeError as err: self.assertEqual("m.model: Test Error",str(err)) else: self.fail("RuntimeError expected")
def setUp(self): """ Called before each test. """ self.model = Assembly() self.model.add('c1', MyComp()) self.model.add('c2', MyComp()) self.model.driver.workflow = CyclicWorkflow() self.model.driver.workflow.add(['c1', 'c2'])
def setUp(self): """this setup function will be called before each test in this class""" self.top = Assembly() self.top.add('g1', GeoSource()) self.top.add('g2', GeoSink()) self.top.connect('g1.g_out', 'g2.g_inp') self.top.driver.workflow.add(['g1', 'g2'])
def test_basic_delegation(self): top = Assembly() top.add('geo', GeomComponent()) # Function not there before we slot self.assertTrue(not hasattr(top.geo, 'apply_deriv')) self.assertTrue(not hasattr(top.geo, 'apply_derivT')) self.assertTrue(not hasattr(top.geo, 'provideJ')) top.geo.add('parametric_geometry', GeoWithDerivatives()) # Now they should be there. self.assertTrue(hasattr(top.geo, 'apply_deriv')) self.assertTrue(hasattr(top.geo, 'apply_derivT')) self.assertTrue(hasattr(top.geo, 'provideJ'))
def test_invalid_form(self): model = Assembly() model.add('driver', DistributionCaseDriver()) model.add('driven', SimpleComponent()) model.driver.workflow.add('driven') model.driver.distribution_generator = FiniteDifferenceGenerator(model.driver) model.driver.add_response('driven.y') model.driver.add_parameter("driven.x", low=-10., high=10., fd_step=0.1) try: model.driver.distribution_generator.form = "INVALID_FORM" except ValueError, err: msg = ": Variable 'form' must be in ['CENTRAL', 'FORWARD', 'BACKWARD'], " \ "but a value of INVALID_FORM <type 'str'> was specified." self.assertEqual(str(err), msg)
def test_super_simple_forward(self): model = Assembly() model.add("driver", DistributionCaseDriver()) model.add("driven", SimpleComponent()) model.driver.workflow.add("driven") # Forward model.driver.distribution_generator = FiniteDifferenceGenerator(model.driver) model.driver.case_outputs = ["driven.y"] model.driver.add_parameter("driven.x", low=-10.0, high=10.0, fd_step=0.1) results = ListCaseRecorder() model.driver.recorders = [results] model.driver.distribution_generator.form = "FORWARD" model.driver.distribution_generator.order = 2 model.run() self.assertAlmostEqual(results.cases[0]["driven.x"], 1.0, places=6) self.assertAlmostEqual(results.cases[0]["driven.y"], 2.0, places=6) self.assertAlmostEqual(results.cases[1]["driven.x"], 1.1, places=6) self.assertAlmostEqual(results.cases[1]["driven.y"], 2.2, places=6) self.assertAlmostEqual(results.cases[2]["driven.x"], 1.2, places=6) self.assertAlmostEqual(results.cases[2]["driven.y"], 2.4, places=6)
def test_nested_2Darray_simul_element_and_full_connection2(self): # Slightly different config top = Assembly() top.add('nest', Assembly()) top.nest.add('comp1', ArrayComp2D()) top.nest.add('comp2', ArrayComp2D()) top.driver.gradient_options.lin_solver = 'petsc_ksp' top.nest.driver.gradient_options.lin_solver = 'petsc_ksp' top.nest.driver.workflow.add(['comp1', 'comp2']) top.nest.connect('comp1.y', 'comp2.x') top.nest.create_passthrough('comp1.x') top.nest.create_passthrough('comp1.y') top.nest.add('yy', Array(iotype='out')) top.nest.connect('comp2.y', 'yy') top.add('driver', SimpleDriver()) top.driver.workflow.add(['nest']) top.driver.add_parameter('nest.x[0][0]', low=-10, high=10) top.driver.add_objective('nest.yy[0][0]') top.driver.add_constraint('nest.y[0][1] < 0') top.run() J = top.driver.calc_gradient(mode='forward') assert_rel_error(self, J[0, 0], 24.0, .000001) assert_rel_error(self, J[1, 0], 4.0, .000001) J = top.driver.calc_gradient(mode='adjoint') assert_rel_error(self, J[0, 0], 24.0, .000001) assert_rel_error(self, J[1, 0], 4.0, .000001) J = top.driver.calc_gradient(mode='fd') assert_rel_error(self, J[0, 0], 24.0, .000001) assert_rel_error(self, J[1, 0], 4.0, .000001)
def test_super_simple_backward(self): model = Assembly() model.add('driver', DistributionCaseDriver()) model.add('driven', SimpleComponent()) model.driver.workflow.add('driven') model.driver.distribution_generator = FiniteDifferenceGenerator(model.driver) model.driver.case_outputs = ['driven.y'] model.driver.add_parameter("driven.x", low=-10., high=10., fd_step = 0.1 ) results = ListCaseRecorder() model.driver.recorders = [results] model.driver.distribution_generator.form = "BACKWARD" model.driver.distribution_generator.order = 2 model.run() self.assertAlmostEqual( results.cases[0][ 'driven.x' ], 1.0, places = 6 ) self.assertAlmostEqual( results.cases[0][ 'driven.y' ], 2.0, places = 6 ) self.assertAlmostEqual( results.cases[1][ 'driven.x' ], 0.8, places = 6 ) self.assertAlmostEqual( results.cases[1][ 'driven.y' ], 1.6, places = 6 ) self.assertAlmostEqual( results.cases[2][ 'driven.x' ], 0.9, places = 6 ) self.assertAlmostEqual( results.cases[2][ 'driven.y' ], 1.8, places = 6 )
def test_super_simple_backward(self): model = Assembly() model.add('driver', DistributionCaseDriver()) model.add('driven', SimpleComponent()) model.driver.workflow.add('driven') model.driver.distribution_generator = FiniteDifferenceGenerator(model.driver) model.driver.add_response('driven.y') model.driver.add_parameter("driven.x", low=-10., high=10., fd_step=0.1) model.driver.distribution_generator.form = "BACKWARD" model.driver.distribution_generator.order = 2 model.run() x = model.driver.case_inputs.driven.x y = model.driver.case_outputs.driven.y self.assertAlmostEqual(x[0], 1.0, places=6) self.assertAlmostEqual(y[0], 2.0, places=6) self.assertAlmostEqual(x[1], 0.8, places=6) self.assertAlmostEqual(y[1], 1.6, places=6) self.assertAlmostEqual(x[2], 0.9, places=6) self.assertAlmostEqual(y[2], 1.8, places=6)
def test_remove(self): top = Assembly() g = top._depgraph.component_graph() comps = [name for name in g] self.assertEqual(comps, ["driver"]) top.add("comp", Component()) g = top._depgraph.component_graph() comps = [name for name in g] self.assertEqual(set(comps), set(["driver", "comp"])) top.remove("comp") g = top._depgraph.component_graph() comps = [name for name in g] self.assertEqual(comps, ["driver"])
def test_remove(self): top = Assembly() g = top._depgraph.component_graph() comps = [name for name in g] self.assertEqual(comps, ['driver']) top.add('comp', Component()) g = top._depgraph.component_graph() comps = [name for name in g] self.assertEqual(set(comps), set(['driver', 'comp'])) top.remove('comp') g = top._depgraph.component_graph() comps = [name for name in g] self.assertEqual(comps, ['driver'])
def _create_assembly(self, dbname, drivertype): asm = Assembly() driver = asm.add('driver', drivertype()) asm.add('comp1', TracedExecComp(exprs=['z=x+y'])) asm.add('comp2', TracedExecComp(exprs=['z=x+y'])) asm.connect('comp1.z', 'comp2.x') driver.workflow.add(['comp1', 'comp2']) asm.recorders = [DBCaseRecorder(dbname, append=True)] return asm
def test_set_recursive(self): asm = Assembly() asm.add('defcomp', MyDefComp()) asm.add('nodefcomp', MyNoDefComp()) self.assertEqual(0., asm.nodefcomp.f_in) self.assertEqual(3.14, asm.defcomp.f_in) asm.nodefcomp.f_in = 99 asm.defcomp.f_in = 99 asm.revert_to_defaults() self.assertEqual(0., asm.nodefcomp.f_in) self.assertEqual(3.14, asm.defcomp.f_in)
def test_invalid_form(self): model = Assembly() model.add("driver", DistributionCaseDriver()) model.add("driven", SimpleComponent()) model.driver.workflow.add("driven") model.driver.distribution_generator = FiniteDifferenceGenerator(model.driver) model.driver.case_outputs = ["driven.y"] model.driver.add_parameter("driven.x", low=-10.0, high=10.0, fd_step=0.1) results = ListCaseRecorder() model.driver.recorders = [results] try: model.driver.distribution_generator.form = "INVALID_FORM" except ValueError, err: msg = ( ": Variable 'form' must be in ['CENTRAL', 'FORWARD', 'BACKWARD'], " "but a value of INVALID_FORM <type 'str'> was specified." ) self.assertEqual(str(err), msg)
def test_multiconnect(self): top = Assembly() for name in ('m1', 'm2', 'm3'): top.add(name, Multiplier()) top.driver.workflow.add(name) top.connect('m1.rval_out', ('m2.mult', 'm3.mult')) top.m1.rval_in = 1. top.m2.rval_in = 3. top.m3.rval_in = 4. top.run() self.assertEqual(top.m2.rval_out, 4.5) self.assertEqual(top.m3.rval_out, 6.)
def test_multiconnect(self): top = Assembly() for name in ("m1", "m2", "m3"): top.add(name, Multiplier()) top.driver.workflow.add(name) top.connect("m1.rval_out", ("m2.mult", "m3.mult")) top.m1.rval_in = 1.0 top.m2.rval_in = 3.0 top.m3.rval_in = 4.0 top.run() self.assertEqual(top.m2.rval_out, 4.5) self.assertEqual(top.m3.rval_out, 6.0)
def test_mimic(self): # Ensure we can mimic a driver. top = Assembly() top.add('c1', Component()) top.add('c2', Component()) top.driver.workflow.add(('c1', 'c2')) top.driver.printvars = ['c1.force_execute', 'c2.force_execute'] recorder1 = FakeRecorder() recorder2 = FakeRecorder() top.driver.recorders = [recorder1, recorder2] workflow_id = id(top.driver.workflow) new_driver = Driver() new_id = id(new_driver) self.assertNotEqual(new_id, id(top.driver)) top.replace('driver', new_driver) self.assertEqual(new_id, id(top.driver)) self.assertEqual(workflow_id, id(top.driver.workflow)) self.assertEqual(top.driver.printvars, ['c1.force_execute', 'c2.force_execute']) self.assertEqual(top.driver.recorders, [recorder1, recorder2])
def _create_assembly(self, dbname): asm = Assembly() driver = asm.add('driver', SimpleCaseIterDriver()) asm.add('comp1', ExecComp(exprs=['z=x+y'])) asm.add('comp2', ExecComp(exprs=['z=x+y'])) asm.connect('comp1.z', 'comp2.x') driver.workflow.add(['comp1', 'comp2']) driver.recorder = DBCaseRecorder(dbname, append=True) return asm
def _create_assembly(self, dbname, drivertype): asm = Assembly() driver = asm.add("driver", drivertype()) asm.add("comp1", ExecComp(exprs=["z=x+y"])) asm.add("comp2", ExecComp(exprs=["z=x+y"])) asm.connect("comp1.z", "comp2.x") driver.workflow.add(["comp1", "comp2"]) driver.recorders = [DBCaseRecorder(dbname, append=True)] return asm
def test_simple_float_subassy(self): model = set_as_top(Assembly()) model.add('sub', Assembly()) model.sub.add('subsub', Assembly()) model.driver.workflow.add('sub') model.sub.driver.workflow.add('subsub') model.sub.subsub.add('comp', SimpleCompFloat()) model.sub.subsub.driver.workflow.add('comp') model.sub.subsub.create_passthrough('comp.x') model.sub.subsub.create_passthrough('comp.y') model.sub.create_passthrough('subsub.x') model.sub.create_passthrough('subsub.y') model.driver.gradient_options.fd_form = 'complex_step' model.driver.gradient_options.force_fd = True model.run() J = model.driver.calc_gradient(inputs=['sub.x'], outputs=['sub.y']) assert_rel_error(self, J[0, 0], 2.0, .000001) self.assertTrue(model.sub.subsub.comp.x is not complex) self.assertTrue(model.sub.subsub.comp.y is not complex)
def setUp(self): self.top = top = set_as_top(Assembly()) driver = top.add('driver', SimpleCaseIterDriver()) top.add('comp1', ExecComp(exprs=['z=x+y'])) top.add('comp2', ExecComp(exprs=['z=x+1'])) top.connect('comp1.z', 'comp2.x') driver.workflow.add(['comp1', 'comp2']) # now create some Cases outputs = ['comp1.z', 'comp2.z'] cases = [] for i in range(10): inputs = [('comp1.x', i), ('comp1.y', i*2)] cases.append(Case(inputs=inputs, outputs=outputs, label='case%s'%i)) driver.iterator = ListCaseIterator(cases)
def test_central(self): model = set_as_top(Assembly()) model.add('comp', MyComp()) model.driver.workflow.add(['comp']) model.driver.gradient_options.fd_form = 'central' model.run() J = model.driver.workflow.calc_gradient(inputs=['comp.x1', 'comp.x2'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.0, 0.0001) # Central gets this right even with a bad step assert_rel_error(self, J[0, 1], 4.0, 0.0001)
def setUp(self): '''setup test''' self.top = set_as_top(Assembly()) self.top.add('comp', Example1FromManualComponent()) self.top.add('driver', NEWSUMTdriver()) self.top.driver.workflow.add('comp') self.top.driver.itmax = 100 self.top.driver.iprint = 0 self.top.driver.lobj = 1 self.top.driver.epsrsf = 0.0005 self.top.driver.epsodm = 0.001 self.top.driver.epsgsn = 0.001 self.top.driver.default_fd_stepsize = 0.001 self.top.driver.stepmx = 1e10 self.top.driver.maxrsf = 30
def _trained_asm(self, avals, bvals): asm = set_as_top(Assembly()) asm.add('metamodel', ConnectableMetaModel()) asm.metamodel.default_surrogate = KrigingSurrogate() asm.metamodel.model = Simple() asm.metamodel.recorder = DumbRecorder() asm.driver.workflow.add(['metamodel']) for a,b in zip(avals, bvals): asm.metamodel.a = a asm.metamodel.b = b asm.metamodel.train_next = 1 asm.metamodel.run() return asm
def test_array3(self): top = set_as_top(Assembly()) top.add('c1', ArrSimple()) top.add('sub', Assembly()) top.sub.add('c2', ArrSimple()) top.sub.create_passthrough('c2.ain') top.sub.create_passthrough('c2.ain2') top.sub.create_passthrough('c2.aout') top.sub.create_passthrough('c2.aout2') top.add('c3', ArrSimple()) top.driver.workflow.add(['c1', 'sub', 'c3']) top.sub.driver.workflow.add('c2') top.connect('c1.aout[1]', 'sub.ain[1]') top.connect('sub.aout[1]', 'c3.ain[1]') top.c1.ain = [55., 44., 33.] top.run() self.assertEqual(top.c1.aout[1], 88.) self.assertEqual(top.sub.ain[1], 88.) self.assertEqual(top.sub.c2.ain[1], 88.) self.assertEqual(top.sub.aout[1], 176.) self.assertEqual(top.c3.ain[1], 176.)
def test_input_pseudocomp(self): top = set_as_top(Assembly()) top.add('comp', ArrayComp()) top.add('driver', DumbDriver()) top.driver.workflow.add('comp') top.driver.add_parameter('comp.a[0]', low=-100, high=100) top.driver.add_constraint('comp.a[0] < 100') # The first time it runs, the pcomp inputs update top.run() self.assertEqual(top.comp.a[0], top._pseudo_0.in0) # The second time it runs, the pcomp inputs no longer update top.run() self.assertEqual(top.comp.a[0], top._pseudo_0.in0)
def test_required_input_vartree_connected(self): top = set_as_top(Assembly()) source = top.add('source', VarTreeSource()) comp = top.add('comp', VarTreeSink()) top.connect('source.outvar', 'comp.invar') try: comp.run() except RuntimeError as err: self.fail( 'required variable invar has incoming connections and should not raise an error' ) top = set_as_top(Assembly()) source = top.add('source', VarTreeSource()) comp = top.add('comp', VarTreeSink()) top.connect('source.outvar.v1', 'comp.invar.v1') try: comp.run() except RuntimeError as err: self.fail( 'required variable invar has incoming connections and should not raise an error' )
def test_connected_varTree_in_subassembly_replace(self): top = set_as_top(Assembly()) top.add('comp', AssemblyWithConnectedVarTree()) top.add('driver', SimpleDriver()) top.driver.workflow.add('comp') top.driver.add_parameter('comp.x1', low=-100, high=100) top.driver.add_parameter('comp.x2', low=-100, high=100) top.driver.add_objective('comp.z') top.driver.add_constraint('comp.x2 + comp.x1 < 10') top.run() top.replace('comp', AssemblyWithCompVarTree()) top.run()
def _setup_move_rename(self): asm = set_as_top(Assembly()) asm.add('sub', Assembly()) asm.add('comp1', Simple()) asm.sub.add('comp2', Simple()) asm.sub.add('comp3', Simple()) asm.add('comp4', Simple()) asm.driver.workflow.add(['comp1', 'sub', 'comp4']) asm.sub.driver.workflow.add(['comp2', 'comp3']) asm.sub.add('a2', Float(iotype='in')) asm.sub.add('c3', Float(iotype='out')) asm.connect('comp1.c', 'sub.a2') asm.connect('sub.c3', 'comp4.a') asm.sub.connect('a2', 'comp2.a') asm.sub.connect('comp2.c', 'comp3.a') asm.sub.connect('comp3.c', 'c3') #asm.connect('comp1.d', 'sub.comp2.b') # autopassthrough #asm.connect('sub.comp3.d', 'comp4.b') # autopassthrough connections = asm.list_connections(show_passthrough=True) self.assertEqual( set(connections), set([ ('comp1.c', 'sub.a2'), #('comp1.d', 'sub.comp2.b'), #('sub.comp3.d', 'comp4.b'), ('sub.c3', 'comp4.a') ])) sub_connections = asm.sub.list_connections(show_passthrough=True) self.assertEqual( set(sub_connections), set([('comp3.c', 'c3'), ('a2', 'comp2.a'), ('comp2.c', 'comp3.a')])) self.assertEqual([c.name for c in asm.driver.workflow], ['comp1', 'sub', 'comp4']) self.assertEqual([c.name for c in asm.sub.driver.workflow], ['comp2', 'comp3']) return asm
def test_simplest(self): top = set_as_top(Assembly()) top.add('comp', ExecComp(['y=4.0*x'])) top.driver.workflow.add('comp') top.run() top.driver.gradient_options.directional_fd = True J = top.driver.workflow.calc_gradient(inputs=['comp.x'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.0, 0.0001) top.driver.gradient_options.fd_form = 'backward' top.driver.workflow.config_changed() J = top.driver.workflow.calc_gradient(inputs=['comp.x'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.0, 0.0001) top.driver.gradient_options.fd_form = 'central' top.driver.workflow.config_changed() J = top.driver.workflow.calc_gradient(inputs=['comp.x'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.0, 0.0001) top.driver.gradient_options.fd_form = 'complex_step' top.driver.workflow.config_changed() J = top.driver.workflow.calc_gradient(inputs=['comp.x'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.0, 0.0001) top.driver.gradient_options.directional_fd = True top.driver.workflow.config_changed() try: J = top.driver.workflow.calc_gradient(inputs=['comp.x'], outputs=['comp.y'], mode='adjoint') except RuntimeError, err: msg = ": Directional derivatives can only be used with forward " msg += "mode." self.assertEqual(str(err), msg)
def test_fd_step(self): model = set_as_top(Assembly()) model.add('comp', MyComp()) model.driver.workflow.add(['comp']) model.run() J = model.driver.workflow.calc_gradient( inputs=['comp.x1', 'comp.x2', 'comp.x3', 'comp.x4'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.0, 0.0001) assert_rel_error(self, J[0, 1], 4.2, 0.0001) assert_rel_error(self, J[0, 2], 4.0, 0.0001) assert_rel_error(self, J[0, 3], 0.0042, 0.0001) # test add_parameter's fdstep model.add('driver', SimpleDriver()) model.driver.workflow.add(['comp']) model.driver.add_parameter('comp.x1', low=-100, high=100, fd_step=.1) J = model.driver.workflow.calc_gradient(outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.2, 0.0001) # Parameter groups model.driver.add_parameter(['comp.x2', 'comp.x3'], low=-100, high=100, fd_step=.001) J = model.driver.workflow.calc_gradient(outputs=['comp.y']) assert_rel_error(self, J[0, 1], 8.004, 0.0001) # More Parameter Groups with pseudocomps in them. model.driver.add_parameter('comp.x4', low=-100, high=100, fd_step=1.001) model.driver.add_objective( 'comp.x1 + comp.x2 + comp.x3 + comp.x4 + comp.y') model.run() model.driver.workflow.config_changed() J = model.driver.workflow.calc_gradient(inputs=['comp.x4'], mode='fd') assert_rel_error(self, J[0, 0], 1.006, 0.0001)
def test_varTree_connections_whole_tree(self): top = set_as_top(Assembly()) top.add('driver', SimpleDriver()) top.add('comp1', CompWithVarTreeSubTree()) top.add('comp2', CompWithVarTree()) top.driver.workflow.add(['comp1', 'comp2']) inputs = ['comp1.ins.x.x1', 'comp1.ins.x.x2', 'comp1.ins.y'] outputs = ['comp2.z', 'comp1.outs.z', 'comp1.ins.x.x1'] top.driver.add_parameter('comp1.ins.x.x1', low=-1000, high=1000) top.driver.add_parameter('comp1.ins.x.x2', low=-1000, high=1000) top.driver.add_parameter('comp1.ins.y', low=-1000, high=1000) top.connect('comp1.outs', 'comp2.ins') top.driver.add_objective('comp2.z') top.driver.add_constraint('comp1.outs.z+comp1.ins.x.x1 < 0') top.run() J_true = array([ [8., 12., 16.], # obj [3., 3., 4.] ]) # c1 obj = [ "%s.out0" % item.pcomp_name for item in top.driver.get_objectives().values() ] con = [ "%s.out0" % item.pcomp_name for item in top.driver.get_constraints().values() ] top.driver.workflow.config_changed() J_fd = top.driver.workflow.calc_gradient(inputs, obj + con, mode='fd') top.driver.workflow.config_changed() J_forward = top.driver.workflow.calc_gradient(inputs, obj + con, mode="forward") top.driver.workflow.config_changed() J_reverse = top.driver.workflow.calc_gradient(inputs, obj + con, mode="adjoint") assert_rel_error(self, linalg.norm(J_true - J_fd), 0, .00001) assert_rel_error(self, linalg.norm(J_true - J_forward), 0, .00001) assert_rel_error(self, linalg.norm(J_true - J_reverse), 0, .00001)
def test_smart_low_high_array_param(self): top = Assembly() top.add('paraboloid', ArrayParaboloid()) driver = top.add('driver', SimpleDriver()) driver.add_objective('paraboloid.f_x') driver.add_parameter('paraboloid.x', low=[-100, -99], high=[100, 99]) driver.workflow.add('paraboloid') top.run() J = top.driver.calc_gradient()
def test_initial_run(self): # Test to make sure fix that put run_iteration # at the top of the execute method is in place and working try: from ipoptdriver.ipoptdriver import IPOPTdriver, IpoptReturnStatus except ImportError: raise SkipTest("this test requires IPOPT to be installed") class MyComp(Component): x = Float(0.0, iotype='in', low=-10, high=10) xx = Float(0.0, iotype='in', low=-10, high=10) f_x = Float(iotype='out') y = Float(iotype='out') def execute(self): if self.xx != 1.0: self.raise_exception("Lazy", RuntimeError) self.f_x = 2.0 * self.x self.y = self.x @add_delegate(HasParameters) class SpecialDriver(Driver): implements(IHasParameters) def execute(self): self.set_parameters([1.0]) top = set_as_top(Assembly()) top.add('comp', MyComp()) top.driver.title = 'Little Test' top.add('driver', IPOPTdriver()) top.driver.print_level = 0 top.driver.set_option('suppress_all_output', 'yes') top.add('subdriver', SpecialDriver()) top.driver.workflow.add('subdriver') top.subdriver.workflow.add('comp') top.subdriver.add_parameter('comp.xx') top.driver.add_parameter('comp.x') top.driver.add_constraint('comp.y > 1.0') top.driver.add_objective('comp.f_x') top.run()
def setUp(self): self.top = set_as_top(Assembly()) self.top.add('comp1', Simple()) self.top.add('comp2', Simple()) self.top.connect('comp1.c', 'comp2.a') self.top.connect('comp1.d', 'comp2.b') self.top.connect('comp1.c_lst', 'comp2.a_lst') self.top.driver.workflow.add(['comp1', 'comp2']) self.inputs = [('comp1.a', 2), ('comp1.b', 4), ('comp1.a_lst', [4, 5, 6])] self.outputs = ['comp2.c+comp2.d', 'comp2.c_lst[2]', 'comp2.d'] self.case = case = Case(inputs=self.inputs, outputs=self.outputs) case.apply_inputs(self.top) self.top.run() case.update_outputs(self.top)
def test_casetree(self): # Record tree of cases via workflow. top = Assembly() top.recorders = [DumbRecorder()] top.add('driver2', CaseDriver(3)) top.add('comp2', CaseComponent()) top.driver2.workflow.add('comp2') top.driver2.add_parameter('comp2.x', low=0, high=10) top.driver2.add_objective('comp2.y') top.add('driver1', CaseDriver(2)) top.add('comp1', CaseComponent()) top.driver1.add_parameter('comp1.x', low=0, high=10) top.driver1.add_objective('comp1.y') top.driver1.workflow.add(['comp1', 'driver2']) top.driver.workflow.add('driver1') top.run() print print 'Forest:' roots = CaseTreeNode.sort(top.recorders[0].get_iterator()) for root in roots: root.dump(1) print print 'Iternames:' for root in roots: for name in root.iternames(): print ' ', name expected = [ '1', '1-driver1.1', '1-driver1.1-driver2.1', '1-driver1.1-driver2.2', '1-driver1.1-driver2.3', '1-driver1.2', '1-driver1.2-driver2.1', '1-driver1.2-driver2.2', '1-driver1.2-driver2.3' ] for i, name in enumerate(roots[0].iternames()): self.assertEqual(name, expected[i])
def test_simple_coupled_adjoint(self): self.top = set_as_top(Assembly()) exp1 = ['y2 = 0.5*sin(x1) - 0.5*x1*y1'] deriv1 = ['dy2_dx1 = 0.5*cos(x1) - 0.5*y1', 'dy2_dy1 = -0.5*x1'] exp2 = ['y1 = x2*x2*y2'] deriv2 = ['dy1_dx2 = 2.0*y2*x2', 'dy1_dy2 = x2*x2'] self.top.add('driver', Driv()) self.top.add('comp1', ExecCompWithDerivatives(exp1, deriv1)) self.top.add('comp2', ExecCompWithDerivatives(exp2, deriv2)) #self.top.add('comp1', ExecComp(exp1)) #self.top.add('comp2', ExecComp(exp2)) self.top.add('solver', BroydenSolver()) self.top.driver.workflow.add(['solver']) self.top.solver.workflow.add(['comp1', 'comp2']) self.top.connect('comp1.y2', 'comp2.y2') # Solver setup self.top.solver.add_parameter('comp1.y1', low=-1.e99, high=1.e99) self.top.solver.add_constraint('comp2.y1 = comp1.y1') # Top driver setup self.top.driver.differentiator = Analytic() self.top.driver.differentiator.mode = 'adjoint' obj = 'comp2.y1' self.top.driver.add_parameter('comp1.x1', low=-100., high=100., fd_step=.001) self.top.driver.add_parameter('comp2.x2', low=-100., high=100., fd_step=.0001) self.top.driver.add_objective(obj) self.top.comp1.x1 = 1.0 self.top.comp2.x2 = 1.0 self.top.run() self.top.driver.differentiator.calc_gradient() grad = self.top.driver.differentiator.get_gradient(obj) assert_rel_error(self, grad[0], 0.08660, .001)
def test_derivative_nested_solver_no_deriv(self): model = set_as_top(Assembly()) model.add('comp', MyComp_No_Deriv()) model.add('solver', BroydenSolver()) model.driver.workflow.add('solver') model.solver.workflow.add('comp') model.solver.tol = 0.0000001 model.solver.add_parameter('comp.x', low=-100, high=100) model.solver.add_parameter('comp.y', low=-100, high=100) model.solver.add_parameter('comp.z', low=-100, high=100) model.solver.add_constraint('comp.res[0] = 0') model.solver.add_constraint('comp.res[1] = 0') model.solver.add_constraint('comp.res[2] = 0') model.comp.eval_only = True model.run() J = model.driver.workflow.calc_gradient(inputs=['comp.c'], outputs=['comp.y_out']) edges = model.driver.workflow._edges # print edges self.assertEqual(edges['@in0'], ['~0.comp|c']) self.assertEqual(edges['~0.comp|y_out'], ['@out0']) self.assertEqual(edges['~0.comp|res[0]'], ['_pseudo_0.in0']) self.assertEqual(edges['~0.comp|res[1]'], ['_pseudo_1.in0']) self.assertEqual(edges['~0.comp|res[2]'], ['_pseudo_2.in0']) # print J assert_rel_error(self, J[0][0], 0.75, 1e-5) model.driver.workflow.config_changed() J = model.driver.workflow.calc_gradient(inputs=['comp.c'], outputs=['comp.y_out'], mode='adjoint') # print J assert_rel_error(self, J[0][0], 0.75, 1e-5) model.driver.workflow.config_changed() J = model.driver.workflow.calc_gradient(inputs=['comp.c'], outputs=['comp.y_out'], mode='fd') # print J assert_rel_error(self, J[0][0], 0.75, 1e-5)
def test_mass_flow_iter(self): a = set_as_top(Assembly()) start = a.add('start', FlowStart()) ref = a.add('ref', FlowStart()) nozzle = a.add('nozzle', Nozzle()) start.W = 100. start.Tt = 700. start.Pt = 50.0 start.Mach = 0.40 ref.W = 1.0 ref.Tt = 518.67 ref.Pt = 15.0 ref.Mach = 0.0 a.connect('start.Fl_O', 'nozzle.Fl_I') a.connect('ref.Fl_O', 'nozzle.Fl_ref') a.add('design', Run_Once()) a.design.workflow.add(['start', 'ref', 'nozzle']) a.design.add_event('start.design') a.design.add_event('ref.design') a.design.add_event('nozzle.design') a.design.run() a.add('off_design', BroydenSolver()) a.off_design.workflow.add(['start', 'ref', 'nozzle']) a.off_design.add_parameter('start.W', low=-1e15, high=1e15) a.off_design.add_constraint('nozzle.WqAexit=nozzle.WqAexit_dmd') TOL = .001 ref.Pt = 39.0 a.off_design.run() self.assertEqual(nozzle.switchRegime, 'UNCHOKED') assert_rel_error(self, nozzle.Fl_O.W, 96.03, TOL) assert_rel_error(self, nozzle.Fl_O.Mach, 0.607, TOL) # set W = 80.80, MN throat = 0.562, MN exit = 0.470 ref.Pt = 43.0 a.off_design.run() self.assertEqual(nozzle.switchRegime, 'UNCHOKED') assert_rel_error(self, nozzle.Fl_O.W, 80.80, TOL) assert_rel_error(self, nozzle.Fl_O.Mach, 0.470, TOL)
def test_scaler_array_expression(self): model = Assembly() model.add('sub', SubAsmb()) model.driver.workflow.add('sub') model.run() J = model.driver.workflow.calc_gradient(inputs=['sub.x', 'sub.y'], outputs=['sub.z']) assert_rel_error(self, J[0, 0], 10.0, .001) assert_rel_error(self, J[0, 1], 10.0, .001) assert_rel_error(self, J[0, 2], 20.0, .001)
def test_smart_low_high(self): top = Assembly() top.add('comp', MyComp()) driver = top.add('driver', SimpleDriver()) top.comp.add('x1', Float(1.0, iotype='in', low=-1.0, high=1.0)) driver.add_objective('comp.y') driver.add_parameter('comp.x1', low=-1.0, high=1.0) driver.workflow.add('comp') top.driver.gradient_options.fd_form = 'central' top.driver.gradient_options.fd_step = 0.1 top.comp.x1 = -0.95 top.run() J = top.driver.workflow.calc_gradient() assert_rel_error(self, J[0, 0], -3.6, 0.001) top.comp.x1 = 0.95 top.run() J = top.driver.workflow.calc_gradient() assert_rel_error(self, J[0, 0], 3.6, 0.001)
def test_sequential(self): # verify that if components aren't connected they should execute in the # order that they were added to the workflow instead of hash order global exec_order top = set_as_top(Assembly()) top.add('c2', Simple()) top.add('c1', Simple()) top.add('c3', Simple()) top.add('c4', Simple()) top.driver.workflow.add(['c1','c2','c3','c4']) top.run() self.assertEqual(exec_order, ['c1','c2','c3','c4']) top.connect('c4.c', 'c3.a') # now make c3 depend on c4 exec_order = [] #top.c4.a = 2 # makes c4 run again top.run() self.assertEqual(exec_order, ['c1','c2','c4','c3'])
def test_newton_nested(self): # Make sure derivatives across the newton-solved system are correct. top = set_as_top(Assembly()) top.add('driver', SimpleDriver()) top.add('d1', Discipline1_WithDerivatives()) top.d1.x1 = 1.0 top.d1.y1 = 1.0 top.d1.y2 = 1.0 top.d1.z1 = 5.0 top.d1.z2 = 2.0 top.add('d2', Discipline2_WithDerivatives()) top.d2.y1 = 1.0 top.d2.y2 = 1.0 top.d2.z1 = 5.0 top.d2.z2 = 2.0 top.connect('d1.y1', 'd2.y1') top.add('solver', NewtonSolver()) top.solver.atol = 1e-9 top.solver.workflow.add(['d1', 'd2']) top.solver.add_parameter('d1.y2', low=-1e99, high=1e99) top.solver.add_constraint('d1.y2 = d2.y2') top.driver.workflow.add(['solver']) top.driver.add_parameter('d1.z1', low=-100, high=100) top.driver.add_objective('d1.y1 + d1.y2') top.run() J = top.driver.calc_gradient(mode='forward') print J assert_rel_error(self, J[0][0], 10.77542099, 1e-5) J = top.driver.calc_gradient(mode='adjoint') print J assert_rel_error(self, J[0][0], 10.77542099, 1e-5) top.driver.gradient_options.fd_step = 1e-7 top.driver.gradient_options.fd_form = 'central' J = top.driver.calc_gradient(mode='fd') print J assert_rel_error(self, J[0][0], 10.77542099, 1e-5)
def test_expr_deps(self): top = set_as_top(Assembly()) driver1 = top.add('driver1', DumbDriver()) driver2 = top.add('driver2', DumbDriver()) top.add('c1', Simple()) top.add('c2', Simple()) top.add('c3', Simple()) top.driver.workflow.add(['driver1', 'driver2', 'c3']) top.driver1.workflow.add('c2') top.driver2.workflow.add('c1') top.connect('c1.c', 'c2.a') top.driver1.add_objective("c2.c*c2.d") top.driver2.add_objective("c1.c") top.run() self.assertEqual(exec_order, ['driver2', 'c1', 'driver1', 'c2', 'c3'])
def test_eval_gradient_lots_of_vars(self): top = set_as_top(Assembly()) top.add('comp1', B()) #build expr expr = "2*comp1.in1 + 3*comp1.in11" exp = ExprEvaluator(expr, top.driver) grad = exp.evaluate_gradient(scope=top) assert_rel_error(self, grad['comp1.in1'], 2.0, 0.00001) assert_rel_error(self, grad['comp1.in11'], 3.0, 0.00001) expr = "asin(comp1.in1)" exp = ExprEvaluator(expr, top.driver) grad = exp.evaluate_gradient(scope=top) assert_rel_error(self, grad['comp1.in1'], 1.0, 0.00001)
def test_errors(self): a = set_as_top(Assembly()) comp = a.add('comp', ExecComp(exprs=["f=x"])) driver = a.add('driver', Brent()) driver.add_parameter('comp.x', -1e99, 1e99) driver.add_constraint('comp.f=0') comp.n = 1.0 comp.c = 0 driver.lower_bound = 1.0 try: a.run() except Exception as err: self.assertEqual( str(err), "driver: bounds (low=1.0, high=100.0) do not bracket a root") else: self.fail("Exception expected")
def setUp(self): self.top = set_as_top(Assembly()) self.top.add('comp', RosenSuzukiMixed()) driver = self.top.add('driver', CONMINdriver()) driver.workflow.add('comp') driver.iprint = 0 driver.itmax = 30 driver.add_objective('10*comp.result') map(driver.add_parameter, ['comp.x0', 'comp.x12', 'comp.x3']) # pylint: disable-msg=C0301 map(driver.add_constraint, [ 'comp.x0**2+comp.x0+comp.x12[0]**2-comp.x12[0]+comp.x12[1]**2+comp.x12[1]+comp.x3**2-comp.x3 < 8', 'comp.x0**2-comp.x0+2*comp.x12[0]**2+comp.x12[1]**2+2*comp.x3**2-comp.x3 < 10', '2*comp.x0**2+2*comp.x0+comp.x12[0]**2-comp.x12[0]+comp.x12[1]**2-comp.x3 < 5' ])
def setUp(self): '''setup''' try: from ipoptdriver.ipoptdriver import IPOPTdriver, IpoptReturnStatus except ImportError: raise SkipTest("this test requires IPOPT to be installed") self.top = set_as_top(Assembly()) self.top.add('comp', ParaboloidComponent()) self.top.add('driver', IPOPTdriver()) self.top.driver.workflow.add('comp') self.top.driver.print_level = 0 self.top.driver.set_option('suppress_all_output', 'yes') map(self.top.driver.add_constraint, [])
def test_fd_step_type_relative(self): model = set_as_top(Assembly()) model.add('driver', SimpleDriver()) model.add('comp', MyComp()) model.driver.workflow.add(['comp']) model.comp.x1 = 1e12 model.run() J = model.driver.calc_gradient(inputs=['comp.x1'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 0.0, 0.0001) model.driver.gradient_options.fd_step_type = 'relative' J = model.driver.calc_gradient(inputs=['comp.x1'], outputs=['comp.y']) assert_rel_error(self, J[0, 0], 4.0e12, 0.0001)
def test_complex_array_data_passing(self): model = set_as_top(Assembly()) model.add('comp1', ComplexArray()) model.add('comp2', ComplexArray()) model.driver.workflow.add(['comp1', 'comp2']) model.connect('comp1.y', 'comp2.x') model.driver.gradient_options.fd_form = 'complex_step' model.run() J = model.driver.calc_gradient(inputs=['comp1.x'], outputs=['comp2.y']) assert_rel_error(self, J[0, 0], 7.0, .0001) assert_rel_error(self, J[0, 1], 0.0, .0001) assert_rel_error(self, J[1, 1], 7.0, .0001) assert_rel_error(self, J[1, 0], 0.0, .0001)