Skip to content

solar_workflow_manager

Classes:

LazyLoader

LazyLoader(lib_name)

LazyLoader is a utility class which postpones the "real" importing of the desired module until the time when it is actually needed

Source code in reskit/solar/workflows/solar_workflow_manager.py
def __init__(self, lib_name):
    """
    LazyLoader is a utility class which postpones the "real" importing of the desired module until the time when it is actually needed
    """
    self.lib_name = lib_name
    self._mod = None

SolarWorkflowManager

SolarWorkflowManager(placements)

Bases: WorkflowManager

__init_(self, placements)

Initialization of an instance of the generic SolarWorkflowManager class.

Parameters:

  • placements

    (pandas Dataframe) –
         The locations that the simulation should be run for.
         Columns must include "lon", "lat"
    

Returns:

  • SolarWorkflorManager

Methods:

Source code in reskit/solar/workflows/solar_workflow_manager.py
def __init__(self, placements):
    """

    __init_(self, placements)

    Initialization of an instance of the generic SolarWorkflowManager class.

    Parameters
    ----------
    placements : pandas Dataframe
                 The locations that the simulation should be run for.
                 Columns must include "lon", "lat"

    Returns
    -------
    SolarWorkflorManager

    """
    # Do basic workflow construction
    super().__init__(placements)
    self._time_sel_ = None
    self._time_index_ = None
    self.module = None

adjust_variable_to_long_run_average

adjust_variable_to_long_run_average(
    variable: str,
    source_long_run_average: Union[str, float, ndarray],
    real_long_run_average: Union[str, float, ndarray],
    real_lra_scaling: float = 1,
    spatial_interpolation: str = "linear-spline",
    nodata_fallback: str = "nan",
    nodata_fallback_scaling: float = 1,
    allow_nans: bool = True,
)

Adjusts the average mean of the specified variable to a known long-run-average

Note:

uses the equation: variable[t] = variable[t] * real_long_run_average / source_long_run_average

Parameters:

  • variable

    (str) –

    The variable to be adjusted

  • source_long_run_average

    (Union[str, float, ndarray]) –

    The variable's native long run average (the average in the weather file) - If a string is given, it is expected to be a path to a raster file which can be used to look up the average values from using the coordinates in .placements - If a numpy ndarray (or derivative) is given, the shape must be one of (time, placements) or at least (placements)

  • real_long_run_average

    (Union[str, float, ndarray]) –

    The variables 'true' long run average - If a string is given, it is expected to be a path to a raster file which can be used to look up the average values from using the coordinates in .placements - If a numpy ndarray (or derivative) is given, the shape must be one of (time, placements) or at least (placements)

  • real_lra_scaling

    (float, default: 1 ) –

    An optional scaling factor to apply to the values derived from real_long_run_average. - This is primarily useful when real_long_run_average is a path to a raster file - By default 1

  • spatial_interpolation

    (str, default: 'linear-spline' ) –

    When either source_long_run_average or real_long_run_average are a path to a raster file, this input specifies which interpolation algorithm should be used - Options are: "near", "linear-spline", "cubic-spline", "average" - By default "linear-spline" - See for more info: geokit.raster.interpolateValues

  • nodata_fallback

    (str, default: 'nan' ) –

    When real_long_run_average has no data, one can decide between different fallback options, by default np.nan: - np.nan or None : return np.nan for missing values in real_long_run_average - float : Apply this float value as a scaling factor for all no-data locations only: source_long_run_average * nodata_fallback. NOTE: A value of 1.0 will return the source lra value in case of missing real lra values (no additional nodata_fallback_scaling applied). - str : Will be interpreted as a filepath to a raster with alternative real_long_run_average values, scaled by nodata_fallback_scaling. - callable : any callable method taking the arguments (all iterables): 'locs' and 'source_long_run_average_value' (the locations as gk.geom.point objects and original value from source data). The output values will be considered as the new real_long_run_average for missing locations only (absolute data, no additional nodata_fallback_scaling applied).

    NOTE: np.nan will also be returned in case that the nodata fallback does not yield values either.

  • nodata_fallback_scaling

    (float, default: 1 ) –

    An optional scaling factor to apply to the values derived from nodata_fallback. - This is primarily useful when nodata_fallback is a path to a raster file - By default 1

  • allow_nans

    (boolean, default: True ) –

    If True, NaN values may remain after scaling, else an error will raised. By default True.

Returns:

Source code in reskit/workflow_manager.py
def adjust_variable_to_long_run_average(
    self,
    variable: str,
    source_long_run_average: Union[str, float, np.ndarray],
    real_long_run_average: Union[str, float, np.ndarray],
    real_lra_scaling: float = 1,
    spatial_interpolation: str = "linear-spline",
    nodata_fallback: str = "nan",
    nodata_fallback_scaling: float = 1,
    allow_nans: bool = True,
):
    """Adjusts the average mean of the specified variable to a known long-run-average

    Note:
    -----
    uses the equation: variable[t] = variable[t] * real_long_run_average / source_long_run_average

    Parameters
    ----------
    variable : str
        The variable to be adjusted

    source_long_run_average : Union[str, float, np.ndarray]
        The variable's native long run average (the average in the weather file)
        - If a string is given, it is expected to be a path to a raster file which can be
        used to look up the average values from using the coordinates in `.placements`
        - If a numpy ndarray (or derivative) is given, the shape must be one of (time, placements)
        or at least (placements)

    real_long_run_average : Union[str, float, np.ndarray]
        The variables 'true' long run average
        - If a string is given, it is expected to be a path to a raster file which can be
        used to look up the average values from using the coordinates in `.placements`
        - If a numpy ndarray (or derivative) is given, the shape must be one of (time, placements)
        or at least (placements)

    real_lra_scaling : float, optional
        An optional scaling factor to apply to the values derived from `real_long_run_average`.
        - This is primarily useful when `real_long_run_average` is a path to a raster file
        - By default 1

    spatial_interpolation : str, optional
        When either `source_long_run_average` or `real_long_run_average` are a path to a raster
        file, this input specifies which interpolation algorithm should be used
        - Options are: "near", "linear-spline", "cubic-spline", "average"
        - By default "linear-spline"
        - See for more info: geokit.raster.interpolateValues

    nodata_fallback: float, str, callable, optional
        When real_long_run_average has no data, one can decide between different fallback options, by default np.nan:
        - np.nan or None : return np.nan for missing values in real_long_run_average
        - float : Apply this float value as a scaling factor for all no-data locations only: source_long_run_average * nodata_fallback.
        NOTE: A value of 1.0 will return the source lra value in case of missing real lra values (no additional nodata_fallback_scaling applied).
        - str : Will be interpreted as a filepath to a raster with alternative real_long_run_average values, scaled by nodata_fallback_scaling.
        - callable : any callable method taking the arguments (all iterables): 'locs' and 'source_long_run_average_value'
        (the locations as gk.geom.point objects and original value from source data). The output values will be considered as
        the new real_long_run_average for missing locations only (absolute data, no additional nodata_fallback_scaling applied).

        NOTE: np.nan will also be returned in case that the nodata fallback does not yield values either.

    nodata_fallback_scaling: float
        An optional scaling factor to apply to the values derived from `nodata_fallback`.
        - This is primarily useful when `nodata_fallback` is a path to a raster file
        - By default 1

    allow_nans : boolean, optional
        If True, NaN values may remain after scaling, else an error will raised. By default True.

    Returns
    -------
    WorkflowManager
        Returns the invoking WorkflowManager (for chaining)
    """
    if not (nodata_fallback is None or callable(nodata_fallback) or isinstance(nodata_fallback, (float, int, str))):
        raise TypeError(f"'nodata_fallback' must be a float or a Callable.")

    # first get source values
    if isinstance(source_long_run_average, str):
        # assume raster fp
        source_lra = self.get_scalar_values_from_raster(
            fp=source_long_run_average, spatial_interpolation="linear-spline"
        )
    else:
        source_lra = source_long_run_average

    # then get lng-run average values for scaling
    if isinstance(real_long_run_average, str):
        # assume a raster path
        real_lra = self.get_scalar_values_from_raster(
            fp=real_long_run_average, spatial_interpolation=spatial_interpolation
        )
    else:
        real_lra = real_long_run_average

    # replace missing values with no-data fallback if needed
    if isinstance(nodata_fallback, str) and nodata_fallback.lower() == "source":
        warnings.warn(
            "'source' value for 'nodata_fallback' is deprecated and will be removed soon. Use 1.0 instead.",
            DeprecationWarning,
        )
        nodata_fallback = 1.0
    if isinstance(nodata_fallback, str) and nodata_fallback.lower() == "nan":
        warnings.warn(
            "'nan' value for 'nodata_fallback' is deprecated and will be removed soon. Use np.nan instead.",
            DeprecationWarning,
        )
        nodata_fallback = np.nan
    if any(np.isnan(real_lra)):  # TODO currently all real_lra are replaced by fallback, is this intentional?
        # we are lacking long-run average values
        if nodata_fallback is None or (isinstance(nodata_fallback, float) and np.isnan(nodata_fallback)):
            # nans will be returned for missing lra values
            fallback_lra = np.array([np.nan] * len(real_lra))
        elif isinstance(nodata_fallback, (int, float)):
            # apply factor to source_lra to scale missing values
            fallback_lra = nodata_fallback * source_lra  # no additional scaling
        elif callable(nodata_fallback):
            # apply function to calculate missing values
            fallback_lra = nodata_fallback(
                locs=self.locs, source_long_run_average_value=source_lra
            )  # no additional scaling
        elif isinstance(nodata_fallback, str):
            # assume this is yet another raster path as fallback and extract missing values
            fallback_lra = (
                self.get_scalar_values_from_raster(fp=nodata_fallback, spatial_interpolation=spatial_interpolation)
                * nodata_fallback_scaling
            )

        # divide by real_lra_scaling once to compensate later multiplication below for
        # scaling factor, nodata_fallback should not be multiplied by real_lra_scaling
        fallback_lra = fallback_lra / real_lra_scaling
        # set fallback values where real_lra is nan
        real_lra[np.isnan(real_lra)] = fallback_lra[np.isnan(real_lra)]

    # save LRA as attribute
    self.real_lra = real_lra

    # calculate scaling factor:
    # nan result will stay nan results, as these placements cannot be calculated any more
    factors = real_lra * real_lra_scaling / source_lra
    if any(np.isnan(real_lra)):
        if allow_nans:
            warnings.warn(f"NaN values remaining in real lra after application of nodata_fallback.")
        else:
            raise ValueError(f"Missing values for variable '{variable}' and NaNs not allowed.")

    # write info with missing values to sim_data:
    self.placements[f"missing_values_{basename(real_long_run_average)}_nodata_fallback{nodata_fallback}"] = (
        np.isnan(factors)
    )

    self.sim_data[variable] = factors * self.sim_data[variable]
    self.placements[f"LRA_factor_{variable}"] = factors
    return self

apply_DIRINT_model

apply_DIRINT_model(
    use_pressure=False, use_dew_temperature=False
)

apply_DIRINT_model(self, use_pressure=False, use_dew_temperature=False)

Determines direct normal irradiance (DNI) using the pvlib.irradiance.dirint() function [1].

Parameters:

  • use_pressure

          Default: False
    
  • use_dew_temperature

                 Default: False
    

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required data in the sim_data dictionary are 'global_horizontal_irradiance', 'surface_pressure', 'surface_dew_temperature', 'apparent_solar_zenith', 'air_mass' and 'extra_terrestrial_irradiance'.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.irradiance.dirint.html

[2] Perez, R., P. Ineichen, E. Maxwell, R. Seals and A. Zelenka, (1992). “Dynamic Global-to-Direct Irradiance Conversion Models”. ASHRAE Transactions-Research Series, pp. 354-369

[3] Maxwell, E. L., “A Quasi-Physical Model for Converting Hourly Global Horizontal to Direct Normal Insolation”, Technical Report No. SERI/TR-215-3087, Golden, CO: Solar Energy Research Institute, 1987.

Source code in reskit/solar/workflows/solar_workflow_manager.py
def apply_DIRINT_model(self, use_pressure=False, use_dew_temperature=False):
    """

    apply_DIRINT_model(self, use_pressure=False, use_dew_temperature=False)

    Determines direct normal irradiance (DNI) using the pvlib.irradiance.dirint() function [1].


    Parameters
    ----------
    use_pressure: boolian, optional
                  Default: False

    use_dew_temperature: boolian, optional
                         Default: False

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required data in the sim_data dictionary are 'global_horizontal_irradiance', 'surface_pressure',
    'surface_dew_temperature', 'apparent_solar_zenith', 'air_mass' and 'extra_terrestrial_irradiance'.

    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.irradiance.dirint.html

    [2]	Perez, R., P. Ineichen, E. Maxwell, R. Seals and A. Zelenka, (1992). “Dynamic Global-to-Direct Irradiance Conversion Models”. ASHRAE Transactions-Research Series, pp. 354-369

    [3]	Maxwell, E. L., “A Quasi-Physical Model for Converting Hourly Global Horizontal to Direct Normal Insolation”, Technical Report No. SERI/TR-215-3087, Golden, CO: Solar Energy Research Institute, 1987.


    """
    assert "global_horizontal_irradiance" in self.sim_data
    assert "surface_pressure" in self.sim_data
    assert "surface_dew_temperature" in self.sim_data
    assert "apparent_solar_zenith" in self.sim_data
    assert "air_mass" in self.sim_data
    assert "extra_terrestrial_irradiance" in self.sim_data

    # self.sim_data["direct_normal_irradiance"] = solarpower.myDirint(
    #     ghi=self.sim_data['global_horizontal_irradiance'],
    #     zenith=self.sim_data["apparent_solar_zenith"],
    #     pressure=self.sim_data["surface_pressure"],
    #     amRel=self.sim_data["air_mass"],
    #     I0=self.sim_data["extra_terrestrial_irradiance"],
    #     temp_dew=self.sim_data["surface_dew_temperature"],
    #     use_delta_kt_prime=True,)

    use_pressure = True
    use_dew_temperature = True

    g = self.sim_data["global_horizontal_irradiance"].flatten()
    z = self.sim_data["apparent_solar_zenith"].flatten()
    p = self.sim_data["surface_pressure"].flatten() if use_pressure else None
    td = self.sim_data["surface_dew_temperature"].flatten() if use_dew_temperature else None
    times = pd.DatetimeIndex(np.column_stack([self._time_index_ for x in range(self._sim_shape_[1])]).flatten())

    self.sim_data["direct_normal_irradiance"] = (
        pvlib.irradiance.dirint(ghi=g, solar_zenith=z, times=times, pressure=p, temp_dew=td)
        .fillna(0)
        .values.reshape(self._sim_shape_)
    )

    return self

apply_angle_of_incidence_losses_to_poa

apply_angle_of_incidence_losses_to_poa()

apply_angle_of_incidence_losses_to_poa(self)

Applies the angle of incidence losses to the plane-of-array irradiance using the pvlib.pvsystem.iam.physical() function [1].

Parameters:

  • None

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required data in the sim_data dictionary are 'poa_direct', 'poa_ground_diffuse' and 'poa_sky_diffuse'.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.iam.physical.html

Source code in reskit/solar/workflows/solar_workflow_manager.py
def apply_angle_of_incidence_losses_to_poa(self):
    """
    apply_angle_of_incidence_losses_to_poa(self)

    Applies the angle of incidence losses to the plane-of-array irradiance using the pvlib.pvsystem.iam.physical() function [1].

    Parameters
    ----------
    None

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required data in the sim_data dictionary are 'poa_direct', 'poa_ground_diffuse' and 'poa_sky_diffuse'.

    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.iam.physical.html


    """
    assert "poa_direct" in self.sim_data
    assert "poa_ground_diffuse" in self.sim_data
    assert "poa_sky_diffuse" in self.sim_data

    tilt = self.sim_data.get("system_tilt", self.placements["tilt"].values)

    self.sim_data["poa_direct"] *= pvlib.pvsystem.iam.physical(
        aoi=self.sim_data["angle_of_incidence"],
        n=1.526,  # PVLIB v0.7.2 default
        K=4.0,  # PVLIB v0.7.2 default
        L=0.002,  # PVLIB v0.7.2 default
    )

    # Effective angle of incidence values from "Solar-Engineering-of-Thermal-Processes-4th-Edition"
    self.sim_data["poa_ground_diffuse"] *= pvlib.pvsystem.iam.physical(
        aoi=(90 - 0.5788 * tilt + 0.002693 * np.power(tilt, 2)),
        n=1.526,  # PVLIB v0.7.2 default
        K=4.0,  # PVLIB v0.7.2 default
        L=0.002,  # PVLIB v0.7.2 default
    )

    self.sim_data["poa_sky_diffuse"] *= pvlib.pvsystem.iam.physical(
        aoi=(59.7 - 0.1388 * tilt + 0.001497 * np.power(tilt, 2)),
        n=1.526,  # PVLIB v0.7.2 default
        K=4.0,  # PVLIB v0.7.2 default
        L=0.002,  # PVLIB v0.7.2 default
    )

    self.sim_data["poa_diffuse"] = self.sim_data["poa_ground_diffuse"] + self.sim_data["poa_sky_diffuse"]
    self.sim_data["poa_global"] = self.sim_data["poa_direct"] + self.sim_data["poa_diffuse"]

    assert (self.sim_data["poa_global"] < 1600).all(), "POA is too large"

    return self

apply_elevation

apply_elevation(elev, fallback_elev=0)

apply_elevation(self)

Adds an elevation (name: 'elev') column to the placements data frame.

Parameters:

  • elev

    If a string is given it must be a path to a rasterfile including the elevations. If an iterable is given it has to include the elevations at each location and be of equal length to self.placements dataframe. If an integer is given, it will be applied to all locations equally.

  • fallback_elev

    The fallback value that will be used in case that elev is a raster path and the extraction of the elevation from raster fails (applied only to no-data locations). By default 0.

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object
Source code in reskit/solar/workflows/solar_workflow_manager.py
def apply_elevation(self, elev, fallback_elev=0):
    """

    apply_elevation(self)

    Adds an elevation (name: 'elev') column to the placements data frame.

    Parameters
    ----------
    elev: str, int, iterable
        If a string is given it must be a path to a rasterfile including the elevations.
        If an iterable is given it has to include the elevations at each location and be
        of equal length to self.placements dataframe.
        If an integer is given, it will be applied to all locations equally.

    fallback_elev: int, optional
        The fallback value that will be used in case that elev is a raster path and the
        extraction of the elevation from raster fails (applied only to no-data locations).
        By default 0.

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object

    """
    assert isinstance(fallback_elev, int), f"'fallback_elev' must be an integer elevantion in [m]."
    if elev is None and "elev" in self.placements.columns:
        # elevation is already an attribute in the placements dataframe, do nothing if no external elev given
        pass
    elif elev is None:
        # we don't have given elevation info, neither as elev arg nor in placements dataframe column
        # set all values to fallback
        self.placements["elev"] = np.array([fallback_elev] * len(self.locs))
    elif isinstance(elev, str):
        # assume we have a str formatted elevation raster path
        clipped_elev = self.ext.pad(0.5).rasterMosaic(elev)
        if clipped_elev is None:
            _elevs = np.array([np.nan] * len(self.locs))
        else:
            _elevs = gk.raster.interpolateValues(clipped_elev, self.locs)
            if np.isnan(_elevs).any():
                # if getting values fails, it could be because of interpolation method
                # replace by 'near' interpolation
                _elevs_near = gk.raster.interpolateValues(clipped_elev, self.locs, mode="near")
                _elevs[np.isnan(_elevs)] = _elevs_near[np.isnan(_elevs)]
        if np.isnan(_elevs).any():
            # if we still have nans, replace nans by fallback value
            _elevs[np.isnan(_elevs)] = (np.ones(shape=_elevs.shape) * fallback_elev)[np.isnan(_elevs)]
        self.placements["elev"] = _elevs
    else:
        # try to just set elev as new column, works with scalars and iterables, and check if we have numeric values
        try:
            self.placements["elev"] = elev
            assert all([isinstance(x, numbers.Number) for x in self.placements["elev"]])
        except:
            # else rise a type error
            raise TypeError(
                f"'elev' must be given as a path to a raster file or an integer or an iterable thereof with equal length to the dataframe length."
            )

    return self

apply_inverter_losses

apply_inverter_losses(inverter, method='sandia')

apply_inverter_losses(self, inverter, method="sandia", )

Applies inverter losses using the pvlib.pvsystem.snlinverter() function [1], the pvlib.pvsystem.retrieve_sam() function [2] and the pvlib.pvsystem.adrinverter() function [3].

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required data in the sim_data dictionary are 'module_dc_power_at_mpp' and 'module_dc_voltage_at_mpp'. Required data in the placements dataframe are 'modules_per_string' and 'strings_per_inverter'. Cannot simultaneously provide 'capacity' and inverter-string parameters.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.snlinverter.html

[2] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.retrieve_sam.html

[3] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.adrinverter.html

[4] SAND2007-5036, “Performance Model for Grid-Connected Photovoltaic Inverters by D. King, S. Gonzalez, G. Galbraith, W. Boyson

[5] System Advisor Model web page. https://sam.nrel.gov.

[6] Beyond the Curves: Modeling the Electrical Efficiency of Photovoltaic Inverters, PVSC 2008, Anton Driesse et. al.

Source code in reskit/solar/workflows/solar_workflow_manager.py
def apply_inverter_losses(
    self,
    inverter,
    method="sandia",
):
    """
     apply_inverter_losses(self, inverter, method="sandia", )

     Applies inverter losses using the pvlib.pvsystem.snlinverter() function [1], the pvlib.pvsystem.retrieve_sam() function [2] and the
     pvlib.pvsystem.adrinverter() function [3].


    Parameters
    ----------
     inverter: str
               Describes the inverter.
               [TODO: Add a more detailed description following the example of 'configure_cec_module']
     method: str
             Options:
             "scandia"
             "driesse"
             Describes the used method to apply the inverter losses.

    Returns
    -------
     Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
     Required data in the sim_data dictionary are 'module_dc_power_at_mpp' and 'module_dc_voltage_at_mpp'.
     Required data in the placements dataframe are 'modules_per_string' and 'strings_per_inverter'.
     Cannot simultaneously provide 'capacity' and inverter-string parameters.


    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.snlinverter.html

    [2] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.retrieve_sam.html

    [3] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.adrinverter.html

    [4]	SAND2007-5036, “Performance Model for Grid-Connected Photovoltaic Inverters by D. King, S. Gonzalez, G. Galbraith, W. Boyson

    [5]	System Advisor Model web page. https://sam.nrel.gov.

    [6]	Beyond the Curves: Modeling the Electrical Efficiency of Photovoltaic Inverters, PVSC 2008, Anton Driesse et. al.

    """
    """method can be: 'sandia' or 'driesse'

    TODO: Make it work with multiplt inverter definitions
    """

    assert "module_dc_power_at_mpp" in self.sim_data
    assert "module_dc_voltage_at_mpp" in self.sim_data
    assert hasattr(self, "module")
    assert "modules_per_string" in self.placements.columns
    assert "strings_per_inverter" in self.placements.columns
    assert not "capacity" in self.placements.columns, (
        "Cannot simultaneously provide 'capacity' and inverter-string parameters"
    )

    if method == "sandia":
        if isinstance(inverter, str):
            db = pvlib.pvsystem.retrieve_sam("SandiaInverter")
            inverter = getattr(db, inverter)

        self.sim_data["inverter_ac_power_at_mpp"] = pvlib.inverter.sandia(
            v_dc=self.sim_data["module_dc_voltage_at_mpp"]
            * np.broadcast_to(self.placements.modules_per_string, self._sim_shape_),
            p_dc=self.sim_data["module_dc_power_at_mpp"]
            * np.broadcast_to(
                self.placements.modules_per_string * self.placements.strings_per_inverter,
                self._sim_shape_,
            ),
            inverter=inverter,
        )

    elif method == "driesse":
        if isinstance(inverter, str):
            db = pvlib.pvsystem.retrieve_sam("CECInverter")
            inverter = getattr(db, inverter)

        self.sim_data["inverter_ac_power_at_mpp"] = pvlib.pvsystem.adrinverter(
            v_dc=self.sim_data["module_dc_voltage_at_mpp"]
            * np.broadcast_to(self.placements.modules_per_string, self._sim_shape_),
            p_dc=self.sim_data["module_dc_power_at_mpp"]
            * np.broadcast_to(
                self.placements.modules_per_string * self.placements.strings_per_inverter,
                self._sim_shape_,
            ),
            inverter=inverter,
        )

    number_of_inverters = getattr(self.placements, "number_of_inverters", 1)
    self.sim_data["total_system_generation"] = self.sim_data["inverter_ac_power_at_mpp"] * np.broadcast_to(
        number_of_inverters, self._sim_shape_
    )

    total_capacity = (
        self.module.I_mp_ref
        * self.module.V_mp_ref
        * self.placements.modules_per_string
        * self.placements.strings_per_inverter
        * number_of_inverters
    )

    self.sim_data["capacity_factor"] = self.sim_data["total_system_generation"] / np.broadcast_to(
        total_capacity, self._sim_shape_
    )

    return self

apply_loss_factor

apply_loss_factor(
    loss: Union[float, ndarray, FunctionType],
    variables: Union[str, List[str]] = ["capacity_factor"],
)

Applies a loss factor onto a specified variable

Parameters:

  • loss

    (Union[float, ndarray, FunctionType]) –

    The loss factor(s) to be applied - If a float or a numpy ndarray is given, then the following operation is performed:

    variable = variable * (1 - loss) - If a function is given, then the following operation is performed: variable = variable * (1 - loss(variable) ) - If a numpy ndarray is given, it must be broadcastable to the variable's shape in .sim_data

  • variables

    (Union[str, List[str]], default: ['capacity_factor'] ) –

    The variable or variables to apply the loss factor to - By default ["capacity_factor"]

Returns:

Source code in reskit/workflow_manager.py
def apply_loss_factor(
    self,
    loss: Union[float, np.ndarray, FunctionType],
    variables: Union[str, List[str]] = ["capacity_factor"],
):
    """Applies a loss factor onto a specified variable

    Parameters
    ----------
    loss : Union[float, np.ndarray, FunctionType]
        The loss factor(s) to be applied
        - If a float or a numpy ndarray is given, then the following operation is performed:
        > variable = variable * (1 - loss)
        - If a function is given, then  the following operation is performed:
        > variable = variable * (1 - loss(variable) )
        - If a numpy ndarray is given, it must be broadcastable to the variable's shape in
        `.sim_data`

    variables : Union[str, List[str]], optional
        The variable or variables to apply the loss factor to
        - By default ["capacity_factor"]

    Returns
    -------
    WorkflowManager
        Returns the invoking WorkflowManager (for chaining)
    """
    # filter only existing variables
    _variables = [_var for _var in variables if _var in self.sim_data.keys()]
    if len(_variables) < len(variables):
        warnings.warn(
            f"Loss factor could not be applied to the following requested variables because variables are not in sim_data: {', '.join(sorted(set(variables) - set(_variables)))}"
        )

    for var in _variables:
        if isinstance(loss, FunctionType):
            self.sim_data[var] *= 1 - loss(self.sim_data[var])
        else:
            self.sim_data[var] *= 1 - loss

    return self

cell_temperature_from_sapm

cell_temperature_from_sapm(mounting='glass_open_rack')

cell_temperature_from_sapm(self, mounting="glass_open_rack")

Calculates the cell temperature based on the pvlib.temperature.sapm_cell() function [1].

Parameters:

  • mounting

      Options:
      "glass_open_rack" [1]
      "glass_close_roof" [1]
      "polymer_open_rack" [1]
      "polymer_insulated_back" [1]
    

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required data in the sim_data dictionary are 'surface_wind_speed', 'surface_air_temperature' and 'poa_global'.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.temperature.sapm_cell.html

Source code in reskit/solar/workflows/solar_workflow_manager.py
def cell_temperature_from_sapm(self, mounting="glass_open_rack"):
    """
    cell_temperature_from_sapm(self, mounting="glass_open_rack")

    Calculates the cell temperature based on the pvlib.temperature.sapm_cell() function [1].


    Parameters
    ----------
    mounting: str
              Options:
              "glass_open_rack" [1]
              "glass_close_roof" [1]
              "polymer_open_rack" [1]
              "polymer_insulated_back" [1]

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required data in the sim_data dictionary are 'surface_wind_speed', 'surface_air_temperature' and 'poa_global'.

    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.temperature.sapm_cell.html


    """
    assert "surface_wind_speed" in self.sim_data
    assert "surface_air_temperature" in self.sim_data
    assert "poa_global" in self.sim_data

    if mounting == "glass_open_rack":
        a, b, dT = -3.47, -0.0594, 3
    elif mounting == "glass_close_roof":
        a, b, dT = -2.98, -0.0471, 1
    elif mounting == "polymer_open_rack":
        a, b, dT = -3.56, -0.075, 3
    elif mounting == "polymer_insulated_back":
        a, b, dT = -2.81, -0.0455, 0
    else:
        raise RuntimeError(
            "mounting not one of: 'glass_open_rack', 'glass_close_roof', 'polymer_open_rack', or 'polymer_insulated_back'"
        )

    self.sim_data["cell_temperature"] = pvlib.temperature.sapm_cell(
        self.sim_data["poa_global"],
        self.sim_data["surface_air_temperature"],
        self.sim_data["surface_wind_speed"],
        a=a,
        b=b,
        deltaT=dT,
        irrad_ref=1000,
    )

    return self

configure_cec_module

configure_cec_module(
    module="WINAICO WSx-240P6", tech_year=2050
)

configure_cec_module(self, module="WINAICO WSx-240P6")

Configures CEC of a module based on the outputs of the pvlib.pvsystem.retrieve_sam() function [1].

Parameters:

  • module

    Must be one of: * A module found in the pvlib.pvsystem.retrieve_sam("CECMod") database * "WINAICO WSx-240P6" -> Good for open-field applications * "LG Electronics LG370Q1C-A5" -> Good for rooftop applications * A dict containing a set of module parameters, including: T_NOCT, A_c, N_s, I_sc_ref, V_oc_ref, I_mp_ref, V_mp_ref, alpha_sc, beta_oc, a_ref, I_L_ref, I_o_ref, R_s, R_sh_ref, Adjust, gamma_r, PTC

  • tech_year

    (int, default: 2050 ) –

    If given in combination with the projected module str names "WINAICO WSx-240P6" or "LG Electronics LG370Q1C-A5", the effifiency will be scaled linearly to the given year. Must then be between year of market comparison in analysis (2019) and 2050. Will be ignored when non-projected existing module names or specific parameters are given, can then be None. By default 2050.

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object
References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.retrieve_sam.html

Source code in reskit/solar/workflows/solar_workflow_manager.py
def configure_cec_module(
    self,
    module="WINAICO WSx-240P6",
    tech_year=2050,
):
    """
    configure_cec_module(self, module="WINAICO WSx-240P6")

    Configures CEC of a module based on the outputs of the pvlib.pvsystem.retrieve_sam() function [1].

    Parameters
    ----------
    module: str or dict
        Must be one of:
            * A module found in the pvlib.pvsystem.retrieve_sam("CECMod") database
            * "WINAICO WSx-240P6" -> Good for open-field applications
            * "LG Electronics LG370Q1C-A5" -> Good for rooftop applications
            * A dict containing a set of module parameters, including:
                T_NOCT, A_c, N_s, I_sc_ref, V_oc_ref, I_mp_ref, V_mp_ref, alpha_sc,
                beta_oc, a_ref, I_L_ref, I_o_ref, R_s, R_sh_ref, Adjust, gamma_r, PTC
    tech_year : int, optional
        If given in combination with the projected module str names "WINAICO WSx-240P6" or
        "LG Electronics LG370Q1C-A5", the effifiency will be scaled linearly to the given
        year. Must then be between year of market comparison in analysis (2019) and 2050.
        Will be ignored when non-projected existing module names or specific parameters
        are given, can then be None. By default 2050.

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object

    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.retrieve_sam.html


    """

    def _interpolate_module_params(projected_module, original_module_name, tech_year, start_year):
        if not isinstance(tech_year, int):
            raise TypeError(f"tech_year must be an integer when projected module is selected")
        # avoid extrapolations
        if not start_year <= tech_year <= 2050:
            raise ValueError(f"tech_year must be between {start_year} and 2050 (max. projection) for this module")

        # get the original (unprojected) module parameters
        db = pvlib.pvsystem.retrieve_sam("CECMod")
        original_module = getattr(db, original_module_name)
        # scale module parameters to tech_year
        module = pd.Series(index=projected_module.index, dtype="float64")
        for param, val_proj in zip(projected_module.index, projected_module):
            if param == "Date":
                module[param] = str(tech_year)
            elif param in ["Version"]:
                # ignore, set dummy nan
                module[param] = np.nan
            elif isinstance(val_proj, (int, float, np.integer)):
                module[param] = original_module[param] + (val_proj - original_module[param]) * (
                    tech_year - start_year
                ) / (2050 - start_year)
            else:
                assert val_proj == original_module[param], (
                    f"parameter '{param}' is not the same for original ({original_module[param]}) and projected ({val_proj}) modules"
                )
                module[param] = val_proj

        return module

    if isinstance(module, str):
        self.register_workflow_parameter("module_name", module)

        if module == "WINAICO WSx-240P6":
            # define projected module parameters
            module_2050 = pd.Series(
                dict(
                    BIPV="N",
                    Date="6/2/2014",
                    T_NOCT=43,
                    A_c=1.663,
                    N_s=60,
                    I_sc_ref=8.41,
                    V_oc_ref=37.12,
                    I_mp_ref=7.96,
                    V_mp_ref=30.2,
                    alpha_sc=0.001164,
                    beta_oc=-0.12357,
                    a_ref=1.6704,
                    I_L_ref=8.961,
                    I_o_ref=1.66e-11,
                    R_s=0.405,
                    R_sh_ref=326.74,
                    Adjust=4.747,
                    gamma_r=-0.383,
                    Version="NRELv1",
                    PTC=220.2,
                    Technology="Multi-c-Si",
                )
            )

            # scale module parameters to tech_year
            module = _interpolate_module_params(
                projected_module=module_2050,
                original_module_name="WINAICO_WSx_240P6",
                tech_year=tech_year,
                start_year=2019,
            )

            module.name = "WINAICO WSx-240P6"

        elif module == "LG Electronics LG370Q1C-A5":
            # define projected module parameters
            module_2050 = pd.Series(
                dict(
                    BIPV="N",
                    Date="12/14/2016",
                    T_NOCT=45.7,
                    A_c=1.673,
                    N_s=60,
                    I_sc_ref=10.82,
                    V_oc_ref=42.8,
                    I_mp_ref=10.01,
                    V_mp_ref=37,
                    alpha_sc=0.003246,
                    beta_oc=-0.10272,
                    a_ref=1.5532,
                    I_L_ref=10.829,
                    I_o_ref=1.12e-11,
                    R_s=0.079,
                    R_sh_ref=92.96,
                    Adjust=14,
                    gamma_r=-0.32,
                    Version="NRELv1",
                    PTC=347.2,
                    Technology="Mono-c-Si",
                )
            )

            # scale module parameters to tech_year
            module = _interpolate_module_params(
                projected_module=module_2050,
                original_module_name="LG_Electronics_Inc__LG370Q1C_A5",
                tech_year=tech_year,
                start_year=2019,
            )

            module.name = "LG Electronics LG370Q1C-A5"

        elif isinstance(module, str):
            if tech_year is not None:
                warnings.warn(
                    f"NOTE: The tech_year argument is ignored when a specific module is given. Set tech_year to None to silence this warning."
                )
            # Extract module parameters
            db = pvlib.pvsystem.retrieve_sam("CECMod")
            try:
                module = getattr(db, module)
            except:
                raise RuntimeError("The module '{}' is not in the CEC database".format(module))
    else:
        if tech_year is not None:
            print(f"NOTE: The tech_year argument is ignored when specific module parameters are given.")
        module = pd.Series(module)
        assert "T_NOCT" in module.index
        assert "A_c" in module.index
        assert "N_s" in module.index
        assert "I_sc_ref" in module.index
        assert "V_oc_ref" in module.index
        assert "I_mp_ref" in module.index
        assert "V_mp_ref" in module.index
        assert "alpha_sc" in module.index
        assert "beta_oc" in module.index
        assert "a_ref" in module.index
        assert "I_L_ref" in module.index
        assert "I_o_ref" in module.index
        assert "R_s" in module.index
        assert "R_sh_ref" in module.index
        assert "Adjust" in module.index
        assert "gamma_r" in module.index
        assert "PTC" in module.index

        try:
            module_desc = json.dumps(module)
        except:
            module_desc = "user-configured"
        self.register_workflow_parameter("module_desc", module_desc)

    # # Check if we need to add the Desoto parameters
    # # defaults for EgRef and dEgdT taken from the note in the docstring for
    # #  'pvlib.pvsystem.calcparams_desoto'
    # if not "EgRef" in module:
    #     module['EgRef'] = 1.121
    # if not "dEgdT" in module:
    #     module['dEgdT'] = -0.0002677

    self.module = module

    return self

determine_air_mass

determine_air_mass(model='kastenyoung1989')

determine_air_mass(self, model='kastenyoung1989')

Determines air mass using the pvlib function pvlib.atmosphere.get_relative_airmass() [1].

Parameters:

  • model

    default 'kastenyoung1989' [1]

    'simple' - secant(apparent zenith angle) - Note that this gives -inf at zenith=90 [2] 'kasten1966' - See reference [2] - requires apparent sun zenith [2] 'youngirvine1967' - See reference [3] - requires true sun zenith [2] 'kastenyoung1989' - See reference [4] - requires apparent sun zenith [2] 'gueymard1993' - See reference [5] - requires apparent sun zenith [2] 'young1994' - See reference [6] - requires true sun zenith [2] 'pickering2002' - See reference [7] - requires apparent sun zenith [2]

Returns:

  • Nothing is returned.
Notes

Required data in the sim_data dictionary are 'apparent_solar_zenith'.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.atmosphere.get_relative_airmass.html

[2] Fritz Kasten. “A New Table and Approximation Formula for the Relative Optical Air Mass”. Technical Report 136, Hanover, N.H.: U.S. Army Material Command, CRREL.

[3] A. T. Young and W. M. Irvine, “Multicolor Photoelectric Photometry of the Brighter Planets,” The Astronomical Journal, vol. 72, pp. 945-950, 1967.

[4] Fritz Kasten and Andrew Young. “Revised optical air mass tables and approximation formula”. Applied Optics 28:4735-4738

[5] C. Gueymard, “Critical analysis and performance assessment of clear sky solar irradiance models using theoretical and measured data,” Solar Energy, vol. 51, pp. 121-138, 1993.

[6] A. T. Young, “AIR-MASS AND REFRACTION,” Applied Optics, vol. 33, pp. 1108-1110, Feb 1994.

[7] Keith A. Pickering. “The Ancient Star Catalog”. DIO 12:1, 20,

[8] Matthew J. Reno, Clifford W. Hansen and Joshua S. Stein, “Global Horizontal Irradiance Clear Sky Models: Implementation and Analysis” Sandia Report, (2012).

Source code in reskit/solar/workflows/solar_workflow_manager.py
def determine_air_mass(self, model="kastenyoung1989"):
    """

    determine_air_mass(self, model='kastenyoung1989')

    Determines air mass using the pvlib function pvlib.atmosphere.get_relative_airmass() [1].


    Parameters
    ----------
    model: str, optional
           default 'kastenyoung1989' [1]

           'simple' - secant(apparent zenith angle) - Note that this gives -inf at zenith=90 [2]
           'kasten1966' - See reference [2] - requires apparent sun zenith [2]
           'youngirvine1967' - See reference [3] - requires true sun zenith [2]
           'kastenyoung1989' - See reference [4] - requires apparent sun zenith [2]
           'gueymard1993' - See reference [5] - requires apparent sun zenith [2]
           'young1994' - See reference [6] - requires true sun zenith [2]
           'pickering2002' - See reference [7] - requires apparent sun zenith [2]



    Returns
    -------
    Nothing is returned.

    Notes
    -----
    Required data in the sim_data dictionary are 'apparent_solar_zenith'.



    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.atmosphere.get_relative_airmass.html

    [2]	Fritz Kasten. “A New Table and Approximation Formula for the Relative Optical Air Mass”. Technical Report 136, Hanover, N.H.: U.S. Army Material Command, CRREL.

    [3]	A. T. Young and W. M. Irvine, “Multicolor Photoelectric Photometry of the Brighter Planets,” The Astronomical Journal, vol. 72, pp. 945-950, 1967.

    [4]	Fritz Kasten and Andrew Young. “Revised optical air mass tables and approximation formula”. Applied Optics 28:4735-4738

    [5]	C. Gueymard, “Critical analysis and performance assessment of clear sky solar irradiance models using theoretical and measured data,” Solar Energy, vol. 51, pp. 121-138, 1993.

    [6]	A. T. Young, “AIR-MASS AND REFRACTION,” Applied Optics, vol. 33, pp. 1108-1110, Feb 1994.

    [7]	Keith A. Pickering. “The Ancient Star Catalog”. DIO 12:1, 20,

    [8]	Matthew J. Reno, Clifford W. Hansen and Joshua S. Stein, “Global Horizontal Irradiance Clear Sky Models: Implementation and Analysis” Sandia Report, (2012).


    """
    assert "apparent_solar_zenith" in self.sim_data

    # 29 because that what the function seems to max out at as zenith approaches 90
    self.sim_data["air_mass"] = np.full_like(self.sim_data["apparent_solar_zenith"], 29)

    s = self.sim_data["apparent_solar_zenith"] < 90
    self.sim_data["air_mass"][s] = pvlib.atmosphere.get_relative_airmass(
        self.sim_data["apparent_solar_zenith"][s], model=model
    )

determine_angle_of_incidence

determine_angle_of_incidence()

determine_angle_of_incidence(self)

Determines the angle of incidence [TODO: credit the PVLib function as you've done in previous examples].

Parameters:

  • None

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required data in the sim_data dictionary are 'apparent_solar_zenith' and 'solar_azimuth'.

Source code in reskit/solar/workflows/solar_workflow_manager.py
def determine_angle_of_incidence(self):
    """

    determine_angle_of_incidence(self)

    Determines the angle of incidence [TODO: credit the PVLib function as you've done in previous examples].

    Parameters
    ----------
    None

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required data in the sim_data dictionary are 'apparent_solar_zenith' and 'solar_azimuth'.

    """
    """tracking can be: 'fixed' or 'singleaxis'"""
    assert "apparent_solar_zenith" in self.sim_data
    assert "solar_azimuth" in self.sim_data

    azimuth = self.sim_data.get("system_azimuth", self.placements["azimuth"].values)
    tilt = self.sim_data.get("system_tilt", self.placements["tilt"].values)

    self.sim_data["angle_of_incidence"] = np.nan_to_num(
        pvlib.irradiance.aoi(
            tilt,
            azimuth,
            self.sim_data["apparent_solar_zenith"],
            self.sim_data["solar_azimuth"],
        ),
        0,
    )

    return self

determine_extra_terrestrial_irradiance

determine_extra_terrestrial_irradiance(**kwargs)

determine_extra_terrestrial_irradiance(self, **kwargs)

Determines extra terrestrial irradiance using the pvlib.irradiance.get_extra_radiation() function [1].

Parameters:

  • None

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.irradiance.get_extra_radiation.html

[2] M. Reno, C. Hansen, and J. Stein, “Global Horizontal Irradiance Clear Sky Models: Implementation and Analysis”, Sandia National Laboratories, SAND2012-2389, 2012.

[3] https://web.archive.org/web/20230529210255/http://solardat.uoregon.edu/SolarRadiationBasics.html, Eqs. SR1 and SR2 (the UO SRML moved to solardata.uoregon.edu and dropped this page; the archived copy is cited because it carries the numbered equations)

[4] Partridge, G. W. and Platt, C. M. R. 1976. Radiative Processes in Meteorology and Climatology.

[5] Duffie, J. A. and Beckman, W. A. 1991. Solar Engineering of Thermal Processes, 2nd edn. J. Wiley and Sons, New York.

[6] ASCE, 2005. The ASCE Standardized Reference Evapotranspiration Equation, Environmental and Water Resources Institute of the American Civil Engineers, Ed. R. G. Allen et al.

Source code in reskit/solar/workflows/solar_workflow_manager.py
def determine_extra_terrestrial_irradiance(self, **kwargs):
    """

    determine_extra_terrestrial_irradiance(self, **kwargs)

    Determines extra terrestrial irradiance using the pvlib.irradiance.get_extra_radiation() function [1].

    Parameters
    ----------
    None

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.


    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.irradiance.get_extra_radiation.html

    [2]	M. Reno, C. Hansen, and J. Stein, “Global Horizontal Irradiance Clear Sky Models: Implementation and Analysis”, Sandia National Laboratories, SAND2012-2389, 2012.

    [3]	<https://web.archive.org/web/20230529210255/http://solardat.uoregon.edu/SolarRadiationBasics.html>, Eqs. SR1 and SR2
    (the UO SRML moved to solardata.uoregon.edu and dropped this page; the
    archived copy is cited because it carries the numbered equations)

    [4]	Partridge, G. W. and Platt, C. M. R. 1976. Radiative Processes in Meteorology and Climatology.

    [5]	Duffie, J. A. and Beckman, W. A. 1991. Solar Engineering of Thermal Processes, 2nd edn. J. Wiley and Sons, New York.

    [6]	ASCE, 2005. The ASCE Standardized Reference Evapotranspiration Equation, Environmental and Water Resources Institute of the American Civil Engineers, Ed. R. G. Allen et al.

    """
    dni_extra = pvlib.irradiance.get_extra_radiation(self._time_index_, **kwargs).values

    shape = len(self._time_index_), self.locs.count
    self.sim_data["extra_terrestrial_irradiance"] = np.broadcast_to(dni_extra.reshape((shape[0], 1)), shape)

    return self

determine_solar_position

determine_solar_position(
    lon_rounding=1, lat_rounding=1, elev_rounding=-2
)

determine_solar_position(self, lon_rounding=1, lat_rounding=1, elev_rounding=-2)

Calculates azimuth and apparent zenith for each location using the pvlib function pvlib.solarposition.spa_python() [1]. Adds azimuth and apparent zenit to the sim_data dictionary.

Parameters:

  • lon_rounding

          Decimal places that the longitude should be rounded to. Default is 1.
    
  • lat_rounding

          Decimal places that the latitude should be rounded to. Default is 1.
    
  • elev_rounding

          Decimal places that the elevation should be rounded to. Default is -2.
    

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object
Notes

Required columns in the placements dataframe to use this functions are 'lon', 'lat' and 'elev'. Required data in the sim_data dictionary are 'surface_pressure' and 'surface_air_temperature'.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.solarposition.spa_python.html

[2] I. Reda and A. Andreas, Solar position algorithm for solar radiation applications. Solar Energy, vol. 76, no. 5, pp. 577-589, 2004.

[3] I. Reda and A. Andreas, Corrigendum to Solar position algorithm for solar radiation applications. Solar Energy, vol. 81, no. 6, p. 838, 2007.

[4] USNO delta T: http://www.usno.navy.mil/USNO/earth-orientation/eo-products/long-term

Source code in reskit/solar/workflows/solar_workflow_manager.py
def determine_solar_position(self, lon_rounding=1, lat_rounding=1, elev_rounding=-2):
    """

    determine_solar_position(self, lon_rounding=1, lat_rounding=1, elev_rounding=-2)

    Calculates azimuth and apparent zenith for each location using the pvlib function pvlib.solarposition.spa_python() [1].
    Adds azimuth and apparent zenit to the sim_data dictionary.


    Parameters
    ----------
    lon_rounding: int, optional
                  Decimal places that the longitude should be rounded to. Default is 1.

    lat_rounding: int, optional
                  Decimal places that the latitude should be rounded to. Default is 1.

    elev_rounding: int, optional
                  Decimal places that the elevation should be rounded to. Default is -2.

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object

    Notes
    -----
    Required columns in the placements dataframe to use this functions are 'lon', 'lat' and 'elev'.
    Required data in the sim_data dictionary are 'surface_pressure' and 'surface_air_temperature'.

    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.solarposition.spa_python.html

    [2] I. Reda and A. Andreas, Solar position algorithm for solar
        radiation applications. Solar Energy, vol. 76, no. 5, pp. 577-589, 2004.

    [3] I. Reda and A. Andreas, Corrigendum to Solar position algorithm for
        solar radiation applications. Solar Energy, vol. 81, no. 6, p. 838,
        2007.

    [4] USNO delta T:
        http://www.usno.navy.mil/USNO/earth-orientation/eo-products/long-term


    """
    assert "lon" in self.placements.columns
    assert "lat" in self.placements.columns
    assert "elev" in self.placements.columns
    assert "surface_pressure" in self.sim_data
    assert "surface_air_temperature" in self.sim_data

    rounded_locs = pd.DataFrame()
    rounded_locs["lon"] = np.round(self.placements["lon"].values, lon_rounding)
    rounded_locs["lat"] = np.round(self.placements["lat"].values, lat_rounding)
    rounded_locs["elev"] = np.round(self.placements["elev"].values, elev_rounding)

    solar_position_library = dict()

    # pd.DataFrame(np.nan, index=self.time_index, columns=self.locs)
    self.sim_data["solar_azimuth"] = np.full_like(self.sim_data["surface_pressure"], np.nan)
    # pd.DataFrame(np.nan, index=self.time_index, columns=self.locs)
    self.sim_data["apparent_solar_zenith"] = np.full_like(self.sim_data["surface_pressure"], np.nan)
    # self.sim_data['apparent_solar_elevation'] = np.full_like(self.sim_data['surface_pressure'], np.nan)  # pd.DataFrame(np.nan, index=self.time_index, columns=self.locs)

    for loc, row in enumerate(rounded_locs.itertuples()):
        key = (row.lon, row.lat, row.elev)
        if key in solar_position_library:
            _solpos_ = solar_position_library[key]
        else:
            # make sure that no input is nan to avoid very hard-to-understand errors later on
            _req = [
                self.time_index,
                row.lat,
                row.lon,
                row.elev,
                self.sim_data["surface_pressure"][:, loc],
                self.sim_data["surface_air_temperature"][:, loc],
            ]
            assert not any([np.isnan(x).any() if hasattr(x, "__iter__") else np.isnan(x) for x in _req]), (
                f"Arguments for pvlib.solarposition.spa_python() may not be NaN."
            )
            _solpos_ = pvlib.solarposition.spa_python(
                self.time_index,
                latitude=row.lat,
                longitude=row.lon,
                altitude=row.elev,
                pressure=self.sim_data["surface_pressure"][:, loc],
                temperature=self.sim_data["surface_air_temperature"][:, loc],
            )
            solar_position_library[key] = _solpos_

        self.sim_data["solar_azimuth"][:, loc] = _solpos_["azimuth"]
        self.sim_data["apparent_solar_zenith"][:, loc] = _solpos_["apparent_zenith"]
        # self.sim_data['apparent_solar_elevation'][:, loc] = _solpos_["apparent_elevation"]

    assert not np.isnan(self.sim_data["solar_azimuth"]).any()
    assert not np.isnan(self.sim_data["apparent_solar_zenith"]).any()
    # assert not np.isnan(self.sim_data['apparent_solar_elevation']).any()

    return self

diffuse_horizontal_irradiance_from_trigonometry

diffuse_horizontal_irradiance_from_trigonometry()

diffuse_horizontal_irradiance_from_trigonometry(self)

Calculates the diffuse horizontal irradiance from global horizontal irradiance, direct normal irradiance and apparent zenith.

[TODO: Add a simple equation such as the one given in 'direct_normal_irradiance_from_trigonometry']

Parameters:

  • None

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required data in the sim_data dictionary are 'global_horizontal_irradiance', 'direct_normal_irradiance' and 'apparent_solar_zenith'.

Source code in reskit/solar/workflows/solar_workflow_manager.py
def diffuse_horizontal_irradiance_from_trigonometry(self):
    """

    diffuse_horizontal_irradiance_from_trigonometry(self)

    Calculates the diffuse horizontal irradiance from global horizontal irradiance, direct normal irradiance and apparent zenith.

    [TODO: Add a simple equation such as the one given in 'direct_normal_irradiance_from_trigonometry']

    Parameters
    ----------
    None

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required data in the sim_data dictionary are 'global_horizontal_irradiance', 'direct_normal_irradiance' and
    'apparent_solar_zenith'.

    """
    assert "global_horizontal_irradiance" in self.sim_data
    assert "direct_normal_irradiance" in self.sim_data
    assert "apparent_solar_zenith" in self.sim_data

    ghi = self.sim_data["global_horizontal_irradiance"]
    dni = self.sim_data["direct_normal_irradiance"]
    elev = np.radians(90 - self.sim_data["apparent_solar_zenith"])

    self.sim_data["diffuse_horizontal_irradiance"] = ghi - dni * np.sin(elev)
    self.sim_data["diffuse_horizontal_irradiance"][self.sim_data["diffuse_horizontal_irradiance"] < 0] = 0

    return self

direct_normal_irradiance_from_trigonometry

direct_normal_irradiance_from_trigonometry()

direct_normal_irradiance_from_trigonometry(self):

Parameters:

  • None

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required columns in the placements dataframe to use this functions are 'lon', 'lat' and 'elev'. Required data in the sim_data dictionary are 'direct_horizontal_irradiance' and 'apparent_solar_zenith'.

Calculates the direct normal irradiance from the following equation: .. math:: dir_nor_irr = dir_hor_irr / cos( solar_zenith )

Where:
dir_nor_irr  -> The direct irradiance on the normal plane
dir_hor_irr  -> The direct irradiance on the horizontal plane
solar_zenith -> The solar zenith angle in radians
Source code in reskit/solar/workflows/solar_workflow_manager.py
def direct_normal_irradiance_from_trigonometry(self):
    """

    direct_normal_irradiance_from_trigonometry(self):

    Parameters
    ----------
    None

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required columns in the placements dataframe to use this functions are 'lon', 'lat' and 'elev'.
    Required data in the sim_data dictionary are 'direct_horizontal_irradiance' and 'apparent_solar_zenith'.

    Calculates the direct normal irradiance from the following equation:
        .. math:: dir_nor_irr = dir_hor_irr / cos( solar_zenith )

        Where:
        dir_nor_irr  -> The direct irradiance on the normal plane
        dir_hor_irr  -> The direct irradiance on the horizontal plane
        solar_zenith -> The solar zenith angle in radians

    """
    # TODO: This can also cover the case when we know GHI & DiffHI
    assert "direct_horizontal_irradiance" in self.sim_data
    assert "apparent_solar_zenith" in self.sim_data

    dni_flat = self.sim_data["direct_horizontal_irradiance"]
    zen = np.radians(self.sim_data["apparent_solar_zenith"])

    self.sim_data["direct_normal_irradiance"] = dni_flat / np.maximum(np.cos(zen), 0.2)

    # catch outliners from zero division
    index_out = (dni_flat < 25) & (np.cos(zen) < 0.05)
    self.sim_data["direct_normal_irradiance"][index_out] = 0

    index_out = (dni_flat < 25) & (np.cos(zen) < 0.05)
    self.sim_data["direct_normal_irradiance"][index_out] = 0

    sel = ~np.isfinite(self.sim_data["direct_normal_irradiance"])
    sel = np.logical_or(sel, self.sim_data["direct_normal_irradiance"] < 0)
    sel = np.logical_or(sel, self.sim_data["direct_normal_irradiance"] > 1600)

    self.sim_data["direct_normal_irradiance"][sel] = 0

    return self

estimate_azimuth_from_latitude

estimate_azimuth_from_latitude()

estimate_azimuth_from_latitude(self)

Estimates the azimuth of the placements of the instance. For a positive latitude the azimuth is set to 180. For a negative latitude the azimuth is set to 0.

Parameters:

  • None

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object
Source code in reskit/solar/workflows/solar_workflow_manager.py
def estimate_azimuth_from_latitude(self):
    """

    estimate_azimuth_from_latitude(self)

    Estimates the azimuth of the placements of the instance.
    For a positive latitude the azimuth is set to 180.
    For a negative latitude the azimuth is set to 0.

    Parameters
    ----------
    None

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object

    """
    self.placements["azimuth"] = 180

    self.placements["azimuth"].values[self.locs.lats < 0] = 0
    return self

estimate_plane_of_array_irradiances

estimate_plane_of_array_irradiances(
    transposition_model="perez", albedo=0.25, **kwargs
)

estimate_plane_of_array_irradiances(self, transposition_model="perez", albedo=0.25, **kwargs)

Estimates the plane of array irradiance using the pvlib.irradiance.get_total_irradiance() function [1].

Parameters:

  • transportion_model

                default "perez"
    
  • albedo

    default 0.25
    Surface albedo [1].
    

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required data in the sim_data dictionary are 'apparent_solar_zenith', 'solar_azimuth', 'direct_normal_irradiance', 'global_horizontal_irradiance', 'diffuse_horizontal_irradiance', 'extra_terrestrial_irradiance' and 'air_mass'.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.irradiance.get_total_irradiance.html

Source code in reskit/solar/workflows/solar_workflow_manager.py
def estimate_plane_of_array_irradiances(self, transposition_model="perez", albedo=0.25, **kwargs):
    """
    estimate_plane_of_array_irradiances(self, transposition_model="perez", albedo=0.25, **kwargs)

    Estimates the plane of array irradiance using the pvlib.irradiance.get_total_irradiance() function [1].


    Parameters
    ----------
    transportion_model: str, optional
                        default "perez"

    albedo: numeric, optional
            default 0.25
            Surface albedo [1].

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required data in the sim_data dictionary are 'apparent_solar_zenith', 'solar_azimuth', 'direct_normal_irradiance',
    'global_horizontal_irradiance', 'diffuse_horizontal_irradiance', 'extra_terrestrial_irradiance' and 'air_mass'.

    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.irradiance.get_total_irradiance.html

    """
    assert "apparent_solar_zenith" in self.sim_data
    assert "solar_azimuth" in self.sim_data
    assert "direct_normal_irradiance" in self.sim_data
    assert "global_horizontal_irradiance" in self.sim_data
    assert "diffuse_horizontal_irradiance" in self.sim_data
    assert "extra_terrestrial_irradiance" in self.sim_data
    assert "air_mass" in self.sim_data

    azimuth = self.sim_data.get("system_azimuth", self.placements["azimuth"].values)
    tilt = self.sim_data.get("system_tilt", self.placements["tilt"].values)

    poa = pvlib.irradiance.get_total_irradiance(
        surface_tilt=tilt,
        surface_azimuth=azimuth,
        solar_zenith=self.sim_data["apparent_solar_zenith"],
        solar_azimuth=self.sim_data["solar_azimuth"],
        dni=self.sim_data["direct_normal_irradiance"],
        ghi=self.sim_data["global_horizontal_irradiance"],
        dhi=self.sim_data["diffuse_horizontal_irradiance"],
        dni_extra=self.sim_data["extra_terrestrial_irradiance"],
        airmass=self.sim_data["air_mass"],
        albedo=albedo,
        model=transposition_model,
        **kwargs,
    )

    for key in poa.keys():
        # This should set: 'poa_global', 'poa_direct', 'poa_diffuse', 'poa_sky_diffuse', and 'poa_ground_diffuse'

        tmp = poa[key]
        tmp[np.isnan(tmp)] = 0

        self.sim_data[key] = tmp

    self._fix_bad_plane_of_array_values()

    return self

estimate_tilt_from_latitude

estimate_tilt_from_latitude(convention)

estimate_tilt_from_latitude(self, convention)

Estimates the tilt of the solar panels based on the latitude of the placements of the instance.

Parameters:

  • convention

    (str) –
         The calculation method used to suggest system tilts.
         Option 1 of convention is "Ryberg2020".
         Option 2 of convention is a string consumable by 'eval'. This string can use the variable latitude.
         For example "latitude*0.76".
         Option 3 of convention is a path to a rasterfile.
         To get more information check out reskit.solar.location_to_tilt for more information.
    

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object
Source code in reskit/solar/workflows/solar_workflow_manager.py
def estimate_tilt_from_latitude(self, convention):
    """

    estimate_tilt_from_latitude(self, convention)

    Estimates the tilt of the solar panels based on the latitude of the placements of the instance.

    Parameters
    ----------
    convention : str, optional
                 The calculation method used to suggest system tilts.
                 Option 1 of convention is "Ryberg2020".
                 Option 2 of convention is a string consumable by 'eval'. This string can use the variable latitude.
                 For example "latitude*0.76".
                 Option 3 of convention is a path to a rasterfile.
                 To get more information check out reskit.solar.location_to_tilt for more information.



    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object

    """
    self.placements["tilt"] = rk_solar_core.system_design.location_to_tilt(self.locs, convention=convention)
    return self

extract_raster_values_at_placements

extract_raster_values_at_placements(raster, **kwargs)

Extracts pixel values at each of the configured placements from the specified raster file

Source code in reskit/workflow_manager.py
def extract_raster_values_at_placements(self, raster, **kwargs):
    """Extracts pixel values at each of the configured placements from the specified raster file"""
    return gk.raster.interpolateValues(raster, points=self.locs, **kwargs)

filter_positive_solar_elevation

filter_positive_solar_elevation()

filter_positive_solar_elevation(self)

Filters positive solar elevations so that future operations are only executed for time steps when the sun is above (or at least near-to) the horizon

Parameters:

  • None

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object
Notes

Required data in the sim_data dictionary are 'apparent_solar_zenith'.

Source code in reskit/solar/workflows/solar_workflow_manager.py
def filter_positive_solar_elevation(self):
    """

    filter_positive_solar_elevation(self)

    Filters positive solar elevations so that future operations are only executed for time steps when the sun is above (or at least near-to) the horizon


    Parameters
    ----------
    None

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object

    Notes
    -----
    Required data in the sim_data dictionary are 'apparent_solar_zenith'.



    """
    if self._time_sel_ is not None:
        warnings.warn("Filtering already applied, skipping...")
        return self
    assert "apparent_solar_zenith" in self.sim_data

    self._time_sel_ = (self.sim_data["apparent_solar_zenith"] < 95).any(axis=1)

    for key in self.sim_data.keys():
        self.sim_data[key] = self.sim_data[key][self._time_sel_, :]

    self._time_index_ = self.time_index[self._time_sel_]
    self._set_sim_shape()

    return self

get_scalar_values_from_raster

get_scalar_values_from_raster(
    fp, spatial_interpolation, points=None
)

Auxiliary function to extract raster values with NaN fallback options.

Source code in reskit/workflow_manager.py
def get_scalar_values_from_raster(self, fp, spatial_interpolation, points=None):
    """
    Auxiliary function to extract raster values with NaN fallback options.
    """
    assert isfile(fp), f"File '{fp}' in adjust_variable_to_long_run_average() does not exist."
    # execute with warnings filter since values outside of source data would trigger geokit UserWarning every time
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

        if points is None:
            points = [(loc.lon, loc.lat) for loc in self.locs._locations]
        else:
            assert isinstance(points, list) and all([isinstance(x, tuple) and len(x) == 2 for x in points]), (
                "points must be a list of (lon, lat) tuples."
            )

        # interpolateValues returns a scalar for a single location; ensure a 1-D array
        # so the nan handling below (and callers) work regardless of the number of points
        _lra = np.atleast_1d(gk.raster.interpolateValues(fp, points, mode=spatial_interpolation))
        # if getting values fails, it could be because of interpolation method.
        # these values will be replaced with the nearest interpolation method
        if np.isnan(_lra).any():
            _lra_near = np.atleast_1d(gk.raster.interpolateValues(fp, self.locs, mode="near"))
            _lra[np.isnan(_lra)] = _lra_near[np.isnan(_lra)]
        # still nans, i.e. the cell itself is nan, but maybe its neighbors are not
        # try the (nan)median of the surrounding cells
        if np.isnan(_lra).any():

            def _nanmedian(vals, xOff, yOff):
                """Aux function to mimic the 3 expected inputs in interpolateValues()"""
                return np.nanmedian(vals)

            points = [(loc.lon, loc.lat) for loc in self.locs._locations]
            _lra_near = np.atleast_1d(gk.raster.interpolateValues(fp, points, mode="func", func=_nanmedian))
            _lra[np.isnan(_lra)] = _lra_near[np.isnan(_lra)]
    return _lra

permit_single_axis_tracking

permit_single_axis_tracking(
    max_angle=90, backtrack=True, gcr=2.0 / 7.0
)

permit_single_axis_tracking(self, max_angle=90, backtrack=True, gcr=2.0 / 7.0)

Permits single axis tracking in the simulation using the pvlib.tracking.singleaxis() function [1].

Parameters:

  • max_angle

       default 90
       A value denoting the maximum rotation angle, in decimal degrees, of the one-axis tracker from its horizontal position
       (horizontal if axis_tilt = 0). A max_angle of 90 degrees allows the tracker to rotate to a vertical position to point the
       panel towards a horizon. max_angle of 180 degrees allows for full rotation [1].
    
  • backtrack

       default True
       Controls whether the tracker has the capability to “backtrack” to avoid row-to-row shading.
       False denotes no backtrack capability. True denotes backtrack capability [1].
    
  • gcr

       default 2.0/7.0
       A value denoting the ground coverage ratio of a tracker system which utilizes backtracking; i.e. the ratio between the
       PV array surface area to total ground area. A tracker system with modules 2 meters wide, centered on the tracking axis,
       with 6 meters between the tracking axes has a gcr of 2/6=0.333. If gcr is not provided, a gcr of 2/7 is default. gcr must be <=1 [1].
    

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required columns in the placements dataframe to use this functions are 'lon', 'lat', 'elev', 'tilt' and 'azimuth'. Required data in the sim_data dictionary are 'apparent_solar_zenith' and 'solar_azimuth'.

References

[1] https://wholmgren-pvlib-python-new.readthedocs.io/en/doc-reorg2/generated/tracking/pvlib.tracking.singleaxis.html

[2] Lorenzo, E et al., 2011, “Tracking and back-tracking”, Prog. in Photovoltaics: Research and Applications, v. 19, pp. 747-753.

Source code in reskit/solar/workflows/solar_workflow_manager.py
def permit_single_axis_tracking(self, max_angle=90, backtrack=True, gcr=2.0 / 7.0):
    """

    permit_single_axis_tracking(self, max_angle=90, backtrack=True, gcr=2.0 / 7.0)

    Permits single axis tracking in the simulation using the pvlib.tracking.singleaxis() function [1].


    Parameters
    ----------
    max_angle: float, optional
               default 90
               A value denoting the maximum rotation angle, in decimal degrees, of the one-axis tracker from its horizontal position
               (horizontal if axis_tilt = 0). A max_angle of 90 degrees allows the tracker to rotate to a vertical position to point the
               panel towards a horizon. max_angle of 180 degrees allows for full rotation [1].

    backtrack: bool, optional
               default True
               Controls whether the tracker has the capability to “backtrack” to avoid row-to-row shading.
               False denotes no backtrack capability. True denotes backtrack capability [1].

    gcr:       float, optional
               default 2.0/7.0
               A value denoting the ground coverage ratio of a tracker system which utilizes backtracking; i.e. the ratio between the
               PV array surface area to total ground area. A tracker system with modules 2 meters wide, centered on the tracking axis,
               with 6 meters between the tracking axes has a gcr of 2/6=0.333. If gcr is not provided, a gcr of 2/7 is default. gcr must be <=1 [1].


    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required columns in the placements dataframe to use this functions are 'lon', 'lat', 'elev', 'tilt' and 'azimuth'.
    Required data in the sim_data dictionary are 'apparent_solar_zenith' and 'solar_azimuth'.

    References
    ----------
    [1] https://wholmgren-pvlib-python-new.readthedocs.io/en/doc-reorg2/generated/tracking/pvlib.tracking.singleaxis.html

    [2]	Lorenzo, E et al., 2011, “Tracking and back-tracking”, Prog. in Photovoltaics: Research and Applications, v. 19, pp. 747-753.

    """
    """See pvlib.tracking.singleaxis for parameter info"""
    assert "apparent_solar_zenith" in self.sim_data
    assert "solar_azimuth" in self.sim_data
    assert "tilt" in self.placements.columns
    assert "azimuth" in self.placements.columns

    self.register_workflow_parameter("tracking_mode", "single_axis")
    self.register_workflow_parameter("tracking_max_angle", max_angle)
    self.register_workflow_parameter("tracking_backtrack", backtrack)
    self.register_workflow_parameter("tracking_gcr", gcr)

    system_tilt = np.empty(self._sim_shape_)
    system_azimuth = np.empty(self._sim_shape_)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

        for i in range(self.locs.count):
            placement = self.placements.iloc[i]

            tmp = pvlib.tracking.singleaxis(
                apparent_zenith=pd.Series(
                    self.sim_data["apparent_solar_zenith"][:, i],
                    index=self._time_index_,
                ),
                apparent_azimuth=pd.Series(self.sim_data["solar_azimuth"][:, i], index=self._time_index_),
                # self.placements['tilt'].values,
                axis_tilt=placement.tilt,
                # self.placements['azimuth'].values,
                axis_azimuth=placement.azimuth,
                max_angle=max_angle,
                backtrack=backtrack,
                gcr=gcr,
            )

            system_tilt[:, i] = tmp["surface_tilt"].values
            system_azimuth[:, i] = tmp["surface_azimuth"].values

            # fix nan values. Why are they there???
            s = np.isnan(system_tilt[:, i])
            system_tilt[s, i] = placement.tilt

            s = np.isnan(system_azimuth[:, i])
            system_azimuth[s, i] = placement.azimuth

    self.sim_data["system_tilt"] = system_tilt
    self.sim_data["system_azimuth"] = system_azimuth

    return self

read

read(
    variables: Union[str, List[str]],
    source_type: str,
    source: str,
    set_time_index: bool = False,
    spatial_interpolation_mode: str = "bilinear",
    temporal_reindex_method: str = "nearest",
    time_index_from=None,
    **kwargs,
)

Reads the specified variables from the NetCDF4-style weather dataset, and then extracts those variables for each of the coordinates configured in .placements. The resulting data is then available in .sim_data.

Parameters:

  • variables

    (str or list of strings) –

    The variables (or variables) to be read from the specified source - If a path to a weather source is given, then only the 'standard' variables configured for that source type are available (see the doc string for the weather source you are interested in) - If either 'elevated_wind_speed' or 'surface_wind_speed' is included in the variable list, then the members .elevated_wind_speed_height and .surface_wind_speed_height, respectfully, are also added. These are constants which specify what the 'native' wind speed height is, which depends on the source - A pre-loaded NCSource can also be given, thus allowing for any variable in the source to be specified in the variables list. But the user needs to take care of initializing the NCSource and loading the data they want

  • source_type

    (str) –

    The type of weather datasource which is to be loaded. Can be one of: "ERA5", "SARAH", "MERRA", or 'user' - If a pre-loaded NCSource is given for the source object, then the source_type should be "user"

  • source

    (str or NCSource) –

    The source to read weather variables from

  • set_time_index

    (bool, default: False ) –

    If True, instructs the workflow manager to set the time index to that which is read from the weather source - By default False

  • spatial_interpolation_mode

    (str, default: 'bilinear' ) –

    The spatial interpolation mode to use while reading data from the weather source at each of the placement coordinates - By default "bilinear"

  • temporal_reindex_method

    (str, default: 'nearest' ) –

    In the event of missing data, this algorithm is used to fill in the missing data. - Can be, for example, "nearest", "ffill", "bfill", "interpolate" - By default "nearest"

Returns:

Raises:

  • RuntimeError

    If set_time_index is False but no .time_index exists

  • RuntimeError

    If source_type is unknown

Source code in reskit/workflow_manager.py
def read(
    self,
    variables: Union[str, List[str]],
    source_type: str,
    source: str,
    set_time_index: bool = False,
    spatial_interpolation_mode: str = "bilinear",
    temporal_reindex_method: str = "nearest",
    time_index_from=None,
    **kwargs,
):
    """Reads the specified variables from the NetCDF4-style weather dataset, and then extracts
    those variables for each of the coordinates configured in `.placements`. The resulting
    data is then available in `.sim_data`.

    Parameters
    ----------
    variables : str or list of strings
        The variables (or variables) to be read from the specified source
        - If a path to a weather source is given, then only the 'standard' variables
        configured for that source type are available (see the doc string for the
        weather source you are interested in)
        - If either 'elevated_wind_speed' or 'surface_wind_speed' is included in the
        variable list, then the members `.elevated_wind_speed_height` and
        `.surface_wind_speed_height`, respectfully, are also added. These are constants
        which specify what the 'native' wind speed height is, which depends on the source
        - A pre-loaded NCSource can also be given, thus allowing for any variable in the
        source to be specified in the `variables` list. But the user needs to take care
        of initializing the NCSource and loading the data they want

    source_type : str
        The type of weather datasource which is to be loaded. Can be one of:
        "ERA5", "SARAH", "MERRA", or 'user'
        - If a pre-loaded NCSource is given for the `source` object, then the `source_type`
        should be "user"

    source : str or rk.weather.NCSource
        The source to read weather variables from

    set_time_index : bool, optional
        If True, instructs the workflow manager to set the time index to that which is read
        from the weather source
        - By default False

    spatial_interpolation_mode : str, optional
        The spatial interpolation mode to use while reading data from the weather source at
        each of the placement coordinates
        - By default "bilinear"

    temporal_reindex_method : str, optional
        In the event of missing data, this algorithm is used to fill in the missing data.
        - Can be, for example, "nearest", "ffill", "bfill", "interpolate"
        - By default "nearest"

    Returns
    -------
    WorkflowManager
        Returns the invoking WorkflowManager (for chaining)

    Raises
    ------
    RuntimeError
        If set_time_index is False but no `.time_index` exists
    RuntimeError
        If source_type is unknown
    """
    if not set_time_index and self.time_index is None:
        raise RuntimeError("Time index is not available")

    if not isinstance(variables, list):
        variables = [
            variables,
        ]

    if isinstance(source, str) and source_type != "user":
        storage_format = kwargs.pop("storage_format", None)
        is_zarr = storage_format == "zarr" or source.endswith(".zarr") or source.startswith("gs://")
        if source_type == "ERA5":
            source_constructor = rk_weather.Era5ZarrSource if is_zarr else rk_weather.Era5Source
        elif source_type == "SARAH":
            source_constructor = rk_weather.SarahSource
        elif source_type == "MERRA":
            source_constructor = rk_weather.MerraSource
        elif source_type == "ICON-LAM":
            source_constructor = rk_weather.IconlamSource
        else:
            raise RuntimeError("Unknown source_type")

        if source_type == "ERA5":
            time_slice = kwargs.pop("time_slice", None)
            era5_kwargs = dict(kwargs)
            if time_slice is not None:
                if not is_zarr:
                    raise RuntimeError(
                        "'time_slice' is only supported for Zarr-backed ERA5 sources; support for "
                        "netCDF4-backed ERA5 sources is planned. Until then, restrict the time span "
                        "of netCDF4 ERA5 data by selecting the corresponding files instead."
                    )
                era5_kwargs["time_slice"] = time_slice
            source = source_constructor(source, bounds=self.ext, time_index_from=time_index_from, **era5_kwargs)
        else:
            source = source_constructor(source, bounds=self.ext, **kwargs)

        # Load the requested variables
        source.sload(*variables)

    else:  # Assume source is already an initialized NCSource-like object
        missing_variables = [var for var in variables if var not in source.data]
        if missing_variables:
            if hasattr(source, "sload"):
                source.sload(*missing_variables)
            else:
                raise AssertionError(
                    "The given source has no '.sload()' method and is missing the variable(s): "
                    + ", ".join(missing_variables)
                )

    if set_time_index:
        self.set_time_index(source.time_index)

    # read variables
    for var in variables:
        self.sim_data[var] = source.get(
            var,
            self.locs,  # Manipulate locs here
            interpolation=spatial_interpolation_mode,
            force_as_data_frame=True,
        )

        if not set_time_index:
            self.sim_data[var] = self.sim_data[var].reindex(self.time_index, method=temporal_reindex_method)

        self.sim_data[var] = self.sim_data[var].values

        # Special check for wind speed height
        if var == "elevated_wind_speed":
            self.elevated_wind_speed_height = source.ELEVATED_WIND_SPEED_HEIGHT

        if var == "surface_wind_speed":
            self.surface_wind_speed_height = source.SURFACE_WIND_SPEED_HEIGHT

    return self

register_workflow_parameter

register_workflow_parameter(
    key: str, value: Union[str, float]
)

Add a parameter to the WorkflowManager which will be included in the output XArray dataset

Parameters:

  • key

    (str) –

    The workflow parameter's access key

  • value

    (Union[str, float]) –

    The workflow parameter's value. Only strings and floats are allowed

Source code in reskit/workflow_manager.py
def register_workflow_parameter(self, key: str, value: Union[str, float]):
    """Add a parameter to the WorkflowManager which will be included in the output XArray dataset

    Parameters
    ----------
    key : str
        The workflow parameter's access key

    value : Union[str,float]
        The workflow parameter's value. Only strings and floats are allowed
    """
    self.workflow_parameters[key] = value

set_time_index

set_time_index(times: DatetimeIndex)

Sets the time index of the WorkflowManager

Source code in reskit/workflow_manager.py
def set_time_index(self, times: pd.DatetimeIndex):
    """Sets the time index of the WorkflowManager

    Parameters
    ----------
        times : pd.DatetimeIndex
            The timesteps to use throughout the WorkflowManager's life cycle. The
            length of this dataset must match the shape of data which is loaded into
            the WorkflorManager.sim_data member.
    """
    self.time_index = times

    self._time_sel_ = None
    self._time_index_ = self.time_index.copy()
    self._set_sim_shape()

simulate_with_interpolated_single_diode_approximation

simulate_with_interpolated_single_diode_approximation(
    module="WINAICO WSx-240P6", tech_year=2050
)

simulate_with_interpolated_single_diode_approximation(self, module="WINAICO WSx-240P6")

Does the simulation with an interpolated single diode approximation using the pvlib.pvsystem.calcparams_desoto() [1] function and the pvlib.pvsystem.singlediode() [2] function.

Parameters:

  • module

    Must be one of: * A module found in the pvlib.pvsystem.retrieve_sam("CECMod") database * "WINAICO WSx-240P6" -> Good for open-field applications * "LG Electronics LG370Q1C-A5" -> Good for rooftop applications

  • tech_year

    (int, default: 2050 ) –

    If given in combination with the projected module str names "WINAICO WSx-240P6" or "LG Electronics LG370Q1C-A5", the effifiency will be scaled linearly to the given year. Must then be between year of market comparison in analysis (2019) and 2050. Will be ignored when non-projected existing module names or specific parameters are given, can then be None. By default 2050.

Returns:

  • Returns a reference to the invoking SolarWorkflowManager object.
Notes

Required columns in the placements dataframe to use this functions are 'lon', 'lat', 'elev', 'tilt' and 'azimuth'. Required data in the sim_data dictionary are 'poa_global' and 'cell_temperature'.

References

[1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.calcparams_desoto.html

[2] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.singlediode.html

[3] (1, 2) W. De Soto et al., “Improvement and validation of a model for photovoltaic array performance”, Solar Energy, vol 80, pp. 78-88, 2006.

[4] System Advisor Model web page. https://sam.nrel.gov.

[5] A. Dobos, “An Improved Coefficient Calculator for the California Energy Commission 6 Parameter Photovoltaic Module Model”, Journal of Solar Energy Engineering, vol 134, 2012.

[6] O. Madelung, “Semiconductors: Data Handbook, 3rd ed.” ISBN 3-540-40488-0

[7] S.R. Wenham, M.A. Green, M.E. Watt, “Applied Photovoltaics” ISBN 0 86758 909 4

[8] A. Jain, A. Kapoor, “Exact analytical solutions of the parameters of real solar cells using Lambert W-function”, Solar Energy Materials and Solar Cells, 81 (2004) 269-277.

[9] D. King et al, “Sandia Photovoltaic Array Performance Model”, SAND2004-3535, Sandia National Laboratories, Albuquerque, NM

[10] “Computer simulation of the effects of electrical mismatches in photovoltaic cell interconnection circuits” JW Bishop, Solar Cell (1988) https://doi.org/10.1016/0379-6787(88)90059-2

Source code in reskit/solar/workflows/solar_workflow_manager.py
def simulate_with_interpolated_single_diode_approximation(
    self,
    module="WINAICO WSx-240P6",
    tech_year=2050,
):
    """
    simulate_with_interpolated_single_diode_approximation(self, module="WINAICO WSx-240P6")

    Does the simulation with an interpolated single diode approximation using the pvlib.pvsystem.calcparams_desoto() [1] function and the
    pvlib.pvsystem.singlediode() [2] function.


    Parameters
    ----------
    module: str
        Must be one of:
            * A module found in the pvlib.pvsystem.retrieve_sam("CECMod") database
            * "WINAICO WSx-240P6" -> Good for open-field applications
            * "LG Electronics LG370Q1C-A5" -> Good for rooftop applications
    tech_year : int, optional
        If given in combination with the projected module str names "WINAICO WSx-240P6" or
        "LG Electronics LG370Q1C-A5", the effifiency will be scaled linearly to the given
        year. Must then be between year of market comparison in analysis (2019) and 2050.
        Will be ignored when non-projected existing module names or specific parameters
        are given, can then be None. By default 2050.

    Returns
    -------
    Returns a reference to the invoking SolarWorkflowManager object.

    Notes
    -----
    Required columns in the placements dataframe to use this functions are 'lon', 'lat', 'elev', 'tilt' and 'azimuth'.
    Required data in the sim_data dictionary are 'poa_global' and 'cell_temperature'.

    References
    ----------
    [1] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.calcparams_desoto.html

    [2] https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.pvsystem.singlediode.html

    [3]	(1, 2) W. De Soto et al., “Improvement and validation of a model for photovoltaic array performance”, Solar Energy, vol 80, pp. 78-88, 2006.

    [4]	System Advisor Model web page. https://sam.nrel.gov.

    [5]	A. Dobos, “An Improved Coefficient Calculator for the California Energy Commission 6 Parameter Photovoltaic Module Model”, Journal of Solar Energy Engineering, vol 134, 2012.

    [6]	O. Madelung, “Semiconductors: Data Handbook, 3rd ed.” ISBN 3-540-40488-0

    [7]	S.R. Wenham, M.A. Green, M.E. Watt, “Applied Photovoltaics” ISBN 0 86758 909 4

    [8]	A. Jain, A. Kapoor, “Exact analytical solutions of the parameters of real solar cells using Lambert W-function”, Solar Energy Materials and Solar Cells, 81 (2004) 269-277.

    [9]	D. King et al, “Sandia Photovoltaic Array Performance Model”, SAND2004-3535, Sandia National Laboratories, Albuquerque, NM

    [10]	“Computer simulation of the effects of electrical mismatches in photovoltaic cell interconnection circuits” JW Bishop, Solar Cell (1988) https://doi.org/10.1016/0379-6787(88)90059-2

    """
    """
    TODO: Make it work with multiple module definitions
    """
    assert "poa_global" in self.sim_data
    assert "cell_temperature" in self.sim_data

    self.configure_cec_module(module, tech_year)

    sel = self.sim_data["poa_global"] > 0

    poa = self.sim_data["poa_global"][sel]
    cell_temp = self.sim_data["cell_temperature"][sel]

    # Use RectBivariateSpline to speed up simulation, but at the cost of accuracy (should still be >99.996%)
    maxpoa = np.nanmax(poa)

    _poa = np.concatenate(
        [
            np.logspace(-1, np.log10(maxpoa / 10), 20, endpoint=False),
            np.linspace(maxpoa / 10, maxpoa, 80),
        ]
    )
    _temp = np.linspace(cell_temp.min(), cell_temp.max(), 100)
    poaM, tempM = np.meshgrid(_poa, _temp)

    sotoParams = pvlib.pvsystem.calcparams_desoto(
        effective_irradiance=poaM.flatten(),
        temp_cell=tempM.flatten(),
        alpha_sc=self.module.alpha_sc,
        a_ref=self.module.a_ref,
        I_L_ref=self.module.I_L_ref,
        I_o_ref=self.module.I_o_ref,
        R_sh_ref=self.module.R_sh_ref,
        R_s=self.module.R_s,
        EgRef=1.121,  # PVLIB v0.7.2 Default
        dEgdT=-0.0002677,  # PVLIB v0.7.2 Default
        irrad_ref=1000,  # PVLIB v0.7.2 Default
        temp_ref=25,  # PVLIB v0.7.2 Default
    )

    photoCur, satCur, resSeries, resShunt, nNsVth = sotoParams
    gen = pvlib.pvsystem.singlediode(
        photocurrent=photoCur,
        saturation_current=satCur,
        resistance_series=resSeries,
        resistance_shunt=resShunt,
        nNsVth=nNsVth,
        method="lambertw",  # PVLIB v0.7.2 Default
    )

    interpolator = RectBivariateSpline(
        _temp,
        _poa,
        np.array(gen["p_mp"]).reshape(poaM.shape),
        kx=3,
        ky=3,  # np.array() since type changed between pvlib versions
    )
    self.sim_data["module_dc_power_at_mpp"] = np.zeros_like(self.sim_data["poa_global"])
    self.sim_data["module_dc_power_at_mpp"][sel] = interpolator(cell_temp, poa, grid=False)

    interpolator = RectBivariateSpline(
        _temp,
        _poa,
        np.array(gen["v_mp"]).reshape(poaM.shape),
        kx=3,
        ky=3,  # np.array() since type changed between pvlib versions
    )
    self.sim_data["module_dc_voltage_at_mpp"] = np.zeros_like(self.sim_data["poa_global"])
    self.sim_data["module_dc_voltage_at_mpp"][sel] = interpolator(cell_temp, poa, grid=False)

    self.sim_data["capacity_factor"] = self.sim_data["module_dc_power_at_mpp"] / (
        self.module.I_mp_ref * self.module.V_mp_ref
    )

    # Estimate total system generation
    if "capacity" in self.placements.columns:
        self.sim_data["total_system_generation"] = self.sim_data["capacity_factor"] * np.broadcast_to(
            self.placements.capacity, self._sim_shape_
        )

    if "modules_per_string" in self.placements.columns and "strings_per_inverter" in self.placements.columns:
        total_modules = (
            self.placements.modules_per_string
            * self.placements.strings_per_inverter
            * getattr(self.placements, "number_of_inverters", 1)
        )

        self.sim_data["total_system_generation"] = self.sim_data["module_dc_power_at_mpp"] * np.broadcast_to(
            total_modules, self._sim_shape_
        )

    return self

spatial_disaggregation

spatial_disaggregation(
    variable: str,
    source_high_resolution: Union[str, float, ndarray],
    source_low_resolution: Union[str, float, ndarray],
    real_lra_scaling: float = 1,
    spatial_interpolation: str = "linear-spline",
)

[summary]

Parameters:

  • variable

    (str) –

    [description]

  • source_long_run_average

    (Union[str, float, ndarray]) –

    [description]

  • real_long_run_average

    (Union[str, float, ndarray]) –

    [description]

  • real_lra_scaling

    (float, default: 1 ) –

    [description], by default 1

  • spatial_interpolation

    (str, default: 'linear-spline' ) –

    [description], by default "linear-spline"

Source code in reskit/workflow_manager.py
def spatial_disaggregation(
    self,
    variable: str,
    source_high_resolution: Union[str, float, np.ndarray],
    source_low_resolution: Union[str, float, np.ndarray],
    real_lra_scaling: float = 1,
    spatial_interpolation: str = "linear-spline",
):
    """[summary]

    Parameters
    ----------
    variable : str
        [description]
    source_long_run_average : Union[str, float, np.ndarray]
        [description]
    real_long_run_average : Union[str, float, np.ndarray]
        [description]
    real_lra_scaling : float, optional
        [description], by default 1
    spatial_interpolation : str, optional
        [description], by default "linear-spline"
    """
    # Get values from high resolution tiff file
    if isinstance(source_high_resolution, str):
        points = [(loc.lon, loc.lat) for loc in self.locs._locations]
        correction_values_high_res = gk.raster.interpolateValues(  # TODO change here
            source_high_resolution, points, mode=spatial_interpolation
        )
        # assert not np.isnan(correction_values_high_res).any() and (correction_values_high_res > 0).all()
    else:
        correction_values_high_res = source_high_resolution

    # Get values from low resolution tiff file (meant over eg. ERA5)
    if isinstance(source_low_resolution, str):
        points = [(loc.lon, loc.lat) for loc in self.locs._locations]
        correction_values_low_res = gk.raster.interpolateValues(  # TODO change here
            source_low_resolution, points, mode=spatial_interpolation
        )
        # assert not np.isnan(correction_values_low_res).any() and (correction_values_low_res > 0).all()
    else:
        correction_values_low_res = source_low_resolution

    # correction factors:
    factors = correction_values_high_res / correction_values_low_res
    factors = np.nan_to_num(factors, nan=1 / real_lra_scaling)
    assert (factors > 0).all()

    # update values
    self.sim_data[variable] = self.sim_data[variable] * factors * real_lra_scaling
    return self

to_netcdf

to_netcdf(
    xds: Dataset,
    output_netcdf_path: str = None,
    output_variables: List[str] = None,
    custom_attributes: dict = None,
    _intermediate_dict=False,
) -> str

Saves an XArray dataset to netCDF4 format

Note: - The .placements data is automatically added to the XArray dataset along the 'locations' dimension - The workflow_parameters data is automatically added as dimensionless variables - The .sim_data is automatically added along the dimensions (time, locations) - The .time_index is automatically added along the dimension 'time'

Parameters:

  • xds

    (Dataset) –

    The XArray dataset to save

  • output_netcdf_path

    (str, default: None ) –

    If given, the XArray dataset will be written to disc at the specified path - By default None

  • output_variables

    (List[str], default: None ) –

    If given, specifies the variables which should be included in the resulting dataset. Otherwise all suitable variables found in .placements, .workflow_parameters, .sim_data, and .time_index will be included - Only variables of numeric or string type are suitable due to NetCDF4 limitations - By default None

  • custom_attributes

    (dict, default: None ) –

    If given, adds the key-value pairs as attributes to the XArray dataset before saving - These will be added in addition to existing attributes - By default None

Returns:

  • output_netcdf_path

    The resulting output_netcdf_path

Source code in reskit/workflow_manager.py
def to_netcdf(
    self,
    xds: xarray.Dataset,
    output_netcdf_path: str = None,
    output_variables: List[str] = None,
    custom_attributes: dict = None,
    _intermediate_dict=False,
) -> str:
    """Saves an XArray dataset to netCDF4 format

    Note:
    - The `.placements` data is automatically added to the XArray dataset along the 'locations' dimension
    - The `workflow_parameters` data is automatically added as dimensionless variables
    - The `.sim_data` is automatically added along the dimensions (time, locations)
    - The `.time_index` is automatically added along the dimension 'time'

    Parameters
    ----------
    xds : xarray.Dataset
        The XArray dataset to save

    output_netcdf_path : str
        If given, the XArray dataset will be written to disc at the specified path
        - By default None

    output_variables : List[str], optional
        If given, specifies the variables which should be included in the resulting
        dataset. Otherwise all suitable variables found in `.placements`, `.workflow_parameters`,
        `.sim_data`, and `.time_index` will be included
        - Only variables of numeric or string type are suitable due to NetCDF4 limitations
        - By default None

    custom_attributes : dict, optional
        If given, adds the key-value pairs as attributes to the XArray dataset before saving
        - These will be added in addition to existing attributes
        - By default None

    Returns
    -------
    output_netcdf_path
        The resulting output_netcdf_path
    """
    encoding = dict()

    # write sim_data
    for key in self.sim_data.keys():
        # check if key in requestet output_variables
        if output_variables is not None:
            if key not in output_variables:
                continue
        encoding[key] = dict(zlib=True)

    # FIXME: WHAT IS THIS FOR?
    # #write sim_data_daily, only if exists
    # if hasattr(self, 'sim_data_daily'):
    #     for key in self.sim_data_daily.keys():
    #         #check if key in requestet output_variables
    #         if output_variables is not None:
    #             if key not in output_variables:
    #                 continue
    #         encoding[key] = dict(zlib=True)

    # Add custom attributes if provided
    if custom_attributes is not None:
        for k, v in custom_attributes.items():
            xds.attrs[k] = v

    if output_netcdf_path is not None:
        xds.to_netcdf(output_netcdf_path, encoding=encoding)
        return output_netcdf_path
    else:
        return xds

to_xarray

to_xarray(
    output_netcdf_path: str = None,
    output_variables: List[str] = None,
    custom_attributes: dict = None,
    _intermediate_dict=False,
) -> Dataset

Generates an XArray dataset from the data currently contained in the WorkflowManager

Note: - The .placements data is automatically added to the XArray dataset along the 'locations' dimension - The workflow_parameters data is automatically added as dimensionless variables - The .sim_data is automatically added along the dimensions (time, locations) - The .time_index is automatically added along the dimension 'time'

Parameters:

  • output_netcdf_path

    (str, default: None ) –

    If given, the XArray dataset will be written to disc at the specified path - By default None

  • output_variables

    (List[str], default: None ) –

    If given, specifies the variables which should be included in the resulting dataset. Otherwise all suitable variables found in .placements, .workflow_parameters, .sim_data, and .time_index will be included - Only variables of numeric or string type are suitable due to NetCDF4 limitations - By default None

  • custom_attributes

    (dict, default: None ) –

    If given, adds the key-value pairs as attributes to the XArray dataset - These will be added in addition to the workflow_parameters - By default None

Returns:

  • Dataset

    The resulting XArray dataset

Source code in reskit/workflow_manager.py
def to_xarray(
    self,
    output_netcdf_path: str = None,
    output_variables: List[str] = None,
    custom_attributes: dict = None,
    _intermediate_dict=False,
) -> xarray.Dataset:
    """Generates an XArray dataset from the data currently contained in the WorkflowManager

    Note:
    - The `.placements` data is automatically added to the XArray dataset along the 'locations' dimension
    - The `workflow_parameters` data is automatically added as dimensionless variables
    - The `.sim_data` is automatically added along the dimensions (time, locations)
    - The `.time_index` is automatically added along the dimension 'time'

    Parameters
    ----------
    output_netcdf_path : str, optional
        If given, the XArray dataset will be written to disc at the specified path
        - By default None

    output_variables : List[str], optional
        If given, specifies the variables which should be included in the resulting
        dataset. Otherwise all suitable variables found in `.placements`, `.workflow_parameters`,
        `.sim_data`, and `.time_index` will be included
        - Only variables of numeric or string type are suitable due to NetCDF4 limitations
        - By default None

    custom_attributes : dict, optional
        If given, adds the key-value pairs as attributes to the XArray dataset
        - These will be added in addition to the workflow_parameters
        - By default None

    Returns
    -------
    xarray.Dataset
        The resulting XArray dataset
    """
    if isinstance(output_variables, str):
        output_variables = [output_variables]
    if isinstance(output_variables, list) and not "RESKit_sim_order" in output_variables:
        output_variables.append("RESKit_sim_order")

    times = self.time_index
    if times[0].tz is not None:
        times = [np.datetime64(dt.tz_convert("UTC").tz_convert(None)) for dt in times]
    times_days = np.unique(pd.DatetimeIndex(times).date).astype("datetime64")
    if times_days[0].astype("datetime64[Y]") != times_days[-1].astype("datetime64[Y]"):
        # old tiles where shifted by 1 hour, so the last day of the previous year also appears. catch this problem whti this if clause
        times_days = times_days[1:]
    xds = OrderedDict()
    encoding = dict()

    if "location_id" in self.placements.columns:
        location_coords = self.placements["location_id"].copy()
        del self.placements["location_id"]
    else:
        location_coords = np.arange(self.placements.shape[0])

    # write placements
    for c in self.placements.columns:
        # check if c in requestet output_variables
        if output_variables is not None:
            if c not in output_variables:
                continue
        if np.issubdtype(self.placements[c].dtype, np.number):
            write = True
        else:
            write = True
            for element in self.placements[c]:
                if not isinstance(element, (str, bytearray)):
                    write = False
                    break
        if write:
            xds[c] = xarray.DataArray(
                self.placements[c],
                dims=["location"],
                coords=dict(location=location_coords),
            )

    # write sim_data
    for key in self.sim_data.keys():
        # check if key in requestet output_variables
        if output_variables is not None:
            if key not in output_variables:
                continue

        tmp = np.full((len(self.time_index), self.locs.count), 0.0, dtype=float)
        tmp[self._time_sel_, :] = self.sim_data[key]

        xds[key] = xarray.DataArray(
            tmp,
            dims=["time", "location"],
            coords=dict(time=times, location=location_coords),
        )
        encoding[key] = dict(zlib=True)

    # write sim_data_daily, only if exists
    if hasattr(self, "sim_data_daily"):
        for key in self.sim_data_daily.keys():
            # check if key in requestet output_variables
            if output_variables is not None:
                if key not in output_variables:
                    continue

            tmp = np.full((len(times_days), self.locs.count), np.nan)
            tmp[:, :] = self.sim_data_daily[key]

            xds[key] = xarray.DataArray(
                tmp,
                dims=["time_days", "location"],
                coords=dict(time_days=times_days, location=location_coords),
            )
            encoding[key] = dict(zlib=True)

    if _intermediate_dict:
        return xds

    xds = xarray.Dataset(xds)

    for k, v in self.workflow_parameters.items():
        xds.attrs[k] = v

    # Add custom attributes if provided
    if custom_attributes is not None:
        for k, v in custom_attributes.items():
            xds.attrs[k] = v

    if output_netcdf_path is not None:
        xds.to_netcdf(output_netcdf_path, encoding=encoding)
        return output_netcdf_path
    else:
        return xds