Example #1
0
def test_smart_start_aep_map_large_radius():
    site = IEA37Site(16)
    n_wt = 4
    np.random.seed(0)
    x, y = site.initial_position[:n_wt].T
    wd_lst = np.arange(0, 360, 45)
    ws_lst = [10]
    turbines = hornsrev1.HornsrevV80()
    site = UniformSite([1], .75)
    site.default_ws = ws_lst
    site.default_wd = wd_lst

    aep = PyWakeAEP(wake_model=NOJ(site, turbines))
    aep_1wt = aep.calculate_AEP([0], [0]).sum()
    tf = TopFarmProblem(
        design_vars={'x': x, 'y': y},
        cost_comp=aep.get_TopFarm_cost_component(n_wt),
        driver=EasyScipyOptimizeDriver(),
        constraints=[SpacingConstraint(160), CircleBoundaryConstraint((0, 0), 2000)]
    )
    x = np.arange(-2000, 2000, 100)
    y = np.arange(-2000, 2000, 100)
    XX, YY = np.meshgrid(x, y)

    tf.smart_start(XX, YY, aep.get_aep4smart_start(wd=wd_lst, ws=ws_lst), radius=40)
    tf.evaluate()

    if 0:
        wt_x, wt_y = tf['x'], tf['y']
        for i, _ in enumerate(wt_x, 1):
            print(aep.calculate_AEP(wt_x[:i], wt_y[:i]).sum((1, 2)))
        X_j, Y_j, aep_map = aep.aep_map(x, y, 0, wt_x, wt_y, ws=ws_lst, wd=wd_lst)
        print(tf.evaluate())
        import matplotlib.pyplot as plt
        c = plt.contourf(X_j, Y_j, aep_map, 100)
        plt.colorbar(c)
        plt.plot(wt_x, wt_y, '2r')
        for c in tf.model.constraint_components:
            c.plot()
        plt.axis('equal')
        plt.show()
    npt.assert_almost_equal(aep_1wt * n_wt, tf['AEP'], 3)
def main(obj=False, max_con_on=True):
    if __name__ == '__main__':
        start = time.time()
        try:
            import matplotlib.pyplot as plt
            plt.gcf()
            plot = True
        except RuntimeError:
            plot = False

        # ------ DEFINE WIND TURBINE TYPES, LOCATIONS & STORE METADATA -------
        windTurbines = WindTurbines(
            names=['Ghost_T1', 'T2'],
            diameters=[40, 84],
            hub_heights=[70, hornsrev1.HornsrevV80().hub_height()],
            ct_funcs=[dummy_thrust(ct_rated=0),
                      hornsrev1.HornsrevV80().ct],
            power_funcs=[
                cube_power(power_rated=0),
                cube_power(power_rated=3000)
            ],
            # hornsrev1.HornsrevV80()._power],
            power_unit='kW')
        Drotor_vector = windTurbines._diameters
        power_rated_vec = np.array(
            [pcurv(25) / 1000 for pcurv in windTurbines._power_funcs])
        hub_height_vector = windTurbines._hub_heights

        x, y = np.meshgrid(range(-840, 840, 420), range(-840, 840, 420))
        n_wt = len(x.flatten())
        # initial turbine positions and other independent variables
        ext_vars = {'x': x.flatten(), 'y': y.flatten(), 'obj': obj * 1}

        capconst = []
        if max_con_on:
            capconst = [
                CapacityConstraint(max_capacity=30.01,
                                   rated_power_array=power_rated_vec)
            ]

        # ---------------- DEFINE SITE & SELECT WAKE MODEL -------------------
    #        site = UniformWeibullSite(p_wd=[50, 50], a=[9, 9], k=[2.3, 2.3], ti=.1, alpha=0, h_ref=100)
        site = UniformWeibullSite(p_wd=[100], a=[9], k=[2.3], ti=.1)
        site.default_ws = [9]  # reduce the number of calculations
        site.default_wd = [0]  # reduce the number of calculations

        wake_model = NOJ(site, windTurbines)

        AEPCalc = AEPCalculator(wake_model)

        # ------------- OUTPUTS AEP PER TURBINE & FARM IRR -------------------
        def aep_func(x, y, type, obj, **kwargs
                     ):  # TODO fix type as input change to topfarm turbinetype
            out = AEPCalc.calculate_AEP(x_i=x, y_i=y,
                                        type_i=type.astype(int)).sum((1, 2))
            if obj:  # if objective is AEP; output the total Farm_AEP
                out = np.sum(out)
            return out * 10**6

        def irr_func(aep, type, **kwargs):
            idx = type.astype(int)
            return economic_evaluation(Drotor_vector[idx],
                                       power_rated_vec[idx],
                                       hub_height_vector[idx],
                                       aep).calculate_irr()

        # ----- WRAP AEP AND IRR INTO TOPFARM COMPONENTS AND THEN GROUP  -----
        aep_comp = CostModelComponent(input_keys=[
            topfarm.x_key, topfarm.y_key, topfarm.type_key, ('obj', obj)
        ],
                                      n_wt=n_wt,
                                      cost_function=aep_func,
                                      output_key="aep",
                                      output_unit="GWh",
                                      objective=obj,
                                      output_val=np.zeros(n_wt),
                                      income_model=True)
        comps = [aep_comp]  # AEP component is always in the group
        if not obj:  # if objective is IRR initiate/add irr_comp
            irr_comp = CostModelComponent(input_keys=[topfarm.type_key, 'aep'],
                                          n_wt=n_wt,
                                          cost_function=irr_func,
                                          output_key="irr",
                                          output_unit="%",
                                          objective=True)
            comps.append(irr_comp)

        group = TopFarmGroup(comps)

        # - INITIATE THE PROBLEM WITH ONLY TURBINE TYPE AS DESIGN VARIABLES -
        tf = TopFarmProblem(
            design_vars={
                topfarm.type_key: ([0] * n_wt, 0, len(windTurbines._names) - 1)
            },
            cost_comp=group,
            driver=EasyRandomSearchDriver(randomize_func=RandomizeAllUniform(
                [topfarm.type_key]),
                                          max_iter=1),
            # driver=EasySimpleGADriver(max_gen=2, random_state=1),
            constraints=capconst,
            # plot_comp=TurbineTypePlotComponent(windTurbines._names),
            plot_comp=NoPlot(),
            ext_vars=ext_vars)

        cost, state, rec = tf.optimize()
        # view_model(problem, outfile='ex5_n2.html', show_browser=False)
        end = time.time()
        print(end - start)
        # %%
        # ------------------- OPTIONAL VISUALIZATION OF WAKES ----------------
        post_visual, save = False, False
        if post_visual:
            #        import matplotlib.pyplot as plt
            for cou, (i, j, k, co, ae) in enumerate(
                    zip(rec['x'], rec['y'], rec['type'], rec['cost'],
                        rec['aep'])):
                AEPCalc.calculate_AEP(x_i=i, y_i=j, type_i=k)
                AEPCalc.plot_wake_map(wt_x=i,
                                      wt_y=j,
                                      wt_type=k,
                                      wd=site.default_wd[0],
                                      ws=site.default_ws[0],
                                      levels=np.arange(2.5, 12, .1))
                windTurbines.plot(i, j, types=k)
                title = f'IRR: {-np.round(co,2)} %, AEP :  {round(np.sum(ae))} GWh, '
                if "totalcapacity" in rec.keys():
                    title += f'Total Capacity: {rec["totalcapacity"][cou]} MW'
                plt.title(title)
                if save:
                    plt.savefig(
                        r'..\..\..\ima2\obj_AEP_{}_MaxConstraint_{}_{}.png'.
                        format(obj, max_con_on, cou))
                plt.show()
Example #3
0
def setup():
    site = Hornsrev1Site()
    windTurbines = hornsrev1.HornsrevV80()

    return site, windTurbines
Example #4
0
def setup():
    site = Hornsrev1Site()
    windTurbines = hornsrev1.HornsrevV80()
    ss = SelfSimilarityDeficit()
    return site, windTurbines, ss
Example #5
0
def main():
    if __name__ == '__main__':
        import matplotlib.pyplot as plt
        from py_wake.examples.data.hornsrev1 import Hornsrev1Site
        from py_wake.examples.data import hornsrev1
        from py_wake.superposition_models import LinearSum
        from py_wake.wind_farm_models import All2AllIterative

        site = Hornsrev1Site()
        windTurbines = hornsrev1.HornsrevV80()
        ws = 10
        D = 80
        R = D / 2
        WS_ilk = np.array([[[ws]]])
        D_src_il = np.array([[D]])
        ct_ilk = np.array([[[.8]]])
        ss = SelfSimilarityDeficit()
        ss20 = SelfSimilarityDeficit2020()

        x, y = -np.arange(200), np.array([0])
        # original model
        deficit = ss.calc_deficit(WS_ilk=WS_ilk,
                                  D_src_il=D_src_il,
                                  dw_ijlk=x.reshape((1, len(x), 1, 1)),
                                  cw_ijlk=y.reshape((1, len(y), 1, 1)),
                                  ct_ilk=ct_ilk)
        # updated method
        deficit20 = ss20.calc_deficit(WS_ilk=WS_ilk,
                                      D_src_il=D_src_il,
                                      dw_ijlk=x.reshape((1, len(x), 1, 1)),
                                      cw_ijlk=y.reshape((1, len(y), 1, 1)),
                                      ct_ilk=ct_ilk)
        plt.figure()
        plt.title('Fig 11 from [1]')
        plt.xlabel('x/R')
        plt.ylabel('a')
        plt.plot(x / R, deficit[0, :, 0, 0] / ws, label='original')
        plt.plot(x / R, deficit20[0, :, 0, 0] / ws, '--', label='updated')
        plt.legend()

        plt.figure()
        x, y = np.array([-2 * R]), np.arange(200)
        deficit = ss.calc_deficit(WS_ilk=WS_ilk,
                                  D_src_il=D_src_il,
                                  dw_ijlk=x.reshape((1, len(x), 1, 1)),
                                  cw_ijlk=y.reshape((1, len(y), 1, 1)),
                                  ct_ilk=ct_ilk)
        deficit20 = ss20.calc_deficit(WS_ilk=WS_ilk,
                                      D_src_il=D_src_il,
                                      dw_ijlk=x.reshape((1, len(x), 1, 1)),
                                      cw_ijlk=y.reshape((1, len(y), 1, 1)),
                                      ct_ilk=ct_ilk)
        plt.title('Fig 10 from [1]')
        r12 = ss.r12(x / R)
        r12_20 = ss20.r12(x / R)
        plt.xlabel('y/R12 (epsilon)')
        plt.ylabel('f')
        plt.plot((y / R) / r12,
                 deficit[0, :, 0, 0] / deficit[0, 0, 0, 0],
                 label='original')
        plt.plot((y / R) / r12_20,
                 deficit20[0, :, 0, 0] / deficit20[0, 0, 0, 0],
                 '--',
                 label='updated')
        plt.legend()

        plt.figure()
        noj_ss = All2AllIterative(site,
                                  windTurbines,
                                  wake_deficitModel=NoWakeDeficit(),
                                  superpositionModel=LinearSum(),
                                  blockage_deficitModel=ss)
        noj_ss20 = All2AllIterative(site,
                                    windTurbines,
                                    wake_deficitModel=NoWakeDeficit(),
                                    superpositionModel=LinearSum(),
                                    blockage_deficitModel=ss20)
        flow_map = noj_ss(x=[0], y=[0], wd=[270], ws=[10]).flow_map()
        flow_map20 = noj_ss20(x=[0], y=[0], wd=[270], ws=[10]).flow_map()
        clevels = [.9, .95, .98, .99, .995, .998, .999, 1., 1.01, 1.02, 1.03]
        flow_map.plot_wake_map()
        plt.contour(flow_map.x,
                    flow_map.y,
                    flow_map.WS_eff[:, :, 0, -1, 0] / 10,
                    levels=clevels,
                    colors='k',
                    linewidths=0.5)
        plt.contour(flow_map.x,
                    flow_map.y,
                    flow_map20.WS_eff[:, :, 0, -1, 0] / 10,
                    levels=clevels,
                    colors='r',
                    linewidths=0.5)
        plt.title('Original (black) vs updated (red)')
        plt.show()

        from py_wake.examples.data.iea37._iea37 import IEA37Site
        from py_wake.examples.data.iea37._iea37 import IEA37_WindTurbines

        # setup site, turbines and wind farm model
        site = IEA37Site(16)
        x, y = site.initial_position.T
        windTurbines = IEA37_WindTurbines()

        noj_ss = All2AllIterative(site,
                                  windTurbines,
                                  wake_deficitModel=NoWakeDeficit(),
                                  superpositionModel=LinearSum(),
                                  blockage_deficitModel=ss)
        noj_ss20 = All2AllIterative(site,
                                    windTurbines,
                                    wake_deficitModel=NoWakeDeficit(),
                                    superpositionModel=LinearSum(),
                                    blockage_deficitModel=ss20)
        # run wind farm simulation
        sim_res = noj_ss(x, y, wd=[0, 30, 45, 60, 90], ws=[5, 10, 15])
        sim_res20 = noj_ss20(x, y, wd=[0, 30, 45, 60, 90], ws=[5, 10, 15])

        # calculate AEP
        aep = sim_res.aep().sum()
        aep20 = sim_res20.aep().sum()

        # plot wake map
        fig, (ax1, ax2) = plt.subplots(1,
                                       2,
                                       figsize=(9, 4.5),
                                       tight_layout=True)
        levels = np.array(
            [.9, .95, .98, .99, .995, .998, .999, 1., 1.01, 1.02, 1.03]) * 10.
        print(noj_ss)
        flow_map = sim_res.flow_map(wd=30, ws=10.)
        flow_map.plot_wake_map(levels=levels, ax=ax1, plot_colorbar=False)
        ax1.set_title('Original Self-Similar, AEP: %.3f GWh' % aep)

        # plot wake map
        print(noj_ss20)
        flow_map = sim_res20.flow_map(wd=30, ws=10.)
        flow_map.plot_wake_map(levels=levels, ax=ax2, plot_colorbar=False)
        ax2.set_title('Self-Similar 2020, AEP: %.3f GWh' % aep20)
        plt.show()