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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gymnasium as gym
|
| 2 |
+
import sinergym
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import sys
|
| 8 |
+
from unihvac.find_files import (
|
| 9 |
+
detect_paths,
|
| 10 |
+
find_manifest,
|
| 11 |
+
find_building_and_weather_from_manifest,
|
| 12 |
+
)
|
| 13 |
+
from unihvac.tables import (
|
| 14 |
+
print_monthly_tables_extra,
|
| 15 |
+
print_monthly_tables_split,
|
| 16 |
+
)
|
| 17 |
+
from unihvac.rollout import run_rollout_to_df
|
| 18 |
+
from unihvac.data_generator import save_dt_training_data
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ============================================
|
| 24 |
+
# FOR TABLE
|
| 25 |
+
pd.set_option("display.max_columns", None)
|
| 26 |
+
pd.set_option("display.width", 240)
|
| 27 |
+
pd.set_option("display.max_colwidth", 32)
|
| 28 |
+
pd.set_option("display.float_format", lambda x: f"{x:,.2f}")
|
| 29 |
+
# ============================================
|
| 30 |
+
|
| 31 |
+
# ==============================================================================
|
| 32 |
+
# USER CONFIGURATION
|
| 33 |
+
# ==============================================================================
|
| 34 |
+
TARGET_LOCATION = "Fairbanks"
|
| 35 |
+
TARGET_THERMAL = "default"
|
| 36 |
+
TARGET_OCCUPANCY = "standard"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
HEATING_SP = 21.0
|
| 40 |
+
COOLING_SP = 24.0
|
| 41 |
+
|
| 42 |
+
# ==========================================
|
| 43 |
+
# PATH DISCOVERY (ROBUST)
|
| 44 |
+
# ==========================================
|
| 45 |
+
paths = detect_paths(outputs_dirname="baseline_results")
|
| 46 |
+
# Get manifest (patched preferred)
|
| 47 |
+
manifest_path = find_manifest(paths, building="OfficeSmall", prefer_patched=True)
|
| 48 |
+
output_root = str(paths.outputs_root)
|
| 49 |
+
os.makedirs(output_root, exist_ok=True)
|
| 50 |
+
|
| 51 |
+
OUTPUT_DIR = "rollout_run"
|
| 52 |
+
|
| 53 |
+
TIME_STEP_HOURS = 900.0 / 3600.0 # 0.25 h
|
| 54 |
+
|
| 55 |
+
# ==========================================
|
| 56 |
+
# 3. COMMON ACTUATORS & VARIABLES
|
| 57 |
+
# ==========================================
|
| 58 |
+
hot_actuators = {
|
| 59 |
+
"Htg_Core": ("Zone Temperature Control", "Heating Setpoint", "CORE_ZN"),
|
| 60 |
+
"Clg_Core": ("Zone Temperature Control", "Cooling Setpoint", "CORE_ZN"),
|
| 61 |
+
"Htg_P1": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_1"),
|
| 62 |
+
"Clg_P1": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_1"),
|
| 63 |
+
"Htg_P2": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_2"),
|
| 64 |
+
"Clg_P2": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_2"),
|
| 65 |
+
"Htg_P3": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_3"),
|
| 66 |
+
"Clg_P3": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_3"),
|
| 67 |
+
"Htg_P4": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_4"),
|
| 68 |
+
"Clg_P4": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_4"),
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
hot_variables = {
|
| 72 |
+
"outdoor_temp": ("Site Outdoor Air DryBulb Temperature", "Environment"),
|
| 73 |
+
"core_temp": ("Zone Air Temperature", "Core_ZN"),
|
| 74 |
+
"perim1_temp": ("Zone Air Temperature", "Perimeter_ZN_1"),
|
| 75 |
+
"perim2_temp": ("Zone Air Temperature", "Perimeter_ZN_2"),
|
| 76 |
+
"perim3_temp": ("Zone Air Temperature", "Perimeter_ZN_3"),
|
| 77 |
+
"perim4_temp": ("Zone Air Temperature", "Perimeter_ZN_4"),
|
| 78 |
+
"elec_power": ("Facility Total HVAC Electricity Demand Rate", "Whole Building"),
|
| 79 |
+
"core_occ_count": ("Zone People Occupant Count", "CORE_ZN"),
|
| 80 |
+
"perim1_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_1"),
|
| 81 |
+
"perim2_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_2"),
|
| 82 |
+
"perim3_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_3"),
|
| 83 |
+
"perim4_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_4"),
|
| 84 |
+
"outdoor_dewpoint": ("Site Outdoor Air Dewpoint Temperature", "Environment"),
|
| 85 |
+
"outdoor_wetbulb": ("Site Outdoor Air Wetbulb Temperature", "Environment"),
|
| 86 |
+
"core_rh": ("Zone Air Relative Humidity", "CORE_ZN"),
|
| 87 |
+
"perim1_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_1"),
|
| 88 |
+
"perim2_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_2"),
|
| 89 |
+
"perim3_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_3"),
|
| 90 |
+
"perim4_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_4"),
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
class BaselineReward:
|
| 94 |
+
|
| 95 |
+
def __init__(self, *args, **kwargs):
|
| 96 |
+
pass
|
| 97 |
+
def __call__(self, obs_dict):
|
| 98 |
+
return 0.0, {}
|
| 99 |
+
# ==========================================
|
| 100 |
+
# 5. RBC CONTROLLER (CONSTANT SETPOINTS)
|
| 101 |
+
# ==========================================
|
| 102 |
+
def get_constant_rbc():
|
| 103 |
+
h_sp, c_sp = HEATING_SP, COOLING_SP
|
| 104 |
+
action = np.array([h_sp, c_sp] * 5, dtype=np.float32)
|
| 105 |
+
return action, h_sp, c_sp
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def run_baseline_for_location(location, building_path, weather_path):
|
| 110 |
+
print("\n" + "=" * 80)
|
| 111 |
+
print(f"Running baseline for location: {location}")
|
| 112 |
+
print(f" Building: {building_path}")
|
| 113 |
+
print(f" Weather: {weather_path}")
|
| 114 |
+
print("=" * 80)
|
| 115 |
+
|
| 116 |
+
out_dir = os.path.join(output_root, location)
|
| 117 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 118 |
+
def policy_fn(obs, info, step):
|
| 119 |
+
action, _, _ = get_constant_rbc()
|
| 120 |
+
return action
|
| 121 |
+
df = run_rollout_to_df(
|
| 122 |
+
building_path=str(building_path),
|
| 123 |
+
weather_path=str(weather_path),
|
| 124 |
+
variables=hot_variables,
|
| 125 |
+
actuators=hot_actuators,
|
| 126 |
+
policy_fn=policy_fn,
|
| 127 |
+
location=location,
|
| 128 |
+
timestep_hours=TIME_STEP_HOURS,
|
| 129 |
+
heating_sp=HEATING_SP,
|
| 130 |
+
cooling_sp=COOLING_SP,
|
| 131 |
+
reward=BaselineReward,
|
| 132 |
+
max_steps=None,
|
| 133 |
+
verbose=True,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
print("setpoint_htg min/max:", df["setpoint_htg"].min(), df["setpoint_htg"].max())
|
| 137 |
+
print("setpoint_clg min/max:", df["setpoint_clg"].min(), df["setpoint_clg"].max())
|
| 138 |
+
print("comfort_violation min/mean/max:", df["comfort_violation_degCh"].min(),
|
| 139 |
+
df["comfort_violation_degCh"].mean(), df["comfort_violation_degCh"].max())
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
df["setpoint_htg"] = HEATING_SP
|
| 143 |
+
df["setpoint_clg"] = COOLING_SP
|
| 144 |
+
|
| 145 |
+
# 7) Print the same tables
|
| 146 |
+
print_monthly_tables_extra(df, location)
|
| 147 |
+
print_monthly_tables_split(df, location, time_step_hours=TIME_STEP_HOURS)
|
| 148 |
+
|
| 149 |
+
# Save raw timeseries for inspection
|
| 150 |
+
df.to_csv(os.path.join(out_dir, "baseline_timeseries.csv"), index=False)
|
| 151 |
+
save_dt_training_data(df, out_dir, location=location)
|
| 152 |
+
|
| 153 |
+
if "month" in df.columns:
|
| 154 |
+
monthly_energy = df.groupby("month")
|
| 155 |
+
return df, monthly_energy
|
| 156 |
+
|
| 157 |
+
return df, None
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
bpath, wpath = find_building_and_weather_from_manifest(
|
| 163 |
+
manifest_path,
|
| 164 |
+
location=TARGET_LOCATION,
|
| 165 |
+
occupancy=TARGET_OCCUPANCY,
|
| 166 |
+
thermal=TARGET_THERMAL,
|
| 167 |
+
require_patched=True,
|
| 168 |
+
)
|
| 169 |
+
run_baseline_for_location(TARGET_LOCATION, str(bpath), str(wpath))
|
data_generator/trajectory_generator.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import time
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
import hashlib
|
| 7 |
+
import traceback
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Dict, Any, List, Tuple, Optional
|
| 10 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from contextlib import contextmanager
|
| 14 |
+
import sys
|
| 15 |
+
|
| 16 |
+
@contextmanager
|
| 17 |
+
def suppress_output(enabled: bool = True):
|
| 18 |
+
if not enabled:
|
| 19 |
+
yield
|
| 20 |
+
return
|
| 21 |
+
with open(os.devnull, "w") as devnull:
|
| 22 |
+
old_out, old_err = sys.stdout, sys.stderr
|
| 23 |
+
sys.stdout, sys.stderr = devnull, devnull
|
| 24 |
+
try:
|
| 25 |
+
yield
|
| 26 |
+
finally:
|
| 27 |
+
sys.stdout, sys.stderr = old_out, old_err
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
import gymnasium as gym
|
| 31 |
+
import sinergym
|
| 32 |
+
from unihvac.find_files import (
|
| 33 |
+
detect_paths,
|
| 34 |
+
find_manifest,
|
| 35 |
+
load_manifest_records,
|
| 36 |
+
get_paths_from_manifest_record,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
from unihvac.rollout import run_rollout_to_df
|
| 40 |
+
from unihvac.rewards import RewardConfig, compute_rewards_vectorized, compute_terminals, config_to_meta
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# ======================================================================================
|
| 45 |
+
# USER CONFIG
|
| 46 |
+
# ======================================================================================
|
| 47 |
+
BUILDING = "OfficeSmall"
|
| 48 |
+
PREFER_PATCHED = True
|
| 49 |
+
OUTPUTS_DIRNAME = "traj_results"
|
| 50 |
+
SAVE_DIRNAME = "TrajectoryData_officesmall"
|
| 51 |
+
EPISODES_PER_RECORD = 1
|
| 52 |
+
QUIET_WORKERS = False
|
| 53 |
+
BEHAVIORS = [
|
| 54 |
+
"rbc_21_24",
|
| 55 |
+
"random_walk",
|
| 56 |
+
"piecewise",
|
| 57 |
+
"sinusoid",
|
| 58 |
+
"aggressive",
|
| 59 |
+
]
|
| 60 |
+
TIME_STEP_HOURS = 900.0 / 3600.0 # 0.25
|
| 61 |
+
HTG_MIN, HTG_MAX = 18.0, 24.0
|
| 62 |
+
CLG_MIN, CLG_MAX = 22.0, 30.0
|
| 63 |
+
DEADBAND_MIN = 1.0
|
| 64 |
+
MAX_STEPS = None
|
| 65 |
+
VERBOSE_ROLLOUT = True
|
| 66 |
+
NUM_WORKERS = 16
|
| 67 |
+
BASE_SEED = 123
|
| 68 |
+
RESUME = True
|
| 69 |
+
REWARD_CFG = RewardConfig(version="v1_energy_only", w_energy=1.0, w_comfort=0.0)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ======================================================================================
|
| 74 |
+
# VARIABLES / ACTUATORS (copy from your baseline runner)
|
| 75 |
+
# ======================================================================================
|
| 76 |
+
hot_actuators = {
|
| 77 |
+
"Htg_Core": ("Zone Temperature Control", "Heating Setpoint", "CORE_ZN"),
|
| 78 |
+
"Clg_Core": ("Zone Temperature Control", "Cooling Setpoint", "CORE_ZN"),
|
| 79 |
+
"Htg_P1": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_1"),
|
| 80 |
+
"Clg_P1": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_1"),
|
| 81 |
+
"Htg_P2": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_2"),
|
| 82 |
+
"Clg_P2": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_2"),
|
| 83 |
+
"Htg_P3": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_3"),
|
| 84 |
+
"Clg_P3": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_3"),
|
| 85 |
+
"Htg_P4": ("Zone Temperature Control", "Heating Setpoint", "PERIMETER_ZN_4"),
|
| 86 |
+
"Clg_P4": ("Zone Temperature Control", "Cooling Setpoint", "PERIMETER_ZN_4"),
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
hot_variables = {
|
| 90 |
+
"outdoor_temp": ("Site Outdoor Air DryBulb Temperature", "Environment"),
|
| 91 |
+
"core_temp": ("Zone Air Temperature", "Core_ZN"),
|
| 92 |
+
"perim1_temp": ("Zone Air Temperature", "Perimeter_ZN_1"),
|
| 93 |
+
"perim2_temp": ("Zone Air Temperature", "Perimeter_ZN_2"),
|
| 94 |
+
"perim3_temp": ("Zone Air Temperature", "Perimeter_ZN_3"),
|
| 95 |
+
"perim4_temp": ("Zone Air Temperature", "Perimeter_ZN_4"),
|
| 96 |
+
"elec_power": ("Facility Total HVAC Electricity Demand Rate", "Whole Building"),
|
| 97 |
+
|
| 98 |
+
"core_occ_count": ("Zone People Occupant Count", "CORE_ZN"),
|
| 99 |
+
"perim1_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_1"),
|
| 100 |
+
"perim2_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_2"),
|
| 101 |
+
"perim3_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_3"),
|
| 102 |
+
"perim4_occ_count": ("Zone People Occupant Count", "PERIMETER_ZN_4"),
|
| 103 |
+
|
| 104 |
+
"outdoor_dewpoint": ("Site Outdoor Air Dewpoint Temperature", "Environment"),
|
| 105 |
+
"outdoor_wetbulb": ("Site Outdoor Air Wetbulb Temperature", "Environment"),
|
| 106 |
+
|
| 107 |
+
"core_rh": ("Zone Air Relative Humidity", "CORE_ZN"),
|
| 108 |
+
"perim1_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_1"),
|
| 109 |
+
"perim2_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_2"),
|
| 110 |
+
"perim3_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_3"),
|
| 111 |
+
"perim4_rh": ("Zone Air Relative Humidity", "PERIMETER_ZN_4"),
|
| 112 |
+
|
| 113 |
+
"core_ash55_notcomfortable_summer": (
|
| 114 |
+
"Zone Thermal Comfort ASHRAE 55 Simple Model Summer Clothes Not Comfortable Time",
|
| 115 |
+
"CORE_ZN",
|
| 116 |
+
),
|
| 117 |
+
"core_ash55_notcomfortable_winter": (
|
| 118 |
+
"Zone Thermal Comfort ASHRAE 55 Simple Model Winter Clothes Not Comfortable Time",
|
| 119 |
+
"CORE_ZN",
|
| 120 |
+
),
|
| 121 |
+
"core_ash55_notcomfortable_any": (
|
| 122 |
+
"Zone Thermal Comfort ASHRAE 55 Simple Model Summer or Winter Clothes Not Comfortable Time",
|
| 123 |
+
"CORE_ZN",
|
| 124 |
+
),
|
| 125 |
+
"p1_ash55_notcomfortable_any": (
|
| 126 |
+
"Zone Thermal Comfort ASHRAE 55 Simple Model Summer or Winter Clothes Not Comfortable Time",
|
| 127 |
+
"PERIMETER_ZN_1",
|
| 128 |
+
),
|
| 129 |
+
"p2_ash55_notcomfortable_any": (
|
| 130 |
+
"Zone Thermal Comfort ASHRAE 55 Simple Model Summer or Winter Clothes Not Comfortable Time",
|
| 131 |
+
"PERIMETER_ZN_2",
|
| 132 |
+
),
|
| 133 |
+
"p3_ash55_notcomfortable_any": (
|
| 134 |
+
"Zone Thermal Comfort ASHRAE 55 Simple Model Summer or Winter Clothes Not Comfortable Time",
|
| 135 |
+
"PERIMETER_ZN_3",
|
| 136 |
+
),
|
| 137 |
+
"p4_ash55_notcomfortable_any": (
|
| 138 |
+
"Zone Thermal Comfort ASHRAE 55 Simple Model Summer or Winter Clothes Not Comfortable Time",
|
| 139 |
+
"PERIMETER_ZN_4",
|
| 140 |
+
),
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
def stable_hash_int(s: str, mod: int = 1000) -> int:
|
| 144 |
+
h = hashlib.md5(s.encode("utf-8")).hexdigest()
|
| 145 |
+
return int(h[:8], 16) % mod
|
| 146 |
+
|
| 147 |
+
def record_id(rec: Dict[str, Any]) -> str:
|
| 148 |
+
loc = rec.get("location", "UNKNOWN")
|
| 149 |
+
vname = rec.get("variation_name", "UNKNOWN")
|
| 150 |
+
btype = rec.get("building_type", BUILDING)
|
| 151 |
+
raw = f"{btype}__{loc}__{vname}"
|
| 152 |
+
safe = "".join(c if c.isalnum() or c in "._-=" else "_" for c in raw)
|
| 153 |
+
return safe
|
| 154 |
+
|
| 155 |
+
def _enforce_bounds(htg: float, clg: float) -> Tuple[float, float]:
|
| 156 |
+
h = float(np.clip(htg, HTG_MIN, HTG_MAX))
|
| 157 |
+
c = float(np.clip(clg, CLG_MIN, CLG_MAX))
|
| 158 |
+
if c < h + DEADBAND_MIN:
|
| 159 |
+
c = min(CLG_MAX, h + DEADBAND_MIN)
|
| 160 |
+
return h, c
|
| 161 |
+
|
| 162 |
+
def action_from_setpoints(htg: float, clg: float) -> np.ndarray:
|
| 163 |
+
h, c = _enforce_bounds(htg, clg)
|
| 164 |
+
return np.array([h, c] * 5, dtype=np.float32)
|
| 165 |
+
|
| 166 |
+
@dataclass
|
| 167 |
+
class PolicyRecorder:
|
| 168 |
+
behavior: str
|
| 169 |
+
rng: np.random.Generator
|
| 170 |
+
timestep_hours: float
|
| 171 |
+
last_htg: float = 21.0
|
| 172 |
+
last_clg: float = 24.0
|
| 173 |
+
piece_until: int = 0
|
| 174 |
+
piece_htg: float = 21.0
|
| 175 |
+
piece_clg: float = 24.0
|
| 176 |
+
|
| 177 |
+
def __post_init__(self):
|
| 178 |
+
self.actions: List[np.ndarray] = []
|
| 179 |
+
|
| 180 |
+
def policy(self, obs: Any, info: Dict[str, Any], step: int) -> np.ndarray:
|
| 181 |
+
b = self.behavior
|
| 182 |
+
if b == "rbc_21_24":
|
| 183 |
+
htg, clg = 21.0, 24.0
|
| 184 |
+
elif b == "random_walk":
|
| 185 |
+
if step == 0:
|
| 186 |
+
self.last_htg, self.last_clg = 21.0, 24.0
|
| 187 |
+
dh = self.rng.normal(0.0, 0.15)
|
| 188 |
+
dc = self.rng.normal(0.0, 0.20)
|
| 189 |
+
if (step % int(6 / self.timestep_hours)) == 0:
|
| 190 |
+
dh += self.rng.normal(0.0, 0.6)
|
| 191 |
+
dc += self.rng.normal(0.0, 0.8)
|
| 192 |
+
htg = self.last_htg + dh
|
| 193 |
+
clg = self.last_clg + dc
|
| 194 |
+
htg, clg = _enforce_bounds(htg, clg)
|
| 195 |
+
self.last_htg, self.last_clg = htg, clg
|
| 196 |
+
elif b == "piecewise":
|
| 197 |
+
if step >= self.piece_until:
|
| 198 |
+
hours = float(self.rng.choice([2, 3, 4, 6, 8, 12]))
|
| 199 |
+
dur_steps = max(1, int(round(hours / self.timestep_hours)))
|
| 200 |
+
self.piece_until = step + dur_steps
|
| 201 |
+
htg = float(self.rng.uniform(HTG_MIN, HTG_MAX))
|
| 202 |
+
clg = float(self.rng.uniform(max(CLG_MIN, htg + DEADBAND_MIN), CLG_MAX))
|
| 203 |
+
self.piece_htg, self.piece_clg = _enforce_bounds(htg, clg)
|
| 204 |
+
htg, clg = self.piece_htg, self.piece_clg
|
| 205 |
+
elif b == "sinusoid":
|
| 206 |
+
t_hours = step * self.timestep_hours
|
| 207 |
+
phase = 2.0 * math.pi * (t_hours / 24.0)
|
| 208 |
+
htg = 21.0 + 1.0 * math.sin(phase - 0.5) + self.rng.normal(0.0, 0.10)
|
| 209 |
+
clg = 24.5 + 1.5 * math.sin(phase) + self.rng.normal(0.0, 0.12)
|
| 210 |
+
htg, clg = _enforce_bounds(htg, clg)
|
| 211 |
+
elif b == "aggressive":
|
| 212 |
+
block = int((step * self.timestep_hours) // 6) % 2
|
| 213 |
+
if block == 0:
|
| 214 |
+
htg = float(self.rng.uniform(21.0, 23.5))
|
| 215 |
+
clg = float(self.rng.uniform(23.5, 25.5))
|
| 216 |
+
else:
|
| 217 |
+
htg = float(self.rng.uniform(HTG_MIN, 20.5))
|
| 218 |
+
clg = float(self.rng.uniform(26.0, CLG_MAX))
|
| 219 |
+
htg, clg = _enforce_bounds(htg, clg)
|
| 220 |
+
else:
|
| 221 |
+
htg, clg = 21.0, 24.0
|
| 222 |
+
a = action_from_setpoints(htg, clg)
|
| 223 |
+
self.actions.append(a)
|
| 224 |
+
return a
|
| 225 |
+
|
| 226 |
+
def select_state_columns(df: pd.DataFrame) -> List[str]:
|
| 227 |
+
base = list(hot_variables.keys())
|
| 228 |
+
time_candidates = [
|
| 229 |
+
"month", "day", "hour",
|
| 230 |
+
"day_of_week", "is_weekend",
|
| 231 |
+
"minute", "time", "timestep",
|
| 232 |
+
]
|
| 233 |
+
cols = []
|
| 234 |
+
for c in base + time_candidates:
|
| 235 |
+
if c in df.columns:
|
| 236 |
+
cols.append(c)
|
| 237 |
+
if not cols:
|
| 238 |
+
bad = set(["done", "terminated", "truncated"])
|
| 239 |
+
cols = [c for c in df.columns if c not in bad and pd.api.types.is_numeric_dtype(df[c])]
|
| 240 |
+
return cols
|
| 241 |
+
|
| 242 |
+
def build_npz_payload(
|
| 243 |
+
df: pd.DataFrame,
|
| 244 |
+
actions: np.ndarray,
|
| 245 |
+
meta: Dict[str, Any],
|
| 246 |
+
) -> Dict[str, Any]:
|
| 247 |
+
state_cols = select_state_columns(df)
|
| 248 |
+
obs = df[state_cols].to_numpy(dtype=np.float32)
|
| 249 |
+
rewards = compute_rewards_vectorized(df, timestep_hours=TIME_STEP_HOURS, cfg=REWARD_CFG)
|
| 250 |
+
terminals = compute_terminals(df)
|
| 251 |
+
meta = dict(meta)
|
| 252 |
+
meta["reward_cfg"] = config_to_meta(REWARD_CFG)
|
| 253 |
+
action_keys = [
|
| 254 |
+
"htg_core", "clg_core",
|
| 255 |
+
"htg_p1", "clg_p1",
|
| 256 |
+
"htg_p2", "clg_p2",
|
| 257 |
+
"htg_p3", "clg_p3",
|
| 258 |
+
"htg_p4", "clg_p4",
|
| 259 |
+
]
|
| 260 |
+
payload = {
|
| 261 |
+
"observations": obs,
|
| 262 |
+
"actions": actions.astype(np.float32),
|
| 263 |
+
"rewards": rewards,
|
| 264 |
+
"terminals": terminals,
|
| 265 |
+
"state_keys": np.array(state_cols, dtype=object),
|
| 266 |
+
"action_keys": np.array(action_keys, dtype=object),
|
| 267 |
+
"meta": np.array([json.dumps(meta)], dtype=object),
|
| 268 |
+
}
|
| 269 |
+
return payload
|
| 270 |
+
|
| 271 |
+
def save_npz(path: str, payload: Dict[str, Any]) -> None:
|
| 272 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 273 |
+
np.savez_compressed(path, **payload)
|
| 274 |
+
|
| 275 |
+
def run_one_episode(
|
| 276 |
+
rec: Dict[str, Any],
|
| 277 |
+
behavior: str,
|
| 278 |
+
episode_idx: int,
|
| 279 |
+
outputs_root: str,
|
| 280 |
+
save_root: str,
|
| 281 |
+
seed: int,
|
| 282 |
+
) -> Optional[str]:
|
| 283 |
+
rid = record_id(rec)
|
| 284 |
+
bpath, wpath = get_paths_from_manifest_record(rec)
|
| 285 |
+
out_dir = os.path.join(outputs_root, OUTPUTS_DIRNAME, rid, behavior, f"ep{episode_idx:03d}")
|
| 286 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 287 |
+
traj_dir = os.path.join(save_root, rid, behavior)
|
| 288 |
+
traj_path = os.path.join(traj_dir, f"traj_ep{episode_idx:03d}_seed{seed}.npz")
|
| 289 |
+
if RESUME and os.path.exists(traj_path):
|
| 290 |
+
return traj_path
|
| 291 |
+
rng = np.random.default_rng(seed)
|
| 292 |
+
recorder = PolicyRecorder(behavior=behavior, rng=rng, timestep_hours=TIME_STEP_HOURS)
|
| 293 |
+
with suppress_output(QUIET_WORKERS):
|
| 294 |
+
df = run_rollout_to_df(
|
| 295 |
+
building_path=str(bpath),
|
| 296 |
+
weather_path=str(wpath),
|
| 297 |
+
variables=hot_variables,
|
| 298 |
+
actuators=hot_actuators,
|
| 299 |
+
policy_fn=recorder.policy,
|
| 300 |
+
location=str(rec.get("location", rec.get("climate", "UNKNOWN"))),
|
| 301 |
+
timestep_hours=TIME_STEP_HOURS,
|
| 302 |
+
heating_sp=21.0,
|
| 303 |
+
cooling_sp=24.0,
|
| 304 |
+
reward=None,
|
| 305 |
+
max_steps=MAX_STEPS,
|
| 306 |
+
verbose=VERBOSE_ROLLOUT,
|
| 307 |
+
)
|
| 308 |
+
actions = np.stack(recorder.actions, axis=0) if recorder.actions else np.zeros((len(df), 10), dtype=np.float32)
|
| 309 |
+
T = len(df)
|
| 310 |
+
if actions.shape[0] > T:
|
| 311 |
+
actions = actions[:T]
|
| 312 |
+
elif actions.shape[0] < T:
|
| 313 |
+
pad = np.repeat(actions[-1][None, :], T - actions.shape[0], axis=0) if actions.shape[0] > 0 else np.zeros((T, 10), dtype=np.float32)
|
| 314 |
+
actions = np.concatenate([actions, pad], axis=0)
|
| 315 |
+
if len(df) == actions.shape[0] and len(df) > 0:
|
| 316 |
+
df["setpoint_htg"] = actions[:, 0]
|
| 317 |
+
df["setpoint_clg"] = actions[:, 1]
|
| 318 |
+
meta = {
|
| 319 |
+
"record_id": rid,
|
| 320 |
+
"behavior": behavior,
|
| 321 |
+
"episode_idx": episode_idx,
|
| 322 |
+
"seed": seed,
|
| 323 |
+
"building_path": str(bpath),
|
| 324 |
+
"weather_path": str(wpath),
|
| 325 |
+
"location": rec.get("location", rec.get("climate")),
|
| 326 |
+
"thermal": rec.get("thermal", rec.get("thermal_variation")),
|
| 327 |
+
"occupancy": rec.get("occupancy", rec.get("occupancy_variation")),
|
| 328 |
+
"timestep_hours": TIME_STEP_HOURS,
|
| 329 |
+
"state_cols": select_state_columns(df),
|
| 330 |
+
}
|
| 331 |
+
payload = build_npz_payload(df=df, actions=actions, meta=meta)
|
| 332 |
+
save_npz(traj_path, payload)
|
| 333 |
+
df.to_csv(os.path.join(traj_dir, f"timeseries_ep{episode_idx:03d}_seed{seed}.csv"), index=False)
|
| 334 |
+
return traj_path
|
| 335 |
+
|
| 336 |
+
def main():
|
| 337 |
+
paths = detect_paths(outputs_dirname=OUTPUTS_DIRNAME)
|
| 338 |
+
manifest_path = find_manifest(paths, building=BUILDING, prefer_patched=PREFER_PATCHED)
|
| 339 |
+
records = load_manifest_records(manifest_path)
|
| 340 |
+
outputs_root = str(paths.outputs_root)
|
| 341 |
+
save_root = os.path.join(outputs_root, SAVE_DIRNAME)
|
| 342 |
+
os.makedirs(save_root, exist_ok=True)
|
| 343 |
+
tasks = []
|
| 344 |
+
task_id = 0
|
| 345 |
+
for rec_idx, rec in enumerate(records):
|
| 346 |
+
for behavior in BEHAVIORS:
|
| 347 |
+
for ep in range(EPISODES_PER_RECORD):
|
| 348 |
+
seed = BASE_SEED + (rec_idx * 100000) + (stable_hash_int(behavior, 100000)) + ep
|
| 349 |
+
tasks.append((task_id, rec, behavior, ep, seed))
|
| 350 |
+
task_id += 1
|
| 351 |
+
t0 = time.time()
|
| 352 |
+
successes = 0
|
| 353 |
+
failures = 0
|
| 354 |
+
saved_paths: List[str] = []
|
| 355 |
+
if NUM_WORKERS <= 1:
|
| 356 |
+
for tid, rec, behavior, ep, seed in tasks:
|
| 357 |
+
try:
|
| 358 |
+
p = run_one_episode(
|
| 359 |
+
rec=rec,
|
| 360 |
+
behavior=behavior,
|
| 361 |
+
episode_idx=ep,
|
| 362 |
+
outputs_root=outputs_root,
|
| 363 |
+
save_root=save_root,
|
| 364 |
+
seed=seed,
|
| 365 |
+
)
|
| 366 |
+
if p:
|
| 367 |
+
saved_paths.append(p)
|
| 368 |
+
successes += 1
|
| 369 |
+
if successes % 10 == 0:
|
| 370 |
+
elapsed = time.time() - t0
|
| 371 |
+
done = successes + failures
|
| 372 |
+
rate = done / elapsed if elapsed > 0 else 0.0
|
| 373 |
+
except Exception as e:
|
| 374 |
+
failures += 1
|
| 375 |
+
rid = record_id(rec)
|
| 376 |
+
print(f"[ERROR] tid={tid} record={rid} behavior={behavior} ep={ep}: {e}")
|
| 377 |
+
print(traceback.format_exc())
|
| 378 |
+
else:
|
| 379 |
+
with ProcessPoolExecutor(max_workers=NUM_WORKERS) as ex:
|
| 380 |
+
futs = []
|
| 381 |
+
for tid, rec, behavior, ep, seed in tasks:
|
| 382 |
+
futs.append(ex.submit(
|
| 383 |
+
run_one_episode,
|
| 384 |
+
rec, behavior, ep, outputs_root, save_root, seed
|
| 385 |
+
))
|
| 386 |
+
for i, fut in enumerate(as_completed(futs), 1):
|
| 387 |
+
try:
|
| 388 |
+
p = fut.result()
|
| 389 |
+
if p:
|
| 390 |
+
saved_paths.append(p)
|
| 391 |
+
successes += 1
|
| 392 |
+
except Exception as e:
|
| 393 |
+
failures += 1
|
| 394 |
+
print(f"[ERROR] future failed: {e}")
|
| 395 |
+
if i % 25 == 0 or i == len(futs):
|
| 396 |
+
elapsed = time.time() - t0
|
| 397 |
+
rate = i / elapsed if elapsed > 0 else 0.0
|
| 398 |
+
print(f"[progress] done={i}/{len(futs)} success={successes} fail={failures} rate={rate:.2f} eps/s elapsed={elapsed:.1f}s")
|
| 399 |
+
print("\nDONE")
|
| 400 |
+
if saved_paths:
|
| 401 |
+
print("Example saved file:", saved_paths[0])
|
| 402 |
+
print("Save root:", save_root)
|
| 403 |
+
|
| 404 |
+
if __name__ == "__main__":
|
| 405 |
+
main()
|