def test_temperature_as_np_array(self):
     """Test temperature as np.array"""
     parameters = {
         "temperature": np.array([267, 268]),
         "temperature_height": 2,
         "hub_height": 100,
     }
     temp_hub_exp = np.array([266.363, 267.36300])
     assert_array_equal(linear_gradient(**parameters), temp_hub_exp)
     assert isinstance(linear_gradient(**parameters), np.ndarray)
Exemple #2
0
    def test_linear_gradient(self):
        parameters = {
            'temperature': pd.Series(data=[267, 268]),
            'temperature_height': 2,
            'hub_height': 100
        }

        # Test temperature as pd.Series
        temp_hub_exp = pd.Series(data=[266.363, 267.36300])
        assert_series_equal(linear_gradient(**parameters), temp_hub_exp)

        # Test temperature as np.array
        temp_hub_exp = np.array([266.363, 267.36300])
        parameters['temperature'] = np.array(parameters['temperature'])
        assert_array_equal(linear_gradient(**parameters), temp_hub_exp)
        assert isinstance(linear_gradient(**parameters), np.ndarray)
 def test_linear_gradient(self):
     """Test temperature as pd.Series"""
     parameters = {
         "temperature": pd.Series(data=[267, 268]),
         "temperature_height": 2,
         "hub_height": 100,
     }
     temp_hub_exp = pd.Series(data=[266.363, 267.36300])
     assert_series_equal(linear_gradient(**parameters), temp_hub_exp)
    def temperature_hub(self, weather_df):
        r"""
        Calculates the temperature of air at hub height.

        The temperature is calculated using the method specified by
        the parameter `temperature_model`.

        Parameters
        ----------
        weather_df : :pandas:`pandas.DataFrame<frame>`
            DataFrame with time series for temperature `temperature` in K.
            The columns of the DataFrame are a MultiIndex where the first level
            contains the variable name (e.g. temperature) and the second level
            contains the height at which it applies (e.g. 10, if it was
            measured at a height of 10 m). See documentation of
            :func:`ModelChain.run_model` for an example on how to create the
            weather_df DataFrame.

        Returns
        -------
        :pandas:`pandas.Series<series>` or numpy.array
            Temperature of air in K at hub height.

        Notes
        -----
        If `weather_df` contains temperatures at different heights the given
        temperature(s) closest to the hub height are used.

        """
        if self.power_plant.hub_height in weather_df["temperature"]:
            temperature_hub = weather_df["temperature"][
                self.power_plant.hub_height]
        elif self.temperature_model == "linear_gradient":
            logging.debug("Calculating temperature using temperature "
                          "gradient.")
            closest_height = weather_df["temperature"].columns[min(
                range(len(weather_df["temperature"].columns)),
                key=lambda i: abs(weather_df["temperature"].columns[i] - self.
                                  power_plant.hub_height),
            )]
            temperature_hub = temperature.linear_gradient(
                weather_df["temperature"][closest_height],
                closest_height,
                self.power_plant.hub_height,
            )
        elif self.temperature_model == "interpolation_extrapolation":
            logging.debug("Calculating temperature using linear inter- or "
                          "extrapolation.")
            temperature_hub = tools.linear_interpolation_extrapolation(
                weather_df["temperature"], self.power_plant.hub_height)
        else:
            raise ValueError(
                "'{0}' is an invalid value. ".format(self.temperature_model) +
                "`temperature_model` must be "
                "'linear_gradient' or 'interpolation_extrapolation'.")
        return temperature_hub
Exemple #5
0
def power_output_density_corr(wind_turbine_fleet, weather_df, data_height):
    r"""
#    Calculate power output of several wind turbines ......
#
#    Simplest way to calculate the power output of a wind farm or other
#    gathering of wind turbines. For the power_output of the single turbines
#    a power_curve without density correction is used. The wind speed at hub
#    height is calculated by the logarithmic wind profile.

    Parameters
    ----------
    wind_turbine_fleet : List of Dictionaries
        Wind turbines of wind farm. Dictionaries must have 'wind_turbine'
        (contains wind turbine object) and 'number_of_turbines' (number of
        turbine type in wind farm) as keys.
    weather_df : pandas.DataFrame
        DataFrame with time series for wind speed `wind_speed` in m/s and
        roughness length `roughness_length` in m.
    data_height : Dictionary
        Contains the heights of the weather measurements or weather
        model in meters with the keys of the data parameter.

    Returns
    -------
    pd.Series
        Simulated power output of wind farm.

    """
    for turbine_type in wind_turbine_fleet:
        wind_speed_hub = wind_speed.logarithmic_profile(
            weather_df.wind_speed,
            data_height['wind_speed'],
            turbine_type['wind_turbine'].hub_height,
            weather_df.roughness_length,
            obstacle_height=0.0)
        temperature_hub = temperature.linear_gradient(
            weather_df.temperature, data_height['temperature'],
            turbine_type['wind_turbine'].hub_height)
        density_hub = density.ideal_gas(
            weather_df.pressure, data_height['pressure'],
            turbine_type['wind_turbine'].hub_height, temperature_hub)
        turbine_type['wind_turbine'].power_output = (
            power_output.power_curve_density_correction(
                wind_speed_hub,
                turbine_type['wind_turbine'].power_curve['wind_speed'],
                turbine_type['wind_turbine'].power_curve['power'],
                density_hub))
    return power_output_simple_aggregation(wind_turbine_fleet, weather_df,
                                           data_height)
def get_merra_data(year, raw_data=False, multi_index=True, heights=None,
                   filename='pickle_dump.p', pickle_load=False):
    r"""
    Reads csv file containing MERRA weather data and dumps it as data frame.

    Data is revised: unnecessary columns are droped, columns are renamed - if
    `raw_data` is False (default). The data will be dumped as a MultiIndex
    pandas DataFrame if `multi_index` is True (default).

    Parameters
    ----------
    year : Integer
        Year the weather data is fetched for.
    raw_data : Boolean
        If True only the raw weather data will be returned and dumped. Set
        `pickle_load` to False if you do not know whether the pickle dump
        contains raw data or revised data. Default: False.
    multi_index : Boolean
        True if the data shall be dumped as a MultiIndex pandas DataFrame.
        Default: True.
    heights : List, optional
        Contains heights for which the temperature shall be calculated (only
        for MultiIndex DataFrame). Default: None.
    filename : String
        Name (including path) of file to load data from or if MERRA data is
        retrieved function 'create_merra_df' is used. Default: 'pickle_dump.p'.
    pickle_load : Boolean
        True if data has already been dumped before. Default: False.

    Returns
    -------
    weather_df : pd.DataFrame
        Containins raw or already revised MERRA-2 weather data.

    """
    if pickle_load:
        weather_df = pickle.load(open(filename, 'rb'))
    else:
        print('---- MERRA-2 data of {0} is being loaded. ----'.format(year))
        # Load data from csv
        data_frame = pd.read_csv(os.path.join(
            os.path.dirname(__file__), 'data/Merra',
            'weather_data_GER_{0}.csv'.format(year)),
            sep=',', decimal='.', index_col=0)
        data_frame.index = pd.to_datetime(data_frame.index, utc=True)
        if not raw_data:
            if multi_index:
                if heights is not None:
                    # Calculate temperature at special heights (hub_heights)
                    # and add to multiindex dataframe
                    temp = data_frame['T']
                    temp_height = data_frame['h1']
                    second_level_columns = [50, 0, 0, 0]
                    first_level_columns = ['wind_speed', 'roughness_length',
                                           'density', 'pressure']
                    for height in heights:
                        second_level_columns.append(height)
                        first_level_columns.append('temperature')
                        df_part = pd.DataFrame(
                            data=temperature.linear_gradient(
                                temp, temp_height, height),
                            index=data_frame.index,
                            columns=['temperature_{0}'.format(height)])
                        data_frame = pd.concat([data_frame, df_part], axis=1)
                index = [data_frame.index, data_frame['lat'], data_frame['lon']]
                data_frame_2 = rename_columns(data_frame, ['T', 'h1', 'lat', 'lon'])
                data_frame_2.index = index
                weather_df = data_frame_2
                weather_df.columns = [first_level_columns,
                                      second_level_columns]
            else:
                weather_df = rename_columns(data_frame)
        else:
            weather_df = data_frame
        print('---- Loading of MERRA-2 data of {0} Done. ----'.format(year))
        pickle.dump(weather_df, open(filename, 'wb'))
    return weather_df