Пример #1
0
    def test_error_raising(self):
        source = os.path.join(os.path.dirname(__file__), '../example/data',
                              'example_power_curves.csv')
        self.test_turbine_data = {
            'hub_height': 100,
            'rotor_diameter': 80,
            'name': 'turbine_not_in_file',
            'fetch_curve': 'power_curve',
            'data_source': source
        }
        # Raise system exit due to turbine type not in file
        with pytest.raises(SystemExit):
            WindTurbine(**self.test_turbine_data)

        # Raise ValueError due to invalid parameter `fetch_curve`
        self.test_turbine_data['fetch_curve'] = 'misspelling'
        self.test_turbine_data['name'] = 'DUMMY 3'
        with pytest.raises(ValueError):
            WindTurbine(**self.test_turbine_data)

        # Raise KeyError due to turbine type not in oedb
        self.test_turbine_data['fetch_curve'] = 'power_curve'
        self.test_turbine_data['data_source'] = 'oedb'
        with pytest.raises(KeyError):
            WindTurbine(**self.test_turbine_data)
 def test_wrongly_defined_to_group_method(self):
     example_turbine = {
         'hub_height': 100,
         'rotor_diameter': 70,
         'turbine_type': 'DUMMY 3',
         'path': self.source
     }
     e_t_1 = WindTurbine(**example_turbine)
     with pytest.raises(ValueError,
                        match="The 'number' and the 'total_capacity' "
                        "parameter are mutually exclusive."):
         e_t_1.to_group(5, 3000)
Пример #3
0
 def test_wrongly_defined_to_group_method(self):
     example_turbine = {
         "hub_height": 100,
         "rotor_diameter": 70,
         "turbine_type": "DUMMY 3",
         "path": self.source,
     }
     e_t_1 = WindTurbine(**example_turbine)
     with pytest.raises(
         ValueError,
         match="The 'number' and the 'total_capacity' "
         "parameter are mutually exclusive.",
     ):
         e_t_1.to_group(5, 3000)
Пример #4
0
def feedin_windpowerlib(weather, turbine, installed_capacity=1):
    """Use the windpowerlib to generate normalised feedin time series.

    Parameters
    ----------
    turbine : dict
        Parameters of the wind turbine (hub height, diameter of the rotor,
        identifier of the turbine to get cp-series, nominal power).
    weather : pandas.DataFrame
        Weather data set. See module header.
    installed_capacity : float
        Overall installed capacity for the given wind turbine. The installed
        capacity is set to 1 by default for normalised time series.

    Returns
    -------
    pandas.DataFrame

    """
    wpp = WindTurbine(**turbine)
    modelchain_data = cfg.get_dict('windpowerlib')
    mc = ModelChain(wpp, **modelchain_data)
    mcwpp = mc.run_model(weather)
    return mcwpp.power_output.div(
        turbine['nominal_power']).multiply(installed_capacity)
Пример #5
0
def check_data_integrity(filename, min_pc_length=5):
    data = pd.read_csv(filename.format("turbine_data"), index_col=[0])
    for data_set in data.iterrows():
        wt_type = data_set[0]
        turbine_data_set = {
            "turbine_type": "{0}".format(wt_type),
            "hub_height": 135,
        }
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            wt = WindTurbine(**turbine_data_set)
            if wt.power_curve is None and data_set[1].has_power_curve is True:
                logging.warning(
                    "{0}: No power curve but has_power_curve=True.".format(
                        wt_type))
            if (wt.power_coefficient_curve is None
                    and data_set[1].has_cp_curve is True):
                logging.warning(
                    "{0}: No cp-curve but has_cp_curve=True.".format(wt_type))
            if wt.power_curve is not None:
                if len(wt.power_curve) < min_pc_length:
                    logging.warning(
                        "{0}: power_curve is too short ({1} values),".format(
                            wt_type, len(wt.power_curve)))
    return data
Пример #6
0
def windpower(wind_instance, tmy):
    """
    Returns:
        wind.power == wind power time series according using windpowerlib chain

    Inputs:
            wind class
            TMY dataframe (converted to windpowerlib API
                               using _prepare_wind_data)
    """
    from windpowerlib.modelchain import ModelChain
    from windpowerlib.wind_turbine import WindTurbine

    wind = wind_instance

    #### prepare wind data
    wind_df = _prepare_wind_data(tmy, wind)

    #### setup turbine
    turbinespec = {
        "turbine_type":
        "E-126/4200",  # turbine type as in oedb turbine library
        "hub_height": 135,  # in m
    }

    # initialize WindTurbine object
    turbine = WindTurbine(**turbinespec)

    #### Run wind ModelChain
    # wind speed    : Hellman
    # temperature   : linear gradient
    # density       : ideal gass
    # power output  : power curve

    modelchain_data = {
        "wind_speed_model": "logarithmic",  # 'logarithmic' (default),
        # 'hellman' or
        # 'interpolation_extrapolation'
        "density_model": "ideal_gas",  # 'barometric' (default), 'ideal_gas'
        #  or 'interpolation_extrapolation'
        "temperature_model": "linear_gradient",  # 'linear_gradient' (def.) or
        # 'interpolation_extrapolation'
        "power_output_model": "power_curve",  # 'power_curve' (default) or
        # 'power_coefficient_curve'
        "density_correction": True,  # False (default) or True
        "obstacle_height": 0,  # default: 0
        "hellman_exp": None,
    }  # None (default) or None

    # initialize ModelChain with own specifications and use run_model method to
    # calculate power output
    mc = ModelChain(turbine, **modelchain_data).run_model(wind_df)

    # write power output time series to wind object
    power = mc.power_output / mc.power_output.max() * wind.installed
    if hasattr(wind, "transport_efficiency"):
        power *= wind.transport_efficiency
    power.index = wind.state.index
    return power
Пример #7
0
def summarized_pc(plot=False):
    enerconE70 = {
        'object_name': 'ENERCON E 70 2300',
        'hub_height': 64,
        'rotor_diameter': 71
    }
    enerconE66 = {
        'object_name': 'ENERCON E 66 1800',
        'hub_height': 65,
        'rotor_diameter': 70
    }
    vestasV126 = {
        'object_name': 'VESTAS V 126 3300',
        'hub_height': 117,
        'rotor_diameter': 126
    }
    e70 = WindTurbine(**enerconE70)
    e66 = WindTurbine(**enerconE66)
    v126 = WindTurbine(**vestasV126)
    parameters = {
        'wind_turbine_fleet': [{
            'wind_turbine': e70,
            'number_of_turbines': 13
        }, {
            'wind_turbine': e66,
            'number_of_turbines': 4
        }, {
            'wind_turbine': v126,
            'number_of_turbines': 2
        }],
        'smoothing':
        True,
        'density_correction':
        False,
        'roughness_length':
        0.4
    }
    power_curve_exp = 2
    summarized_power_curve_df = summarized_power_curve(**parameters)
    if plot:
        plt.plot(summarized_power_curve_df['wind_speed'],
                 summarized_power_curve_df['power'])
        plt.show()
        plt.close()
    return summarized_power_curve_df
 def test_warning(self, recwarn):
     test_turbine_data = {
         'hub_height': 100,
         'rotor_diameter': 80,
         'turbine_type': 'turbine_not_in_file',
         'path': self.source
     }
     assert (WindTurbine(**test_turbine_data).power_curve is None)
     assert recwarn.pop(WindpowerlibUserWarning)
Пример #9
0
    def run(self):
        print("Thread " + str(self.input_file))
        weather = get_weather_data(filename="weather" + str(self.input_file) +
                                   ".csv")
        #print(weather[['wind_speed', 'temperature', 'pressure']][0:3])

        # initialize WindTurbine object
        t = WindTurbine(**self.turbine)

        # initialize ModelChain with own specifications and use run_model method to
        # calculate power output
        mc_t = ModelChain(t, **self.modelchain_data).run_model(weather)
        # write power output time series to WindTurbine object
        t.power_output = mc_t.power_output

        power_file = open("power" + str(self.input_file) + ".csv", "w")
        power_file.write(t.power_output.to_csv())
        print("Thread " + str(self.input_file) + " finished")
Пример #10
0
 def test_warning(self, recwarn):
     test_turbine_data = {
         "hub_height": 100,
         "rotor_diameter": 80,
         "turbine_type": "turbine_not_in_file",
         "path": self.source,
     }
     assert WindTurbine(**test_turbine_data).power_curve is None
     assert recwarn.pop(WindpowerlibUserWarning)
Пример #11
0
 def test_power_curve_is_of_wrong_type(self):
     """Error raising due to wrong type of WindTurbine.power_curve."""
     test_turbine_data = {
         "hub_height": 100,
         "rotor_diameter": 80,
         "turbine_type": "test_type",
         "power_curve": "string",
     }
     with pytest.raises(TypeError):
         WindTurbine(**test_turbine_data)
Пример #12
0
 def test_create_unphysical_turbine(self):
     err_msg = "1/2rotor_diameter cannot be greater than hub_height"
     char = {
         "hub_height": 80,
         "rotor_diameter": 160,
         "turbine_type": "DUMMY 3",
         "path": self.source,
     }
     with pytest.raises(ValueError, match=err_msg):
         WindTurbine(**char)
 def test_power_curve_is_of_wrong_type(self):
     """Error raising due to wrong type of WindTurbine.power_curve."""
     test_turbine_data = {
         'hub_height': 100,
         'rotor_diameter': 80,
         'turbine_type': 'test_type',
         'power_curve': 'string'
     }
     with pytest.raises(TypeError):
         WindTurbine(**test_turbine_data)
Пример #14
0
    def wind_farm_power(self):

        # specification of wind turbine where
        # power coefficient curve and nominal
        # power is provided in an own csv file

        if self.multiplier == 0:
            data = np.zeros(8760)
            df = pd.DataFrame(data, columns=['wind_farm'])
            return df

        csv_path = os.path.join(os.path.dirname(__file__), "..", "data",
                                'oedb')
        myTurbine = {
            'turbine_type': self.turbine_name,  # turbine type as in file
            'hub_height': self.hub_height,  # in m
            'rotor_diameter': self.rotor_diameter,  # in m
            'path': csv_path  # using power_curve csv
        }

        # initialise WindTurbine object
        siemens = WindTurbine(**myTurbine)

        # specification of wind farm data
        farm = {
            'name':
            'example_farm',
            'wind_turbine_fleet': [{
                'wind_turbine': siemens,
                'number_of_turbines': self.multiplier
            }],
            'efficiency':
            self.wind_farm_efficiency
        }

        # initialize WindFarm object
        farm_obj = WindFarm(**farm)

        weather = self.weather_data()

        # power output calculation for example_farm
        # initialize TurbineClusterModelChain with default parameters and use
        # run_model method to calculate power output
        mc_farm = TurbineClusterModelChain(farm_obj).run_model(weather)
        # write power output time series to WindFarm object
        farm_obj.power_output = mc_farm.power_output

        # units in kWh
        # times by 0.5 to correct for MEERA dataset
        series = (farm_obj.power_output * 0.5 / 1000).round(2)
        df = series.to_frame()
        df.columns = ['wind_farm']

        return df
Пример #15
0
def test_feedin_windpowerlib():
    fn = os.path.join(
        os.path.dirname(__file__),
        os.pardir,
        "tests",
        "data",
        "test_coastdat_weather.csv",
    )
    weather = pd.read_csv(fn, header=[0, 1])["1126088"]
    turbine = {"hub_height": 135, "turbine_type": "E-141/4200"}
    data_height = cfg.get_dict("coastdat_data_height")
    wind_weather = coastdat.adapt_coastdat_weather_to_windpowerlib(
        weather, data_height)  # doctest: +SKIP
    assert int(feedin.feedin_windpowerlib(wind_weather, turbine).sum()) == 2164
    turbine = WindTurbine(**turbine)
    assert int(feedin.feedin_windpowerlib(wind_weather, turbine).sum()) == 2164
Пример #16
0
def feedin_windpowerlib_test():
    fn = os.path.join(os.path.dirname(__file__), os.pardir, 'tests', 'data',
                      'test_coastdat_weather.csv')
    weather = pd.read_csv(fn, header=[0, 1])['1126088']
    turbine = {
        'hub_height': 135,
        'rotor_diameter': 127,
        'name': 'E-141/4200',
        'nominal_power': 4200000,
        'fetch_curve': 'power_coefficient_curve'
    }
    data_height = cfg.get_dict('coastdat_data_height')
    wind_weather = coastdat.adapt_coastdat_weather_to_windpowerlib(
        weather, data_height)  # doctest: +SKIP
    eq_(int(feedin.feedin_windpowerlib(wind_weather, turbine).sum()), 1737)
    turbine = WindTurbine(**turbine)
    eq_(int(feedin.feedin_windpowerlib(wind_weather, turbine).sum()), 1737)
 def test_to_group_method(self):
     example_turbine = {
         'hub_height': 100,
         'rotor_diameter': 70,
         'turbine_type': 'DUMMY 3',
         'path': self.source
     }
     e_t_1 = WindTurbine(**example_turbine)
     assert (isinstance(e_t_1.to_group(), WindTurbineGroup))
     assert (e_t_1.to_group(5).number_of_turbines == 5)
     assert (e_t_1.to_group(number_turbines=5).number_of_turbines == 5)
     assert (e_t_1.to_group(total_capacity=3e6).number_of_turbines == 2.0)
Пример #18
0
 def test_to_group_method(self):
     example_turbine = {
         "hub_height": 100,
         "rotor_diameter": 70,
         "turbine_type": "DUMMY 3",
         "path": self.source,
     }
     e_t_1 = WindTurbine(**example_turbine)
     assert isinstance(e_t_1.to_group(), WindTurbineGroup)
     assert e_t_1.to_group(5).number_of_turbines == 5
     assert e_t_1.to_group(number_turbines=5).number_of_turbines == 5
     assert e_t_1.to_group(total_capacity=3e6).number_of_turbines == 2.0
Пример #19
0
    def user_power(self):
        """wind power output for user-defined turbine

        inputs weather and turbine spec
        initialises the wind turbine object
        runs model
        calculates power output

        Returns:
            pandas df -- hourly year power output
        """

        if self.multiplier == 0:
            data = np.zeros(8760)
            df = pd.DataFrame(data, columns=['wind_user'])
            return df

        multi = self.multiplier

        # this returns dict which contains all the info for the windturbine
        myTurbine = {
            'name': self.turbine_name,
            'nominal_power': self.nominal_power,
            'hub_height': self.hub_height,
            'rotor_diameter': self.rotor_diameter,
            'power_curve': self.power_curve
        }

        # input weather data
        weather = self.weather_data()

        # initialises a wind turbine object using
        # the WindTurbine class from windpowerlib
        UserTurbine = WindTurbine(**myTurbine)
        mc_my_turbine = ModelChain1(UserTurbine).run_model(weather)

        # 1000 factor to make it into kW,
        # and the multi to give number of wind turbines
        # multiply by 0.5 to correct MEERA dataset if needed
        series = (mc_my_turbine.power_output * multi / 1000.).round(2)
        df = series.to_frame()
        df.columns = ['wind_user']
        df = df.reset_index(drop=True)

        return df
Пример #20
0
def feedin_windpowerlib(weather, turbine, installed_capacity=1):
    """Use the windpowerlib to generate normalised feedin time series.

    Parameters
    ----------
    turbine : dict or windpowerlib.wind_turbine.WindTurbine
        Parameters of the wind turbine (hub height, diameter of the rotor,
        identifier of the turbine to get cp-series, nominal power).
    weather : pandas.DataFrame
        Weather data set. See module header.
    installed_capacity : float
        Overall installed capacity for the given wind turbine. The installed
        capacity is set to 1 by default for normalised time series.

    Returns
    -------
    pandas.DataFrame

    Examples
    --------
    >>> from reegis import coastdat
    >>> fn=os.path.join(os.path.dirname(__file__), os.pardir, 'tests',
    ...                  'data', 'test_coastdat_weather.csv')
    >>> weather=pd.read_csv(fn, header=[0, 1])['1126088']
    >>> turbine={
    ...     'hub_height': 135,
    ...     'rotor_diameter': 127,
    ...     'name': 'E-82/2300',
    ...     'nominal_power': 4200000,
    ...     'fetch_curve': 'power_coefficient_curve'}
    >>> data_height=cfg.get_dict('coastdat_data_height')
    >>> wind_weather=coastdat.adapt_coastdat_weather_to_windpowerlib(
    ...     weather, data_height)  # doctest: +SKIP
    >>> int(feedin_windpowerlib(wind_weather, turbine).sum())  # doctest: +SKIP
    1737
    """
    if not isinstance(turbine, WindTurbine):
        turbine = WindTurbine(**turbine)
    modelchain_data = cfg.get_dict("windpowerlib")
    mc = ModelChain(turbine, **modelchain_data)
    mcwpp = mc.run_model(weather)
    return mcwpp.power_output.div(
        turbine.nominal_power).multiply(installed_capacity)
Пример #21
0
def normalised_feedin_for_each_data_set(year,
                                        wind=True,
                                        solar=True,
                                        overwrite=False):
    """
    Loop over all weather data sets (regions) and calculate a normalised time
    series for each data set with the given parameters of the power plants.

    This file could be more elegant and shorter but it will be rewritten soon
    with the new feedinlib features.

    year : int
        The year of the weather data set to use.
    wind : boolean
        Set to True if you want to create wind feed-in time series.
    solar : boolean
        Set to True if you want to create solar feed-in time series.

    Returns
    -------

    """
    # Get coordinates of the coastdat data points.
    data_points = pd.read_csv(
        os.path.join(
            cfg.get("paths", "geometry"),
            cfg.get("coastdat", "coastdatgrid_centroid"),
        ),
        index_col="gid",
    )

    pv_sets = None
    wind_sets = None

    # Open coastdat-weather data hdf5 file for the given year or try to
    # download it if the file is not found.
    weather_file_name = os.path.join(
        cfg.get("paths", "coastdat"),
        cfg.get("coastdat", "file_pattern").format(year=year),
    )
    if not os.path.isfile(weather_file_name):
        download_coastdat_data(year=year, filename=weather_file_name)

    weather = pd.HDFStore(weather_file_name, mode="r")

    # Fetch coastdat data heights from ini file.
    data_height = cfg.get_dict("coastdat_data_height")

    # Create basic file and path pattern for the resulting files
    coastdat_path = os.path.join(cfg.get("paths_pattern", "coastdat"))

    feedin_file = os.path.join(coastdat_path, cfg.get("feedin",
                                                      "file_pattern"))

    # Fetch coastdat region-keys from weather file.
    key_file_path = coastdat_path.format(year="", type="")[:-2]
    key_file = os.path.join(key_file_path, "coastdat_keys.csv")
    if not os.path.isfile(key_file):
        coastdat_keys = weather.keys()
        if not os.path.isdir(key_file_path):
            os.makedirs(key_file_path)
        pd.Series(coastdat_keys).to_csv(key_file)
    else:
        coastdat_keys = pd.read_csv(key_file,
                                    index_col=[0],
                                    squeeze=True,
                                    header=None)

    txt_create = "Creating normalised {0} feedin time series for {1}."
    hdf = {"wind": {}, "solar": {}}
    if solar:
        logging.info(txt_create.format("solar", year))
        # Add directory if not present
        os.makedirs(coastdat_path.format(year=year, type="solar"),
                    exist_ok=True)
        # Create the pv-sets defined in the solar.ini
        pv_sets = feedin.create_pvlib_sets()

        # Open a file for each main set (subsets are stored in columns)
        for pv_key, pv_set in pv_sets.items():
            filename = feedin_file.format(type="solar",
                                          year=year,
                                          set_name=pv_key)
            if not os.path.isfile(filename) or overwrite:
                hdf["solar"][pv_key] = pd.HDFStore(filename, mode="w")

    if wind:
        logging.info(txt_create.format("wind", year))
        # Add directory if not present
        os.makedirs(coastdat_path.format(year=year, type="wind"),
                    exist_ok=True)
        # Create the pv-sets defined in the wind.ini
        wind_sets = feedin.create_windpowerlib_sets()
        # Open a file for each main set (subsets are stored in columns)
        for wind_key, wind_set in wind_sets.items():
            for subset_key, subset in wind_set.items():
                wind_sets[wind_key][subset_key] = WindTurbine(**subset)
            filename = feedin_file.format(type="wind",
                                          year=year,
                                          set_name=wind_key)
            if not os.path.isfile(filename) or overwrite:
                hdf["wind"][wind_key] = pd.HDFStore(filename, mode="w")

    # Define basic variables for time logging
    remain = len(coastdat_keys)
    done = 0
    start = datetime.datetime.now()

    # Loop over all regions
    for coastdat_key in coastdat_keys:
        # Get weather data set for one location
        local_weather = weather[coastdat_key]

        # Adapt the coastdat weather format to the needs of pvlib.
        # The expression "len(list(hdf['solar'].keys()))" returns the number
        # of open hdf5 files. If no file is open, there is nothing to do.
        if solar and len(list(hdf["solar"].keys())) > 0:
            # Get coordinates for the weather location
            local_point = data_points.loc[int(coastdat_key[2:])]

            # Create a pvlib Location object
            location = pvlib.location.Location(latitude=local_point["lat"],
                                               longitude=local_point["lon"])

            # Adapt weather data to the needs of the pvlib
            local_weather_pv = adapt_coastdat_weather_to_pvlib(
                local_weather, location)

            # Create one DataFrame for each pv-set and store into the file
            for pv_key, pv_set in pv_sets.items():
                if pv_key in hdf["solar"]:
                    hdf["solar"][pv_key][coastdat_key] = feedin.feedin_pv_sets(
                        local_weather_pv, location, pv_set)

        # Create one DataFrame for each wind-set and store into the file
        if wind and len(list(hdf["wind"].keys())) > 0:
            local_weather_wind = adapt_coastdat_weather_to_windpowerlib(
                local_weather, data_height)
            for wind_key, wind_set in wind_sets.items():
                if wind_key in hdf["wind"]:
                    hdf["wind"][wind_key][
                        coastdat_key] = feedin.feedin_wind_sets(
                            local_weather_wind, wind_set)

        # Start- time logging *******
        remain -= 1
        done += 1
        if divmod(remain, 10)[1] == 0:
            elapsed_time = (datetime.datetime.now() - start).seconds
            remain_time = elapsed_time / done * remain
            end_time = datetime.datetime.now() + datetime.timedelta(
                seconds=remain_time)
            msg = "Actual time: {:%H:%M}, estimated end time: {:%H:%M}, "
            msg += "done: {0}, remain: {1}".format(done, remain)
            logging.info(msg.format(datetime.datetime.now(), end_time))
        # End - time logging ********

    for k1 in hdf.keys():
        for k2 in hdf[k1].keys():
            hdf[k1][k2].close()
    weather.close()
    logging.info("All feedin time series for {0} are stored in {1}".format(
        year, coastdat_path.format(year=year, type="")))
Пример #22
0
    def database_power(self):
        """wind turbine database power output

        power output calculation
        initialise ModelChain with default
        parameters and use run_model method
        to calculate power output

        Returns:
            pandas df -- hourly year of power output
        """

        if self.multiplier == 0:
            data = np.zeros(8760)
            df = pd.DataFrame(data, columns=['wind_database'])
            return df

        multi = self.multiplier

        # specification of wind turbine where
        # power coefficient curve and nominal
        # power is provided in an own csv file

        csv_path = os.path.join(os.path.dirname(__file__), "..", "data",
                                'oedb')  #, 'power_curves.csv')

        myTurbine = {
            'turbine_type': self.turbine_name,  # turbine type as in file
            'hub_height': self.hub_height,  # in m
            'rotor_diameter': self.rotor_diameter,  # in m
            'path': csv_path  # using power_curve csv
        }

        # own specifications for ModelChain setup
        modelchain_data = {
            'wind_speed_model': 'logarithmic',  # 'logarithmic' (default),
            # 'hellman' or
            # 'interpolation_extrapolation'
            'density_model':
            'barometric',  # 'barometric' (default), 'ideal_gas' or
            # 'interpolation_extrapolation'
            'temperature_model':
            'linear_gradient',  # 'linear_gradient' (def.) or
            # 'interpolation_extrapolation'
            'power_output_model': 'power_curve',  # 'power_curve' (default) or
            # 'power_coefficient_curve'
            'density_correction': False,  # False (default) or True
            'obstacle_height': 0,  # default: 0
            'hellman_exp': None
        }  # None (default) or None

        # initialise WindTurbine object
        turbineObj = WindTurbine(**myTurbine)

        weather = self.weather_data()

        mc_my_turbine = ModelChain1(turbineObj,
                                    **modelchain_data).run_model(weather)
        # write power output timeseries to WindTurbine object
        # divide by 1000 to keep in kW
        # multply by 0.5 for correcting reanalysis dataset
        series = (mc_my_turbine.power_output * multi * 0.5 / 1000).round(2)
        df = series.to_frame()
        df.columns = ['wind_database']
        df = df.reset_index(drop=True)

        return df
def preprocess_wind(df, target, features):

    # Convert to standard indexing structure (ref_datetime, valid_datetime)
    df.index.name = 'valid_datetime'
    idx_ref_datetime = df.index.hour == 1
    df.loc[idx_ref_datetime, 'ref_datetime'] = df.index[idx_ref_datetime]
    df.loc[:, 'ref_datetime'] = df.loc[:,
                                       'ref_datetime'].fillna(method='ffill')
    df = df.set_index('ref_datetime', append=True,
                      drop=True)[df.columns.levels[0][:-1]]
    df.index = df.index.reorder_levels(['ref_datetime', 'valid_datetime'])
    df = df.sort_index()

    # Remove hidden ref_datetime column from multiindex
    columns = [
        df.columns.levels[0][:-1].values, df.columns.levels[1][:-1].values
    ]
    df.columns = pd.MultiIndex.from_product(columns)

    for farm in df.columns.levels[0]:
        df_features = pd.DataFrame(index=df.index)

        df_features.loc[:, 'Utot10'] = np.sqrt(df.loc[:, (farm, 'U10')]**2 +
                                               df.loc[:, (farm, 'V10')]**2)
        df_features.loc[:, 'Theta10'] = np.angle(df.loc[:, (farm, 'U10')] +
                                                 df.loc[:, (farm, 'V10')] * 1j,
                                                 deg=True)
        df_features.loc[:, 'Utot100'] = np.sqrt(df.loc[:, (farm, 'U100')]**2 +
                                                df.loc[:, (farm, 'V100')]**2)
        df_features.loc[:, 'Theta100'] = np.angle(
            df.loc[:, (farm, 'U100')] + df.loc[:, (farm, 'V100')] * 1j,
            deg=True)

        df_features.loc[:, 'Utot10_Acc'] = df_features.loc[:, 'Utot10'].diff(1)
        df_features.loc[:, 'Utot100_Acc'] = df_features.loc[:,
                                                            'Utot100'].diff(1)

        df_features.loc[:, 'Utot310'] = df_features.loc[:, 'Utot10']**3
        df_features.loc[:, 'Utot3100'] = df_features.loc[:, 'Utot100']**3
        df_features.loc[:,
                        'Utotdiff'] = df_features.loc[:,
                                                      'Utot100'] - df_features.loc[:,
                                                                                   'Utot10']

        for feature in df_features.columns:
            df.loc[:, (farm, feature)] = df_features[feature]

    for farm in df.columns.levels[0]:
        df_features = pd.DataFrame(index=df.index)

        df_features.loc[:,
                        'O_UTot100_Mean'] = df.loc[:, pd.
                                                   IndexSlice[:,
                                                              'Utot100']].mean(
                                                                  axis=1)
        df_features.loc[:,
                        'O_UTot100_Std'] = df.loc[:, pd.
                                                  IndexSlice[:,
                                                             'Utot100']].std(
                                                                 axis=1)
        df_features.loc[:,
                        'O_UTot100_Min'] = df.loc[:, pd.
                                                  IndexSlice[:,
                                                             'Utot100']].min(
                                                                 axis=1)
        df_features.loc[:,
                        'O_UTot100_Max'] = df.loc[:, pd.
                                                  IndexSlice[:,
                                                             'Utot100']].max(
                                                                 axis=1)
        df_features.loc[:,
                        'O_Theta100_Mean'] = df.loc[:, pd.
                                                    IndexSlice[:,
                                                               'Theta100']].mean(
                                                                   axis=1)
        df_features.loc[:,
                        'O_Theta100_Std'] = df.loc[:, pd.
                                                   IndexSlice[:,
                                                              'Theta100']].std(
                                                                  axis=1)
        df_features.loc[:,
                        'O_Theta100_Min'] = df.loc[:, pd.
                                                   IndexSlice[:,
                                                              'Theta100']].min(
                                                                  axis=1)
        df_features.loc[:,
                        'O_Theta100_Max'] = df.loc[:, pd.
                                                   IndexSlice[:,
                                                              'Theta100']].max(
                                                                  axis=1)
        df_features.loc[:,
                        'O_UTot100_Acc_Mean'] = df.loc[:, pd.
                                                       IndexSlice[:,
                                                                  'Utot100_Acc']].mean(
                                                                      axis=1)
        df_features.loc[:,
                        'O_UTot100_Acc_Std'] = df.loc[:, pd.
                                                      IndexSlice[:,
                                                                 'Utot100_Acc']].std(
                                                                     axis=1)
        df_features.loc[:,
                        'O_UTot100_Acc_Min'] = df.loc[:, pd.
                                                      IndexSlice[:,
                                                                 'Utot100_Acc']].min(
                                                                     axis=1)
        df_features.loc[:,
                        'O_UTot100_Acc_Max'] = df.loc[:, pd.
                                                      IndexSlice[:,
                                                                 'Utot100_Acc']].max(
                                                                     axis=1)

        #other_farms = df.columns.levels[0].difference([farm])
        for ofarm in df.columns.levels[0]:
            df_features.loc[:, 'O_UTot100_' +
                            ofarm] = df.loc[:, pd.IndexSlice[ofarm,
                                                             'Utot100']].values

        for ofarm in df.columns.levels[0]:
            df_features.loc[:, 'O_Theta100_' +
                            ofarm] = df.loc[:,
                                            pd.IndexSlice[ofarm,
                                                          'Theta100']].values

        for feature in df_features.columns:
            df.loc[:, (farm, feature)] = df_features[feature]

    # Physical forecast
    columns = [df.columns.levels[0], ['wind_speed'], [10, 100]]
    df_weather = pd.DataFrame(columns=pd.MultiIndex.from_product(columns))
    for farm, height in itertools.product(columns[0], columns[2]):
        df_weather.loc[:, (farm, 'wind_speed',
                           height)] = df.loc[:, (farm, 'Utot' + str(height))]
    for farm in df.columns.levels[0]:
        df_weather.loc[:, (farm, 'roughness_length', 0)] = 0.03

    wt = WindTurbine(turbine_type='E-126/4200',
                     hub_height=135,
                     rotor_diameter=127)
    wf = WindFarm(name='GEFCom2014',
                  wind_turbine_fleet=[{
                      'wind_turbine': wt,
                      'number_of_turbines': 30
                  }])
    wf.efficiency = 1.0
    mc = TurbineClusterModelChain(wf, wake_losses_model=None)

    for farm in df_weather.columns.levels[0]:
        power = mc.run_model(df_weather[farm]).power_output
        del mc.power_output
        power_norm = power / wf.nominal_power
        df.loc[:, (farm, 'P_out')] = power_norm

    # Select only features specified in parameter file
    df_temp = pd.DataFrame(index=df.index,
                           columns=pd.MultiIndex.from_product(
                               [df.columns.levels[0], [target] + features]))
    df_temp.loc[:,
                pd.IndexSlice[:, [target] +
                              features]] = df.loc[:,
                                                  pd.IndexSlice[:, [target] +
                                                                features]]

    # Add custom weights
    for farm in df_temp.columns.levels[0]:
        df_temp.loc[:, (farm, 'weights')] = 0.5

    return df_temp
Пример #24
0
print(turbines[turbines["turbine_id"].str.contains("ENERCON")])

# specification of own wind turbine (Note: power coefficient values and
# nominal power have to be in Watt)
myTurbine = {
    'name': 'myTurbine',
    'nominal_power': 3e6,  # in W
    'hub_height': 105,  # in m
    'rotor_diameter': 90,  # in m
    'power_curve': pd.DataFrame(
            data={'power': [p * 1000 for p in [
                      0.0, 26.0, 180.0, 1500.0, 3000.0, 3000.0]],  # in W
                  'wind_speed': [0.0, 3.0, 5.0, 10.0, 15.0, 25.0]})  # in m/s
    }
# initialise WindTurbine object
my_turbine = WindTurbine(**myTurbine)

# specification of wind turbine where power curve is provided
# if you want to use the power coefficient curve change the value of
# 'fetch_curve' to 'power_coefficient_curve'
enerconE126 = {
    'name': 'ENERCON E 126 7500',  # turbine name as in register
    'hub_height': 135,  # in m
    'rotor_diameter': 127,  # in m
    'fetch_curve': 'power_curve'  # fetch power curve
}
# initialise WindTurbine object
e126 = WindTurbine(**enerconE126)

# power output calculation for my_turbine
# initialise ModelChain with default parameters and use run_model
Пример #25
0
 def test_string_representation_of_wind_turbine(self):
     assert "Wind turbine: ['hub height=120 m'" in repr(WindTurbine(120))
Пример #26
0
df = wt.get_turbine_types(print_out=False)

# find all Enercons
print(df[df["manufacturer"].str.contains("Enercon")])

print(df[df["turbine_type"].str.contains("E-101")])

# specification of wind turbine where power curve is provided in the
# oedb turbine library

enercon_e126 = {
    'turbine_type': 'E-126/4200',  # turbine type as in oedb turbine library
    'hub_height': 135  # in m
}
# initialize WindTurbine object
e126 = WindTurbine(**enercon_e126)

# power output calculation for e126

# own specifications for ModelChain setup
modelchain_data = {
    'wind_speed_model': 'logarithmic',  # 'logarithmic' (default),
    # 'hellman' or
    # 'interpolation_extrapolation'
    'density_model': 'ideal_gas',  # 'barometric' (default), 'ideal_gas'
    #  or 'interpolation_extrapolation'
    'temperature_model': 'linear_gradient',  # 'linear_gradient' (def.) or
    # 'interpolation_extrapolation'
    'power_output_model': 'power_curve',  # 'power_curve' (default) or
    # 'power_coefficient_curve'
    'density_correction': True,  # False (default) or True