def test_CO(self): prob = SellarCO() set_as_top(prob) # Set up initial conditions prob.dis1.z1 = 5.0 prob.dis2.z1 = 5.0 prob.dis1.z2 = 2.0 prob.dis2.z2 = 2.0 prob.dis1.x1 = 1.0 prob.dis2.y1 = 3.16 prob.dis1.y2 = 0.0 prob.run() # In the top workflow, the subdrivers should each become a PA. self.assertTrue(len(prob.driver.workflow._system.subsystems()) == 10) comp_list = prob.driver.workflow._system.subsystems()[5]._nodes self.assertTrue(len(comp_list) == 1) self.assertTrue(('localopt2',) in comp_list) comp_list = prob.driver.workflow._system.subsystems()[6]._nodes self.assertTrue(len(comp_list) == 1) self.assertTrue(('localopt1',) in comp_list) assert_rel_error(self, prob.global_des_var_targets[0], 2.0, 0.1) assert_rel_error(self, 1.0-prob.global_des_var_targets[1], 1.0, 0.01) assert_rel_error(self, 1.0-prob.local_des_var_targets[0], 1.0, 0.1)
def test_component(self): comp = set_as_top(self.factory.create('ASTestComp')) comp.set('x', 6) comp.set('y', 7) path = 'output' with comp.dir_context: with open(path, 'w') as out: out.write('Hello world!') comp.set('in_file', FileRef(path, comp)) with comp.dir_context: os.remove(path) comp.run() self.assertEqual(comp.get('z'), 42.) with comp.get('out_file').open() as inp: data = inp.read() self.assertEqual(data, 'Hello world!') before = self.get_state(comp, 'the_obj', comp._client) state_file = 'state.pickle' try: comp.save(state_file) restored = Component.load(state_file) after = self.get_state(restored, 'the_obj', restored._client) restored.pre_delete() self.assertEqual(after, before) finally: os.remove(state_file) os.remove('AS-the_obj.in_file.dat') os.remove('AS-the_obj.out_file.dat') comp.pre_delete() comp = set_as_top(self.factory.create('ASTestComp')) comp.__del__()
def test_Anopp2(self): # Import the time module so we can assess the time taken to run this test. import time # This is the iteration number. iIteration = 0 # This is the increment in x that we want to jump to determine a local maximum. fltdelta_x = 100.0 # Set the current optimization problem as ANOPP2 Optimize. opt_problem = Anopp2Optimize() # Run the set_as_top function for the Anopp2 Optimize problem. set_as_top(opt_problem) # Set the time as tt. tt = time.time() # Execute the Anopp2Optimize opt_problem.run() # Write messages on the screen when a maximum noise is found. print "\n" print "Local Maximum found at (%f)" % opt_problem.anopp2.x print "EPNdB at this maximum (%f)" % opt_problem.anopp2.fltEpnl.value print "Elapsed time: ", time.time()-tt, "seconds"
def main(): # pragma no cover """ Runs ADPAC for the given casename (which may be in a different directory). Since this will overwrite existing ``.input`` and ``.boundata`` files, they will be renamed to ``.input.<N>`` and ``.boundata.<N>``. Usage: ``python wrapper.py casename`` """ if len(sys.argv) > 1: path = sys.argv[1] directory = os.path.dirname(path) casename = os.path.basename(path) if directory: os.chdir(directory) adpac = ADPAC(casename=casename) set_as_top(adpac) # Move original inputs out of the way. i = 0 while os.path.exists(casename+'.input.%d' % i): i += 1 for ext in ('.input', '.boundata'): os.rename(casename+ext, casename+ext+'.%d' % i) adpac.run() else: print 'usage: python wrapper.py casename'
def execute(hD): print "\n\n" print "Running", sys.version, "in", sys.executable print "----------------------------------------------------------------------" a = FuzzyAssemblyOpt() set_as_top(a) a.compatibility.count = 0 #flag for counting incompatibilities #if count = 1: return the total number of incompatibilities a.postprocess.printResults = 0 #print results flag a.driver.opt_type = 'max' a.driver.generations = 50 a.driver.popMult = 15.0 a.driver.crossover_Rate = 0.65 a.driver.mutation_rate = 0.07 a.driver.crossN = 3 a.driver.bitsPerGene = 4 a.driver.tourneySize = 3 a.driver.hammingDist = hD a.driver.livePlotGens = 0 tt = time.time() a.run() print "\n" #print len(a.fuzz_combine.system_inputs) print "---------- Optimization Complete ----------" print "Elapsed time: ", time.time()-tt, "seconds" print "----------------------------------------------------------------------"
def test_MIMO_Broyden3(self): # Testing Broyden on a 2 input 2 output case self.prob = MIMOBroyden() set_as_top(self.prob) driver = self.prob.driver driver.add_parameter('dis1.x[0]') driver.add_parameter('dis1.x[1]') driver.add_parameter('dis1.x[2]') driver.add_parameter('dis1.x[3]') driver.add_parameter('dis1.x[4]') driver.add_constraint('dis1.f1 = 0.0') driver.add_constraint('dis1.f2 = 0.0') driver.add_constraint('dis1.f3 = 0.0') driver.add_constraint('dis1.f4 = 0.0') driver.add_constraint('dis1.f5 = 0.0') self.prob.dis1.x = [1., 1., 1., 1., 1.] driver.algorithm = "broyden3" self.prob.run() assert_rel_error(self, 1.0 - self.prob.dis1.x[0], 1.0, 0.0001) assert_rel_error(self, 1.0 - self.prob.dis1.x[1], 1.0, 0.0001) assert_rel_error(self, 1.0 - self.prob.dis1.x[2], 1.0, 0.0001) assert_rel_error(self, 1.0 - self.prob.dis1.x[3], 1.0, 0.0001) assert_rel_error(self, 1.0 - self.prob.dis1.x[4], 1.0, 0.0001)
def test_unique(self): logging.debug('') logging.debug('test_unique') model = Model() ## This part isn't valid any more because Assemblies now do not configure ## themselves unless they're part of a rooted hierarchy. That means in this ## case that model.a and model.b won't exist until set_as_top is called on model #for comp in (model.a, model.b): #self.assertEqual(comp.create_instance_dir, True) #self.assertNotEqual(model.a.directory, 'a') #self.assertNotEqual(model.b.directory, 'b') set_as_top(model) for comp in (model.a, model.b): self.assertEqual(comp.create_instance_dir, False) self.assertEqual(comp.return_code, 0) self.assertEqual(comp.timed_out, False) self.assertEqual(model.a.directory, 'a') self.assertEqual(model.b.directory, 'b') model.infile = FileRef(INP_FILE, model, input=True) model.run() for comp in (model.a, model.b): self.assertEqual(comp.return_code, 0) self.assertEqual(comp.timed_out, False) with model.outfile.open() as inp: result = inp.read() self.assertEqual(result, INP_DATA)
def test_Abasic_SNOPT_derivatives_linear_constraints(self): try: from pyoptsparse import Optimization except ImportError: raise SkipTest("this test requires pyoptsparse to be installed") self.top = OptimizationConstrainedDerivatives() set_as_top(self.top) try: self.top.driver.optimizer = 'SNOPT' except ValueError: raise SkipTest("SNOPT not present on this system") self.top.driver.title = 'Little Test with Gradient' optdict = {} self.top.driver.options = optdict self.top.driver.clear_constraints() self.top.driver.add_constraint('paraboloid.x-paraboloid.y >= 15.0') self.top.driver.add_constraint('paraboloid.x > 7.1', linear=True) self.top.run() assert_rel_error(self, self.top.paraboloid.x, 7.175775, 0.01) assert_rel_error(self, self.top.paraboloid.y, -7.824225, 0.01)
def test_unconstrained(self): try: from pyopt_driver.pyopt_driver import pyOptDriver except ImportError: raise SkipTest("this test requires pyOpt to be installed") self.top = OptimizationUnconstrained() set_as_top(self.top) for optimizer in [ 'CONMIN', 'COBYLA', 'SNOPT', 'SLSQP' ] : try: self.top.driver.optimizer = optimizer except ValueError: raise SkipTest("%s not present on this system" % optimizer) self.top.driver.title = 'Little Test' optdict = {} self.top.driver.options = optdict self.top.driver.pyopt_diff = True self.top.run() assert_rel_error(self, self.top.paraboloid.x, 6.6667, 0.01) assert_rel_error(self, self.top.paraboloid.y, -7.3333, 0.01)
def test_CO_Multi(self): prob = SellarCO_Multi() set_as_top(prob) # Set up initial conditions prob.z1 = 5.0 prob.dis1.z1 = 5.0 prob.dis2b.z1 = 5.0 prob.z2 = 2.0 prob.dis1.z2 = 2.0 prob.dis2c.z2 = 2.0 prob.x1 = 1.0 prob.dis1.x1 = 1.0 prob.y1 = 3.16 prob.dis2a.y1 = 3.16 prob.y2 = 0.0 prob.dis1.y2 = 0.0 prob.run() # In the top workflow, the subdrivers should each become a PA. PA1 = prob.driver.workflow._derivative_graph.node['~localopt1']['pa_object'] self.assertEqual( PA1.itercomps, ['localopt1']) PA2 = prob.driver.workflow._derivative_graph.node['~localopt2']['pa_object'] self.assertEqual( PA2.itercomps, ['localopt2']) assert_rel_error(self, prob.z1, 2.0, 0.1) assert_rel_error(self, 1.0-prob.z2, 1.0, 0.01) assert_rel_error(self, 1.0-prob.x1, 1.0, 0.1)
def test_basic_CONMIN(self): try: from pyopt_driver.pyopt_driver import pyOptDriver except ImportError: raise SkipTest("this test requires pyOpt to be installed") self.top = OptimizationConstrained() set_as_top(self.top) try: self.top.driver.optimizer = 'CONMIN' self.top.driver.optimizer = 'COBYLA' except ValueError: raise SkipTest("CONMIN not present on this system") self.top.driver.title = 'Little Test' optdict = {} self.top.driver.options = optdict self.top.driver.pyopt_diff = True self.top.run() assert_rel_error(self, self.top.paraboloid.x, 7.175775, 0.01) assert_rel_error(self, self.top.paraboloid.y, -7.824225, 0.01)
def test_MIMO_ExcitingMixing(self): # Testing Broyden on a 2 input 2 output case prob = MIMOBroyden() set_as_top(prob) driver = prob.driver driver.add_parameter('dis1.x[0]', low=-9.e99, high=9.e99) driver.add_parameter('dis1.x[1]', low=-9.e99, high=9.e99) driver.add_parameter('dis1.x[2]', low=-9.e99, high=9.e99) driver.add_parameter('dis1.x[3]', low=-9.e99, high=9.e99) driver.add_parameter('dis1.x[4]', low=-9.e99, high=9.e99) driver.add_constraint('dis1.f1 = 0.0') driver.add_constraint('dis1.f2 = 0.0') driver.add_constraint('dis1.f3 = 0.0') driver.add_constraint('dis1.f4 = 0.0') driver.add_constraint('dis1.f5 = 0.0') prob.dis1.x = [1., 1., 1., 1., 1.] driver.algorithm = "excitingmixing" driver.alpha = 0.1 prob.run() assert_rel_error(self, 1.0 - prob.dis1.x[0], 1.0, 0.0001) assert_rel_error(self, 1.0 - prob.dis1.x[1], 1.0, 0.0001) assert_rel_error(self, 1.0 - prob.dis1.x[2], 1.0, 0.0001) assert_rel_error(self, 1.0 - prob.dis1.x[3], 1.0, 0.0001) assert_rel_error(self, 1.0 - prob.dis1.x[4], 1.0, 0.0001)
def test_GA_multi_obj_multi_con(self): # Note, just verifying that things work functionally, rather than run # this for many generations. try: from pyopt_driver.pyopt_driver import pyOptDriver except ImportError: raise SkipTest("this test requires pyOpt to be installed") self.top = MultiObjectiveOptimization() set_as_top(self.top) try: self.top.driver.optimizer = 'NSGA2' except ValueError: raise SkipTest("NSGA2 not present on this system") # PyOpt Flags self.top.driver.title = 'Two-Objective Fitness MultiFunction Test' optdict = {} optdict['PopSize'] = 100 # a multiple of 4 optdict['maxGen'] = 5 optdict['pCross_real'] = 0.6 #prob of crossover of design variables in range (0.6-1.0) optdict['pMut_real'] = 0.5 #prob of mutation of (1/design varaibles) optdict['eta_c'] = 10.0 #distribution index for crossover in range (5 - 20) optdict['eta_m'] = 50.0 #distribution index for mutation in range (5 - 50) optdict['pCross_bin'] = 1.0 #prob of crossover of binary variable in range(0.6 - 1.0) optdict['pMut_real'] = 1.0 #prob of mutation of binary variables in (1/nbits) optdict['PrintOut'] = 0 #flag to turn on output to files (0-None, 1-Subset,2-All) optdict['seed'] = 0.0 #random seed number (0-autoseed based on time clock) self.top.driver.options = optdict self.top.run()
def test_CO_Multi(self): prob = SellarCO_Multi() set_as_top(prob) # Set up initial conditions prob.z1 = 5.0 prob.dis1.z1 = 5.0 prob.dis2b.z1 = 5.0 prob.z2 = 2.0 prob.dis1.z2 = 2.0 prob.dis2c.z2 = 2.0 prob.x1 = 1.0 prob.dis1.x1 = 1.0 prob.y1 = 3.16 prob.dis2a.y1 = 3.16 prob.y2 = 0.0 prob.dis1.y2 = 0.0 prob.run() assert_rel_error(self, prob.z1, 2.0, 0.1) assert_rel_error(self, 1.0-prob.z2, 1.0, 0.01) assert_rel_error(self, 1.0-prob.x1, 1.0, 0.1)
def test_ALPSO_integer_design_var(self): # probNEW.py # #Set's up component for Schittkowski's TP37 Problem. # # min -x1*x2*x3 # s.t.: x1 + 2.*x2 + 2.*x3 - 72 <= 0 # - x1 - 2.*x2 - 2.*x3 <= 0 # 0 <= xi <= 42, i = 1,2,3 # # f* = -3456 , x* = [24, 12, 12] # # *Problem taken from pyOpt example tp037 try: from pyopt_driver.pyopt_driver import pyOptDriver except ImportError: raise SkipTest("this test requires pyOpt to be installed") opt_problem = BenchMarkOptimization() set_as_top(opt_problem) opt_problem.run() self.assertEqual(opt_problem.benchmark.x1, 24) self.assertEqual(opt_problem.benchmark.x2, 12) self.assertEqual(opt_problem.benchmark.x3, 12)
def test_simvehicle_one(self): my_sim = VehicleSim() set_as_top(my_sim) my_sim.run() self.assertAlmostEqual(my_sim.driver.accel_time, 7.5, places=2)
def test_CO(self): prob = SellarCO() set_as_top(prob) # Set up initial conditions prob.z1_t = 5.0 prob.dis1.z1 = 5.0 prob.dis2.z1 = 5.0 prob.z2_t = 2.0 prob.dis1.z2 = 2.0 prob.dis2.z2 = 2.0 prob.x1_t = 1.0 prob.dis1.x1 = 1.0 prob.y1_t = 3.16 prob.dis2.y1 = 3.16 prob.y2_t = 0.0 prob.dis1.y2 = 0.0 prob.run() assert_rel_error(self, prob.z1_t, 2.0, 0.1) assert_rel_error(self, 1.0-prob.z2_t, 1.0, 0.01) assert_rel_error(self, 1.0-prob.x1_t, 1.0, 0.1)
def test_restore(self): # Restore from case, run, verify outputs match expected. top = set_as_top(SellarMDF()) #top.name = 'top' top.recorders = [JSONCaseRecorder()] top.run() assert_rel_error(self, top.sub.globals.z1, 1.977639, .0001) assert_rel_error(self, top.half.z2a, 0., .0001) assert_rel_error(self, top.sub.x1, 0., .0001) assert_rel_error(self, top.sub.states.y[0], 3.160004, .0001) assert_rel_error(self, top.sub.states.y[1], 3.755280, .0001) assert_rel_error(self, top.driver.eval_objective(), 3.18339413394, .0001) cds = CaseDataset('cases.json', 'json') cases = cds.data.fetch() n_orig = len(cases) # Typically 142 top = set_as_top(SellarMDF()) top._setup() cds.restore(top, cases[-1]['_id']) top.recorders = [JSONCaseRecorder('cases.restored')] top.run() assert_rel_error(self, top.sub.globals.z1, 1.977639, .0001) assert_rel_error(self, top.half.z2a, 0., .0001) assert_rel_error(self, top.sub.x1, 0., .0001) assert_rel_error(self, top.sub.states.y[0], 3.160000, .0001) assert_rel_error(self, top.sub.states.y[1], 3.755278, .0001) assert_rel_error(self, top.driver.eval_objective(), 3.18339397762, .0001) cases = CaseDataset('cases.restored', 'json').data.fetch() # Exact case counts are unreliable, just assure restore was quicker. self.assertTrue(len(cases) < n_orig/4) # Typically 15
def test_casetree(self): # Record tree of cases via CaseIteratorDriver. top = set_as_top(TreeModel()) top.driver1.sequential = True top.driver2.sequential = True top.run() 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' ] self.verify_tree(top, expected) # Nested CaseIteratorDrivers have some issues: # 1. If the second level is concurrent, the first level's iterator # can't be pickled. # 2. If the first level is concurrent, we don't see the second level's # recorded cases (they're remote). top = set_as_top(TreeModel()) top.driver1.sequential = False top.driver2.sequential = True top.run() expected = [ '1', '1-driver1.1', '1-driver1.2' ] self.verify_tree(top, expected)
def test_EI(self): # pyevolve does some caching that causes failures during our # complete unit tests due to stale values in the cache attributes # below, so reset them here Selectors.GRankSelector.cachePopID = None Selectors.GRankSelector.cacheCount = None Selectors.GRouletteWheel.cachePopID = None Selectors.GRouletteWheel.cacheWheel = None analysis = Analysis() set_as_top(analysis) #analysis.DOE_trainer.DOEgenerator = FullFactorial(num_levels=10) analysis.run() # This test looks for the presence of at least one point close to # each optimum. #print analysis.EI.EI #print analysis.branin_meta_model.x #print analysis.branin_meta_model.y points = [(-pi,12.275,.39789),(pi,2.275,.39789),(9.42478,2.745,.39789)] errors = [] for x,y,z in points: analysis.branin_meta_model.x = x analysis.branin_meta_model.y = y analysis.branin_meta_model.execute() errors.append((analysis.branin_meta_model.f_xy.mu - z)/z*100) avg_error = sum(errors)/float(len(errors)) self.assertTrue(avg_error <= 35)
def test_simvehicle_three(self): my_sim = VehicleSim2() set_as_top(my_sim) my_sim.run() self.assertAlmostEqual(my_sim.sim_acc.accel_time, 7.5, places=2) self.assertAlmostEqual(my_sim.sim_EPA_city.fuel_economy, 24.8079694553, places=2) self.assertAlmostEqual(my_sim.sim_EPA_highway.fuel_economy, 33.4540583989, places=2)
def test_constrained_derivative(self): model = OCD() set_as_top(model) model.run() assert_rel_error(self, model.paraboloid.x, 7.175775, 0.01) assert_rel_error(self, model.paraboloid.y, -7.824225, 0.01)
def test_unconstrained(self): model = OptimizationUnconstrained() set_as_top(model) model.run() assert_rel_error(self, model.paraboloid.x, 6.666309, 0.01) assert_rel_error(self, model.paraboloid.y, -7.333026, 0.01)
def test_constrained(self): model = OptimizationConstrained() set_as_top(model) model.run() assert_rel_error(self, model.paraboloid.x, 7.175775, 0.01) assert_rel_error(self, model.paraboloid.y, -7.824225, 0.01)
def publish_class(path, version, comment, filename, classname, host='localhost', port=server.DEFAULT_PORT): """ Publish egg on server at `host`:`port` under `path` and `version` with `comment` given `filename` and `classname`. path: string Component path to be published. version: string Version to be published. comment: string Description of this version of this component. filename: string Name of Python file. classname: string Name of component class in `filename`. host: string Host name of server to publish to. port: int Port number of server to publish to. """ dirname = os.path.dirname(filename) if not os.path.isabs(dirname): cwd = os.getcwd() if dirname: dirname = os.path.join(cwd, dirname) else: dirname = cwd if not dirname in sys.path: # Ensure importable. sys.path.insert(0, dirname) modname = os.path.basename(filename)[:-3] # Drop '.py' try: __import__(modname) except ImportError as exc: raise RuntimeError("Can't import %r: %r" % (modname, exc)) module = sys.modules[modname] try: cls = getattr(module, classname) except AttributeError as exc: raise RuntimeError("Can't get class %r in %r: %r" % (classname, modname, exc)) try: obj = cls() except Exception as exc: raise RuntimeError("Can't instantiate %s.%s: %r" % (modname, classname, exc)) if obj._call_cpath_updated == True: set_as_top(obj) publish_object(path, version, comment, obj, host, port)
def _update_roots(self): ''' Ensure that all root containers in the project dictionary know their own name and are set as top. ''' for k, v in self.proj.items(): if has_interface(v, IContainer): if v.name != k: v.name = k if v._call_cpath_updated: set_as_top(v)
def test_MDF(self): prob = SellarMDF() set_as_top(prob) prob.dis1.z1 = prob.dis2.z1 = 5.0 prob.dis1.z2 = prob.dis2.z2 = 2.0 prob.dis1.x1 = 1.0 prob.run() assert_rel_error(self, prob.dis1.z1, 1.977, 0.01) assert_rel_error(self, 1.0-prob.dis1.z2, 1.0, 0.01) assert_rel_error(self, 1.0-prob.dis1.x1, 1.0, 0.1)
def test_BLISS(self): prob = SellarBLISS() set_as_top(prob) prob.dis1.z1 = prob.dis2.z1 = prob.z_store[0] = 5.0 prob.dis1.z2 = prob.dis2.z2 = prob.z_store[1] = 2.0 prob.dis1.x1 = prob.x1_store = 1.0 prob.run() assert_rel_error(self, prob.dis1.z1, 1.977, 0.04) assert_rel_error(self, 1.0-prob.dis1.z2, 1.0, 0.01) assert_rel_error(self, 1.0-prob.dis1.x1, 1.0, 0.1)
def test_non_diff(self): # Test grouping comps with non-differentiable connections. model = set_as_top(Assembly()) model.add('comp1', ND_Send()) model.add('comp2', ND_Receive()) model.connect('comp1.y', 'comp2.x') model.connect('comp1.n', 'comp2.n') model.driver.workflow.add(['comp1', 'comp2']) model.run() inputs = ['comp1.x'] outputs = ['comp2.y'] J = model.driver.workflow.calc_gradient(inputs, outputs, mode='forward') self.assertAlmostEqual(J[0, 0], 2.5) meta = model.driver.workflow._derivative_graph.node['~0'] self.assertTrue('comp1' in meta['pa_object'].comps) self.assertTrue('comp2' in meta['pa_object'].comps) model.run() model.driver.workflow.config_changed() J = model.driver.workflow.calc_gradient(inputs, outputs, mode='fd') self.assertAlmostEqual(J[0, 0], 2.5) meta = model.driver.workflow._derivative_graph.node['~0'] self.assertTrue('comp1' in meta['pa_object'].comps) self.assertTrue('comp2' in meta['pa_object'].comps) # What about subassys? model = set_as_top(Assembly()) model.add('sub', Assembly()) model.add('comp1', ND_Send()) model.sub.add('comp2', ND_Receive()) model.sub.create_passthrough('comp2.x') model.sub.create_passthrough('comp2.y') model.sub.create_passthrough('comp2.n') model.connect('comp1.y', 'sub.x') model.connect('comp1.n', 'sub.n') model.driver.workflow.add(['comp1', 'sub']) model.sub.driver.workflow.add(['comp2']) model.run() inputs = ['comp1.x'] outputs = ['sub.y'] J = model.driver.workflow.calc_gradient(inputs, outputs, mode='forward') self.assertAlmostEqual(J[0, 0], 2.5) meta = model.driver.workflow._derivative_graph.node['~0'] self.assertTrue('comp1' in meta['pa_object'].comps) self.assertTrue('sub' in meta['pa_object'].comps)
def test_no_change_in_value(self): prob = DumbAssembly() set_as_top(prob) prob.driver.algorithm = "broyden2" try: prob.run() except RuntimeError, err: msg = "Broyden iteration has stopped converging. Change in " + \ "input has produced no change in output. This could " + \ "indicate a problem with your component connections. " + \ "It could also mean that this solver method is " + \ "inadequate for your problem." self.assertEqual(str(err), msg)
self.DOE_Validate.DOEgenerator.num_samples = 100 self.DOE_Validate.add_parameter(("sin_meta_model.x", "sin_verify.x"), low=0, high=20) # , name="combined_input" self.DOE_Validate.add_response("sin_verify.f_x") self.DOE_Validate.add_response("sin_meta_model.f_x") #Iteration Hierarchy self.driver.workflow.add(['DOE_Trainer', 'DOE_Validate']) self.DOE_Trainer.workflow.add('sin_calc') self.DOE_Validate.workflow.add(['sin_verify', 'sin_meta_model']) if __name__ == "__main__": sim = set_as_top(Simulation()) sim.run() #This is how you can access any of the data train_inputs = sim.DOE_Trainer.case_inputs.sin_calc.x train_actual = sim.DOE_Trainer.case_outputs.sin_calc.f_x inputs = sim.DOE_Validate.case_inputs.sin_meta_model.x actual = sim.DOE_Validate.case_outputs.sin_verify.f_x predicted = sim.DOE_Validate.case_outputs.sin_meta_model.f_x if '--noplot' not in sys.argv: import pylab as p p.scatter(train_inputs, train_actual, c='g', label="training data") p.scatter(inputs, predicted, c='b', label="predicted result") p.legend()
def test_eval_gradient(self): top = set_as_top(Assembly()) top.add('comp1', Simple()) top.run() exp = ExprEvaluator('3.0*comp1.c', top.driver) grad = exp.evaluate_gradient(scope=top) self.assertEqual(top.comp1.c, 7.0) assert_rel_error(self, grad['comp1.c'], 3.0, 0.00001) # Commented out this test, until we find a case that can't be # handled analytically # interface test: step size # (for linear slope, larger stepsize more accurate because of # python's rounding) # grad2 = exp.evaluate_gradient(scope=top, stepsize=0.1) # assert( abs(grad['comp1.c'] - 3.0) > abs(grad2['comp1.c'] - 3.0) ) # More complicated, multiple comps top.add('comp2', Simple()) exp = ExprEvaluator('comp2.b*comp1.c**2', top.driver) grad = exp.evaluate_gradient(scope=top) self.assertEqual(len(grad), 2) assert_rel_error(self, grad['comp1.c'], 70.0, 0.00001) assert_rel_error(self, grad['comp2.b'], 49.0, 0.00001) # test limited varset grad = exp.evaluate_gradient(scope=top, wrt=['comp2.b']) self.assertEqual(len(grad), 1) exp = ExprEvaluator('pow(comp2.b,2)', top.driver) grad = exp.evaluate_gradient(scope=top) assert_rel_error(self, grad['comp2.b'], 10.0, 0.00001) exp = ExprEvaluator('pow(comp2.b,3)', top.driver) grad = exp.evaluate_gradient(scope=top) assert_rel_error(self, grad['comp2.b'], 75.0, 0.00001) exp = ExprEvaluator('log(comp2.a)', top.driver) grad = exp.evaluate_gradient(scope=top) assert_rel_error(self, grad['comp2.a'], 1. / top.comp2.a, 0.00001) exp = ExprEvaluator('sin(cos(comp2.b))+sqrt(comp2.a)/comp1.c', top.driver) grad = exp.evaluate_gradient(scope=top) g1 = -sin(top.comp2.b) * cos(cos(top.comp2.b)) # true gradient components g2 = (2 * sqrt(top.comp2.a) * top.comp1.c) ** -1 g3 = -sqrt(top.comp2.a) / top.comp1.c ** 2 assert_rel_error(self, grad['comp2.b'], g1, 0.00001) assert_rel_error(self, grad['comp2.a'], g2, 0.00001) assert_rel_error(self, grad['comp1.c'], g3, 0.00001) exp = ExprEvaluator('gamma(comp2.a)', top.driver) grad = exp.evaluate_gradient(scope=top) from scipy.special import polygamma g1 = gamma(top.comp2.a) * polygamma(0, top.comp2.a) # true partial derivative assert_rel_error(self, grad['comp2.a'], g1, 0.001) exp = ExprEvaluator('abs(comp2.a)', top.driver) grad = exp.evaluate_gradient(scope=top) assert_rel_error(self, grad['comp2.a'], 1.0, 0.0001)
def setUp(self): """ Called before each test in this class. """ self.model = set_as_top(Model())
self.connect('velocity', ['chassis.velocity', 'transmission.velocity']) self.connect('tire_circumference', ['chassis.tire_circ', 'transmission.tire_circ']) # Hook it all up self.connect('transmission.RPM', 'engine.RPM') self.connect('transmission.torque_ratio', 'chassis.torque_ratio') self.connect('engine.torque', 'chassis.engine_torque') self.connect('engine.engine_weight', 'chassis.mass_engine') if __name__ == "__main__": # pragma: no cover from openmdao.main.api import set_as_top top = set_as_top(Assembly()) top.add('car', Vehicle()) top.driver.workflow.add('Testing') top.car.current_gear = 1 top.car.velocity = 20.0 * (26.8224 / 60.0) top.car.throttle = 1.0 top.car.run() def prz(vehicle): """ Printing the results""" print "Accel = ", vehicle.acceleration print "Fuelburn = ", vehicle.fuel_burn print "(power, torque) ", vehicle.power, vehicle.torque print "RPM = ", vehicle.engine.RPM
def test_2_nested_drivers_same_assembly(self): print "*** test_2_nested_drivers_same_assembly ***" # # Solve (x-3)^2 + xy + (y+4)^2 = 3 # using two optimizers nested. The inner loop optimizes y # the outer loop takes care of x # # Optimal solution: x = 6.6667; y = -7.3333 top = set_as_top(Assembly()) # create the outer driver outer_driver = top.add('driver', CONMINdriver()) # create the inner driver inner_driver = top.add('driver1', CONMINdriver()) top.add('comp1', ExprComp(expr='x-3')) top.add('comp2', ExprComp(expr='-3')) top.add('comp3', ExprComp2(expr='x*x + (x+3)*y + (y+4)**2')) top.add('comp4', ExprComp2(expr='x+y')) top.comp1.x = 50 top.comp3.y = -50 # Hook stuff up top.connect('comp1.f_x', 'comp3.x') top.connect('comp3.f_xy', 'comp4.y') top.connect('comp2.f_x', 'comp4.x') # Driver process definition outer_driver.workflow.add('driver1') inner_driver.workflow.add(['comp1', 'comp2', 'comp3', 'comp4']) inner_driver.itmax = 30 inner_driver.fdch = .000001 inner_driver.fdchm = .000001 inner_driver.add_objective('comp3.f_xy') inner_driver.add_parameter('comp3.y', low=-50, high=50) outer_driver.itmax = 30 outer_driver.fdch = .000001 outer_driver.fdchm = .000001 outer_driver.add_objective('comp4.f_xy') outer_driver.add_parameter('comp1.x', low=-50, high=50) top.run() # Notes: CONMIN does not quite reach the anlytical minimum # In fact, it only gets to about 2 places of accuracy. # This is also the case for a single 2-var problem. self.assertAlmostEqual(top.comp1.x, 6.66667, places=4) self.assertAlmostEqual(top.comp3.y, -7.33333, places=4) # test dumping of iteration tree stream = StringIO() dump_iteration_tree(top, full=False, f=stream, tabsize=3) s = stream.getvalue() s = s.replace('comp2', 'comp2or3') s = s.replace('comp3', 'comp2or3') self.assertEqual( s, '\n driver\n driver1\n comp1\n comp2or3\n' ' comp2or3\n comp4\n') # test all_wflows_order comps = top.all_wflows_order() self.assertEqual(comps, [ 'driver', 'driver1', 'comp1', 'comp3', '_pseudo_0', 'comp2', 'comp4', '_pseudo_1' ])
def test_4_authkey(self): logging.debug('') logging.debug('test_authkey') factory = self.start_factory() # Start server in non-public-key mode. # Connections must have matching authkey, # but data is sent in the clear!? # This is standard multiprocessing behaviour. authkey = 'password' server_dir = 'Factory_authkey' if os.path.exists(server_dir): shutil.rmtree(server_dir) os.mkdir(server_dir) os.chdir(server_dir) self.server_dirs.append(server_dir) try: logging.debug('starting server (authkey %s)...', authkey) allowed_types = ['openmdao.main.test.test_distsim.Box'] server, server_cfg = start_server(authkey=authkey, allowed_types=allowed_types, timeout=30) cfg = read_server_config(server_cfg) address = cfg['address'] port = cfg['port'] key = cfg['key'] logging.debug('server address: %s', address) logging.debug('server port: %s', port) logging.debug('server tunnel: %s', cfg['tunnel']) logging.debug('server key: %s', key) finally: os.chdir('..') factory = None try: assert_raises(self, 'connect(address, port, pubkey=key)', globals(), locals(), AuthenticationError, 'digest sent was rejected') factory = connect(address, port, authkey=authkey) logging.debug('factory: %r', factory) # Create model and run it. box = factory.create(_MODULE + '.Box') model = set_as_top(Model(box)) model.run() # Check results. for width in range(1, 2): for height in range(1, 3): for depth in range(1, 4): case = model.driver.recorders[0].cases.pop(0) self.assertEqual(case.outputs[0][2], width * height * depth) finally: if factory is not None: factory.cleanup() logging.debug('terminating server (authkey %s) pid %s', authkey, server.pid) server.terminate(timeout=10) server = None
windDown = np.trapz( dataEnd[:, 1] / 3600, dataEnd[:, 0]) * 1000 #km covered during wind down along I-580 to SF middleLength = self.tube_length - (startUp + windDown) middleTime = middleLength / (self.speed_max) self.time = middleTime + 435 + t3 + t3 + 100 + t2 + 400 + t1 self.energy = (self.pwr_req * self.time / 3600.) * ( 1 + self.pwr_marg) #convert to hours print self.itername print " W_i: ", self.parent.compress.W_in, 10 * ( self.parent.compress.W_in - self.parent.flow_limit.W_excess) print "total mission time: ", self.time / 60, " minutes" print " R_tube: ", self.parent.pod.radius_tube_inner, .01 * ( self.parent.pod.area_compressor_bypass - self.parent.compress.area_c1_out) print " Bearing_Ps: ", self.parent.compress.c2_PR_des, self.parent.compress.Ps_bearing_residual print if __name__ == "__main__": from openmdao.main.api import set_as_top m = set_as_top(Mission()) m.run()
def setUp(self): class TestComponent(ImplicitComponent): # in V = Array(iotype='in') P = Array(iotype='in') Prated = Float(iotype='in') # state Vrated = Float(iotype='state') # residual residual = Float(iotype='residual') # out dummy = Float(iotype='out') def execute(self): f = interp1d(self.V, self.P, kind='cubic') P = f(self.Vrated) self.residual = P - self.Prated self.dummy = 2 * self.Prated class TestAssembly(Assembly): V = Array(iotype='in') P = Array(iotype='in') Prated = Float(iotype='in') Vin = Float(iotype='in') Vout = Float(iotype='in') invalid_bracket_return = Float(iotype='in') Vrated = Float(iotype='out') def configure(self): self.add('comp', TestComponent()) self.add('brent', Brent()) self.brent.workflow.add(['comp']) self.driver.workflow.add(['brent']) # connections to comp self.connect('V', 'comp.V') self.connect('P', 'comp.P') self.connect('Prated', 'comp.Prated') # setup Brent self.connect('Vin', 'brent.lower_bound') self.connect('Vout', 'brent.upper_bound') self.brent.add_parameter('comp.Vrated') self.brent.add_constraint('comp.residual = 0') self.connect('invalid_bracket_return', 'brent.invalid_bracket_return') # connect outputs self.connect('comp.Vrated', 'Vrated') # openmdao self.assembly = set_as_top(TestAssembly())
def setUp(self): """ this function is used to test each type...""" self.top = set_as_top(Assembly()) self.top.add('oneinp', Oneinp()) self.top.add('oneout', Oneout()) self.top.driver.workflow.add(['oneinp', 'oneout'])
def test_basic_CO(self): # Our CO model failed if our submodels didn't have outputs in the graph. # This test covers the fix. sim = set_as_top(SolverCO()) sim.run()
def test_replace_driver(self): top = set_as_top(Assembly()) top.add('driver', EqInEqdriver()) top.add('comp1', Simple()) top.add('comp2', Simple()) top.driver.workflow.add(['comp1', 'comp2']) top.driver.add_parameter('comp1.a', low=-100, high=100, scaler=1.2, adder=3, start=7, fd_step=0.034, name='param1', scope=top) top.driver.add_parameter('comp2.a', low=-50, high=50, scope=top) top.driver.add_objective('comp1.d+comp2.c-comp2.d', scope=top) top.driver.add_constraint('comp1.d-comp1.c=.5') old_params = top.driver.get_parameters() old_objectives = top.driver.get_objectives() old_constraints = top.driver.get_eq_constraints() self.assertEqual(old_params, top.driver.get_parameters()) self.assertEqual(old_objectives, top.driver.get_objectives()) self.assertEqual(old_constraints, top.driver.get_eq_constraints()) try: top.replace('driver', InEqdriver()) except Exception as err: self.assertEqual(str(err), ": Couldn't replace 'driver' of type EqInEqdriver" " with type InEqdriver: driver: Equality" " constraint 'comp1.d-comp1.c = .5' is not" " supported on this driver") else: self.fail("Exception expected") top.replace('driver', Eqdriver()) self.assertEqual(old_params, top.driver.get_parameters()) self.assertEqual(old_objectives, top.driver.get_objectives()) self.assertEqual(old_constraints, top.driver.get_eq_constraints()) top.add('driver', Objectivesdriver()) top.driver.add_objective('comp1.d+comp2.c-comp2.d', scope=top) top.driver.add_objective('comp1.c-comp2.d*3.5', scope=top) try: top.replace('driver', Eqdriver()) except Exception as err: self.assertEqual(str(err), ": Couldn't replace 'driver' of type" " Objectivesdriver with type Eqdriver: driver:" " This driver allows a maximum of 1 objectives," " but the driver being replaced has 2") top.add('driver', InEqdriver()) top.driver.add_parameter('comp1.a', low=-100, high=100, scaler=1.2, adder=3, start=7, fd_step=0.034, name='param1', scope=top) top.driver.add_objective('comp1.d+comp2.c-comp2.d', scope=top) try: top.replace('driver', Objectivesdriver()) except Exception as err: self.assertEqual(str(err), ": Couldn't replace 'driver' of type InEqdriver" " with type Objectivesdriver: driver: target" " delegate '_hasparameters' has no match") top.add('driver', InEqdriver()) top.driver.add_objective('comp1.d+comp2.c-comp2.d', scope=top) top.driver.add_constraint('comp1.d-comp1.c<.5') try: top.replace('driver', Objectivesdriver()) except Exception as err: self.assertEqual(str(err), ": Couldn't replace 'driver' of type InEqdriver" " with type Objectivesdriver: driver: target" " delegate '_hasineqconstraints' has no match")
self.driver.iprint = 1 self.driver.itmax = 30 self.driver.fdch = .001 self.driver.fdchm = .001 self.driver.delfun = .0001 self.driver.dabfun = .000001 self.driver.ct = -.01 self.driver.ctlmin = 0.0001 if __name__ == "__main__": # pragma: no cover import time prob = SellarMDF() set_as_top(prob) prob.coupler.z1_in = 5.0 prob.coupler.z2_in = 2.0 prob.dis1.x1 = 1.0 tt = time.time() prob.run() print "\n" print "CONMIN Iterations: ", prob.driver.iter_count print "Minimum found at (%f, %f, %f)" % (prob.coupler.z1_in, \ prob.coupler.z2_in, \ prob.dis1.x1) print "Couping vars: %f, %f" % (prob.dis1.y1, prob.dis2.y2) print "Minimum objective: ", prob.driver.objective.evaluate()
def test_uninitialized_array(self): expected = ": out1.x was not initialized. OpenMDAO does not support uninitialized variables." """ out1.x is: - uninitialized - flattenable - the source of a connection - not a slice """ top = set_as_top(Assembly()) top.add('out1', self.C1()) top.add('in1', self.C2()) top.connect('out1.x', 'in1.x') top.driver.workflow.add(['out1', 'in1']) try: top.run() except ValueError as e: self.assertEqual(str(e), expected) else: self.fail("Should have raised error message: {}".format(expected)) """ out1.x is: - uninitialized - not flattenable - the source of a connection - not a slice """ top = set_as_top(Assembly()) top.add('out1', self.C3()) top.add('in1', self.C2()) top.connect('out1.x', 'in1.x') top.driver.workflow.add(['out1', 'in1']) top.run() """ out1.x is: - initialized - flattenable - the source of a connection - not a slice """ top = set_as_top(Assembly()) top.add('out1', self.C4(eye(2))) top.add('in1', self.C2()) top.connect('out1.x', 'in1.x') top.driver.workflow.add(['out1', 'in1']) top.run() """ out1.x is: - initialized - flattenable - the source of a connection - not a slice in1.x[::1] is: - initialized - flattenable - the source of a connection - a slice """ top = set_as_top(Assembly()) top.add('out1', self.C4(array(range(5)))) top.add('in1', self.C2()) top.add('in2', self.C2()) top.connect('out1.x', 'in1.x') top.connect('in1.x[::1]', 'in2.x') top.driver.workflow.add(['out1', 'in1', 'in2']) top.run() """ sub.out1.x is: - not initialized - flattenable - source of a connection - not a slice """ expected = "sub: out1.x was not initialized. OpenMDAO does not support uninitialized variables." top = set_as_top(Assembly()) top.add('sub', Assembly()) top.sub.add('out1', self.C1()) top.sub.add('in1', self.C2()) top.sub.connect('out1.x', 'in1.x') top.sub.driver.workflow.add(['out1', 'in1']) top.driver.workflow.add(['sub']) try: top.run() except ValueError as e: self.assertEqual(str(e), expected) else: self.fail("Should have raised error message: {}".format(expected))
def setUp(self): self.asm = set_as_top(Assembly()) self.asm.add('comp1', Simple()) self.asm.add('comp2', Simple()) self.asm.add('comp3', SimpleUnits()) self.asm.add('comp4', SimpleUnits())
y = self.y self.f_xy = (x - 3.0)**2 + x * y + (y + 4.0)**2 - 3.0 class A1(Assembly): """ test assembly. """ def configure(self): self.add('p2', Paraboloid()) self.driver.workflow.add('p2') self.create_passthrough('p2.f_xy') class Topp(Assembly): def configure(self): self.add('A1', A1()) self.add('p1', Paraboloid()) self.driver.workflow.add(['A1', 'p1']) self.create_passthrough('p1.y') self.connect('A1.f_xy', 'p1.x') if __name__ == '__main__': asm = set_as_top(Topp()) asm.remove('y') asm.create_passthrough('p1.y')
def setUp(self): class TestComponent(ImplicitComponent): # in a = Float(iotype='in') ap = Float(iotype='in') lambda_r = Float(iotype='in') # states phi = Float(iotype='state') # residuals residual = Float(iotype='residual') # outputs dummy = Float(iotype='out') eval_only = True def evaluate(self): self.residual = sin(self.phi)/(1-self.a) - cos(self.phi)/self.lambda_r/(1+self.ap) self.dummy = self.phi * 2 class TestAssembly(Assembly): a = Float(iotype='in') ap = Float(iotype='in') lambda_r = Float(iotype='in') phi_star = Float(iotype='out') def configure(self): self.add('comp', TestComponent()) self.add('brent', Brent()) self.brent.workflow.add(['comp']) self.driver.workflow.add(['brent']) # connections to comp self.connect('a', 'comp.a') self.connect('ap', 'comp.ap') self.connect('lambda_r', 'comp.lambda_r') # setup Brent eps = 1e-6 self.brent.lower_bound = eps self.brent.upper_bound = pi/2 - eps self.brent.add_parameter('comp.phi') self.brent.add_constraint('comp.residual = 0') def resize(lower, upper, iter): if lower == eps and upper == pi/2 - eps: return -pi/4, -eps, True elif lower == -pi/4 and upper == -eps: return pi/2+eps, pi-eps, True else: return lower, upper, False self.brent.f_resize_bracket = resize # connect outputs self.connect('comp.phi', 'phi_star') eps = 1e-6 # for manual usage def f(phi, assembly): return sin(phi)/(1-assembly.a) - cos(phi)/assembly.lambda_r/(1+assembly.ap) # openmdao self.assembly = set_as_top(TestAssembly()) self.manual_f = f
def test_large_dataflow(self): self.top = set_as_top(Assembly()) exp1 = ['y1 = 2.0*x1**2', 'y2 = 3.0*x1'] deriv1 = ['dy1_dx1 = 4.0*x1', 'dy2_dx1 = 3.0'] exp2 = ['y1 = 0.5*x1'] deriv2 = ['dy1_dx1 = 0.5'] exp3 = ['y1 = 3.5*x1'] deriv3 = ['dy1_dx1 = 3.5'] exp4 = ['y1 = x1 + 2.0*x2', 'y2 = 3.0*x1', 'y3 = x1*x2'] deriv4 = [ 'dy1_dx1 = 1.0', 'dy1_dx2 = 2.0', 'dy2_dx1 = 3.0', 'dy2_dx2 = 0.0', 'dy3_dx1 = x2', 'dy3_dx2 = x1' ] exp5 = ['y1 = x1 + 3.0*x2 + 2.0*x3'] deriv5 = ['dy1_dx1 = 1.0', 'dy1_dx2 = 3.0', 'dy1_dx3 = 2.0'] #self.top.add('comp1', ExecCompWithDerivatives(exp1, deriv1)) #self.top.add('comp2', ExecCompWithDerivatives(exp2, deriv2)) #self.top.add('comp3', ExecCompWithDerivatives(exp3, deriv3)) #self.top.add('comp4', ExecCompWithDerivatives(exp4, deriv4)) #self.top.add('comp5', ExecCompWithDerivatives(exp5, deriv5)) self.top.add('comp1', ExecComp(exp1)) self.top.add('comp2', ExecComp(exp2)) self.top.add('comp3', ExecComp(exp3)) self.top.add('comp4', ExecComp(exp4)) self.top.add('comp5', ExecComp(exp5)) self.top.connect('comp1.y1', 'comp2.x1') self.top.connect('comp1.y2', 'comp3.x1') self.top.connect('comp2.y1', 'comp4.x1') self.top.connect('comp3.y1', 'comp4.x2') self.top.connect('comp4.y1', 'comp5.x1') self.top.connect('comp4.y2', 'comp5.x2') self.top.connect('comp4.y3', 'comp5.x3') self.top.driver.workflow.add(['comp1', 'comp2', 'comp3', \ 'comp4', 'comp5']) self.top.comp1.x1 = 2.0 self.top.run() comps = ['comp2', 'comp3', 'comp4'] wrt = ['comp2.x1', 'comp3.x1'] outs = ['comp4.y1', 'comp4.y2', 'comp4.y3'] fd = FDhelper(self.top, comps, wrt, outs) input_dict = {} for item in wrt: input_dict[item] = self.top.get(item) output_dict = {} for item in outs: output_dict[item] = self.top.get(item) derivs = fd.run(input_dict, output_dict) assert_rel_error(self, derivs['comp2.x1']['comp4.y1'], 0.5, .001) assert_rel_error(self, derivs['comp2.x1']['comp4.y2'], 1.5, .001) assert_rel_error(self, derivs['comp2.x1']['comp4.y3'], 10.5, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y1'], 7.0, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y2'], 0.0, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y3'], 14.0, .001) fd.model.driver.distribution_generator.form = 'FORWARD' derivs = fd.run(input_dict, output_dict) assert_rel_error(self, derivs['comp2.x1']['comp4.y1'], 0.5, .001) assert_rel_error(self, derivs['comp2.x1']['comp4.y2'], 1.5, .001) assert_rel_error(self, derivs['comp2.x1']['comp4.y3'], 10.5, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y1'], 7.0, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y2'], 0.0, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y3'], 14.0, .001) fd.model.driver.distribution_generator.form = 'BACKWARD' derivs = fd.run(input_dict, output_dict) assert_rel_error(self, derivs['comp2.x1']['comp4.y1'], 0.5, .001) assert_rel_error(self, derivs['comp2.x1']['comp4.y2'], 1.5, .001) assert_rel_error(self, derivs['comp2.x1']['comp4.y3'], 10.5, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y1'], 7.0, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y2'], 0.0, .001) assert_rel_error(self, derivs['comp3.x1']['comp4.y3'], 14.0, .001)
def setUp(self): self.model = set_as_top(MyModel())
def test_2_nested_assemblies(self): print "*** test_2_nested_assemblies ***" # # Solve (x-3)^2 + xy + (y+4)^2 = 3 # using two optimizers nested. The inner loop optimizes y # the outer loop takes care of x # Enough components created to assure that the optimizers don't "touch" # # Optimal solution: x = 6.6667; y = -7.3333 self.top = set_as_top(Assembly()) # create the outer driver outer_driver = self.top.add('driver', CONMINdriver()) nested = self.top.add('nested', Assembly()) # create the inner driver inner_driver = nested.add('driver', CONMINdriver()) #inner_driver = nested.driver nested.add('comp1', ExprComp(expr='x-3')) nested.add('comp2', ExprComp(expr='-3')) nested.add('comp3', ExprComp2(expr='x*x + (x+3)*y + (y+4)**2')) nested.add('comp4', ExprComp2(expr='x+y')) nested.comp1.x = 50 nested.comp3.y = -50 # Hook stuff up nested.connect('comp1.f_x', 'comp3.x') nested.connect('comp3.f_xy', 'comp4.y') nested.connect('comp2.f_x', 'comp4.x') nested.create_passthrough('comp1.x') nested.create_passthrough('comp4.f_xy') outer_driver.workflow.add('nested') inner_driver.workflow.add(['comp1', 'comp2', 'comp3', 'comp4']) inner_driver.itmax = 30 inner_driver.fdch = .000001 inner_driver.fdchm = .000001 #inner_driver.conmin_diff = True inner_driver.add_objective('comp3.f_xy') inner_driver.add_parameter('comp3.y', low=-50, high=50) outer_driver.itmax = 30 outer_driver.fdch = .000001 outer_driver.fdchm = .000001 outer_driver.conmin_diff = True outer_driver.add_objective('nested.f_xy') # comp4.f_xy passthrough outer_driver.add_parameter('nested.x', low=-50, high=50) # comp1.x passthrough self.top.run() # Notes: CONMIN does not quite reach the analytical minimum # In fact, it only gets to about 2 places of accuracy. # This is also the case for a single 2-var problem. self.assertAlmostEqual(nested.x, 6.66667, places=4) self.assertAlmostEqual(nested.comp3.y, -7.33333, places=4) # test dumping of iteration tree stream = StringIO() dump_iteration_tree(self.top, full=False, f=stream, tabsize=3) s = stream.getvalue() # Comp2 and Comp3 are ambiguous in the sort s = s.replace('comp2', 'comp2or3') s = s.replace('comp3', 'comp2or3') self.assertEqual( s, '\n driver\n nested\n driver\n ' 'comp1\n comp2or3\n comp2or3\n' ' comp4\n')
# Optimization Constraints (not used... yet) vrCon = VariableTree() vrCon.MaxDelta = -0.1 vrCon.MinDelta = 0.1 vrCon.FOSmat = 0.55 # 1.3 vrCon.FOSbuck = 0.5 # 1.3 vrCon.FOSquadbuck = 5. vrCon.FOStorbuck = 0.5 # 1.5 vrCon.FOSwire = 0.5 # 2 if __name__ == '__main__': # enable_trace() opt = set_as_top(HeliOptM(10)) print 'Starting multipoint optimization at %s ...' % time.strftime('%X') time1 = time.time() opt.run() time2 = time.time() print 'Optimization complete at %s (elapsed time: %5.2f minutes)' \ % (time.strftime('%X'), ((time2-time1)/60)) print print 'Objective: P =', opt.mp.P print 'Constraint: Low Weight-Lift =', opt.mp.Mtot_low * 9.8 - opt.mp.Ttot_low print 'Constraint: High Weight-Lift =', opt.mp.Mtot_high * 9.8 - opt.mp.Ttot_high
def test_2_nested_drivers_same_assembly_extra_comp(self): print "*** test_2_nested_drivers_same_assembly ***" # # Same as above, but one extra trailing component in outer # workflow. # # Optimal solution: x = 6.6667; y = -7.3333 self.top = set_as_top(Assembly()) top = self.top # create the outer driver outer_driver = top.add('driver', CONMINdriver()) # create the inner driver inner_driver = top.add('driver1', CONMINdriver()) top.add('comp1', ExprComp(expr='x-3')) top.add('comp2', ExprComp(expr='-3')) top.add('comp3', ExprComp2(expr='x*x + (x+3)*y + (y+4)**2')) top.add('comp4', ExprComp2(expr='x+y')) top.add('comp5', ExprComp(expr='x')) top.comp1.x = 50 top.comp3.y = -50 # Hook stuff up top.connect('comp1.f_x', 'comp3.x') top.connect('comp3.f_xy', 'comp4.y') top.connect('comp2.f_x', 'comp4.x') top.connect('comp4.f_xy', 'comp5.x') # Driver process definition outer_driver.workflow.add(['driver1', 'comp5']) inner_driver.workflow.add(['comp1', 'comp2', 'comp3', 'comp4']) inner_driver.itmax = 30 inner_driver.fdch = .000001 inner_driver.fdchm = .000001 inner_driver.add_objective('comp3.f_xy') inner_driver.add_parameter('comp3.y', low=-50, high=50) outer_driver.itmax = 30 outer_driver.fdch = .000001 outer_driver.fdchm = .000001 outer_driver.add_objective('comp5.f_x') outer_driver.add_parameter('comp1.x', low=-50, high=50) self.top.run() # Notes: CONMIN does not quite reach the anlytical minimum # In fact, it only gets to about 2 places of accuracy. # This is also the case for a single 2-var problem. self.assertAlmostEqual(top.comp1.x, 6.66667, places=4) self.assertAlmostEqual(top.comp3.y, -7.33333, places=4) # test dumping of iteration tree stream = StringIO() dump_iteration_tree(self.top, full=False, f=stream, tabsize=3) s = stream.getvalue() s = s.replace('comp2', 'comp2or3') s = s.replace('comp3', 'comp2or3') self.assertEqual( s, '\n driver\n driver1\n comp1\n comp2or3\n' ' comp2or3\n comp4\n comp5\n')
ht_out = (fs_ideal.ht - Fl_I.ht) / self.eff_des + Fl_I.ht Fl_O.setTotal_hP(ht_out, Pt_out) Fl_O.Mach = self.MNexit_des self._exit_area_des = Fl_O.area self._Wc_des = Fl_I.Wc else: #Assumed Op Line Calculation self.PR = self._op_line(Fl_I.Wc) self.eff = self.eff_des #TODO: add in eff variation with W #Operational Conditions Pt_out = Fl_I.Pt * self.PR fs_ideal.setTotalSP(Fl_I.s, Pt_out) ht_out = (fs_ideal.ht - Fl_I.ht) / self.eff + Fl_I.ht Fl_O.setTotal_hP(ht_out, Pt_out) Fl_O.area = self._exit_area_des #causes Mach to be calculated based on fixed area C = GAS_CONSTANT * math.log(self.PR) delta_s = Fl_O.s - Fl_I.s self.eff_poly = C / (C + delta_s) self.pwr = Fl_I.W * (Fl_O.ht - Fl_I.ht) * 1.4148532 #btu/s to hp self.tip_radius = (Fl_O.area / math.pi / (1 - self.hub_to_tip**2))**.5 self.hub_radius = self.hub_to_tip * self.tip_radius if __name__ == "__main__": from openmdao.main.api import set_as_top c = set_as_top(Compressor()) c.run()
def setUp(self): self.top = set_as_top(Sellar_MDA())
def create_example_se_assembly(wind_class='I', sea_depth=0.0, with_new_nacelle=False, with_landbos=False, flexible_blade=False, with_3pt_drive=False, with_ecn_opex=False, ecn_file=None, with_openwind=False, ow_file=None, ow_wkbook=None): """ Inputs: wind_class : str ('I', 'III', 'Offshore' - selected wind class for project) sea_depth : float (sea depth if an offshore wind plant) """ # === Create LCOE SE assembly ======== from openmdao.main.api import set_as_top lcoe_se = set_as_top( lcoe_se_seam_assembly(with_new_nacelle, with_landbos, flexible_blade, with_3pt_drive, with_ecn_opex, ecn_file)) # === Set assembly variables and objects === lcoe_se.sea_depth = sea_depth # 0.0 for land-based turbine lcoe_se.turbine_number = 100 lcoe_se.year = 2009 lcoe_se.month = 12 # bos_a = lcoe_se.bos_a # opex_a = lcoe_se.opex_a aep_a = lcoe_se.aep_a fin_a = lcoe_se.fin_a # Turbine =========== #=========== SEAM inputs # DTU 10 MW Turbine '''lcoe_se.site_type = 'onshore' lcoe_se.rotor_diameter = 178.0 lcoe_se.rated_power = 10.0 lcoe_se.hub_height = 120.0 lcoe_se.max_tipspeed = 90.0''' # NREL 5 MW Turbine # lcoe_se.site_type = 'onshore' lcoe_se.rotor_diameter = 126.0 lcoe_se.rated_power = 5000.0 lcoe_se.hub_height = 90.0 lcoe_se.max_tipspeed = 80.0 lcoe_se.BladeCostPerMass = 15.0 lcoe_se.HubCostPerMass = 3.5 lcoe_se.SpinnerCostPerMass = 4.5 lcoe_se.hub_cost_per_mass = 3.5 lcoe_se.spinner_cost_per_mass = 4.5 lcoe_se.tower_cost_per_mass = 4.0 lcoe_se.AddWeightFactorBlade = 1.2 lcoe_se.blade_material_density = 2100.0 lcoe_se.tower_bottom_diameter = 6. lcoe_se.tower_top_diameter = 3.78 lcoe_se.blade_edge_dynload_factor_ext = 2.5 lcoe_se.blade_edge_dynload_factor_fat = 0.75 lcoe_se.F = 0.777 lcoe_se.MaxChordrR = 0.2 lcoe_se.project_lifetime = 20.0 lcoe_se.lifetime_cycles = 10000000.0 lcoe_se.blade_sections = 21 lcoe_se.PMtarget_blades = 1.0 lcoe_se.PMtarget_tower = 1.0 lcoe_se.safety_factor_blade = 1.1 lcoe_se.safety_factor_tower = 1.5 lcoe_se.stress_limit_extreme_tower = 235.0 lcoe_se.stress_limit_fatigue_tower = 14.885 lcoe_se.stress_limit_extreme_blade = 200.0 lcoe_se.stress_limit_fatigue_blade = 27.0 lcoe_se.tif_blade_root_flap_ext = 1.0 lcoe_se.tif_blade_root_flap_fat = 1.0 lcoe_se.tif_blade_root_edge_ext = 1.0 lcoe_se.weibull_C = 11.0 lcoe_se.weibull_k = 2.0 lcoe_se.wohler_exponent_blade_flap = 10.0 lcoe_se.wohler_exponent_tower = 4.0 lcoe_se.dLoad_dU_factor_flap = 0.9 lcoe_se.dLoad_dU_factor_tower = 0.8 lcoe_se.n_wsp = 26 lcoe_se.min_wsp = 0.0 lcoe_se.max_wsp = 25.0 lcoe_se.nSigma4fatFlap = 1.2 lcoe_se.nSigma4fatTower = 0.8 lcoe_se.rho_steel = 7800.0 lcoe_se.sc_frac_edge = 0.8 lcoe_se.sc_frac_flap = 0.3 lcoe_se.tsr = 8.0 lcoe_se.air_density = 1.225 lcoe_se.turbulence_int = 0.16 lcoe_se.max_Cp = 0.49 lcoe_se.gearloss_const = 0.01 # Fraction lcoe_se.gearloss_var = 0.014 # Fraction lcoe_se.genloss = 0.03 # Fraction lcoe_se.convloss = 0.03 # Fraction #============== # === nacelle ====== lcoe_se.blade_number = 3 # turbine level that must be added for SEAM lcoe_se.rotor_tilt = 5.0 # turbine level that must be added for SEAM lcoe_se.generator_speed = 1173.7 lcoe_se.nacelle.L_ms = 1.0 # (Float, m): main shaft length downwind of main bearing in low-speed shaft lcoe_se.nacelle.L_mb = 2.5 # (Float, m): main shaft length in low-speed shaft lcoe_se.nacelle.h0_front = 1.7 # (Float, m): height of Ibeam in bedplate front lcoe_se.nacelle.h0_rear = 1.35 # (Float, m): height of Ibeam in bedplate rear lcoe_se.nacelle.drivetrain_design = 'geared' lcoe_se.nacelle.crane = True # (Bool): flag for presence of crane lcoe_se.nacelle.bevel = 0 # (Int): Flag for the presence of a bevel stage - 1 if present, 0 if not lcoe_se.nacelle.gear_configuration = 'eep' # (Str): tring that represents the configuration of the gearbox (stage number and types) lcoe_se.nacelle.Np = [3, 3, 1] # (Array): number of planets in each stage lcoe_se.nacelle.ratio_type = 'optimal' # (Str): optimal or empirical stage ratios lcoe_se.nacelle.shaft_type = 'normal' # (Str): normal or short shaft length #lcoe_se.nacelle.shaft_angle = 5.0 # (Float, deg): Angle of the LSS inclindation with respect to the horizontal lcoe_se.nacelle.shaft_ratio = 0.10 # (Float): Ratio of inner diameter to outer diameter. Leave zero for solid LSS lcoe_se.nacelle.carrier_mass = 8000.0 # estimated for 5 MW lcoe_se.nacelle.mb1Type = 'CARB' # (Str): Main bearing type: CARB, TRB or SRB lcoe_se.nacelle.mb2Type = 'SRB' # (Str): Second bearing type: CARB, TRB or SRB lcoe_se.nacelle.yaw_motors_number = 8.0 # (Float): number of yaw motors lcoe_se.nacelle.uptower_transformer = True lcoe_se.nacelle.flange_length = 0.5 #m lcoe_se.nacelle.gearbox_cm = 0.1 lcoe_se.nacelle.hss_length = 1.5 lcoe_se.nacelle.overhang = 5.0 #TODO - should come from turbine configuration level lcoe_se.nacelle.check_fatigue = 0 #0 if no fatigue check, 1 if parameterized fatigue check, 2 if known loads inputs # ================= # tcc ==== lcoe_se.advanced_blade = True lcoe_se.offshore = False lcoe_se.assemblyCostMultiplier = 0.30 lcoe_se.profitMultiplier = 0.20 lcoe_se.overheadCostMultiplier = 0.0 lcoe_se.transportMultiplier = 0.0 # for new landBOS # === new landBOS === if with_landbos: lcoe_se.voltage = 137 lcoe_se.distInter = 5 lcoe_se.terrain = 'FLAT_TO_ROLLING' lcoe_se.layout = 'SIMPLE' lcoe_se.soil = 'STANDARD' # aep ==== # based on COE review for land-based machines if not with_openwind: lcoe_se.array_losses = 0.059 lcoe_se.wind_speed_50m = 8.9 # weibull of 7.25 at 50 m with shear exp of 0.143 lcoe_se.weibull_k = 2.0 lcoe_se.other_losses = 0.101 if not with_ecn_opex: lcoe_se.availability = 0.94 # fin === lcoe_se.fixed_charge_rate = 0.095 lcoe_se.construction_finance_rate = 0.0 lcoe_se.tax_rate = 0.4 lcoe_se.discount_rate = 0.07 lcoe_se.construction_time = 1.0 lcoe_se.project_lifetime = 20.0 # Set plant level inputs === shearExp = 0.2 #TODO : should be an input to lcoe if not with_openwind: lcoe_se.array_losses = 0.1 lcoe_se.other_losses = 0.0 if not with_ecn_opex: lcoe_se.availability = 0.98 lcoe_se.multiplier = 2.23 if wind_class == 'Offshore': # rotor.cdf_reference_mean_wind_speed = 8.4 # TODO - aep from its own module # rotor.cdf_reference_height_wind_speed = 50.0 # rotor.weibull_shape = 2.1 shearExp = 0.14 # TODO : should be an input to lcoe lcoe_se.array_losses = 0.15 if not with_ecn_opex: lcoe_se.availability = 0.96 lcoe_se.offshore = True lcoe_se.multiplier = 2.33 lcoe_se.fixed_charge_rate = 0.118 # ==== # === Run default assembly and print results # lcoe_se.run() # ==== # === Print === return lcoe_se
def setUp(self): self.top = set_as_top(Assembly())
def test_RK4_issue(self): n = 60 m = 20 LDs = [5233.5, 5294.5, 5356.5, 5417.5, 5478.5, 5537.5] r_e2b_I0s = [ np.array([ 4505.29362, -3402.16069, -3943.74582, 4.1923899, -1.56280012, 6.14347427 ]), np.array([ -1005.46693, -597.205348, -6772.86532, -0.61047858, -7.54623146, 0.75907455 ]), np.array([ 4401.10539, 2275.95053, -4784.13188, -5.26605537, -1.08194926, -5.37013745 ]), np.array([ -4969.91222, 4624.84149, 1135.9414, 0.1874654, -1.62801666, 7.4302362 ]), np.array([ -235.021232, 2195.72976, 6499.79919, -2.55956031, -6.82743519, 2.21628099 ]), np.array([ -690.314375, -1081.78239, -6762.90367, 7.44316722, 1.19745345, -0.96035904 ]) ] top = set_as_top(Assembly()) top.add('pt', CADRE(n, m)) top.driver.workflow.add('pt') i = 0 top.pt.set("LD", LDs[i]) top.pt.set("r_e2b_I0", r_e2b_I0s[i]) top.run() inputs = ['BsplineParameters.CP_gamma'] outputs = ['Comm_DataDownloaded.Data'] J1 = top.pt.driver.calc_gradient(inputs, outputs, mode='forward') #nn = len(top.pt.driver.workflow.res) #J = np.zeros([nn, nn]) #arg = np.zeros((nn, )) #for j in range(nn): #arg[j] = 1.0 #J[:, j] = top.pt.driver.workflow.matvecFWD(arg) #arg[j] = 0.0 J2 = top.pt.driver.calc_gradient(inputs, outputs, mode='adjoint') #Jt = np.zeros([nn, nn]) #for j in range(nn): #arg[j] = 1.0 #Jt[:, j] = top.pt.driver.workflow.matvecREV(arg) #arg[j] = 0.0 #print J #print Jt.T #print J-Jt.T Jfd = top.pt.driver.calc_gradient(inputs, outputs, mode='fd') np.set_printoptions(threshold='nan') #print np.nonzero(J1) #print np.nonzero(J2) #print np.nonzero(Jfd) #print J1 #print J2 #print Jfd print np.max(abs(J1 - Jfd)) print np.max(abs(J2 - Jfd)) print np.max(abs(J1 - J2)) self.assertTrue(np.max(J1 - J2) < 1.0e-6) self.assertTrue(np.max(J1 - Jfd) < 1.0e-4) self.assertTrue(np.max(J2 - Jfd) < 1.0e-4)
def setUp(self): self.top = top = set_as_top(Assembly()) top.add('comp', Paraboloid()) top.add('driver', SimpleDriver()) top.driver.workflow.add(['comp'])
def test_MissionSegment(self): num_elem = 100 num_cp = 30 x_range = 9000.0 altitude = np.zeros(num_elem + 1) altitude = 10 * np.sin(np.pi * np.linspace(0, 1, num_elem + 1)) x_range *= 1.852 x_init = x_range * 1e3 * ( 1 - np.cos(np.linspace(0, 1, num_cp) * np.pi)) / 2 / 1e6 M_init = np.ones(num_cp) * 0.8 h_init = 10 * np.sin(np.pi * x_init / (x_range / 1e3)) model = set_as_top( MissionSegment(num_elem=num_elem, num_cp=num_cp, x_pts=x_init, surr_file='../crm_surr')) model.h_pt = h_init model.M_pt = M_init model.set_init_h_pt(altitude) # Initial parameters model.S = 427.8 / 1e2 model.ac_w = 210000 * 9.81 / 1e6 model.thrust_sl = 1020000.0 / 1e6 model.SFCSL = 8.951 * 9.81 model.AR = 8.68 model.oswald = 0.8 # Some adjustments to match the case ran for the pickle #model.SysFuelWeight.fuel_scale = 1e6 #model.SysTau.thrust_scale = 0.072 model.run() # Load in original data from pickle dirname = os.path.abspath(os.path.dirname(__file__)) filename = os.path.join(dirname, 'analysis2.p') old_data = pickle.load(open(filename, 'rb')) # Some names changed old_data['Gamma'] = old_data['gamma'] old_data['temp'] = old_data['Temp'] # Don't compare the extra constraint/objective stuff, because we # don't create comps for them. old_keys = old_data.keys() old_keys.remove('gamma') old_keys.remove('CL_tar') old_keys.remove('Temp') old_keys.remove('M_i') old_keys.remove('M_f') old_keys.remove('h_i') old_keys.remove('h_f') old_keys.remove('M_spline') old_keys.remove('jason') old_keys.remove('time') # Find data in model new_data = {} comps = [ comp for comp in model.list_components() if comp not in ['coupled_solver'] ] for name in comps: comp = model.get(name) s1 = set(comp.list_vars()) s2 = set(old_keys) s_int = s1.intersection(s2) for key in s_int: new_data[key] = comp.get(key) old_keys.remove(key) print old_keys self.assertEqual(len(old_keys), 0) for key in new_data.keys(): old = old_data[key] new = new_data[key] #diff = np.nan_to_num(abs(new - old) / old) diff = new - old print key print old print new assert_rel_error(self, diff.max(), 0.0, 1e-3)
# for debugging only num_elem = 6 num_cp = 3 altitude = np.zeros(num_elem + 1) altitude = 10 * np.sin(np.pi * np.linspace(0, 1, num_elem + 1)) x_range *= 1.852 x_init = x_range * 1e3 * ( 1 - np.cos(np.linspace(0, 1, num_cp) * np.pi)) / 2 / 1e6 M_init = np.ones(num_cp) * 0.82 h_init = 10 * np.sin(np.pi * x_init / (x_range / 1e3)) model = set_as_top( MissionSegment(num_elem=num_elem, num_cp=num_cp, x_pts=x_init, surr_file='crm_surr')) model.h_pt = h_init model.M_pt = M_init #model.set_init_h_pt(altitude) # Calculate velocity from the Mach we have specified. model.SysSpeed.v_specified = False # Initial parameters model.S = 427.8 / 1e2 model.ac_w = 210000 * 9.81 / 1e6 model.thrust_sl = 1020000.0 / 1e6 model.SFCSL = 8.951 * 9.81
def setUp(self): self.top = set_as_top(Assembly()) self.top.add('driver', SLSQPdriver()) self.top.add('comp', OptRosenSuzukiComponent()) self.top.driver.workflow.add('comp') self.top.driver.iprint = 0