GreenScheduler / cats

CATS: the Climate-Aware Task Scheduler :cat2: :tiger2: :leopard:
https://greenscheduler.github.io/cats/
MIT License
50 stars 8 forks source link

Enable extension to other carbon intensity forecast providers #37

Closed tlestang closed 1 year ago

tlestang commented 1 year ago

It is currently assumed that carbon intensity data comes from carbonintensity.org.uk. While it is likely to remain the case for a time (until we find data sources for other countries, see #22), it didn't seem a lot of effort -- and changes -- to abstract away the API-specific bits, namely:

This PR add two new arguments request_url_fun and parse_response_fun to the parsedata.get_tuple:

def get_tuple(
    postcode: str,
    request_url_fun: Callable[[datetime, str], str],
    parse_response_fun: Callable[[dict], list[tuple[datetime, int]]],
) -> list[list[tuple[datetime, int]]]:
    """
    get carbon intensity from a web API
    # ...
   """

These two arguments are functions and are specified at runtime.

The list of currently supported API interfaces (i.e. the list of avilable implementations of both functions) is provided by a module api_interface. This module makes available a dictionary of APIInterface instances, which are nothing but namedtuple instances specifying both functions for a given web service.

from cats.apt_interface import API_interfaces

api_interface = API_interfaces["carbonintensity.org.uk"]
tuples = get_tuple(
    postcode,
    api_interface.get_request_url,
    api_interface.parse_reponse_data,
)

Isolating the API-specific logic will also help should the carbonintensity.org.uk change its interface in the future. For instance the endpoint syntax or response structure.