Exemple #1
0
def test_TopFarmListRecorder_continue_wrong_recorder(tf_generator):

    tf = TopFarmProblem({'type': ([0, 0, 0], 0, 1)},
                        cost_comp=DummyCost(np.array([[0, 1, 0]]).T, ['type']),
                        driver=EasyScipyOptimizeDriver(disp=False),
                        record_id=tfp +
                        'recordings/test_TopFarmListRecorder_continue:latest')

    tf.optimize()
    assert 'type' in tf.recorder.keys()
    assert 'x' not in tf.recorder.keys()
def main():
    if __name__ == '__main__':
        n_wt = 16
        site = IEA37Site(n_wt)
        windTurbines = IEA37_WindTurbines()
        windFarmModel = IEA37SimpleBastankhahGaussian(site, windTurbines)
        tf = TopFarmProblem(
            design_vars=dict(zip('xy', site.initial_position.T)),
            cost_comp=PyWakeAEPCostModelComponent(windFarmModel, n_wt),
            driver=EasyRandomSearchDriver(
                randomize_func=RandomizeTurbinePosition_Circle(), max_iter=5),
            constraints=[CircleBoundaryConstraint([0, 0], 1300.1)],
            plot_comp=XYPlotComp())
        tf.optimize()
        tf.plot_comp.show()
Exemple #3
0
def testAEP_topfarm_optimization_2tb_scale(get_fuga, scale):
    D = 80.0
    B = 2 * D + 10
    init_pos = np.array([(-10, 1 * D), (10, -D)])

    wind_atlas = 'MyFarm/north_pm30_only.lib'
    pyFuga = get_fuga(init_pos[:1, 0], init_pos[:1, 1], wind_atlas=wind_atlas)
    AEP_pr_tb = pyFuga.get_aep()[1]
    pyFuga = get_fuga(init_pos[:, 0], init_pos[:, 1], wind_atlas=wind_atlas)
    boundary = [(-B, B), (B, B), (B, -B), (-B, -B), (-B, B)]

    plot_comp = NoPlot()
    # plot_comp = PlotComp()

    cost_comp = AEPCostModelComponent(
        'xy',
        init_pos.shape[0],
        lambda x, y: scale * pyFuga.get_aep(np.array([x, y]).T)[0],  # only aep
        lambda x, y: scale * pyFuga.get_aep_gradients(np.array([x, y]).T)[:2]
    )  # only dAEPdx and dAEPdy

    tf = TopFarmProblem(
        dict(zip('xy', init_pos.T)),
        cost_comp,
        constraints=[SpacingConstraint(2 * D),
                     XYBoundaryConstraint(boundary)],
        plot_comp=plot_comp,
        driver=EasyScipyOptimizeDriver(tol=1e-8, disp=False),
        expected_cost=AEP_pr_tb * 2 * scale)
    cost, _, rec = tf.optimize()
    tf.plot_comp.show()
    uta.assertAlmostEqual(-cost / scale, AEP_pr_tb * 2, delta=.02)
Exemple #4
0
def test_TopFarmListRecorder_continue(tf_generator, load_case, n_rec, n_fev):

    D = 80.0
    D2 = 2 * D + 10
    init_pos = np.array([(0, 2 * D), (0, 0), (0, -2 * D)])
    init_pos[:, 0] += [-40, 0, 40]

    pyFuga = test_pyfuga.get_fuga()(init_pos[:, 0],
                                    init_pos[:, 1],
                                    wind_atlas='MyFarm/north_pm45_only.lib')
    boundary = [(-D2, -D2), (D2, D2)]
    plot_comp = XYPlotComp()
    plot_comp = NoPlot()
    tf = TopFarmProblem(
        dict(zip('xy', init_pos.T)),
        cost_comp=pyFuga.get_TopFarm_cost_component(),
        constraints=[
            SpacingConstraint(2 * D),
            XYBoundaryConstraint(boundary, 'square')
        ],
        driver=EasyScipyOptimizeDriver(tol=1e-10, disp=False),
        plot_comp=plot_comp,
        record_id=tfp +
        'recordings/test_TopFarmListRecorder_continue:%s' % load_case,
        expected_cost=25)

    _, _, recorder = tf.optimize()
    # Create test file:
    # 1) delete file "test_files/recordings/test_TopFarmListRecorder_continue"
    # 2) Uncomment line below, run and recomment
    # if load_case=="": recorder.save() # create test file
    npt.assert_equal(recorder.driver_cases.num_cases, n_rec)
    npt.assert_equal(tf.driver.result['nfev'], n_fev)

    tf.plot_comp.show()
Exemple #5
0
def main():
    if __name__ == '__main__':
        site = IEA37Site(16)
        windTurbines = IEA37_WindTurbines()
        wake_model = IEA37SimpleBastankhahGaussian(windTurbines)
        aep_calc = PyWakeAEP(site, windTurbines, wake_model)
        tf = TopFarmProblem(
            design_vars=dict(zip('xy', site.initial_position.T)),
            cost_comp=aep_calc.get_TopFarm_cost_component(16),
            driver=EasyRandomSearchDriver(
                randomize_func=RandomizeTurbinePosition_Circle(), max_iter=5),
            constraints=[CircleBoundaryConstraint([0, 0], 1300.1)],
            plot_comp=XYPlotComp())
        # tf.evaluate()
        tf.optimize()
        tf.plot_comp.show()
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_TopFarmProblem_with_cirleboundary_constraint():
    optimal = np.array([(0, 0)])
    desvar = dict(zip('xy', optimal.T))

    b = CircleBoundaryConstraint([2, 2], 2)
    tf = TopFarmProblem(desvar, DummyCost(optimal, 'xy'), constraints=[b])
    _, state, _ = tf.optimize()

    npt.assert_array_less((state['x'] - 2)**2 + (state['y'] - 2)**2, 9)
def test_TopFarmProblem_with_cirleboundary_constraint_and_limits():
    optimal = np.array([(0, 0)])
    desvar = {'x': ([0], 1, 4), 'y': [0]}

    b = CircleBoundaryConstraint([2, 2], 2)
    tf = TopFarmProblem(desvar, DummyCost(optimal, 'xy'), constraints=[b])
    _, state, _ = tf.optimize()

    npt.assert_array_less((state['x'] - 2)**2 + (state['y'] - 2)**2, 9)
    npt.assert_array_less(.9999999, state['x'])
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()
Exemple #10
0
def main():
    if __name__ == '__main__':
        # define the conditions for the wind farm
        boundary = [(0, 0), (6, 0), (6, -10), (0, -10)]  # turbine boundaries
        initial = np.array([[6, 0], [6, -8], [1, 1], [-1, -8]])  # initial turbine pos
        desired = np.array([[3, -3], [7, -7], [4, -3], [3, -7]])  # desired turbine pos
        optimal = np.array([[2.5, -3], [6, -7], [4.5, -3], [3, -7]])  # optimal layout
        min_spacing = 2  # min distance between turbines

        # ------------------------ OPTIMIZATION ------------------------

        # create the wind farm and run the optimization

        def wt_cost(i, x, y):
            time.sleep(0.01)
            return (desired[i, 0] - x[i])**2 + (desired[i, 1] - y[i])**2

        n_wt = len(initial)
        comps = [CostModelComponent('xy', 4,
                                    cost_function=lambda x, y, i=i:wt_cost(i, x, y),
                                    objective=False,
                                    output_key='cost%d' % i) for i in range(n_wt)]

        def sum_map(**kwargs):

            return np.sum([kwargs['cost%d' % i] for i in range(n_wt)])

        comps.append(CostModelComponent(['cost%d' % i for i in range(n_wt)], 1,
                                        cost_function=sum_map,
                                        objective=True))
        cost_comp = TopFarmParallelGroup(comps)

        tf = TopFarmProblem(
            design_vars={'x': initial[:, 0], 'y': initial[:, 1]},
            cost_comp=cost_comp,
            constraints=[XYBoundaryConstraint(boundary),
                         SpacingConstraint(min_spacing)],
#            plot_comp=DummyCostPlotComp(desired),
            plot_comp=NoPlot(),
            driver=EasyScipyOptimizeDriver()
        )
#        view_model(tf)
        #print(tf.evaluate({'x': desired[:, 0], 'y': desired[:, 1]}))
        print(tf.evaluate({'x': optimal[:, 0], 'y': optimal[:, 1]}, disp=False))
        #print(tf.evaluate({'x': initial[:, 0], 'y': initial[:, 1]}))
#        tic = time.time()
        cost, state, recorder = tf.optimize()
#        toc = time.time()
#        print('optimized in {:.3f}s '.format(toc-tic))
        tf.plot_comp.show()
Exemple #11
0
def test_NestedTopFarmListRecorder(tf_generator):
    optimal = [(0, 2, 4, 1), (4, 2, 1, 0)]
    type_lst = [[0, 0], [1, 0], [0, 1]]
    p1 = DummyCost(optimal_state=optimal, inputs=['x', 'y', 'z', 'type'])
    p2 = tf_generator(cost_comp=p1, driver=EasyScipyOptimizeDriver(disp=False))

    tf = TopFarmProblem({'type': ([0, 0], 0, 1)},
                        cost_comp=p2,
                        driver=DOEDriver(
                            ListGenerator([[('type', t)] for t in type_lst])))

    cost, _, recorder = tf.optimize()
    npt.assert_almost_equal(cost, 0)
    npt.assert_array_almost_equal(recorder.get('type'), type_lst)
    npt.assert_array_almost_equal(recorder.get('cost'), [1, 0, 2])

    for sub_rec in recorder.get('recorder'):
        npt.assert_array_almost_equal(
            np.array([sub_rec[k][-1] for k in ['x', 'y', 'z']]).T,
            np.array(optimal)[:, :3])
def test_turbineXYZ_optimization():
    optimal = np.array([(5, 4, 3), (3, 2, 1)])
    turbineXYZ = np.array([[0, 0, 0], [2, 2, 2]])
    design_vars = {k: v for k, v in zip('xy', turbineXYZ.T)}
    design_vars['z'] = (turbineXYZ[:, 2], 1, 4)

    xy_boundary = [(0, 0), (5, 5)]
    tf = TopFarmProblem(
        design_vars=design_vars,
        cost_comp=DummyCost(optimal, 'xyz'),
        driver=EasyScipyOptimizeDriver(disp=False),
        constraints=[XYBoundaryConstraint(xy_boundary, 'square')])

    cost, state = tf.evaluate()
    assert cost == 52
    np.testing.assert_array_equal(state['x'], [0, 2])

    cost = tf.optimize()[0]
    assert cost < 1e6
    np.testing.assert_array_almost_equal(tf.turbine_positions, optimal[:, :2],
                                         3)
Exemple #13
0
def test_random_search_driver_randomize_all_uniform():
    np.random.seed(1)

    class Cost():
        i = 0

        def __call__(self, *args, **kwargs):
            self.i += 1
            return self.i

    cost_comp = CostModelComponent(input_keys=['x', 'y', 'type'],
                                   n_wt=2,
                                   cost_function=Cost(),
                                   income_model=True)

    tf = TopFarmProblem(
        {
            'x': ([1, 6], [0, 1], [5, 6]),
            'y': ([-1., 0], -6, 0),
            'type': ([3, 3], 3, 8)
        },
        cost_comp=cost_comp,
        constraints=[],
        driver=EasyRandomSearchDriver(randomize_func=RandomizeAllUniform(
            ['x', 'type']),
                                      max_iter=600,
                                      disp=False),
    )
    _, state, recorder = tf.optimize()

    # check that integer design variables are somewhat evenly distributed
    x, y, t = recorder['x'], recorder['y'], recorder['type']
    for arr, l, u in [(x[:, 0], 0, 5), (x[:, 1], 1, 6), (t[:, 0], 3, 8)]:
        count = [(arr == i).sum() for i in range(l, u + 1)]
        npt.assert_equal(601, sum(count))
        npt.assert_array_less(600 / len(count) * .70, count)

    count, _ = np.histogram(y[:, 0], np.arange(-6, 1))
    npt.assert_equal(y.shape[0], sum(count))
    npt.assert_array_less(600 / len(count) * .70, count)
Exemple #14
0
def test_random_search_driver_type_and_position(topfarm_generator):
    np.random.seed(1)

    tf = TopFarmProblem(
        {
            'x': [1, 6, 6],
            'y': [1, 0, -8],
            'type': ([0, 0, 0], 0, 3)
        },
        cost_comp=DummyCost(desired, ['x', 'y', 'type']),
        constraints=[SpacingConstraint(1),
                     XYBoundaryConstraint(boundary)],
        driver=EasyRandomSearchDriver(
            randomize_func=RandomizeTurbineTypeAndPosition(1), max_iter=2000),
    )
    _, state, _ = tf.optimize()
    tb_pos = tf.turbine_positions[:, :2]
    tol = 1e-1
    assert tb_pos[1][0] < 6 + tol  # check within border

    np.testing.assert_array_almost_equal(tb_pos, [[3, -3], [6, -7], [4, -3]],
                                         -int(np.log10(tol)))
    np.testing.assert_array_equal(state['type'], [1, 2, 3])