Esempio n. 1
0
def test_3level_type_multistart_XYZ_optimization():
    design_vars = {k: v for k, v in zip('xy', optimal.T)}
    design_vars['z'] = (optimal[:, 2], 0, 4)
    xyz_problem = TopFarmProblem(design_vars,
                                 cost_comp=DummyCost(optimal,
                                                     ['x', 'y', 'z', 'type']),
                                 constraints=[
                                     SpacingConstraint(2),
                                     XYBoundaryConstraint([(0, 0), (4, 4)],
                                                          'square')
                                 ],
                                 driver=EasyScipyOptimizeDriver(disp=False))

    initial_xyz_problem = TopFarmProblem(
        design_vars={k: v
                     for k, v in zip('xyz', optimal.T)},
        cost_comp=xyz_problem,
        driver=DOEDriver(
            ListGenerator([[('x', [0, 4]), ('y', [2, 2]), ('z', [4, 1])]])))

    tf = TopFarmProblem({'type': ([0, 0], 0, 1)},
                        cost_comp=initial_xyz_problem,
                        driver=DOEDriver(FullFactorialGenerator(2)))

    cost, _, recorder = tf.optimize()
    best_index = np.argmin(recorder.get('cost'))
    initial_xyz_recorder = recorder['recorder'][best_index]
    xyz_recorder = initial_xyz_recorder.get('recorder')[0]
    npt.assert_almost_equal(xyz_recorder['cost'][-1], cost)
Esempio n. 2
0
def test_design_var_list(turbineTypeOptimizationProblem, design_vars):
    tf = TopFarmProblem(design_vars=design_vars,
                        cost_comp=DummyCost(np.array([[2, 0, 1]]).T, ['type']),
                        driver=DOEDriver(FullFactorialGenerator(3)))
    cost, _, = tf.evaluate()
    npt.assert_equal(tf.cost, cost)
    assert tf.cost == 5
Esempio n. 3
0
def test_turbine_Type_multistart_XYZ_optimization():
    plot_comp = DummyCostPlotComp(optimal, delay=.5)
    plot_comp = NoPlot()
    xyz = [(0, 0, 0), (1, 1, 1)]

    p1 = DummyCost(optimal_state=optimal,
                   inputs=['x', 'y', 'z', 'type'])

    p2 = TurbineXYZOptimizationProblem(
        cost_comp=p1,
        turbineXYZ=xyz,
        min_spacing=2,
        boundary_comp=get_boundary_comp(),
        plot_comp=plot_comp,
        driver=EasyScipyOptimizeDriver(disp=True, optimizer='COBYLA', maxiter=10))
    p3 = InitialXYZOptimizationProblem(
        cost_comp=p2,
        turbineXYZ=xyz, min_spacing=2,
        boundary_comp=get_boundary_comp(),
        driver=DOEDriver(ListGenerator([[('x', [0, 4]), ('y', [2, 2]), ('z', [4, 1])]])))
    tf = TurbineTypeOptimizationProblem(
        cost_comp=p3,
        turbineTypes=[0, 0], lower=0, upper=1,
        driver=DOEDriver(FullFactorialGenerator(1)))

    case_gen = tf.driver.options['generator']
    cost, state, recorder = tf.optimize()
    print(cost)
    # print (state)
    print(recorder.get('type'))
    print(recorder.get('cost'))
    best_index = np.argmin(recorder.get('cost'))
    initial_xyz_recorder = recorder['recorder'][best_index]
    xyz_recorder = initial_xyz_recorder.get('recorder')[0]
    npt.assert_almost_equal(xyz_recorder['cost'][-1], cost)
Esempio n. 4
0
def turbineTypeOptimizationProblem():
    return TurbineTypeOptimizationProblem(
        TurbineTypeDummyCost([2, 0, 1]),
        turbineTypes=[0, 0, 0],
        lower=[0, 0, 0],
        upper=[2, 2, 2],
        driver=DOEDriver(FullFactorialGenerator(3)))
Esempio n. 5
0
    def test_full_factorial_array(self):
        prob = Problem()
        model = prob.model

        model.add_subsystem('p1',
                            IndepVarComp('xy', np.array([0., 0.])),
                            promotes=['*'])
        model.add_subsystem('comp', ParaboloidArray(), promotes=['*'])

        model.add_design_var('xy',
                             lower=np.array([-50., -50.]),
                             upper=np.array([50., 50.]))
        model.add_objective('f_xy')

        prob.driver = DOEDriver(FullFactorialGenerator(levels=3))
        prob.driver.add_recorder(SqliteRecorder("cases.sql"))

        prob.setup(check=False)
        prob.run_driver()
        prob.cleanup()

        expected = {
            0: {
                'xy': np.array([-50., -50.])
            },
            1: {
                'xy': np.array([0., -50.])
            },
            2: {
                'xy': np.array([50., -50.])
            },
            3: {
                'xy': np.array([-50., 0.])
            },
            4: {
                'xy': np.array([0., 0.])
            },
            5: {
                'xy': np.array([50., 0.])
            },
            6: {
                'xy': np.array([-50., 50.])
            },
            7: {
                'xy': np.array([0., 50.])
            },
            8: {
                'xy': np.array([50., 50.])
            },
        }

        cases = CaseReader("cases.sql").driver_cases

        self.assertEqual(cases.num_cases, 9)

        for n in range(cases.num_cases):
            outputs = cases.get_case(n).outputs
            self.assertEqual(outputs['xy'][0], expected[n]['xy'][0])
            self.assertEqual(outputs['xy'][1], expected[n]['xy'][1])
Esempio n. 6
0
    def test_full_factorial(self):
        prob = Problem()
        model = prob.model

        model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x'])
        model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y'])
        model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])

        model.add_design_var('x', lower=0.0, upper=1.0)
        model.add_design_var('y', lower=0.0, upper=1.0)
        model.add_objective('f_xy')

        prob.driver = DOEDriver(FullFactorialGenerator(levels=3), parallel=True)
        prob.driver.add_recorder(SqliteRecorder("CASES.db"))

        prob.setup()

        failed, output = run_driver(prob)
        self.assertFalse(failed)

        prob.cleanup()

        expected = {
            0: {'x': np.array([0.]), 'y': np.array([0.]), 'f_xy': np.array([22.00])},
            1: {'x': np.array([.5]), 'y': np.array([0.]), 'f_xy': np.array([19.25])},
            2: {'x': np.array([1.]), 'y': np.array([0.]), 'f_xy': np.array([17.00])},

            3: {'x': np.array([0.]), 'y': np.array([.5]), 'f_xy': np.array([26.25])},
            4: {'x': np.array([.5]), 'y': np.array([.5]), 'f_xy': np.array([23.75])},
            5: {'x': np.array([1.]), 'y': np.array([.5]), 'f_xy': np.array([21.75])},

            6: {'x': np.array([0.]), 'y': np.array([1.]), 'f_xy': np.array([31.00])},
            7: {'x': np.array([.5]), 'y': np.array([1.]), 'f_xy': np.array([28.75])},
            8: {'x': np.array([1.]), 'y': np.array([1.]), 'f_xy': np.array([27.00])},
        }

        size = prob.comm.size
        rank = prob.comm.rank

        # cases will be split across files for each proc
        filename = "CASES.db_%d" % rank

        expect_msg = "Cases from rank %d are being written to %s." % (rank, filename)
        self.assertTrue(expect_msg in output)

        cases = CaseReader(filename).driver_cases

        # cases recorded on this proc
        num_cases = cases.num_cases
        self.assertEqual(num_cases, len(expected)//size+(rank<len(expected)%size))

        for n in range(num_cases):
            case = cases.get_case(n)
            idx = n * size + rank  # index of expected case

            self.assertEqual(cases.get_case(n).outputs['x'], expected[idx]['x'])
            self.assertEqual(cases.get_case(n).outputs['y'], expected[idx]['y'])
            self.assertEqual(cases.get_case(n).outputs['f_xy'], expected[idx]['f_xy'])
def test_turbineType_optimization():
    optimal = np.array([[1], [0]])
    tf = TopFarmProblem(design_vars={'type': (optimal[:, 0], 0, 1)},
                        cost_comp=DummyCost(optimal_state=optimal,
                                            inputs=['type']),
                        driver=DOEDriver(FullFactorialGenerator(2)))
    cost, state, _ = tf.optimize()
    assert cost == 0
    npt.assert_array_equal(state['type'], [1, 0])
def test_turbineType_optimization():
    cost_comp = DummyCost(optimal_state=optimal, inputs=['type'])
    tf = TurbineTypeOptimizationProblem(cost_comp=cost_comp,
                                        turbineTypes=[0, 0],
                                        lower=0,
                                        upper=1,
                                        driver=DOEDriver(
                                            FullFactorialGenerator(2)))
    cost, state, _ = tf.optimize()
    assert cost == 0
    npt.assert_array_equal(state['type'], [1, 0])
def main():
    if __name__ == '__main__':
        # ------------------------ INPUTS ------------------------

        # define the conditions for the wind farm
        positions = np.array([[0, 0], [6, 6]])  # initial turbine pos
        optimal_types = np.array([[2], [6]])  # optimal layout

        # ===============================================================================
        # Setup the problem and plotting
        # ===============================================================================

        try:
            import matplotlib.pyplot as plt
            plt.gcf()
            plot_comp = TurbineTypePlotComponent(
                turbine_type_names=["Turbine %d" % i for i in range(5)],
                plot_initial=False,
                delay=0.1,
                legendloc=0)
            plot = True
        except RuntimeError:
            plot_comp = NoPlot()
            plot = False

        # create the wind farm
        tf = TopFarmProblem(
            design_vars={'type': ([0, 0], 0, 4)},
            cost_comp=DummyCost(optimal_types, ['type']),
            plot_comp=plot_comp,
            driver=FullFactorialGenerator(5),
            ext_vars={
                'x': positions[:, 0],
                'y': positions[:, 1]
            },
        )

        # ===============================================================================
        # #  Run the optimization
        # ===============================================================================
        state = {}
        cost, state, recorder = tf.optimize(state)

        # ===============================================================================
        # plot and prin the the final, optimal types
        # ===============================================================================
        print(state['type'])
        tf.evaluate(state)

        # save the figure
        if plot:
            folder, file = os.path.split(__file__)
            plt.savefig(folder + "/figures/" + file.replace('.py', '.png'))
            plt.show()
Esempio n. 10
0
    def test_full_factorial(self):
        from openmdao.api import Problem, IndepVarComp
        from openmdao.test_suite.components.paraboloid import Paraboloid

        from openmdao.api import DOEDriver, FullFactorialGenerator
        from openmdao.api import SqliteRecorder, CaseReader

        from mpi4py import MPI

        prob = Problem()
        model = prob.model

        model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x'])
        model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y'])
        model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])

        model.add_design_var('x', lower=0.0, upper=1.0)
        model.add_design_var('y', lower=0.0, upper=1.0)
        model.add_objective('f_xy')

        prob.driver = DOEDriver(FullFactorialGenerator(levels=3))
        prob.driver.options['parallel'] = True

        prob.driver.add_recorder(SqliteRecorder("cases.sql"))

        prob.setup()
        prob.run_driver()
        prob.cleanup()

        self.assertEqual(MPI.COMM_WORLD.size, 2)

        # check recorded cases from each case file
        rank = MPI.COMM_WORLD.rank
        filename = "cases.sql_%d" % rank
        self.assertEqual(filename, "cases.sql_%d" % rank)

        cases = CaseReader(filename).driver_cases
        self.assertEqual(cases.num_cases, 5 if rank == 0 else 4)

        values = []
        for n in range(cases.num_cases):
            outputs = cases.get_case(n).outputs
            values.append((outputs['x'], outputs['y'], outputs['f_xy']))

        self.assertEqual(
            "\n" + "\n".join([
                "x: %5.2f, y: %5.2f, f_xy: %6.2f" % (x, y, f_xy)
                for x, y, f_xy in values
            ]), self.expect_text)
Esempio n. 11
0
    def test_indivisable_error(self):
        prob = Problem()

        prob.driver = DOEDriver(FullFactorialGenerator(levels=3))
        prob.driver.options['parallel'] = 3

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

        self.assertEqual(
            str(context.exception),
            "The number of processors is not evenly divisable by the "
            "specified number of parallel cases.\n Provide a number of "
            "processors that is a multiple of 3, or specify a number "
            "of parallel cases that divides into 4.")
Esempio n. 12
0
def test_2level_turbineType_and_XYZ_optimization():
    design_vars = {k: v for k, v in zip('xy', optimal.T)}
    design_vars['z'] = (optimal[:, 2], 0, 4)
    xyz_problem = TopFarmProblem(design_vars,
                                 cost_comp=DummyCost(optimal,
                                                     ['x', 'y', 'z', 'type']),
                                 constraints=[
                                     SpacingConstraint(2),
                                     XYBoundaryConstraint([(0, 0), (4, 4)],
                                                          'square')
                                 ],
                                 driver=EasyScipyOptimizeDriver(disp=False))
    tf = TopFarmProblem({'type': ([0, 0], 0, 1)},
                        cost_comp=xyz_problem,
                        driver=DOEDriver(FullFactorialGenerator(2)))
    cost = tf.optimize()[0]
    assert cost == 0
Esempio n. 13
0
    def test_minprocs_error(self):
        prob = Problem(FanInGrouped())

        # require 2 procs for the ParallelGroup
        prob.model._proc_info['sub'] = (2, None, 1.0)

        # run cases on all procs
        prob.driver = DOEDriver(FullFactorialGenerator(levels=3))
        prob.driver.options['parallel'] = True

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

        self.assertEqual(
            str(context.exception),
            ": MPI process allocation failed: can't meet min_procs "
            "required for the following subsystems: ['sub']")
Esempio n. 14
0
    def test_fan_in_grouped(self):
        from openmdao.api import Problem
        from openmdao.test_suite.groups.parallel_groups import FanInGrouped

        from openmdao.api import DOEDriver, FullFactorialGenerator
        from openmdao.api import SqliteRecorder, CaseReader

        from mpi4py import MPI

        prob = Problem(FanInGrouped())
        model = prob.model

        model.add_design_var('iv.x1', lower=0.0, upper=1.0)
        model.add_design_var('iv.x2', lower=0.0, upper=1.0)

        model.add_objective('c3.y')

        prob.driver = DOEDriver(FullFactorialGenerator(levels=3))
        prob.driver.add_recorder(SqliteRecorder("cases.sql"))

        # run 2 cases at a time, each using 2 of our 4 procs
        doe_parallel = prob.driver.options['parallel'] = 2

        prob.setup()
        prob.run_driver()
        prob.cleanup()

        rank = MPI.COMM_WORLD.rank

        # check recorded cases from each case file
        if rank < doe_parallel:
            filename = "cases.sql_%d" % rank

            cases = CaseReader(filename).driver_cases

            values = []
            for n in range(cases.num_cases):
                outputs = cases.get_case(n).outputs
                values.append(
                    (outputs['iv.x1'], outputs['iv.x2'], outputs['c3.y']))

            self.assertEqual(
                "\n" + "\n".join([
                    "iv.x1: %5.2f, iv.x2: %5.2f, c3.y: %6.2f" % (x1, x2, y)
                    for x1, x2, y in values
                ]), self.expect_text)
Esempio n. 15
0
def test_turbineType_and_XYZ_optimization():
    plot_comp = DummyCostPlotComp(optimal)
    plot_comp = NoPlot()
    cost_comp = DummyCost(
        optimal_state=optimal,
        inputs=['x', 'y', 'z', 'type'])
    xyz_opt_problem = TurbineXYZOptimizationProblem(
        cost_comp,
        turbineXYZ=[(0, 0, 0), (1, 1, 1)],
        min_spacing=2,
        boundary_comp=get_boundary_comp(),
        plot_comp=plot_comp,
        driver=EasyScipyOptimizeDriver(disp=False))
    tf = TurbineTypeOptimizationProblem(
        cost_comp=xyz_opt_problem,
        turbineTypes=[0, 0], lower=0, upper=1,
        driver=DOEDriver(FullFactorialGenerator(2)))
    cost = tf.optimize()[0]
    npt.assert_almost_equal(cost, 0)
Esempio n. 16
0
    def test_full_factorial(self):
        prob = Problem()
        model = prob.model

        model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x'])
        model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y'])
        model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])

        model.add_design_var('x', lower=0.0, upper=1.0)
        model.add_design_var('y', lower=0.0, upper=1.0)
        model.add_objective('f_xy')

        prob.driver = DOEDriver(generator=FullFactorialGenerator(levels=3))
        prob.driver.add_recorder(SqliteRecorder("CASES.db"))

        prob.setup(check=False)
        prob.run_driver()
        prob.cleanup()

        expected = {
            0: {'x': np.array([0.]), 'y': np.array([0.]), 'f_xy': np.array([22.00])},
            1: {'x': np.array([.5]), 'y': np.array([0.]), 'f_xy': np.array([19.25])},
            2: {'x': np.array([1.]), 'y': np.array([0.]), 'f_xy': np.array([17.00])},

            3: {'x': np.array([0.]), 'y': np.array([.5]), 'f_xy': np.array([26.25])},
            4: {'x': np.array([.5]), 'y': np.array([.5]), 'f_xy': np.array([23.75])},
            5: {'x': np.array([1.]), 'y': np.array([.5]), 'f_xy': np.array([21.75])},

            6: {'x': np.array([0.]), 'y': np.array([1.]), 'f_xy': np.array([31.00])},
            7: {'x': np.array([.5]), 'y': np.array([1.]), 'f_xy': np.array([28.75])},
            8: {'x': np.array([1.]), 'y': np.array([1.]), 'f_xy': np.array([27.00])},
        }

        cases = CaseReader("CASES.db").driver_cases

        self.assertEqual(cases.num_cases, 9)

        for n in range(cases.num_cases):
            self.assertEqual(cases.get_case(n).outputs['x'], expected[n]['x'])
            self.assertEqual(cases.get_case(n).outputs['y'], expected[n]['y'])
            self.assertEqual(cases.get_case(n).outputs['f_xy'], expected[n]['f_xy'])
Esempio n. 17
0
def turbineTypeOptimizationProblem():
    return TopFarmProblem(
        design_vars={'type': ([0, 0, 0], 0, 2)},
        cost_comp=DummyCost(np.array([[2, 0, 1]]).T, ['type']),
        driver=DOEDriver(FullFactorialGenerator(3)))
Esempio n. 18
0
    def test_fan_in_grouped_serial(self):
        # run cases on all procs (parallel model will run on single proc)
        doe_parallel = True

        prob = Problem(FanInGrouped())
        model = prob.model

        model.add_design_var('iv.x1', lower=0.0, upper=1.0)
        model.add_design_var('iv.x2', lower=0.0, upper=1.0)

        model.add_objective('c3.y')

        prob.driver = DOEDriver(FullFactorialGenerator(levels=3))
        prob.driver.add_recorder(SqliteRecorder("cases.sql"))
        prob.driver.options['parallel'] = doe_parallel

        prob.setup(check=False)

        failed, output = run_driver(prob)
        self.assertFalse(failed)

        prob.cleanup()

        expected = {
            0: {
                'iv.x1': np.array([0.]),
                'iv.x2': np.array([0.]),
                'c3.y': np.array([0.0])
            },
            1: {
                'iv.x1': np.array([.5]),
                'iv.x2': np.array([0.]),
                'c3.y': np.array([-3.0])
            },
            2: {
                'iv.x1': np.array([1.]),
                'iv.x2': np.array([0.]),
                'c3.y': np.array([-6.0])
            },
            3: {
                'iv.x1': np.array([0.]),
                'iv.x2': np.array([.5]),
                'c3.y': np.array([17.5])
            },
            4: {
                'iv.x1': np.array([.5]),
                'iv.x2': np.array([.5]),
                'c3.y': np.array([14.5])
            },
            5: {
                'iv.x1': np.array([1.]),
                'iv.x2': np.array([.5]),
                'c3.y': np.array([11.5])
            },
            6: {
                'iv.x1': np.array([0.]),
                'iv.x2': np.array([1.]),
                'c3.y': np.array([35.0])
            },
            7: {
                'iv.x1': np.array([.5]),
                'iv.x2': np.array([1.]),
                'c3.y': np.array([32.0])
            },
            8: {
                'iv.x1': np.array([1.]),
                'iv.x2': np.array([1.]),
                'c3.y': np.array([29.0])
            },
        }

        rank = prob.comm.rank
        size = prob.comm.size // doe_parallel

        num_cases = 0

        # cases will be split across files for each proc up to the number requested
        filename = "cases.sql_%d" % rank

        expect_msg = "Cases from rank %d are being written to %s." % (rank,
                                                                      filename)
        self.assertTrue(expect_msg in output)

        cases = CaseReader(filename).driver_cases

        # cases recorded on this proc
        num_cases = cases.num_cases
        self.assertEqual(num_cases,
                         len(expected) // size + (rank < len(expected) % size))

        for n in range(num_cases):
            idx = n * size + rank  # index of expected case

            outputs = cases.get_case(n).outputs

            self.assertEqual(outputs['iv.x1'], expected[idx]['iv.x1'])
            self.assertEqual(outputs['iv.x2'], expected[idx]['iv.x2'])
            self.assertEqual(outputs['c3.y'], expected[idx]['c3.y'])

        # total number of cases recorded across all requested procs
        num_cases = prob.comm.allgather(num_cases)
        self.assertEqual(sum(num_cases), len(expected))