Пример #1
0
    def test_run_apply(self):
        # This test makes sure that we correctly apply the "run_apply" flag
        # to all targets in the "broken" connection, even when they are
        # nested in Groups.

        prob = Problem()
        root = prob.root = Group()

        sub1 = root.add('sub1', Group())
        sub2 = root.add('sub2', Group())

        sub1.add('p1', Paraboloid())
        sub1.add('p2', Paraboloid())
        sub2.add('p1', Paraboloid())
        sub2.add('p2', Paraboloid())

        root.connect('sub1.p1.f_xy', 'sub2.p1.x')
        root.connect('sub1.p2.f_xy', 'sub2.p1.y')
        root.connect('sub1.p1.f_xy', 'sub2.p2.x')
        root.connect('sub1.p2.f_xy', 'sub2.p2.y')
        root.connect('sub2.p1.f_xy', 'sub1.p1.x')
        root.connect('sub2.p2.f_xy', 'sub1.p1.y')
        root.connect('sub2.p1.f_xy', 'sub1.p2.x')
        root.connect('sub2.p2.f_xy', 'sub1.p2.y')

        root.nl_solver = NLGaussSeidel()
        root.ln_solver = ScipyGMRES()

        prob.setup(check=False)

        # Will be True in one group and False in the other, depending on
        # where it cuts.
        self.assertTrue(root.sub1.p1._run_apply != root.sub2.p1._run_apply)
        self.assertTrue(root.sub1.p2._run_apply != root.sub2.p2._run_apply)
Пример #2
0
    def test_parab_subbed_Pcomps(self):

        model = Problem(impl=impl)
        root = model.root = Group()
        root.ln_solver = lin_solver()

        par = root.add('par', ParallelGroup())

        par.add('s1', MP_Point(root=2.0))
        par.add('s2', MP_Point(root=3.0))

        root.add('sumcomp', ExecComp('sum = x1+x2'))
        root.connect('par.s1.c.y', 'sumcomp.x1')
        root.connect('par.s2.c.y', 'sumcomp.x2')

        driver = model.driver = pyOptSparseDriver()
        driver.options['optimizer'] = OPTIMIZER
        driver.options['print_results'] = False
        driver.add_desvar('par.s1.p.x', lower=-100, upper=100)
        driver.add_desvar('par.s2.p.x', lower=-100, upper=100)
        driver.add_objective('sumcomp.sum')

        model.setup(check=False)
        model.run()

        if not MPI or self.comm.rank == 0:
            assert_rel_error(self, model['par.s1.p.x'], 2.0, 1.e-6)

        if not MPI or self.comm.rank == 1:
            assert_rel_error(self, model['par.s2.p.x'], 3.0, 1.e-6)
Пример #3
0
    def test_multiple_problems(self):
        if MPI:
            # split the comm and run an instance of the Problem in each subcomm
            subcomm = self.comm.Split(self.comm.rank)
            prob = Problem(Group(), impl=impl, comm=subcomm)

            size = 5
            value = self.comm.rank + 1
            values = np.ones(size)*value

            A1 = prob.root.add('A1', IndepVarComp('x', values))
            C1 = prob.root.add('C1', ABCDArrayComp(size))

            prob.root.connect('A1.x', 'C1.a')
            prob.root.connect('A1.x', 'C1.b')

            prob.setup(check=False)
            prob.run()

            # check the first output array and store in result
            self.assertTrue(all(prob['C1.c'] == np.ones(size)*(value*2)))
            result = prob['C1.c']

            # gather the results from the separate processes/problems and check
            # for expected values
            results = self.comm.allgather(result)
            self.assertEqual(len(results), self.comm.size)

            for n in range(self.comm.size):
                expected = np.ones(size)*2*(n+1)
                self.assertTrue(all(results[n] == expected))
Пример #4
0
    def test_too_few_procs(self):
        size = 3
        group = Group()
        group.add('P', IndepVarComp('x', numpy.ones(size)))
        group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size,
                                        x=numpy.zeros(size),
                                        y=numpy.zeros(size)))
        group.add('C2', ExecComp(['z=3.0*y'],
                                 y=numpy.zeros(size),
                                 z=numpy.zeros(size)))

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('P.x', 'C1.x')
        prob.root.connect('C1.y', 'C2.y')

        try:
            prob.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err),
                             "This problem was given 1 MPI processes, "
                             "but it requires between 2 and 2.")
        else:
            if MPI:
                self.fail("Exception expected")
    def test_alloc_jacobian(self):
        # Testing the helper function

        p = Problem()
        root = p.root = Group()

        root.add('comp1', ExecComp(["y[0]=x[0]*2.0+x[1]*7.0",
                                    "y[1]=x[0]*5.0-x[1]*3.0+x[2]*1.5"],
                                    x=np.zeros(3), y=np.zeros(2)))
        root.add('comp2', SimpleImplicitComp())

        root.ln_solver.options['maxiter'] = 2
        p.setup(check=False)

        # Explciit
        J = root.comp1.alloc_jacobian()

        self.assertTrue(len(J) == 1)
        self.assertTrue(('y', 'x') in J)
        self.assertTrue(J[('y', 'x')].shape == (2,3))

        # Implicit
        J = root.comp2.alloc_jacobian()

        self.assertTrue(len(J) == 4)
        self.assertTrue(('y', 'x') in J)
        self.assertTrue(('y', 'z') in J)
        self.assertTrue(('z', 'x') in J)
        self.assertTrue(('z', 'z') in J)
        self.assertTrue(J[('y', 'x')].shape == (1, 1))
        self.assertTrue(J[('y', 'z')].shape == (1, 1))
        self.assertTrue(J[('z', 'x')].shape == (1, 1))
        self.assertTrue(J[('z', 'z')].shape == (1, 1))

        p.run()
Пример #6
0
    def test_file_diamond(self):
        # connect a source FileRef to two target FileRefs on
        # components running in parallel, and connect the outputs
        # of those components to a common sink component.  All filenames
        # are different, so files will actually be copied for each connection.
        if MPI:
            num = self.N_PROCS
        else:
            num = 1

        prob = Problem(Group(), impl=impl)

        src = prob.root.add("src", FileSrc('src'))
        par = prob.root.add('par', ParallelGroup())
        sink = prob.root.add("sink", FileSink('sink', num))

        for i in range(num):
            par.add("mid%d"%i, FileMid('mid%d'%i,'mid%d'%i))
            prob.root.connect('src.fout', 'par.mid%d.fin'%i)
            prob.root.connect('par.mid%d.fout'%i, 'sink.fin%d'%i)

        prob.setup(check=False)
        prob.run()

        for i in range(num):
            with sink.params['fin%d'%i].open('r') as f:
                self.assertEqual(f.read(), "src\npar.mid%d\n"%i)
Пример #7
0
    def test_pbo_desvar_slsqp_scipy(self):
        top = Problem()

        root = top.root = Group()

        root.add('p1', IndepVarComp('x', u'var_x', pass_by_obj=True))
        root.add('p2', IndepVarComp('y', -4.0))
        root.add('p', PassByObjParaboloid())

        root.connect('p1.x', 'p.x')
        root.connect('p2.y', 'p.y')

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'

        top.driver.add_desvar('p1.x')
        top.driver.add_desvar('p2.y')
        top.driver.add_objective('p.f_xy')

        try:
            top.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err), "Parameter 'p1.x' is a 'pass_by_obj' variable and "
                             "can't be used with a gradient based driver of type 'SLSQP'.")
        else:
            self.fail("Exception expected")
Пример #8
0
    def test_simple_deriv_xfer(self):

        prob = Problem(impl=impl)
        prob.root = FanInGrouped()
        prob.setup(check=False)

        prob.root.comp3.dpmat[None]['x1'] = 7.
        prob.root.comp3.dpmat[None]['x2'] = 11.
        prob.root._transfer_data(mode='rev', deriv=True)

        if not MPI or self.comm.rank == 0:
            self.assertEqual(prob.root.sub.comp1.dumat[None]['y'], 7.)

        if not MPI or self.comm.rank == 1:
            self.assertEqual(prob.root.sub.comp2.dumat[None]['y'], 11.)

        prob.root.comp3.dpmat[None]['x1'] = 0.
        prob.root.comp3.dpmat[None]['x2'] = 0.
        self.assertEqual(prob.root.comp3.dpmat[None]['x1'], 0.)
        self.assertEqual(prob.root.comp3.dpmat[None]['x2'], 0.)

        prob.root._transfer_data(mode='fwd', deriv=True)

        self.assertEqual(prob.root.comp3.dpmat[None]['x1'], 7.)
        self.assertEqual(prob.root.comp3.dpmat[None]['x2'], 11.)
Пример #9
0
def configure(cfg):

    pf = read_blade_planform(os.path.join(PATH, 'data/DTU_10MW_RWT_blade_axis_prebend.dat'))
    nsec = 8
    s_new = np.linspace(0, 1, nsec)
    pf = redistribute_planform(pf, s=s_new)

    cfg['redistribute_flag'] = False
    cfg['blend_var'] = np.array([0.241, 0.301, 0.36, 1.0])
    afs = []
    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/cylinder.dat')]:

        afs.append(np.loadtxt(f))
    cfg['base_airfoils'] = afs
    d = PGLLoftedBladeSurface(cfg, size_in=nsec, size_out=(200, nsec, 3), suffix='_st')
    p = Problem(root=Group())
    r = p.root.add('blade_surf', d, promotes=['*'])
    p.setup()
    for k, v in pf.iteritems():
        if k+'_st' in p.root.blade_surf.params.keys():
            p.root.blade_surf.params[k+'_st'] = v

    return p
Пример #10
0
    def test_iprint(self):

        top = Problem()
        top.root = SellarStateConnection()
        top.setup(check=False)

        base_stdout = sys.stdout

        try:
            ostream = cStringIO()
            sys.stdout = ostream
            top.run()
        finally:
            sys.stdout = base_stdout

        printed = ostream.getvalue()
        self.assertEqual(printed, '')

        # Turn on all iprints
        top.print_all_convergence()

        try:
            ostream = cStringIO()
            sys.stdout = ostream
            top.run()
        finally:
            sys.stdout = base_stdout

        printed = ostream.getvalue()
        self.assertEqual(printed.count('NEWTON'), 3)
        self.assertEqual(printed.count('GMRES'), 4)
        self.assertTrue('[root] NL: NEWTON   0 | ' in printed)
        self.assertTrue('   [root.sub] LN: GMRES   0 | ' in printed)
Пример #11
0
    def test_conflicting_promotions(self):
        # verify we get an error if we have conflicting promotions
        root = Group()

        # promoting G1.x will create an implicit connection to G3.x
        # this is a conflict because G3.x (aka G3.C4.x) is already connected
        # to G3.C3.x
        G2 = root.add('G2', Group())
        G2.add('C1', IndepVarComp('x', 5.), promotes=['x'])

        G1 = G2.add('G1', Group(), promotes=['x'])
        G1.add('C2', ExecComp('y=x*2.0'), promotes=['x'])

        G3 = root.add('G3', Group(), promotes=['x'])
        G3.add('C3', ExecComp('y=x*2.0'), promotes=['y'])          # promoting y
        G3.add('C4', ExecComp('y=x*2.0'), promotes=['x', 'y'])     # promoting y again.. BAD

        prob = Problem(root)

        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "'G3': promoted name 'y' matches multiple unknowns: ('G3.C3.y', 'G3.C4.y')"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
Пример #12
0
    def test_byobj_run(self):
        prob = Problem(root=ExampleByObjGroup())

        prob.setup(check=False)
        prob.run()

        self.assertEqual(prob['G3.C4.y'], 'fooC2C3C4')
Пример #13
0
    def test_no_vecs(self):
        prob = Problem(root=ExampleGroup())
        prob.setup(check=False)

        # test that problem has no unknowns, params, etc.
        try:
            prob.unknowns['G3.C4.y']
        except AttributeError as err:
            self.assertEqual(str(err), "'Problem' object has no attribute 'unknowns'")
        else:
            self.fail("AttributeError expected")

        try:
            prob.params['G3.C4.x']
        except AttributeError as err:
            self.assertEqual(str(err), "'Problem' object has no attribute 'params'")
        else:
            self.fail("AttributeError expected")

        try:
            prob.resids['G3.C4.x']
        except AttributeError as err:
            self.assertEqual(str(err), "'Problem' object has no attribute 'resids'")
        else:
            self.fail("AttributeError expected")
Пример #14
0
    def test_conflicting_connections(self):
        # verify we get an error if we have conflicting implicit and explicit connections
        root = Group()

        # promoting G1.x will create an implicit connection to G3.x
        # this is a conflict because G3.x (aka G3.C4.x) is already connected
        # to G3.C3.x
        G2 = root.add('G2', Group(), promotes=['x'])  # BAD PROMOTE
        G2.add('C1', IndepVarComp('x', 5.), promotes=['x'])

        G1 = G2.add('G1', Group(), promotes=['x'])
        G1.add('C2', ExecComp('y=x*2.0'), promotes=['x'])

        G3 = root.add('G3', Group(), promotes=['x'])
        G3.add('C3', ExecComp('y=x*2.0'))
        G3.add('C4', ExecComp('y=x*2.0'), promotes=['x'])

        root.connect('G2.G1.C2.y', 'G3.C3.x')
        G3.connect('C3.y', 'x')

        prob = Problem(root)

        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "Target 'G3.C4.x' is connected to multiple unknowns: ['G2.C1.x', 'G3.C3.y']"
            self.assertTrue(msg in str(error))
        else:
            self.fail("Error expected")
Пример #15
0
    def setup_model(self, mode):
        asize = 3
        prob = Problem()
        root = prob.model
        root.linear_solver = LinearBlockGS()

        p = root.add_subsystem('p', IndepVarComp('x', np.arange(asize, dtype=float)+1.0))
        G1 = root.add_subsystem('G1', ParallelGroup())
        G1.linear_solver = LinearBlockGS()

        c2 = G1.add_subsystem('c2', ExecComp('y = x * 2.0',
                                        x=np.zeros(asize), y=np.zeros(asize)))
        c3 = G1.add_subsystem('c3', ExecComp('y = ones(3).T*x.dot(arange(3.,6.))',
                                        x=np.zeros(asize), y=np.zeros(asize)))
        c4 = root.add_subsystem('c4', ExecComp('y = x * 4.0',
                                          x=np.zeros(asize), y=np.zeros(asize)))
        c5 = root.add_subsystem('c5', ExecComp('y = x * 5.0',
                                          x=np.zeros(asize), y=np.zeros(asize)))

        prob.model.add_design_var('p.x', indices=[1, 2])
        prob.model.add_constraint('c4.y', upper=0.0, indices=[1], parallel_deriv_color='par_resp')
        prob.model.add_constraint('c5.y', upper=0.0, indices=[2], parallel_deriv_color='par_resp')

        root.connect('p.x', 'G1.c2.x')
        root.connect('p.x', 'G1.c3.x')
        root.connect('G1.c2.y', 'c4.x')
        root.connect('G1.c3.y', 'c5.x')

        prob.setup(check=False, mode=mode)
        prob.run_driver()

        return prob
Пример #16
0
    def test_fan_in(self):
        prob = Problem(Group(), impl=impl)
        par = prob.root.add('par', ParallelGroup())

        G1 = par.add('G1', Group())
        A1 = G1.add('A1', IndepVarComp('a', [1.,1.,1.,1.,1.]))
        C1 = G1.add('C1', PBOComp())

        G2 = par.add('G2', Group())
        B1 = G2.add('B1', IndepVarComp('b', [3.,3.,3.,3.,3.]))
        C2 = G2.add('C2', PBOComp())

        C3 = prob.root.add('C3', PBOComp())

        par.connect('G1.A1.a', 'G1.C1.a')
        par.connect('G2.B1.b', 'G2.C2.a')
        prob.root.connect('par.G1.C1.c', 'C3.a')
        prob.root.connect('par.G2.C2.c', 'C3.b')

        prob.setup(check=False)

        prob.run()

        self.assertEqual(prob['C3.a'], [2.,3.,4.,5.,6.])
        self.assertEqual(prob['C3.b'], [4.,5.,6.,7.,8.])
        self.assertEqual(prob['C3.c'], [6.,8.,10.,12.,14.])
        self.assertEqual(prob['C3.d'], [-2.,-2.,-2.,-2.,-2.])
        self.assertEqual(prob.root.unknowns.vec.size, 0)
Пример #17
0
    def test_basic(self):
        prob = Problem()
        model = prob.model

        n_cp = 80
        n_point = 160

        t = np.linspace(0, 3.0*np.pi, n_cp)
        x = np.sin(t)

        model.add_subsystem('px', IndepVarComp('x', val=x))
        model.add_subsystem('interp', BsplinesComp(num_control_points=n_cp,
                                                   num_points=n_point,
                                                   in_name='h_cp',
                                                   out_name='h',
                                                   distribution='uniform'))

        model.connect('px.x', 'interp.h_cp')

        prob.setup(check=False)
        prob.run_model()

        xx = prob['interp.h'].flatten()
        tt = np.linspace(0, 3.0*np.pi, n_point)

        x_expected = np.sin(tt)
        delta = xx - x_expected

        # Here we test that we don't have crazy interpolation error.
        self.assertLess(max(delta), .15)
        # And that it gets middle points a little better.
        self.assertLess(max(delta[15:-15]), .06)
Пример #18
0
    def test_hierarchy_iprint(self):

        prob = Problem()
        model = prob.model

        model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])))

        sub1 = model.add_subsystem('sub1', Group())
        sub2 = sub1.add_subsystem('sub2', Group())
        g1 = sub2.add_subsystem('g1', SubSellar())
        g2 = model.add_subsystem('g2', SubSellar())

        model.connect('pz.z', 'sub1.sub2.g1.z')
        model.connect('sub1.sub2.g1.y2', 'g2.x')
        model.connect('g2.y2', 'sub1.sub2.g1.x')

        model.nonlinear_solver = NewtonSolver()
        model.linear_solver = ScipyKrylov()
        model.nonlinear_solver.options['solve_subsystems'] = True
        model.nonlinear_solver.options['max_sub_solves'] = 0

        g1.nonlinear_solver = NewtonSolver()
        g1.linear_solver = LinearBlockGS()

        g2.nonlinear_solver = NewtonSolver()
        g2.linear_solver = ScipyKrylov()
        g2.linear_solver.precon = LinearBlockGS()
        g2.linear_solver.precon.options['maxiter'] = 2

        prob.set_solver_print(level=2)

        prob.setup(check=False)

        output = run_model(prob)
Пример #19
0
    def test_specify_subgroup_solvers(self):
        from openmdao.api import Problem, NewtonSolver, ScipyKrylov, DirectSolver, NonlinearBlockGS, LinearBlockGS
        from openmdao.test_suite.components.double_sellar import DoubleSellar

        prob = Problem()
        model = prob.model = DoubleSellar()

        # each SubSellar group converges itself
        g1 = model.g1
        g1.nonlinear_solver = NewtonSolver()
        g1.linear_solver = DirectSolver()  # used for derivatives

        g2 = model.g2
        g2.nonlinear_solver = NewtonSolver()
        g2.linear_solver = DirectSolver()

        # Converge the outer loop with Gauss Seidel, with a looser tolerance.
        model.nonlinear_solver = NonlinearBlockGS(rtol=1.0e-5)
        model.linear_solver = ScipyKrylov()
        model.linear_solver.precon = LinearBlockGS()

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['g1.y1'], 0.64, .00001)
        assert_rel_error(self, prob['g1.y2'], 0.80, .00001)
        assert_rel_error(self, prob['g2.y1'], 0.64, .00001)
        assert_rel_error(self, prob['g2.y2'], 0.80, .00001)
Пример #20
0
    def test_hierarchy_iprint3(self):

        prob = Problem()
        model = prob.model

        model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])))

        sub1 = model.add_subsystem('sub1', Group())
        sub2 = sub1.add_subsystem('sub2', Group())
        g1 = sub2.add_subsystem('g1', SubSellar())
        g2 = model.add_subsystem('g2', SubSellar())

        model.connect('pz.z', 'sub1.sub2.g1.z')
        model.connect('sub1.sub2.g1.y2', 'g2.x')
        model.connect('g2.y2', 'sub1.sub2.g1.x')

        model.nonlinear_solver = NonlinearBlockJac()
        sub1.nonlinear_solver = NonlinearBlockJac()
        sub2.nonlinear_solver = NonlinearBlockJac()
        g1.nonlinear_solver = NonlinearBlockJac()
        g2.nonlinear_solver = NonlinearBlockJac()

        prob.set_solver_print(level=2)

        prob.setup(check=False)

        output = run_model(prob)
Пример #21
0
    def test_src_indices_error(self):
        size = 3
        group = Group()
        group.add('P', IndepVarComp('x', numpy.ones(size)))
        group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size,
                                        x=numpy.zeros(size),
                                        y=numpy.zeros(size)))
        group.add('C2', ExecComp(['z=3.0*y'],
                                 y=numpy.zeros(size),
                                 z=numpy.zeros(size)))

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('P.x', 'C1.x')
        prob.root.connect('C1.y', 'C2.y')

        prob.driver.add_desvar('P.x')
        prob.driver.add_objective('C1.y')

        try:
            prob.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err), "'C1.y' is a distributed variable"
                                       " and may not be used as a design var,"
                                       " objective, or constraint.")
        else:
            if MPI:
                self.fail("Exception expected")
Пример #22
0
    def test_check_totals_calls_run_once(self):
        prob = Problem()
        root = prob.root = Group()
        root.add('p1', IndepVarComp('x', 1.0), promotes=['*'])
        root.add('p2', IndepVarComp('y', 1.0), promotes=['*'])
        root.add('comp', Paraboloid(), promotes=['*'])

        prob.driver.add_desvar('x')
        prob.driver.add_desvar('y')
        prob.driver.add_objective('f_xy')

        prob.setup(check=False)

        prob['x'] = 5.0
        prob['y'] = 2.0

        iostream = StringIO()

        data = prob.check_total_derivatives(out_stream=iostream)

        self.assertAlmostEqual(first=prob["f_xy"],
                               second= (prob['x']-3.0)**2 \
                                       + prob['x']*prob['y'] \
                                       + (prob['y']+4.0)**2 - 3.0,
                               places=5,
                               msg="check partial derivatives did not call"
                                   "run_once on the driver as expected.")

        self.assertEqual(first=iostream.getvalue()[:39],
                         second="Executing model to populate unknowns...",
                         msg="check partial derivatives failed to run driver once")
Пример #23
0
    def test_mult_conns(self):

        class SubGroup(Group):
            def setup(self):
                self.add_subsystem('c1', ExecComp('y = 2*x', x=np.ones(4), y=2*np.ones(4)),
                                   promotes=['y', 'x'])
                self.add_subsystem('c2', ExecComp('z = 2*y', y=np.ones(4), z=2*np.ones(4)),
                                   promotes=['z', 'y'])

        prob = Problem()
        indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*'])
        indeps.add_output('x', 10*np.ones(4))
        indeps.add_output('y', np.ones(4))

        prob.model.add_subsystem('sub', SubGroup())

        prob.model.connect('x', 'sub.x')
        prob.model.connect('y', 'sub.y')

        with self.assertRaises(Exception) as context:
            prob.setup()

        self.assertEqual(str(context.exception),
                         "The following inputs have multiple connections: "
                         "sub.c2.y from ['indeps.y', 'sub.c1.y']")
Пример #24
0
class TestDeprecatedExternalCode(unittest.TestCase):

    def setUp(self):
        self.startdir = os.getcwd()
        self.tempdir = tempfile.mkdtemp(prefix='test_extcode-')
        os.chdir(self.tempdir)
        shutil.copy(os.path.join(DIRECTORY, 'extcode_example.py'),
                    os.path.join(self.tempdir, 'extcode_example.py'))

        msg = "'ExternalCode' has been deprecated. Use 'ExternalCodeComp' instead."

        with assert_warning(DeprecationWarning, msg):
            self.extcode = DeprecatedExternalCodeForTesting()

        self.prob = Problem()

        self.prob.model.add_subsystem('extcode', self.extcode)

    def tearDown(self):
        os.chdir(self.startdir)
        try:
            shutil.rmtree(self.tempdir)
        except OSError:
            pass

    def test_normal(self):
        self.extcode.options['command'] = [
            'python', 'extcode_example.py', 'extcode.out'
        ]

        self.extcode.options['external_input_files'] = ['extcode_example.py']
        self.extcode.options['external_output_files'] = ['extcode.out']

        self.prob.setup(check=True)
        self.prob.run_model()
Пример #25
0
    def test_parab_FD(self):

        model = Problem(impl=impl)
        root = model.root = Group()
        par = root.add('par', ParallelGroup())

        par.add('c1', Parab1D(root=2.0))
        par.add('c2', Parab1D(root=3.0))

        root.add('p1', IndepVarComp('x', val=0.0))
        root.add('p2', IndepVarComp('x', val=0.0))
        root.connect('p1.x', 'par.c1.x')
        root.connect('p2.x', 'par.c2.x')

        root.add('sumcomp', ExecComp('sum = x1+x2'))
        root.connect('par.c1.y', 'sumcomp.x1')
        root.connect('par.c2.y', 'sumcomp.x2')

        driver = model.driver = pyOptSparseDriver()
        driver.options['optimizer'] = OPTIMIZER
        driver.options['print_results'] = False
        driver.add_desvar('p1.x', lower=-100, upper=100)
        driver.add_desvar('p2.x', lower=-100, upper=100)
        driver.add_objective('sumcomp.sum')

        root.fd_options['force_fd'] = True

        model.setup(check=False)
        model.run()

        if not MPI or self.comm.rank == 0:
            assert_rel_error(self, model['p1.x'], 2.0, 1.e-6)
            assert_rel_error(self, model['p2.x'], 3.0, 1.e-6)
Пример #26
0
    def test_beam_tutorial_viewtree(self):

        top = Problem()
        top.root = BeamTutorial()

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'
        top.driver.options['tol'] = 1.0e-8
        top.driver.options['maxiter'] = 10000 #maximum number of solver iterations
        top.driver.options['disp'] = False

        #room length and width bounds
        top.driver.add_desvar('ivc_rlength.room_length', lower=5.0*12.0, upper=50.0*12.0) #domain: 1in <= length <= 50ft
        top.driver.add_desvar('ivc_rwidth.room_width', lower=5.0*12.0, upper=30.0*12.0) #domain: 1in <= width <= 30ft

        top.driver.add_objective('d_neg_area.neg_room_area') #minimize negative area (or maximize area)

        top.driver.add_constraint('d_len_minus_wid.length_minus_width', lower=0.0) #room_length >= room_width
        top.driver.add_constraint('d_deflection.deflection', lower=720.0) #deflection >= 720
        top.driver.add_constraint('d_bending.bending_stress_ratio', upper=0.5) #bending < 0.5
        top.driver.add_constraint('d_shear.shear_stress_ratio', upper=1.0/3.0) #shear < 1/3

        top.setup(check=False)
        from openmdao.api import view_tree
        view_tree(top, show_browser=False)
        import os.path

        self.assertTrue(os.path.isfile('partition_tree_n2.html'))
        os.remove('partition_tree_n2.html')
Пример #27
0
    def test_parallel_diamond(self):
        size = 3
        prob = Problem(Group(), impl=impl)
        root = prob.root
        root.add('P1', IndepVarComp('x', np.ones(size, float) * 1.1))
        G1 = root.add('G1', ParallelGroup())
        G1.add('C1', ABCDArrayComp(size))
        G1.add('C2', ABCDArrayComp(size))
        root.add('C3', ABCDArrayComp(size))

        root.connect('P1.x', 'G1.C1.a')
        root.connect('P1.x', 'G1.C2.b')
        root.connect('G1.C1.c', 'C3.a')
        root.connect('G1.C2.d', 'C3.b')

        prob.setup(check=False)
        prob.run()

        if not MPI or self.comm.rank == 0:
            assert_rel_error(self, prob.root.G1.C1.unknowns['c'],
                             np.ones(size)*2.1, 1.e-10)
            assert_rel_error(self, prob.root.G1.C1.unknowns['d'],
                             np.ones(size)*.1, 1.e-10)
            assert_rel_error(self, prob.root.C3.params['a'],
                             np.ones(size)*2.1, 1.e-10)
            assert_rel_error(self, prob.root.C3.params['b'],
                             np.ones(size)*-.1, 1.e-10)

        if not MPI or self.comm.rank == 1:
            assert_rel_error(self, prob.root.G1.C2.unknowns['c'],
                             np.ones(size)*2.1, 1.e-10)
            assert_rel_error(self, prob.root.G1.C2.unknowns['d'],
                             np.ones(size)*-.1, 1.e-10)
Пример #28
0
    def test_add_params(self):
        self.comp.add_param("x", 0.0)
        self.comp.add_param("y", 0.0)
        self.comp.add_param("z", shape=(1, ))
        self.comp.add_param("t", shape=2)
        self.comp.add_param("u", shape=1)

        # This should no longer raise an error
        self.comp.add_param("w")

        prob = Problem()
        self.comp._init_sys_data('', prob._probdata)
        params, unknowns = self.comp._setup_variables()

        self.assertEqual(["x", "y", "z", "t", "u", 'w'], list(params.keys()))

        self.assertEqual(params["x"], {'shape': 1, 'pathname': 'x', 'val': 0.0, 'size': 1})
        self.assertEqual(params["y"], {'shape': 1, 'pathname': 'y', 'val': 0.0, 'size': 1})
        np.testing.assert_array_equal(params["z"]["val"], np.zeros((1,)))
        np.testing.assert_array_equal(params["t"]["val"], np.zeros((2,)))
        self.assertEqual(params["u"], {'shape': 1, 'pathname': 'u', 'val': 0.0, 'size': 1})

        prob = Problem()
        root = prob.root = Group()
        root.add('comp', self.comp)

        with self.assertRaises(RuntimeError) as cm:
            prob.setup(check=False)

        self.assertEqual(str(cm.exception), "Unconnected param 'comp.w' is missing a shape or default value.")
Пример #29
0
    def test_simple(self):
        prob = Problem(Group(), impl=impl)

        size = 5
        A1 = prob.root.add('A1', IndepVarComp('a', np.zeros(size, float)))
        B1 = prob.root.add('B1', IndepVarComp('b', np.zeros(size, float)))
        B2 = prob.root.add('B2', IndepVarComp('b', np.zeros(size, float)))
        S1 = prob.root.add('S1', IndepVarComp('s', ''))
        L1 = prob.root.add('L1', IndepVarComp('l', []))

        C1 = prob.root.add('C1', ABCDArrayComp(size))
        C2 = prob.root.add('C2', ABCDArrayComp(size))

        prob.root.connect('A1.a', 'C1.a')
        prob.root.connect('B1.b', 'C1.b')
        # prob.root.connect('S1:s', 'C1.in_string')
        # prob.root.connect('L1:l', 'C1.in_list')

        prob.root.connect('C1.c', 'C2.a')
        prob.root.connect('B2.b', 'C2.b')
        # prob.root.connect('C1.out_string', 'C2.in_string')
        # prob.root.connect('C1.out_list',   'C2.in_list')

        prob.setup(check=False)

        prob['A1.a'] = np.ones(size, float) * 3.0
        prob['B1.b'] = np.ones(size, float) * 7.0
        prob['B2.b'] = np.ones(size, float) * 5.0

        prob.run()

        self.assertTrue(all(prob['C2.a'] == np.ones(size, float)*10.))
        self.assertTrue(all(prob['C2.b'] == np.ones(size, float)*5.))
        self.assertTrue(all(prob['C2.c'] == np.ones(size, float)*15.))
        self.assertTrue(all(prob['C2.d'] == np.ones(size, float)*5.))
Пример #30
0
    def runO(x):
        p = Problem()
        p.model.add_subsystem('hs', HeatSink(num_nodes=1))

        p.setup(check=False)

        p['hs.fin_gap'] = x[0]
        p['hs.fin_w'] = x[1]

        p.run_model()



        def printstuff():
            print('=============')
            print('V_in (m/s) : %f' %p['hs.V_in'])
            print('V_fin (m/s) : %f' %p['hs.V_fin'])
            print('Nu : %f' %p['hs.Nu'])
            print('Pr : %f' %p['hs.Pr'])
            print('Re : %f' %p['hs.Re'])
            print('fin height: %f' %p['hs.fin_h'])
            print('# of fins : %f' %p['hs.n_fins'])
            print('-------------')
            print('fin thickness (m): %f' % p['hs.fin_w'])
            print('fin gap (m): %f' % p['hs.fin_gap'])
            print('Volumetric Flow Rate (m^3/s): %f' % p['hs.V_dot'])
            print('Maximum thermal resistance (K/W): %f' %p['hs.R_max'])
            print('Actual total thermal resistance (K/W): %f' % p['hs.R_tot'])
            #print('Actual total thermal resistance1 (K/W): %f' % p['hs.R_tot1'])
            #print('h %f' % p['hs.h'])
            print('Pressure Drop (Pa): %f' % p['hs.dP'])
            print()
        printstuff()

        return np.array([p['hs.R_tot']*10000 + p['hs.dP']*1.4])