예제 #1
0
    def _carbon_intensity_gb_regional(self, postcode, time_dur=None):
        """"Retrieves forecasted carbon intensity (gCO2eq/kWh) in GB by
        postcode."""
        url = f"{API_URL}/regional"

        if time_dur is not None:
            from_str, to_str = self._time_from_to_str(time_dur)
            url += f"/intensity/{from_str}/{to_str}"

        url += f"/postcode/{postcode}"
        response = requests.get(url)
        if not response.ok:
            raise exceptions.CarbonIntensityFetcherError(response.json())
        data = response.json()["data"]

        # CO2Signal has a bug s.t. if we query current then we get a list.
        if time_dur is None:
            data = data[0]

        carbon_intensities = []
        for ci in data["data"]:
            carbon_intensities.append(ci["intensity"]["forecast"])
        carbon_intensity = np.mean(carbon_intensities)

        return carbon_intensity
예제 #2
0
 def _emission_prognosis(self, time_dur):
     from_str, to_str = self._interval(time_dur=time_dur)
     url = ("https://api.energidataservice.dk/datastore_search_sql?"
            """sql=SELECT co2."CO2Emission" from "co2emisprog" as co2 """
            f"""WHERE co2."Minutes5UTC" > timestamp'{from_str}' AND """
            f"""co2."Minutes5UTC" < timestamp'{to_str}' """
            """ORDER BY co2."Minutes5UTC" DESC""")
     response = requests.get(url)
     if not response.ok:
         raise exceptions.CarbonIntensityFetcherError(response.json())
     data = response.json()["result"]["records"]
     carbon_intensities = [record["CO2Emission"] for record in data]
     return np.mean(carbon_intensities)
예제 #3
0
    def _carbon_intensity_gb_national(self, time_dur=None):
        """Retrieves forecasted national carbon intensity (gCO2eq/kWh) in GB.
        """
        url = f"{API_URL}/intensity"

        if time_dur is not None:
            from_str, to_str = self._time_from_to_str(time_dur)
            url += f"/{from_str}/{to_str}"

        response = requests.get(url)
        if not response.ok:
            raise exceptions.CarbonIntensityFetcherError(response.json())
        carbon_intensity = response.json()["data"][0]["intensity"]["forecast"]
        return carbon_intensity
예제 #4
0
    def _emission_current(self):
        def url_creator(area):
            return ("https://api.energidataservice.dk/datastore_search_sql?"
                    """sql=SELECT co2."CO2Emission" from "co2emis" as co2 """
                    f"""WHERE co2."PriceArea" = '{area}' ORDER BY """
                    """co2."Minutes5UTC" DESC LIMIT 1""")

        areas = ["DK1", "DK2"]
        carbon_intensities = []

        for area in areas:
            url = url_creator(area)
            response = requests.get(url)
            if not response.ok:
                raise exceptions.CarbonIntensityFetcherError(response.json())
            carbon_intensities.append(
                response.json()["result"]["records"][0]["CO2Emission"])

        return np.mean(carbon_intensities)
예제 #5
0
    def _carbon_intensity_by_location(self,
                                      lon=None,
                                      lat=None,
                                      country_code=None):
        """Retrieves carbon intensity (gCO2eq/kWh) by location.

        Note:
            Only use arguments (lon, lat) or country_code.

        Args:
            lon (float): Longitude. Defaults to None.
            lat (float): Lattitude. Defaults to None.
            country_code (str): Alpha-2 country code. Defaults to None.

        Returns:
            Carbon intensity in gCO2eq/kWh.

        Raises:
            UnitError: The unit of the carbon intensity does not match the
                expected unit.
        """
        if country_code is not None:
            params = (("countryCode", country_code), )
            assert (lon is None and lat is None)
        elif lon is not None and lat is not None:
            params = (("lon", lon), ("lat", lat))
            assert (country_code is None)

        headers = {"auth-token": AUTH_TOKEN}

        response = requests.get(API_URL, headers=headers, params=params)
        if not response.ok:
            raise exceptions.CarbonIntensityFetcherError(response.json())
        carbon_intensity = response.json()["data"]["carbonIntensity"]
        unit = response["units"]["carbonIntensity"]
        expected_unit = "gCO2eq/kWh"
        if unit != expected_unit:
            raise exceptions.UnitError(
                expected_unit, unit,
                "Carbon intensity query returned the wrong unit.")

        return carbon_intensity