Spaces:
Sleeping
Sleeping
KrisKeshav commited on
Fix PLL simulation issues and improve observation handling
Browse filesThis commit includes several fixes and improvements to the PLL simulation environment, including updates to the handling of attack signals, observation windows, and episode termination conditions.
3 unmodified lines456789101112131415161718192021222324252664 unmodified lines91929394959697989910010110227 unmodified lines1301311321331341351361371381399 unmodified lines14915015115215315415515615715810 unmodified lines1691701711721731741751761771781791801811821831 unmodified line18518618718818919019119219319419519619734 unmodified lines23223323423523623723823955 unmodified lines29529629729829930030145 unmodified lines3473483493503513523533543553563573583596 unmodified lines3663673683693703713723 unmodified linesImplements step(), reset(), get_state(), and compute_reward().Manages the PLL simulation, attack injection, observation windowing,episode history, and grading.Fixes applied vs previous version:1. grade_task_easy() now receives attack_start_step (was missing, causingTypeError at episode end for task_id=0).2. attack_active is derived from attack_signal != 0.0 instead ofis_active() — single source of truth prevents signal/label divergence.3. Lock-loss check guarded by step_count > attack_start_step — preventsspurious lock-loss from PLL transient on step 0.4. Task 3 early termination added: done=True when lock_lost, not just atstep 500. Avoids 200+ meaningless steps after failure.5. _get_observation() updated to remove theta_err_window (ground-truthleak) and add omega_deviation_window (raw omega deviation in rad/s),matching the corrected Observation model.6. theta_err_window deque removed from instance state.7. Initial raw_voltages fixed: pll is warm-started with one silent step sova_m/vb_m/vc_m are non-zero at reset() return.8. omega_deviation_window deque added for the new Observation field."""import uuid64 unmodified linesdef reset(self, task_id: int = 0, seed: Optional[int] = None) -> Observation:"""Reset the environment for a new episode.Args:task_id: 0=easy (sinusoidal), 1=medium (multi-type),2=hard (stealthy).seed: Optional RNG seed for reproducibility.Returns:Initial Observation with non-zero raw_voltages."""27 unmodified lines# Sample attack for this episodeself._setup_attack()# Fix 7: warm-start PLL with WINDOW_SIZE silent steps so that# windows contain realistic (non-zero) PLL-settled values and# raw_voltages are non-zero on the first observation.for _ in range(WINDOW_SIZE):pll_out = self.pll.step(0.0) # no attack during warm-upomega_norm = (pll_out["omega_hat"] - OMEGA0) / OMEGA09 unmodified linesdef step(self, action: Action) -> Tuple[Observation, Reward, bool, Dict[str, Any]]:"""Advance the environment by one step.Args:action: Agent's Action for this step.Returns:(observation, reward, done, info)"""10 unmodified lines)# --- Attack signal ------------------------------------------------# Fix 2: derive attack_active from the actual injected signal value,# not from is_active(). Single source of truth — label matches physics.attack_signal = self.attack_generator.get_signal(self.step_count, self.pll.t)self.attack_active = self.attack_generator.is_active(self.step_count)# --- Advance PLL --------------------------------------------------pll_out = self.pll.step(attack_signal)# --- Update observation windows -----------------------------------omega_norm = (pll_out["omega_hat"] - OMEGA0) / OMEGA0omega_dev = pll_out["omega_hat"] - OMEGA0 # raw deviation (rad/s)self.vq_window.append(pll_out["vq"])1 unmodified lineself.omega_window.append(omega_norm)self.omega_deviation_window.append(omega_dev)# --- Lock-loss check (Task 2 / hard only) -------------------------PLL_CONVERGENCE_STEPS = 60 # PLL transient settles by ~step 50, use 60 for marginif (self.task_id == 2and not self.lock_lostand self.step_count > self.attack_start_stepand self.step_count > PLL_CONVERGENCE_STEPS # ← guard against startup transient):if abs(pll_out["theta_err"]) > LOCK_LOSS_THRESHOLD:self.lock_lost = True34 unmodified linesdef compute_reward(self, action: Action) -> Reward:"""Compute the dense reward signal for the current step.Reward components:detection_reward: +0.10 true positive (per step)+0.05 true negative (per step)55 unmodified lines)def get_state(self) -> State:"""Return full internal state for debugging / GET /state endpoint."""return State(theta_true=self.pll.theta_true,theta_hat=self.pll.theta_hat,45 unmodified linesdef _get_observation(self) -> Observation:"""Build the current Observation from internal windows.Fix 5: theta_err_window replaced with omega_deviation_window.theta_err requires knowing theta_true (not observable in a realinverter) and leaked ground truth directly to the agent.omega_deviation (omega_hat - OMEGA0 in rad/s) is a realistic proxythat correlates with phase drift under stealthy attacks."""return Observation(vq_window=list(self.vq_window),6 unmodified lines)def _compute_grader_score(self) -> float:"""Run the appropriate grader at episode end."""if self.task_id == 0:return grade_task_easy(self.history, self.attack_start_step)elif self.task_id == 1:3 unmodified lines45678964 unmodified lines7475767778798081828327 unmodified lines1111121131141151161179 unmodified lines12712812913013113213313410 unmodified lines1451461471481491501511521531541551561571 unmodified line15916016116216316416516616716816917017134 unmodified lines20620720820921021121255 unmodified lines26826927027127227327445 unmodified lines3203213223233243253266 unmodified lines3333343353363373383393 unmodified linesImplements step(), reset(), get_state(), and compute_reward().Manages the PLL simulation, attack injection, observation windowing,episode history, and grading."""import uuid64 unmodified linesdef reset(self, task_id: int = 0, seed: Optional[int] = None) -> Observation:"""Reset the environment for a new episode.Args:task_id: 0=easy (sinusoidal), 1=medium (multi-type),2=hard (stealthy).seed: Optional RNG seed for reproducibility.Returns:Initial Observation with non-zero raw_voltages."""27 unmodified lines# Sample attack for this episodeself._setup_attack()for _ in range(WINDOW_SIZE):pll_out = self.pll.step(0.0) # no attack during warm-upomega_norm = (pll_out["omega_hat"] - OMEGA0) / OMEGA09 unmodified linesdef step(self, action: Action) -> Tuple[Observation, Reward, bool, Dict[str, Any]]:"""Advance the environment by one step.Args:action: Agent's Action for this step.Returns:(observation, reward, done, info)"""10 unmodified lines)# --- Attack signal ------------------------------------------------attack_signal = self.attack_generator.get_signal(self.step_count, self.pll.t)self.attack_active = self.attack_generator.is_active(self.step_count)# --- Advance PLL --------------------------------------------------pll_out = self.pll.step(attack_signal)# --- Updating observation windows -----------------------------------omega_norm = (pll_out["omega_hat"] - OMEGA0) / OMEGA0omega_dev = pll_out["omega_hat"] - OMEGA0 # raw deviation (rad/s)self.vq_window.append(pll_out["vq"])1 unmodified lineself.omega_window.append(omega_norm)self.omega_deviation_window.append(omega_dev)# --- Lock-loss check (Task 2) -------------------------PLL_CONVERGENCE_STEPS = 60 # PLL transient settles by ~step 50, using 60 for marginif (self.task_id == 2and not self.lock_lostand self.step_count > self.attack_start_stepand self.step_count > PLL_CONVERGENCE_STEPS # guard against startup transient):if abs(pll_out["theta_err"]) > LOCK_LOSS_THRESHOLD:self.lock_lost = True34 unmodified linesdef compute_reward(self, action: Action) -> Reward:"""Computes the dense reward signal for the current step.Reward components:detection_reward: +0.10 true positive (per step)+0.05 true negative (per step)55 unmodified lines)def get_state(self) -> State:"""Returning full internal state for debugging / GET /state endpoint."""return State(theta_true=self.pll.theta_true,theta_hat=self.pll.theta_hat,45 unmodified linesdef _get_observation(self) -> Observation:"""Building the current Observation from internal windows."""return Observation(vq_window=list(self.vq_window),6 unmodified lines)def _compute_grader_score(self) -> float:"""Running the appropriate grader at episode end."""if self.task_id == 0:return grade_task_easy(self.history, self.attack_start_step)elif self.task_id == 1:
src/env.py+9-42