Upload 10 files
Browse files- Dockerfile +6 -0
- README.md +60 -11
- inference.py +154 -0
- openenv.yaml +10 -0
- pyproject.toml +21 -0
- server/__init__.py +1 -0
- server/__pycache__/__init__.cpython-314.pyc +0 -0
- server/__pycache__/app.cpython-314.pyc +0 -0
- server/app.py +226 -0
- uv.lock +0 -0
Dockerfile
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
COPY . .
|
| 4 |
+
RUN pip install uv && uv sync
|
| 5 |
+
EXPOSE 7860
|
| 6 |
+
CMD ["uv", "run", "server"]
|
README.md
CHANGED
|
@@ -1,11 +1,60 @@
|
|
| 1 |
-
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Grid-Scale Energy Storage Arbitrage
|
| 2 |
+
|
| 3 |
+
An OpenEnv environment where an LLM agent acts as an energy trader managing a grid-scale battery storage system. The agent must buy cheap electricity from the grid, store it, and sell it back at peak prices, all while managing battery degradation and grid obligations.
|
| 4 |
+
|
| 5 |
+
## 1. Environment Description
|
| 6 |
+
Grid-scale batteries (like Tesla Megapacks) sit between the electricity grid and the market. Because electricity prices fluctuate based on demand (cheaper at night, expensive during evening peaks), operators can perform "arbitrage"—buying low and selling high. This environment is built entirely on pure Python math to simulate real-world energy trading constraints without heavy physics engines.
|
| 7 |
+
|
| 8 |
+
## 2. Action Space
|
| 9 |
+
The agent can perform one of three actions per step:
|
| 10 |
+
* `charge`: Buy electricity from the grid to store in the battery.
|
| 11 |
+
* `discharge`: Sell electricity from the battery to the grid.
|
| 12 |
+
* `hold`: Do nothing for the current hour.
|
| 13 |
+
|
| 14 |
+
**Format:**
|
| 15 |
+
* Single Battery: `{"action_type": "charge", "amount_kwh": 25.0}`
|
| 16 |
+
* Multi-Battery (Task 3): `[{"battery_id": 0, "action_type": "charge", "amount_kwh": 25.0}, ...]`
|
| 17 |
+
|
| 18 |
+
## 3. Observation Space
|
| 19 |
+
The environment returns a state dictionary containing:
|
| 20 |
+
* `hour` (int): The current hour of the episode.
|
| 21 |
+
* `charge_level` (float): Total kWh currently stored across all batteries.
|
| 22 |
+
* `capacity_max` (float): Maximum possible kWh storage (degrades over time).
|
| 23 |
+
* `charge_pct` (float): Percentage of battery currently charged.
|
| 24 |
+
* `current_price` (float): The current price of electricity in £/kWh.
|
| 25 |
+
* `price_forecast` (list[float]): The predicted prices for the next 6 hours.
|
| 26 |
+
* `profit_so_far` (float): Cumulative profit generated in the episode.
|
| 27 |
+
* `demand_charge_peak` (float): The peak kW drawn from the grid (for penalty calculations).
|
| 28 |
+
* `regulation_obligation` (float): The required kWh to be held in reserve (Task 3).
|
| 29 |
+
* `cycle_count` (float): Cumulative full discharge cycles completed.
|
| 30 |
+
* `done` (bool): Whether the episode has concluded.
|
| 31 |
+
|
| 32 |
+
## 4. Tasks
|
| 33 |
+
1. **single-day-arbitrage (Easy):** 1 battery, 24 steps. Fixed, predictable price profile. The agent must simply learn to charge at night and discharge during the evening.
|
| 34 |
+
2. **weekly-demand-charge (Medium):** 1 battery, 48 steps. Highly volatile prices. Introduces a £15 demand charge penalty if the agent draws >80 kWh from the grid in any single step.
|
| 35 |
+
3. **multi-battery-regulation (Hard):** 3 distinct batteries with varying efficiencies and degradation rates. 48 steps. Introduces a shifting regulation floor obligation; falling below it incurs a £3 penalty per kWh short.
|
| 36 |
+
|
| 37 |
+
## 5. Reward Function
|
| 38 |
+
Reward is calculated purely deterministically based on revenue, costs, and penalties per step:
|
| 39 |
+
* **Charge Cost:** `- (amount_kwh * current_price)`
|
| 40 |
+
* **Discharge Revenue:** `(amount_kwh * efficiency * current_price) - (amount_kwh * 0.5 * degradation_rate * current_price)`
|
| 41 |
+
* **Penalties:**
|
| 42 |
+
* Low Charge (<5% capacity): `- 0.5`
|
| 43 |
+
* Demand Charge Violation (>80kWh in Task 2): `- 15.0`
|
| 44 |
+
* Regulation Violation (Task 3): `- 3.0 * (shortfall_kwh)`
|
| 45 |
+
|
| 46 |
+
## 6. Baseline Scores
|
| 47 |
+
Using the provided `inference.py` script with `qwen/qwen-2.5-72b-instruct`:
|
| 48 |
+
* Task 1 (`single-day-arbitrage`): ~0.214
|
| 49 |
+
* Task 2 (`weekly-demand-charge`): ~0.000
|
| 50 |
+
* Task 3 (`multi-battery-regulation`): ~0.102
|
| 51 |
+
|
| 52 |
+
## 7. Setup & Validation Instructions
|
| 53 |
+
Ensure you have Docker and `uv` installed locally.
|
| 54 |
+
|
| 55 |
+
1. Generate lockfile: `uv lock`
|
| 56 |
+
2. Start local server: `uv run server`
|
| 57 |
+
3. Ping the environment: `curl -X POST localhost:7860/reset`
|
| 58 |
+
4. Run validation checks: `openenv validate`
|
| 59 |
+
5. Build Docker image: `docker build .`
|
| 60 |
+
6. Run inference: `python inference.py`
|
inference.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.request
|
| 5 |
+
from openai import OpenAI
|
| 6 |
+
|
| 7 |
+
# --- Environment Configuration ---
|
| 8 |
+
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
|
| 9 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
|
| 10 |
+
API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
|
| 11 |
+
ENV_URL = "http://localhost:7860"
|
| 12 |
+
|
| 13 |
+
TASKS = ["single-day-arbitrage", "weekly-demand-charge", "multi-battery-regulation"]
|
| 14 |
+
|
| 15 |
+
# --- Prompt Engineering ---
|
| 16 |
+
SYSTEM_PROMPT_SINGLE = """
|
| 17 |
+
You are an expert energy trader managing a grid-scale battery storage system.
|
| 18 |
+
Your goal is to maximize profit. Charge when cheap, discharge when expensive.
|
| 19 |
+
The battery loses ~8-10% efficiency on round trips.
|
| 20 |
+
|
| 21 |
+
Output your action as valid JSON on the final line. Format:
|
| 22 |
+
{"action_type": "charge"|"discharge"|"hold", "amount_kwh": float}
|
| 23 |
+
|
| 24 |
+
Before acting, briefly explain your reasoning in 2 sentences.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
SYSTEM_PROMPT_MULTI = """
|
| 28 |
+
You are managing THREE grid-scale batteries.
|
| 29 |
+
Output your action as a JSON list of objects on the final line. Format:
|
| 30 |
+
[
|
| 31 |
+
{"battery_id": 0, "action_type": "charge"|"discharge"|"hold", "amount_kwh": float},
|
| 32 |
+
{"battery_id": 1, "action_type": "charge"|"discharge"|"hold", "amount_kwh": float},
|
| 33 |
+
{"battery_id": 2, "action_type": "charge"|"discharge"|"hold", "amount_kwh": float}
|
| 34 |
+
]
|
| 35 |
+
Briefly explain your reasoning in 2 sentences first.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def extract_json_action(text: str, is_multi: bool):
|
| 39 |
+
try:
|
| 40 |
+
lines = text.strip().split('\n')
|
| 41 |
+
for line in reversed(lines):
|
| 42 |
+
if line.strip().startswith('{') or line.strip().startswith('['):
|
| 43 |
+
return json.loads(line)
|
| 44 |
+
import re
|
| 45 |
+
match = re.search(r'```json\s*(.*?)\s*```', text, re.DOTALL)
|
| 46 |
+
if match:
|
| 47 |
+
return json.loads(match.group(1))
|
| 48 |
+
except Exception:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
if is_multi:
|
| 52 |
+
return [{"battery_id": i, "action_type": "hold", "amount_kwh": 0.0} for i in range(3)]
|
| 53 |
+
return {"action_type": "hold", "amount_kwh": 0.0}
|
| 54 |
+
|
| 55 |
+
def format_action_string(action_payload):
|
| 56 |
+
if isinstance(action_payload, list):
|
| 57 |
+
return "|".join([f"b{a.get('battery_id', 0)}:{a.get('action_type', 'hold')}:{a.get('amount_kwh', 0.0)}" for a in action_payload])
|
| 58 |
+
return f"{action_payload.get('action_type', 'hold')}:{action_payload.get('amount_kwh', 0.0)}"
|
| 59 |
+
|
| 60 |
+
def post_json(endpoint: str, data: dict):
|
| 61 |
+
req = urllib.request.Request(f"{ENV_URL}{endpoint}", method="POST")
|
| 62 |
+
req.add_header('Content-Type', 'application/json')
|
| 63 |
+
data_bytes = json.dumps(data).encode('utf-8')
|
| 64 |
+
with urllib.request.urlopen(req, data=data_bytes) as response:
|
| 65 |
+
return json.loads(response.read().decode('utf-8'))
|
| 66 |
+
|
| 67 |
+
def run_task(client: OpenAI, task_name: str):
|
| 68 |
+
print(f"[START] task={task_name} env=grid-energy-arbitrage model={MODEL_NAME}", flush=True)
|
| 69 |
+
|
| 70 |
+
is_multi = task_name == "multi-battery-regulation"
|
| 71 |
+
system_prompt = SYSTEM_PROMPT_MULTI if is_multi else SYSTEM_PROMPT_SINGLE
|
| 72 |
+
|
| 73 |
+
obs = post_json("/reset", {"task_name": task_name})
|
| 74 |
+
|
| 75 |
+
rewards = []
|
| 76 |
+
steps = 0
|
| 77 |
+
done = False
|
| 78 |
+
final_score = 0.0
|
| 79 |
+
|
| 80 |
+
while not done:
|
| 81 |
+
steps += 1
|
| 82 |
+
|
| 83 |
+
user_prompt = (
|
| 84 |
+
f"Step: {steps}\n"
|
| 85 |
+
f"Current Hour: {obs['hour']}\n"
|
| 86 |
+
f"Current Price: {obs['current_price']:.4f}\n"
|
| 87 |
+
f"Forecast (next 6h): {obs['price_forecast']}\n"
|
| 88 |
+
f"Charge Level: {obs['charge_level']:.2f} / {obs['capacity_max']:.2f} kWh\n"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# --- ROBUST RETRY MECHANISM ---
|
| 92 |
+
action_payload = None
|
| 93 |
+
max_retries = 5
|
| 94 |
+
|
| 95 |
+
for attempt in range(max_retries):
|
| 96 |
+
try:
|
| 97 |
+
completion = client.chat.completions.create(
|
| 98 |
+
model=MODEL_NAME,
|
| 99 |
+
messages=[
|
| 100 |
+
{"role": "system", "content": system_prompt},
|
| 101 |
+
{"role": "user", "content": user_prompt}
|
| 102 |
+
],
|
| 103 |
+
temperature=0.7,
|
| 104 |
+
max_tokens=350,
|
| 105 |
+
timeout=30.0
|
| 106 |
+
)
|
| 107 |
+
response_text = completion.choices[0].message.content
|
| 108 |
+
action_payload = extract_json_action(response_text, is_multi)
|
| 109 |
+
break # Success! Exit the retry loop
|
| 110 |
+
|
| 111 |
+
except Exception as e:
|
| 112 |
+
print(f"\n[DEBUG] API Error: {e}", flush=True) # <-- Add this line
|
| 113 |
+
if attempt < max_retries - 1:
|
| 114 |
+
time.sleep(3 * (attempt + 1))
|
| 115 |
+
else:
|
| 116 |
+
action_payload = extract_json_action("", is_multi)
|
| 117 |
+
|
| 118 |
+
action_str = format_action_string(action_payload)
|
| 119 |
+
|
| 120 |
+
step_data = post_json("/step", action_payload)
|
| 121 |
+
|
| 122 |
+
obs = step_data["observation"]
|
| 123 |
+
reward = step_data["reward"]
|
| 124 |
+
done = step_data["done"]
|
| 125 |
+
info = step_data["info"]
|
| 126 |
+
|
| 127 |
+
rewards.append(reward)
|
| 128 |
+
done_str = str(done).lower()
|
| 129 |
+
|
| 130 |
+
print(f"[STEP] step={steps} action={action_str} reward={reward:.2f} done={done_str} error=null", flush=True)
|
| 131 |
+
|
| 132 |
+
if done:
|
| 133 |
+
final_score = info.get("score", 0.0)
|
| 134 |
+
|
| 135 |
+
success = final_score > 0.1
|
| 136 |
+
rewards_str = ",".join([f"{r:.2f}" for r in rewards])
|
| 137 |
+
print(f"[END] success={str(success).lower()} steps={steps} score={final_score:.3f} rewards={rewards_str}", flush=True)
|
| 138 |
+
|
| 139 |
+
def main():
|
| 140 |
+
if not API_KEY:
|
| 141 |
+
print("ERROR: HF_TOKEN environment variable not set!")
|
| 142 |
+
return
|
| 143 |
+
|
| 144 |
+
client = OpenAI(
|
| 145 |
+
base_url=API_BASE_URL,
|
| 146 |
+
api_key=API_KEY,
|
| 147 |
+
max_retries=3 # Let the internal client handle basic connection drops
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
for task in TASKS:
|
| 151 |
+
run_task(client, task)
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
main()
|
openenv.yaml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: grid-energy-arbitrage
|
| 2 |
+
version: "1.0.0"
|
| 3 |
+
description: "Grid-scale battery storage arbitrage environment for RL agents"
|
| 4 |
+
tasks:
|
| 5 |
+
- name: single-day-arbitrage
|
| 6 |
+
difficulty: easy
|
| 7 |
+
- name: weekly-demand-charge
|
| 8 |
+
difficulty: medium
|
| 9 |
+
- name: multi-battery-regulation
|
| 10 |
+
difficulty: hard
|
pyproject.toml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "grid-energy-arbitrage"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
requires-python = ">=3.10"
|
| 9 |
+
dependencies = [
|
| 10 |
+
"openenv-core>=0.1.0",
|
| 11 |
+
"fastapi>=0.100.0",
|
| 12 |
+
"uvicorn>=0.23.0",
|
| 13 |
+
"pydantic>=2.0.0",
|
| 14 |
+
"openai>=1.0.0",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
[project.scripts]
|
| 18 |
+
server = "server.app:main"
|
| 19 |
+
|
| 20 |
+
[tool.hatch.build.targets.wheel]
|
| 21 |
+
packages = ["server"]
|
server/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
server/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (172 Bytes). View file
|
|
|
server/__pycache__/app.cpython-314.pyc
ADDED
|
Binary file (14.4 kB). View file
|
|
|
server/app.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import uvicorn
|
| 3 |
+
from fastapi import FastAPI, Body
|
| 4 |
+
from pydantic import BaseModel, Field
|
| 5 |
+
from typing import List, Literal, Any
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
# --- Global State ---
|
| 10 |
+
GLOBAL_STATE = {}
|
| 11 |
+
|
| 12 |
+
# --- Pydantic Models ---
|
| 13 |
+
class EnergyObservation(BaseModel):
|
| 14 |
+
hour: int
|
| 15 |
+
charge_level: float
|
| 16 |
+
capacity_max: float
|
| 17 |
+
charge_pct: float
|
| 18 |
+
current_price: float
|
| 19 |
+
price_forecast: List[float]
|
| 20 |
+
profit_so_far: float
|
| 21 |
+
demand_charge_peak: float
|
| 22 |
+
regulation_obligation: float
|
| 23 |
+
cycle_count: float
|
| 24 |
+
done: bool
|
| 25 |
+
|
| 26 |
+
class EnergyAction(BaseModel):
|
| 27 |
+
action_type: Literal["charge", "discharge", "hold"]
|
| 28 |
+
amount_kwh: float = Field(ge=0.0, description="Amount must be >= 0")
|
| 29 |
+
|
| 30 |
+
class SingleBatteryAction(BaseModel):
|
| 31 |
+
battery_id: int
|
| 32 |
+
action_type: Literal["charge", "discharge", "hold"]
|
| 33 |
+
amount_kwh: float = Field(ge=0.0)
|
| 34 |
+
|
| 35 |
+
class EnvStepResult(BaseModel):
|
| 36 |
+
observation: EnergyObservation
|
| 37 |
+
reward: float
|
| 38 |
+
done: bool
|
| 39 |
+
info: dict
|
| 40 |
+
|
| 41 |
+
# --- Core Engine Logic ---
|
| 42 |
+
def generate_price_profile(seed: int, hours: int, volatility: str) -> list[float]:
|
| 43 |
+
rng = random.Random(seed)
|
| 44 |
+
base_profile = []
|
| 45 |
+
for h in range(hours):
|
| 46 |
+
hour_of_day = h % 24
|
| 47 |
+
if 0 <= hour_of_day <= 5:
|
| 48 |
+
base = 0.04 + rng.uniform(0, 0.02)
|
| 49 |
+
elif 6 <= hour_of_day <= 11:
|
| 50 |
+
base = 0.12 + rng.uniform(0, 0.10)
|
| 51 |
+
elif 12 <= hour_of_day <= 17:
|
| 52 |
+
base = 0.14 + rng.uniform(0, 0.08)
|
| 53 |
+
else:
|
| 54 |
+
base = 0.22 + rng.uniform(0, 0.14)
|
| 55 |
+
|
| 56 |
+
if volatility == "medium" and rng.random() < 0.06:
|
| 57 |
+
base = rng.uniform(0.45, 0.60)
|
| 58 |
+
elif volatility == "hard" and rng.random() < 0.10:
|
| 59 |
+
if rng.random() < 0.2:
|
| 60 |
+
base = -0.02
|
| 61 |
+
else:
|
| 62 |
+
base = rng.uniform(0.50, 0.70)
|
| 63 |
+
|
| 64 |
+
base_profile.append(round(base, 4))
|
| 65 |
+
return base_profile
|
| 66 |
+
|
| 67 |
+
def calculate_max_profit(prices: list[float], capacity: float, efficiency: float) -> float:
|
| 68 |
+
sorted_prices = sorted(enumerate(prices), key=lambda x: x[1])
|
| 69 |
+
buy_hours = sorted_prices[:len(prices)//4]
|
| 70 |
+
sell_hours = sorted_prices[-(len(prices)//4):]
|
| 71 |
+
|
| 72 |
+
max_charge = capacity
|
| 73 |
+
revenue = sum(capacity * efficiency * p for _, p in sell_hours)
|
| 74 |
+
cost = sum(capacity * p for _, p in buy_hours)
|
| 75 |
+
return max(1.0, revenue - cost)
|
| 76 |
+
|
| 77 |
+
def get_observation() -> EnergyObservation:
|
| 78 |
+
step = GLOBAL_STATE.get("step", 0)
|
| 79 |
+
prices = GLOBAL_STATE.get("prices", [0.0])
|
| 80 |
+
max_steps = GLOBAL_STATE.get("max_steps", 24)
|
| 81 |
+
task = GLOBAL_STATE.get("task", "single-day-arbitrage")
|
| 82 |
+
|
| 83 |
+
done = step >= max_steps
|
| 84 |
+
current_price = prices[step] if not done else 0.0
|
| 85 |
+
forecast = prices[step+1 : step+7] if not done else []
|
| 86 |
+
while len(forecast) < 6: forecast.append(0.0)
|
| 87 |
+
|
| 88 |
+
total_charge = sum(b["charge"] for b in GLOBAL_STATE.get("batteries", []))
|
| 89 |
+
total_cap = sum(b["cap"] for b in GLOBAL_STATE.get("batteries", []))
|
| 90 |
+
|
| 91 |
+
reg_ob = 0.0
|
| 92 |
+
if task == "multi-battery-regulation" and not done:
|
| 93 |
+
reg_ob = 100.0 + (step // 8) * 10.0
|
| 94 |
+
|
| 95 |
+
return EnergyObservation(
|
| 96 |
+
hour=step,
|
| 97 |
+
charge_level=total_charge,
|
| 98 |
+
capacity_max=total_cap,
|
| 99 |
+
charge_pct=total_charge / total_cap if total_cap > 0 else 0.0,
|
| 100 |
+
current_price=current_price,
|
| 101 |
+
price_forecast=forecast,
|
| 102 |
+
profit_so_far=GLOBAL_STATE.get("profit_so_far", 0.0),
|
| 103 |
+
demand_charge_peak=GLOBAL_STATE.get("last_drawn", 0.0),
|
| 104 |
+
regulation_obligation=reg_ob,
|
| 105 |
+
cycle_count=GLOBAL_STATE.get("cycle_count", 0.0),
|
| 106 |
+
done=done
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# --- API Routes ---
|
| 110 |
+
@app.post("/reset", response_model=EnergyObservation)
|
| 111 |
+
async def reset(payload: dict = Body(default_factory=dict)):
|
| 112 |
+
task = payload.get("task_name", "single-day-arbitrage")
|
| 113 |
+
|
| 114 |
+
if task == "single-day-arbitrage":
|
| 115 |
+
hours, seed, vol = 24, 42, "easy"
|
| 116 |
+
batteries = [{"id": 0, "cap": 100.0, "charge": 50.0, "eff": 0.92, "deg": 0.0002, "orig_cap": 100.0}]
|
| 117 |
+
elif task == "weekly-demand-charge":
|
| 118 |
+
hours, seed, vol = 48, 123, "medium"
|
| 119 |
+
batteries = [{"id": 0, "cap": 150.0, "charge": 75.0, "eff": 0.90, "deg": 0.0002, "orig_cap": 150.0}]
|
| 120 |
+
elif task == "multi-battery-regulation":
|
| 121 |
+
hours, seed, vol = 48, 999, "hard"
|
| 122 |
+
batteries = [
|
| 123 |
+
{"id": 0, "cap": 200.0, "charge": 100.0, "eff": 0.95, "deg": 0.0001, "orig_cap": 200.0},
|
| 124 |
+
{"id": 1, "cap": 120.0, "charge": 60.0, "eff": 0.88, "deg": 0.0003, "orig_cap": 120.0},
|
| 125 |
+
{"id": 2, "cap": 80.0, "charge": 40.0, "eff": 0.91, "deg": 0.0002, "orig_cap": 80.0}
|
| 126 |
+
]
|
| 127 |
+
else:
|
| 128 |
+
task, hours, seed, vol = "single-day-arbitrage", 24, 42, "easy"
|
| 129 |
+
batteries = [{"id": 0, "cap": 100.0, "charge": 50.0, "eff": 0.92, "deg": 0.0002, "orig_cap": 100.0}]
|
| 130 |
+
|
| 131 |
+
GLOBAL_STATE["task"] = task
|
| 132 |
+
GLOBAL_STATE["step"] = 0
|
| 133 |
+
GLOBAL_STATE["max_steps"] = hours
|
| 134 |
+
GLOBAL_STATE["prices"] = generate_price_profile(seed, hours, vol)
|
| 135 |
+
GLOBAL_STATE["batteries"] = batteries
|
| 136 |
+
GLOBAL_STATE["profit_so_far"] = 0.0
|
| 137 |
+
GLOBAL_STATE["cycle_count"] = 0.0
|
| 138 |
+
GLOBAL_STATE["last_drawn"] = 0.0
|
| 139 |
+
|
| 140 |
+
return get_observation()
|
| 141 |
+
|
| 142 |
+
@app.post("/step", response_model=EnvStepResult)
|
| 143 |
+
async def step_env(action_payload: Any = Body(...)):
|
| 144 |
+
if "task" not in GLOBAL_STATE or GLOBAL_STATE["step"] >= GLOBAL_STATE["max_steps"]:
|
| 145 |
+
return EnvStepResult(observation=get_observation(), reward=0.0, done=True, info={"error": "Episode done or needs reset"})
|
| 146 |
+
|
| 147 |
+
task = GLOBAL_STATE["task"]
|
| 148 |
+
current_price = GLOBAL_STATE["prices"][GLOBAL_STATE["step"]]
|
| 149 |
+
|
| 150 |
+
# Normalize inputs to a list of actions
|
| 151 |
+
actions = []
|
| 152 |
+
if isinstance(action_payload, dict):
|
| 153 |
+
if "battery_id" in action_payload:
|
| 154 |
+
actions.append(action_payload)
|
| 155 |
+
else:
|
| 156 |
+
actions.append({"battery_id": 0, "action_type": action_payload.get("action_type", "hold"), "amount_kwh": action_payload.get("amount_kwh", 0.0)})
|
| 157 |
+
elif isinstance(action_payload, list):
|
| 158 |
+
actions = action_payload
|
| 159 |
+
|
| 160 |
+
step_reward = 0.0
|
| 161 |
+
total_drawn = 0.0
|
| 162 |
+
|
| 163 |
+
# Process physical constraints and revenues
|
| 164 |
+
for act in actions:
|
| 165 |
+
b_id = act.get("battery_id", 0)
|
| 166 |
+
a_type = act.get("action_type", "hold")
|
| 167 |
+
amount = float(act.get("amount_kwh", 0.0))
|
| 168 |
+
|
| 169 |
+
b = next((bat for bat in GLOBAL_STATE["batteries"] if bat["id"] == b_id), None)
|
| 170 |
+
if not b or amount <= 0: continue
|
| 171 |
+
|
| 172 |
+
if a_type == "charge":
|
| 173 |
+
amount = min(amount, b["cap"] - b["charge"])
|
| 174 |
+
cost = amount * current_price
|
| 175 |
+
step_reward -= cost
|
| 176 |
+
b["charge"] += amount
|
| 177 |
+
total_drawn += amount
|
| 178 |
+
elif a_type == "discharge":
|
| 179 |
+
amount = min(amount, b["charge"])
|
| 180 |
+
rev = amount * b["eff"] * current_price
|
| 181 |
+
deg_cost = amount * 0.5 * b["deg"] * current_price
|
| 182 |
+
step_reward += (rev - deg_cost)
|
| 183 |
+
b["charge"] -= amount
|
| 184 |
+
b["cap"] -= amount * b["deg"]
|
| 185 |
+
GLOBAL_STATE["cycle_count"] += (amount / b["orig_cap"])
|
| 186 |
+
|
| 187 |
+
# Apply Rule Penalties
|
| 188 |
+
total_charge = sum(b["charge"] for b in GLOBAL_STATE["batteries"])
|
| 189 |
+
total_cap = sum(b["cap"] for b in GLOBAL_STATE["batteries"])
|
| 190 |
+
|
| 191 |
+
if total_charge < 0.05 * total_cap:
|
| 192 |
+
step_reward -= 0.5
|
| 193 |
+
|
| 194 |
+
if task == "weekly-demand-charge" and total_drawn > 80.0:
|
| 195 |
+
step_reward -= 15.0
|
| 196 |
+
|
| 197 |
+
if task == "multi-battery-regulation":
|
| 198 |
+
reg_ob = 100.0 + (GLOBAL_STATE["step"] // 8) * 10.0
|
| 199 |
+
if total_charge < reg_ob:
|
| 200 |
+
step_reward -= 3.0 * (reg_ob - total_charge)
|
| 201 |
+
|
| 202 |
+
# Advance State
|
| 203 |
+
GLOBAL_STATE["profit_so_far"] += step_reward
|
| 204 |
+
GLOBAL_STATE["step"] += 1
|
| 205 |
+
GLOBAL_STATE["last_drawn"] = total_drawn
|
| 206 |
+
|
| 207 |
+
done = GLOBAL_STATE["step"] >= GLOBAL_STATE["max_steps"]
|
| 208 |
+
obs = get_observation()
|
| 209 |
+
|
| 210 |
+
info = {}
|
| 211 |
+
if done:
|
| 212 |
+
# Calculate theoretical max based on premium battery logic to derive episode score
|
| 213 |
+
b0 = GLOBAL_STATE["batteries"][0]
|
| 214 |
+
max_prof = calculate_max_profit(GLOBAL_STATE["prices"], b0["orig_cap"], b0["eff"])
|
| 215 |
+
score = GLOBAL_STATE["profit_so_far"] / max_prof if max_prof > 0 else 0.0
|
| 216 |
+
if max_prof <= 0: score = 0.5 if GLOBAL_STATE["profit_so_far"] >= 0 else 0.0
|
| 217 |
+
info["score"] = max(0.0, min(1.0, score))
|
| 218 |
+
|
| 219 |
+
return EnvStepResult(observation=obs, reward=step_reward, done=done, info=info)
|
| 220 |
+
|
| 221 |
+
# --- Server Entrypoint (MANDATORY) ---
|
| 222 |
+
def main():
|
| 223 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 224 |
+
|
| 225 |
+
if __name__ == "__main__":
|
| 226 |
+
main()
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|