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文件 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") # Ensure time starts at zero time = df['Time'].to_numpy() time = time - time[0] return { 'Time': time, 'Speed': df['Speed'].to_numpy() / 3.6 # Convert km/h to m/s } 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 """ # === Input Processing === v = w[0] # vehicle speed a = w[1] # vehicle acceleration fc_ratio = u[0] # 燃料电池功率输出比例 cooling_level = u[1] # 冷却强度 [0.2, 1.0] split_ratio = u[2] # 三通阀分流比例 α # === Wheel Dynamics === 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) # === Final Drive === fd_spd = fd.spdRatio * wheel_spd fd_trq = wheel_trq / fd.spdRatio + fd.loss * np.sign(wheel_trq) # === Simple Motor Dynamics === shaft_spd = fd_spd shaft_trq = fd_trq mot_pwr = shaft_spd * shaft_trq # === Fuel Cell Ideal Output === fc_ratio = np.clip(fc_ratio, 0, 1) fc_pwr = fc_ratio * fc.maxPwr batt_pwr = mot_pwr - fc_pwr # === Fuel Cell Efficiency & Hydrogen Usage === fc_eff = fc.effMap(fc_pwr) fc_eff = np.maximum(fc_eff, np.finfo(float).eps) h2_rate = fc.h2Map(fc_pwr) # print(f"H2 Rate: {h2_rate}, || Fuel Cell Power: {fc_pwr}") # === Cooling System === fc.maxCoolFlow = 0.2 # 假设的最大冷却流速 kg/s m_dot_total = cooling_level * fc.maxCoolFlow m_dot_fc = split_ratio * m_dot_total m_dot_batt = (1 - split_ratio) * m_dot_total # === Feasibility Check === 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 # === Output Intermediate Variables === intVar = [ batt_pwr, # 1 fc_pwr, # 2 h2_rate, # 3 np.ones_like(fc_pwr) * shaft_spd, # 4 m_dot_fc, # 5 m_dot_batt # 6 ] 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 """ # === Extract state variables === SOC = x[0] T_fc = x[1] T_core = x[2] T_surf = x[3] # === Extract intermediate variables === battPwr = intVar[0] fcPwr = intVar[1] H2_rate = intVar[2] m_dot_fc = intVar[4] m_dot_batt = intVar[5] # === Constants === dt = 1.0 # Time step (s) T_amb = 20.0 # Ambient temperature (°C) cp = 4180.0 # Specific heat capacity of coolant (J/kg°C) # === Battery electrical model === 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 update === SOC_new = SOC - Ibatt / (batt.maxCap * 3600) * dt battUnfeas = (Ibatt > batt.maxCurr(SOC)) | (Ibatt < batt.minCurr(SOC)) # === Fuel Cell Thermal Model === 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 # === Battery thermal model === 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 # === Stage cost calculation === stageCost = H2_rate # Add cooling system power penalty (quadratic) m_dot_total = m_dot_fc + m_dot_batt stageCost += 1e-3 * m_dot_total ** 2 # Add control smoothness penalty (Δu²) if isinstance(w, dict) and "u_prev" in w: u_prev = w["u_prev"][0] # 之前的fcRatio fcRatio = u[0] delta_u = fcRatio - u_prev stageCost += 1e-4 * delta_u ** 2 # === Temperature feasibility check (hard constraint) === T_ref_fc = 60.0 T_th_fc = 80.0 k_fc = 8.0 # --- Battery degradation penalty --- 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) # 或 120 上限 T_fc = np.clip(T_fc, 0, 100) TempUnfeas = True else: TempUnfeas = False # === Lifetime degradation penalties (soft constraint) === # Fuel cell degradation penalty fc_life_penalty = np.where( T_fc > T_th_fc, 1e-2 * np.exp((T_fc - T_ref_fc) / k_fc), 0.0 ) # Battery degradation penalty 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 # === Output new states === x_new = [ SOC_new, T_fc_new, T_core_new, T_surf_new ] # Combine feasibility flags 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 # kg gravity: float = 9.81 wh_radius: float = 0.32 # m 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 # J/kg self.h2Map = lambda P: 1e3 * P / np.maximum(self.effMap(P) * LHV_H2, np.finfo(float).eps) @dataclass class Battery: maxCap: float = 10 # Ah minPwr: float = -20000 # W maxPwr: float = 25000 # W 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 # Load vehicle, powertrain, battery, and fuel cell parameters self.veh, self.fd, self.fc, self.batt = fcev_fcdom_data() # Load and interpolate driving cycle to match simulation timestep 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 # Obs Space:[SOC, T_fc, T_core, T_surf, speed, acceleration] 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) # Act Space:[fc_ratio, cooling_level, split_ratio] 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] # [SOC, T_fc, T_core, T_surf] 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 # print(f"{self.step_count >= self.steps} 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() # Demo 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)