Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nsteins committed Jun 11, 2024
1 parent 11690f2 commit 2513d31
Show file tree
Hide file tree
Showing 9 changed files with 1,405 additions and 116 deletions.
203 changes: 140 additions & 63 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,91 +1,168 @@
# if-plugin-template
# WattTime Grid Emissions Plugin

`if-plugin-template` is an environmental impact calculator template which exposes an API for [IF](https://github.com/Green-Software-Foundation/if) to retrieve energy and embodied carbon estimates.
> [!NOTE] >
> `Watt-time` is a community plugin and not a part of the IF standard library. As a result, the IF core team does not closely monitor these plugins for updates. It is recommended to conduct your own research before implementing them.
## Implementation
## Introduction

Here can be implementation details of the plugin. For example which API is used, transformations and etc.
WattTime technology—based on real-time grid data, cutting-edge algorithms, and machine learning—provides first-of-its-kind insight into your local electricity grid’s marginal emissions rate. [Read More...](https://www.watttime.org/api-documentation/#introduction)

## Usage
## Overview

To run the `<YOUR-CUSTOM-PLUGIN>`, an instance of `PluginInterface` must be created. Then, the plugin's `execute()` method can be called, passing required arguments to it.

This is how you could run the model in Typescript:

```typescript
async function runPlugin() {
const newPlugin = await new MyCustomPlugin().configure(params);
const usage = await newPlugin.calculate([
{
timestamp: '2021-01-01T00:00:00Z',
duration: '15s',
'cpu-util': 34,
},
{
timestamp: '2021-01-01T00:00:15Z',
duration: '15s',
'cpu-util': 12,
},
]);

console.log(usage);
}

runPlugin();
```
The `WattTimeGridEmissions` plugin is designed to compute the average carbon emissions of a power grid over a specified duration. It leverages data from the WattTime API to furnish carbon intensity information for precise locations and timeframes. This plugin proves beneficial for applications requiring carbon footprint monitoring or optimization, such as energy management systems or environmental impact assessments. The plugin supports only v3 version of the WattTime API. The API returns data in `lbs/MWh`, which the plugin converts to `Kg/MWh` (g/KWh) by dividing by `0.453592`.

## Testing model integration
### Authentication

### Using local links
WattTime API requires activation of subscription before usage. Please refer to the [WattTime website](https://watttime.org/docs-dev/data-plans/) for more information.

For using locally developed model in `IF Framework` please follow these steps:
## Prerequisites

1. On the root level of a locally developed model run `npm link`, which will create global package. It uses `package.json` file's `name` field as a package name. Additionally name can be checked by running `npm ls -g --depth=0 --link=true`.
2. Use the linked model in impl by specifying `name`, `method`, `path` in initialize models section.
Before utilizing this plugin, ensure the following prerequisites are fulfilled:

```yaml
name: plugin-demo-link
description: loads plugin
tags: null
initialize:
plugins:
my-custom-plugin:
method: MyCustomPlugin
path: "<name-field-from-package.json>"
global-config:
...
...
1. **Environment Variables**: The plugin requires environment variables `WATT_TIME_USERNAME` and `WATT_TIME_PASSWORD` to be set. These credentials are utilized for authentication with the WattTime API.

**Required Parameters:**

```txt
WATT_TIME_USERNAME: <your-username>
WATT_TIME_PASSWORD: <your-password>
```

**Optional Parameter:**

```txt
WATT_TIME_TOKEN: <your-token>
```

### Using directly from Github
2. **Dependencies**: Confirm the installation of all required dependencies, including `luxon` and `zod`. These dependencies are imperative for date-time manipulation and input validation, respectively.

## Usage

To employ the `WattTimeGridEmissions` plugin, adhere to these steps:

1. **Initialize Plugin**: Import the `WattTimeGridEmissions` function and initialize it with optional global configuration parameters.

2. **Execute Plugin**: Invoke the `execute` method of the initialized plugin instance with an array of input parameters. Each input parameter should include a `timestamp`, `duration`, and either `geolocation`, `cloud/region-wt-id`, or `cloud/region-geolocation` information.

3. **Result**: The plugin will return an array of plugin parameters enriched with the calculated average carbon intensity (`grid/carbon-intensity`) for each input.

## Input Parameters

The plugin expects the following input parameters:

- `timestamp`: A string representing the start time of the query period.
- `duration`: A number indicating the duration of the query period in seconds.
- `geolocation`: A string representing the latitude and longitude of the location in the format `latitude,longitude`. Alternatively, this information can be provided through `cloud/region-geolocation` or `cloud/region-wt-id` parameters.
- `cloud/region-geolocation`: Similar to `geolocation`, with calculations performed by the `cloud-metadata` plugin.
- `cloud/region-wt-id`: A string representing the region abbreviation associated with the location (e.g., 'CAISO_NORTH').
- `signal-type`: A string representing the signal type of the selected region (optional) (e.g., 'co2_moer').

You can simply push your model to the public Github repository and pass the path to it in your impl.
For example, for a model saved in `github.com/my-repo/my-model` you can do the following:
## Output

npm install your model:
The plugin enriches each input parameter with the average carbon intensity (`grid/carbon-intensity`) calculated over the specified duration.

## Error Handling

The plugin conducts input validation using the `zod` library and may throw errors if the provided parameters are invalid or if there are authentication or data retrieval issues with the WattTime API.

## Plugin Algorithm

1. **Initialization**: Authenticate with the WattTime API using the provided credentials. If the `token` is not provided in the environment variables, it uses `username` and `password`, otherwise, it throws an error. To authenticate users, the plugin utilizes the `https://api.watttime.org/login` URL.

2. **Execution**:

- Iterate through each input.

- If `cloud/region-wt-id is provided`, the plugin sets it to `region`, renames `signal-type` to `signal_type`, and sends a request to `https://api.watttime.org/v3/forecast/historical` endpoint with calculated `start` and `end` time as well. If the `signal_type` is not provided, the plugin requests `https://api.watttime.org/v3/my-access` to obtain access to the account and takes the first signal type from there.
- If `geolocation` is provided, the plugin converts it to a `latitude` and `longitude` pair, renames `signal-type` to `signal_type`, and sends a request to `https://api.watttime.org/v3/region-from-loc` to retrieve the `region`. Then the `https://api.watttime.org/v3/forecast/historical` endpoint is called with `region`, `signal_type`, calculated `start` and `end` time from `timestamp` and `duration`.

- Validate input parameters. If `cloud/region-geolocation` is provided, the `geolocation` is overridden. If `cloud/region-wt-id` is provided, it takes precedence over the `geolocation`.

- Retrieve WattTime data for the specified duration. The WattTime API adds aggregated emissions for every 5 minutes. To address this limitation, the plugin sets the previous emission's value if the specified `duration` is less than 5 minutes.

- Calculate average emissions based on retrieved data. The WattTime API returns full data for the entire duration; the plugin checks if the data's period time is within the specified input range and collects data in `kgMWh`.

3. **Output**: Return results with the average grid emissions for each input.

### TypeScript Usage

```ts
// Initialize the plugin
const plugin = WattTimeGridEmissions();

// Execute the plugin with input parameters
const inputs = [
{
timestamp: '2024-03-26T12:00:000Z',
duration: 3600, // 1 hour
geolocation: '36.7783,-119.417931', // San Francisco, CA
},
// Add more input parameters as needed
];
const result = await plugin.execute(inputs);

console.log(result);
```
npm install -g https://github.com/my-repo/my-model

### Manifest Usage

#### Input

```yaml
name: watt-time
description: simple demo invoking watt-time
tags:
initialize:
plugins:
watt-time:
method: WattTimeGridEmissions
path: '@grnsft/if-unofficial-plugins'
outputs:
- yaml
tree:
children:
child:
pipeline:
- watt-time
inputs:
- timestamp: '2024-03-05T00:00:00.000Z'
duration: 3600
geolocation: 36.7783,-119.417931
```
Then, in your `impl`, provide the path in the model instantiation. You also need to specify which class the model instantiates. In this case you are using the `PluginInterface`, so you can specify `OutputModel`.
#### Output
```yaml
name: plugin-demo-git
description: loads plugin
name: watt-time
description: simple demo invoking watt-time
tags: null
initialize:
plugins:
my-custom-plugin:
method: MyCustomPlugin
path: https://github.com/my-repo/my-model
global-config:
...
...
watt-time:
path: '@grnsft/if-unofficial-plugins'
method: WattTimeGridEmissions
outputs:
- yaml
tree:
children:
child:
pipeline:
- watt-time
inputs:
- timestamp: '2024-03-05T00:00:00.000Z'
duration: 3600
geolocation: 36.7783,-119.417931
outputs:
- timestamp: '2024-03-05T00:00:00.000Z'
duration: 3600
geolocation: 36.7783,-119.417931
grid/carbon-intensity: 287.7032521512652
```
Now, when you run the `manifest` using the IF CLI, it will load the model automatically. Run using:
You can execute this by passing it to `ie`. Run the impact using the following command from the project root:

```sh
ie --manifest <path-to-your-impl> --output <path-to-save-output>
npm i -g @grnsft/if
npm i -g @grnsft/if-unofficial-plugins
ie --manifest ./examples/manifests/test/watt-time.yml --output ./examples/outputs/watt-time.yml
```
24 changes: 0 additions & 24 deletions src/__tests__/unit/lib/my-custom-plugin.test.ts

This file was deleted.

Loading

0 comments on commit 2513d31

Please sign in to comment.