|
import os
|
|
import random
|
|
import numpy as np
|
|
import pandas as pd
|
|
import gymnasium as gym
|
|
from gymnasium.spaces import Box
|
|
from scipy.interpolate import interp1d
|
|
from dataclasses import dataclass, field
|
|
|
|
def load_drive_cycle(path_or_dir):
|
|
"""Load a drive cycle from a CSV file or a directory containing CSV files.
|
|
|
|
Args:
|
|
path_or_dir (str): Path to a CSV file or a directory containing CSVs.
|
|
|
|
Returns:
|
|
dict: Dictionary with 'Time' and 'Speed' in SI units (seconds, m/s).
|
|
|
|
Raises:
|
|
ValueError: If no CSV file is found or required columns are missing.
|
|
"""
|
|
if os.path.isfile(path_or_dir) and path_or_dir.endswith('.csv'):
|
|
csv_path = path_or_dir
|
|
elif os.path.isdir(path_or_dir):
|
|
|
|
csv_files = []
|
|
for root, _, files in os.walk(path_or_dir):
|
|
for f in files:
|
|
if f.endswith('.csv'):
|
|
csv_files.append(os.path.join(root, f))
|
|
if not csv_files:
|
|
raise ValueError(f"No CSV file found in directory: {path_or_dir}")
|
|
csv_path = random.choice(csv_files)
|
|
print(f"Randomly selected CSV drive cycle: {csv_path}")
|
|
else:
|
|
raise ValueError(f"Invalid path: {path_or_dir}")
|
|
|
|
df = pd.read_csv(csv_path)
|
|
|
|
if 'Time' not in df.columns or 'Speed' not in df.columns:
|
|
raise ValueError("CSV must contain 'Time' and 'Speed' columns")
|
|
|
|
|
|
time = df['Time'].to_numpy()
|
|
time = time - time[0]
|
|
|
|
return {
|
|
'Time': time,
|
|
'Speed': df['Speed'].to_numpy() / 3.6
|
|
}
|
|
|
|
|
|
def fcev_ext(u, w, veh, fd, fc, batt):
|
|
"""
|
|
External dynamic model for a fuel cell electric vehicle (FCEV) primarily powered by a fuel cell.
|
|
Supports the main cooling loop with a three-way valve split control structure.
|
|
|
|
Inputs:
|
|
u[0]: Fuel cell output ratio (range: 0 to 1)
|
|
u[1]: Total cooling level (normalized, range: 0.2 to 1.0)
|
|
u[2]: Split ratio to the fuel cell system (FCS) (range: 0 to 1)
|
|
w[0]: Vehicle speed (m/s)
|
|
w[1]: Vehicle acceleration (m/s²)
|
|
|
|
Returns:
|
|
intVar: List of intermediate variables
|
|
unfeas: Infeasibility flag
|
|
"""
|
|
|
|
|
|
v = w[0]
|
|
a = w[1]
|
|
fc_ratio = u[0]
|
|
cooling_level = u[1]
|
|
split_ratio = u[2]
|
|
|
|
|
|
wheel_spd = v / veh.wh_radius
|
|
wheel_acc = a / veh.wh_radius
|
|
|
|
rolling = veh.mass * veh.gravity * (veh.first_rrc + veh.second_rrc * v)
|
|
aero = veh.aero_coeff * v ** 2
|
|
inertia = veh.mass * a
|
|
veh_force = rolling + aero + inertia
|
|
|
|
wheel_trq = veh_force * veh.wh_radius + veh.axle_loss * (wheel_spd != 0)
|
|
|
|
|
|
fd_spd = fd.spdRatio * wheel_spd
|
|
fd_trq = wheel_trq / fd.spdRatio + fd.loss * np.sign(wheel_trq)
|
|
|
|
|
|
shaft_spd = fd_spd
|
|
shaft_trq = fd_trq
|
|
mot_pwr = shaft_spd * shaft_trq
|
|
|
|
|
|
fc_ratio = np.clip(fc_ratio, 0, 1)
|
|
fc_pwr = fc_ratio * fc.maxPwr
|
|
batt_pwr = mot_pwr - fc_pwr
|
|
|
|
|
|
fc_eff = fc.effMap(fc_pwr)
|
|
fc_eff = np.maximum(fc_eff, np.finfo(float).eps)
|
|
h2_rate = fc.h2Map(fc_pwr)
|
|
|
|
|
|
|
|
fc.maxCoolFlow = 0.2
|
|
m_dot_total = cooling_level * fc.maxCoolFlow
|
|
|
|
m_dot_fc = split_ratio * m_dot_total
|
|
m_dot_batt = (1 - split_ratio) * m_dot_total
|
|
|
|
|
|
fc_unfeas = (fc_pwr > fc.maxPwr) | (fc_pwr < fc.minPwr)
|
|
batt_unfeas = (batt_pwr > batt.maxPwr) | (batt_pwr < batt.minPwr)
|
|
unfeas = fc_unfeas | batt_unfeas
|
|
|
|
|
|
intVar = [
|
|
batt_pwr,
|
|
fc_pwr,
|
|
h2_rate,
|
|
np.ones_like(fc_pwr) * shaft_spd,
|
|
m_dot_fc,
|
|
m_dot_batt
|
|
]
|
|
|
|
return intVar, unfeas
|
|
|
|
|
|
def fcev_int(x, w, u, intVar, batt, fc):
|
|
"""
|
|
Internal state update function for a fuel cell electric vehicle (FCEV),
|
|
including thermal and electrical models for both battery and fuel cell.
|
|
|
|
Args:
|
|
x (list[float]): Current state variables:
|
|
x[0]: State of Charge (SOC)
|
|
x[1]: Fuel cell temperature (T_fc)
|
|
x[2]: Battery core temperature (T_core)
|
|
x[3]: Battery surface temperature (T_surf)
|
|
w (Union[list, dict]): External inputs (e.g., vehicle speed/acc) and previous controls if available.
|
|
u (list[float]): Control inputs:
|
|
u[0]: Fuel cell output ratio (0 to 1)
|
|
u[1]: Normalized total cooling level (0.2 to 1.0)
|
|
u[2]: Coolant split ratio to fuel cell (0 to 1)
|
|
intVar (list[float]): Intermediate variables:
|
|
intVar[0]: Battery power
|
|
intVar[1]: Fuel cell power
|
|
intVar[2]: Hydrogen consumption rate
|
|
intVar[4]: Coolant flow rate through fuel cell
|
|
intVar[5]: Coolant flow rate through battery
|
|
batt: Battery model object (with methods like `ocv()`, `chrgRes()`, `dischrgRes()`, etc.)
|
|
fc: Fuel cell model object (with methods like `effMap()` and `heatCap`)
|
|
|
|
Returns:
|
|
tuple:
|
|
x_new (list[float]): Updated state vector [SOC, T_fc, T_core, T_surf]
|
|
stageCost (float): Calculated cost including hydrogen consumption and penalties
|
|
unfeas (bool): Feasibility flag (True if thermal or electrical limits exceeded)
|
|
H2_rate (float): Hydrogen consumption rate
|
|
dT_core (float): Battery core temperature change rate
|
|
dT_fc (float): Fuel cell temperature change rate
|
|
"""
|
|
|
|
SOC = x[0]
|
|
T_fc = x[1]
|
|
T_core = x[2]
|
|
T_surf = x[3]
|
|
|
|
|
|
battPwr = intVar[0]
|
|
fcPwr = intVar[1]
|
|
H2_rate = intVar[2]
|
|
m_dot_fc = intVar[4]
|
|
m_dot_batt = intVar[5]
|
|
|
|
|
|
dt = 1.0
|
|
T_amb = 20.0
|
|
cp = 4180.0
|
|
|
|
|
|
battPwr_adj = np.where(battPwr > 0, battPwr / 0.95, battPwr * 0.95)
|
|
Rbat = np.where(battPwr > 0, batt.dischrgRes(SOC), batt.chrgRes(SOC))
|
|
Vbat = batt.ocv(SOC)
|
|
|
|
sqrt_term = Vbat ** 2 - 4 * Rbat * battPwr_adj
|
|
sqrt_term = np.maximum(sqrt_term, 0)
|
|
Ibatt = (Vbat - np.sqrt(sqrt_term)) / (2 * Rbat)
|
|
Ibatt = np.real(Ibatt)
|
|
|
|
|
|
SOC_new = SOC - Ibatt / (batt.maxCap * 3600) * dt
|
|
battUnfeas = (Ibatt > batt.maxCurr(SOC)) | (Ibatt < batt.minCurr(SOC))
|
|
|
|
|
|
eta_fc = np.maximum(fc.effMap(fcPwr), np.finfo(float).eps)
|
|
Qgen_fc = (1 - eta_fc) * fcPwr
|
|
Qcool_fc = m_dot_fc * cp * (T_fc - T_amb)
|
|
dT_fc = (Qgen_fc - Qcool_fc) / fc.heatCap
|
|
T_fc_new = T_fc + dt * dT_fc
|
|
|
|
|
|
Qgen_batt = Ibatt ** 2 * Rbat
|
|
Rth_in = 0.2
|
|
Ccore = 3000.0
|
|
Csurf = 2000.0
|
|
Qcool_batt = m_dot_batt * cp * (T_surf - T_amb)
|
|
|
|
dT_core = (Qgen_batt - (T_core - T_surf) / Rth_in) / Ccore
|
|
dT_surf = ((T_core - T_surf) / Rth_in - Qcool_batt) / Csurf
|
|
|
|
T_core_new = T_core + dt * dT_core
|
|
T_surf_new = T_surf + dt * dT_surf
|
|
|
|
|
|
stageCost = H2_rate
|
|
|
|
|
|
m_dot_total = m_dot_fc + m_dot_batt
|
|
stageCost += 1e-3 * m_dot_total ** 2
|
|
|
|
|
|
if isinstance(w, dict) and "u_prev" in w:
|
|
u_prev = w["u_prev"][0]
|
|
fcRatio = u[0]
|
|
delta_u = fcRatio - u_prev
|
|
stageCost += 1e-4 * delta_u ** 2
|
|
|
|
|
|
T_ref_fc = 60.0
|
|
T_th_fc = 80.0
|
|
k_fc = 8.0
|
|
|
|
|
|
T_ref_batt = 35.0
|
|
T_th_batt = 45.0
|
|
k_batt = 6.0
|
|
if T_core >= 100 or T_fc >= 100:
|
|
T_core = np.clip(T_core, 0, 100)
|
|
T_fc = np.clip(T_fc, 0, 100)
|
|
TempUnfeas = True
|
|
else:
|
|
TempUnfeas = False
|
|
|
|
|
|
|
|
|
|
fc_life_penalty = np.where(
|
|
T_fc > T_th_fc,
|
|
1e-2 * np.exp((T_fc - T_ref_fc) / k_fc),
|
|
0.0
|
|
)
|
|
|
|
|
|
batt_life_penalty = np.where(
|
|
T_core > T_th_batt,
|
|
1e-2 * np.exp((T_core - T_ref_batt) / k_batt),
|
|
0.0
|
|
)
|
|
|
|
|
|
stageCost += fc_life_penalty + batt_life_penalty
|
|
|
|
|
|
x_new = [
|
|
SOC_new,
|
|
T_fc_new,
|
|
T_core_new,
|
|
T_surf_new
|
|
]
|
|
|
|
|
|
unfeas = battUnfeas or TempUnfeas
|
|
|
|
if unfeas:
|
|
print(battUnfeas, f" {SOC} || {T_core} || {T_surf} || {T_fc} || f{Ibatt} || f{batt.maxCurr(SOC)} || f{batt.minCurr(SOC)}")
|
|
|
|
return x_new, stageCost, unfeas, H2_rate, dT_core, dT_fc
|
|
|
|
|
|
@dataclass
|
|
class Vehicle:
|
|
mass: float = 1920
|
|
gravity: float = 9.81
|
|
wh_radius: float = 0.32
|
|
first_rrc: float = 0.009
|
|
second_rrc: float = 0.001
|
|
aero_coeff: float = field(init=False)
|
|
axle_loss: float = 100
|
|
|
|
def __post_init__(self):
|
|
Cd = 0.29
|
|
A = 2.3
|
|
rho = 1.225
|
|
self.aero_coeff = 0.5 * Cd * A * rho
|
|
|
|
|
|
@dataclass
|
|
class FinalDrive:
|
|
spdRatio: float = 9.0
|
|
loss: float = 50
|
|
|
|
|
|
@dataclass
|
|
class FuelCell:
|
|
minPwr: float = 0
|
|
maxPwr: float = 114000
|
|
pwrBrk: np.ndarray = field(default_factory=lambda: np.linspace(0, 114000, 20))
|
|
etaBrk: np.ndarray = field(default_factory=lambda: np.array([
|
|
0.0, 0.25, 0.4, 0.48, 0.53, 0.56, 0.59, 0.6,
|
|
0.605, 0.61, 0.6, 0.59, 0.58, 0.57, 0.56, 0.54,
|
|
0.52, 0.5, 0.48, 0.46
|
|
]))
|
|
thermEff: float = 0.4
|
|
coolingCoeff: float = 40
|
|
heatCap: float = 20000
|
|
effMap: callable = field(init=False)
|
|
h2Map: callable = field(init=False)
|
|
|
|
def __post_init__(self):
|
|
eff_interp = interp1d(self.pwrBrk, self.etaBrk, kind='linear', fill_value='extrapolate')
|
|
self.effMap = lambda P: np.minimum(1, np.maximum(eff_interp(P), np.finfo(float).eps))
|
|
|
|
LHV_H2 = 33.3e6
|
|
self.h2Map = lambda P: 1e3 * P / np.maximum(self.effMap(P) * LHV_H2, np.finfo(float).eps)
|
|
|
|
|
|
@dataclass
|
|
class Battery:
|
|
maxCap: float = 10
|
|
minPwr: float = -20000
|
|
maxPwr: float = 25000
|
|
socBrk: np.ndarray = field(default_factory=lambda: np.linspace(0, 1, 11))
|
|
ocvData: np.ndarray = field(init=False)
|
|
chrgResData: np.ndarray = field(init=False)
|
|
dischrgResData: np.ndarray = field(init=False)
|
|
minCurrData: np.ndarray = field(init=False)
|
|
maxCurrData: np.ndarray = field(init=False)
|
|
ocv: callable = field(init=False)
|
|
chrgRes: callable = field(init=False)
|
|
dischrgRes: callable = field(init=False)
|
|
minCurr: callable = field(init=False)
|
|
maxCurr: callable = field(init=False)
|
|
coolingCoeff: float = 10
|
|
heatCap: float = 6000
|
|
|
|
def __post_init__(self):
|
|
self.ocvData = 320 + 20 * self.socBrk
|
|
self.chrgResData = 0.3 - 0.1 * self.socBrk
|
|
self.dischrgResData = 0.2 + 0.05 * (1 - self.socBrk)
|
|
self.minCurrData = -120 + np.zeros_like(self.socBrk)
|
|
self.maxCurrData = 180 + np.zeros_like(self.socBrk)
|
|
|
|
self.ocv = interp1d(self.socBrk, self.ocvData, kind='linear', fill_value='extrapolate')
|
|
self.chrgRes = interp1d(self.socBrk, self.chrgResData, kind='linear', fill_value='extrapolate')
|
|
self.dischrgRes = interp1d(self.socBrk, self.dischrgResData, kind='linear', fill_value='extrapolate')
|
|
self.minCurr = interp1d(self.socBrk, self.minCurrData, kind='linear', fill_value='extrapolate')
|
|
self.maxCurr = interp1d(self.socBrk, self.maxCurrData, kind='linear', fill_value='extrapolate')
|
|
|
|
|
|
def fcev_fcdom_data():
|
|
veh = Vehicle()
|
|
fd = FinalDrive()
|
|
fc = FuelCell()
|
|
batt = Battery()
|
|
return veh, fd, fc, batt
|
|
|
|
def reward_function(stage_cost, speed, beta=0.01, c=10):
|
|
if stage_cost == 0 and speed == 0:
|
|
return 0.0
|
|
return 1 / (1 + np.exp(beta * (stage_cost - c)))
|
|
|
|
class FCEVEnv(gym.Env):
|
|
"""
|
|
Custom OpenAI Gym environment for a fuel cell electric vehicle (FCEV) with
|
|
thermal-electric hybrid modeling. The environment simulates internal vehicle
|
|
dynamics and evaluates control actions based on energy efficiency and constraints.
|
|
|
|
Observations:
|
|
[vehicle_speed, acceleration, SOC, T_fc, T_core, T_surf]
|
|
|
|
Actions:
|
|
[fuel_cell_output_ratio (0~1), cooling_level (0.2~1.0), coolant_split_ratio (0~1)]
|
|
|
|
Reward:
|
|
Based on custom reward function applied to stage cost.
|
|
"""
|
|
def __init__(self, drive_cycle):
|
|
super(FCEVEnv, self).__init__()
|
|
self.dt = 1.0
|
|
|
|
|
|
self.veh, self.fd, self.fc, self.batt = fcev_fcdom_data()
|
|
|
|
|
|
self.speed_profile = np.interp(
|
|
np.arange(0, drive_cycle['Time'][-1] + 1),
|
|
drive_cycle['Time'] - drive_cycle['Time'][0],
|
|
drive_cycle['Speed']
|
|
)
|
|
self.steps = len(self.speed_profile)
|
|
self.step_count = 0
|
|
|
|
|
|
self.observation_space = Box(low=np.array([-np.inf, -np.inf, -np.inf, -np.inf, -np.inf, -np.inf]),
|
|
high=np.array([np.inf, np.inf, np.inf, np.inf, np.inf, np.inf]),
|
|
dtype=np.float32)
|
|
|
|
|
|
self.action_space = Box(low=np.array([0, 0, 0]),
|
|
high=np.array([1.0, 1.0, 1.0]),
|
|
dtype=np.float32)
|
|
|
|
self.reset()
|
|
|
|
def reset(self):
|
|
"""Reset the simulation to initial state."""
|
|
self.state = [0.5, 25, 25, 25]
|
|
self.step_count = 0
|
|
return self._get_obs(), None
|
|
|
|
def _get_obs(self):
|
|
"""Get the current observation including vehicle dynamics and system state."""
|
|
speed = self.speed_profile[self.step_count] if self.step_count < self.steps else self.speed_profile[self.step_count - 1]
|
|
if self.step_count + 1 < self.steps:
|
|
next_speed = self.speed_profile[self.step_count + 1]
|
|
else:
|
|
next_speed = self.speed_profile[self.step_count]
|
|
acc = (next_speed - speed) / self.dt
|
|
return np.array([speed, acc] + self.state, dtype=np.float32)
|
|
|
|
def step(self, action):
|
|
"""
|
|
Apply a control action and update the environment state.
|
|
|
|
Args:
|
|
action (list or ndarray): Action input [fc_ratio, cooling_level, split_ratio]
|
|
|
|
Returns:
|
|
tuple: (observation, reward, done, unfeasible_flag, info_dict)
|
|
"""
|
|
u = [float(a) for a in action]
|
|
speed = self.speed_profile[self.step_count]
|
|
if self.step_count + 1 < self.steps:
|
|
next_speed = self.speed_profile[self.step_count + 1]
|
|
else:
|
|
next_speed = self.speed_profile[self.step_count]
|
|
|
|
acc = (next_speed - speed) / self.dt
|
|
|
|
w = [speed, acc]
|
|
|
|
|
|
intVar, _ = fcev_ext(u, w, self.veh, self.fd, self.fc, self.batt)
|
|
|
|
|
|
x_new, stageCost, unfeas, h2_rate, dT_core, dT_fc = fcev_int(self.state, w, u, intVar, self.batt, self.fc)
|
|
|
|
self.state = x_new
|
|
self.step_count += 1
|
|
done = self.step_count >= self.steps - 1 or unfeas
|
|
|
|
obs = self._get_obs()
|
|
reward = reward_function(stageCost, speed) if not unfeas else -99
|
|
|
|
|
|
return obs, reward, done, unfeas, {"H2_rate": h2_rate * self.dt, "dT_core": dT_core * self.dt, "dT_fc": dT_fc * self.dt}
|
|
|
|
def render(self, mode='human'):
|
|
"""Render the current step's state to console."""
|
|
print(f"Step {self.step_count}, State: {self.state}")
|
|
|
|
def get_logs(self):
|
|
"""Return final state and step count for logging."""
|
|
return {
|
|
"final_state": self.state,
|
|
"step_count": self.step_count
|
|
}
|
|
|
|
|
|
if __name__ == '__main__':
|
|
veh, fd, fc, batt = fcev_fcdom_data()
|
|
|
|
|
|
P_test = np.array([0, 20000, 60000, 110000])
|
|
eff = fc.effMap(P_test)
|
|
h2 = fc.h2Map(P_test)
|
|
|
|
print("H2 Efficiency:", eff)
|
|
print("Hydrogen Consumption (g/s):", h2)
|
|
|