Skip to content

Commit 32bc3a5

Browse files
committed
feat(sim): add stochastic weather, CSV export, imbalance settlement
1 parent 11988cc commit 32bc3a5

File tree

11 files changed

+593
-2
lines changed

11 files changed

+593
-2
lines changed

Cargo.lock

Lines changed: 60 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ version = "0.1.0"
44
edition = "2024"
55

66
[dependencies]
7+
csv = "1"
78
rand = "0.9.2"

src/devices/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@ pub mod battery;
88
pub mod ev_charger;
99
/// Solar photovoltaic generation model.
1010
pub mod solar;
11+
/// Solar PV with AR(1) cloud variability model.
12+
pub mod solar_ar1;
1113
pub mod types;
1214

1315
// Re-export the main types for convenience
1416
pub use baseload::BaseLoad;
1517
pub use battery::Battery;
1618
pub use ev_charger::EvCharger;
1719
pub use solar::SolarPv;
20+
pub use solar_ar1::SolarPvAr1;
1821
pub use types::Device;
1922
pub use types::DeviceContext;

src/devices/solar_ar1.rs

Lines changed: 277 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,277 @@
1+
//! Solar PV model with temporally correlated cloud variability (AR(1) process).
2+
3+
use crate::devices::types::{Device, DeviceContext, gaussian_noise};
4+
use crate::sim::types::SimConfig;
5+
use rand::{SeedableRng, rngs::StdRng};
6+
7+
/// Solar PV generator with an AR(1) cloud multiplier for realistic variability.
8+
///
9+
/// Unlike [`SolarPv`](super::SolarPv) which applies independent Gaussian noise
10+
/// per timestep, `SolarPvAr1` models temporally correlated cloud fronts via a
11+
/// first-order autoregressive process on a PV multiplier.
12+
///
13+
/// The multiplier evolves as:
14+
/// ```text
15+
/// m(t) = alpha * m(t-1) + (1 - alpha) * epsilon(t)
16+
/// ```
17+
/// where `epsilon` is Gaussian noise and `alpha` controls temporal correlation.
18+
/// The multiplier is clamped to \[0.2, 1.2\].
19+
///
20+
/// # Power Flow Convention (Feeder)
21+
/// Returns **negative** values during daylight (generation reduces feeder load).
22+
#[derive(Debug, Clone)]
23+
pub struct SolarPvAr1 {
24+
/// Maximum power output in kilowatts under ideal conditions.
25+
pub kw_peak: f32,
26+
27+
/// Number of time steps per simulated day.
28+
steps_per_day: usize,
29+
30+
/// Time step index when sunrise occurs (inclusive).
31+
pub sunrise_idx: usize,
32+
33+
/// Time step index when sunset occurs (exclusive).
34+
pub sunset_idx: usize,
35+
36+
/// AR(1) correlation coefficient (0.0 = uncorrelated, 1.0 = fully persistent).
37+
pub alpha: f32,
38+
39+
/// Standard deviation of the AR(1) innovation noise.
40+
pub cloud_noise_std: f32,
41+
42+
/// Current cloud multiplier state.
43+
multiplier: f32,
44+
45+
/// Random number generator for noise generation.
46+
rng: StdRng,
47+
}
48+
49+
/// Minimum cloud multiplier (heavy overcast).
50+
const MULTIPLIER_MIN: f32 = 0.2;
51+
/// Maximum cloud multiplier (enhanced irradiance from cloud edges).
52+
const MULTIPLIER_MAX: f32 = 1.2;
53+
54+
impl SolarPvAr1 {
55+
/// Creates a new solar PV generator with AR(1) cloud variability.
56+
///
57+
/// # Arguments
58+
///
59+
/// * `kw_peak` - Maximum power output in kilowatts under ideal conditions
60+
/// * `sunrise_idx` - Time step index when sunrise occurs (inclusive)
61+
/// * `sunset_idx` - Time step index when sunset occurs (exclusive)
62+
/// * `alpha` - AR(1) correlation coefficient (typical: 0.8–0.95)
63+
/// * `cloud_noise_std` - Standard deviation of innovation noise (typical: 0.15–0.3)
64+
/// * `config` - Simulation configuration for timing
65+
/// * `seed` - Random seed for reproducible noise generation
66+
///
67+
/// # Panics
68+
///
69+
/// Panics if `sunrise_idx >= sunset_idx` or `sunset_idx > steps_per_day`.
70+
pub fn new(
71+
kw_peak: f32,
72+
sunrise_idx: usize,
73+
sunset_idx: usize,
74+
alpha: f32,
75+
cloud_noise_std: f32,
76+
config: &SimConfig,
77+
seed: u64,
78+
) -> Self {
79+
assert!(
80+
sunrise_idx < sunset_idx && sunset_idx <= config.steps_per_day,
81+
"sunrise_idx must be < sunset_idx and sunset_idx must be <= steps_per_day"
82+
);
83+
Self {
84+
kw_peak: kw_peak.max(0.0),
85+
steps_per_day: config.steps_per_day,
86+
sunrise_idx,
87+
sunset_idx,
88+
alpha: alpha.clamp(0.0, 1.0),
89+
cloud_noise_std: cloud_noise_std.max(0.0),
90+
multiplier: 1.0,
91+
rng: StdRng::seed_from_u64(seed),
92+
}
93+
}
94+
95+
/// Calculates the daylight fraction for a specific time step.
96+
///
97+
/// Delegates to the shared [`super::types::daylight_frac`] free function.
98+
fn daylight_frac(&self, t: usize) -> f32 {
99+
super::types::daylight_frac(t, self.steps_per_day, self.sunrise_idx, self.sunset_idx)
100+
}
101+
102+
/// Advances the AR(1) cloud multiplier by one step and returns the new value.
103+
fn advance_multiplier(&mut self) -> f32 {
104+
let epsilon = gaussian_noise(&mut self.rng, self.cloud_noise_std);
105+
self.multiplier = self.alpha * self.multiplier + (1.0 - self.alpha) * epsilon;
106+
self.multiplier = self.multiplier.clamp(MULTIPLIER_MIN, MULTIPLIER_MAX);
107+
self.multiplier
108+
}
109+
}
110+
111+
impl Device for SolarPvAr1 {
112+
/// Calculates the power generation at a specific time step in feeder convention.
113+
///
114+
/// Returns **negative** values during daylight (generation exports to grid).
115+
/// Returns 0.0 during nighttime hours. The cloud multiplier evolves every
116+
/// timestep regardless of daylight, maintaining temporal correlation.
117+
fn power_kw(&mut self, context: &DeviceContext) -> f32 {
118+
let m = self.advance_multiplier();
119+
let frac = self.daylight_frac(context.timestep);
120+
if frac <= 0.0 {
121+
return 0.0;
122+
}
123+
124+
let kw = self.kw_peak * frac * m;
125+
// Return negative for generation (feeder convention: negative = export)
126+
-(kw.max(0.0))
127+
}
128+
129+
fn device_type(&self) -> &'static str {
130+
"SolarPV_ar1"
131+
}
132+
}
133+
134+
#[cfg(test)]
135+
mod tests {
136+
use super::*;
137+
138+
fn cfg() -> SimConfig {
139+
SimConfig::new(24, 1, 0)
140+
}
141+
142+
fn ctx(t: usize) -> DeviceContext {
143+
DeviceContext::new(t)
144+
}
145+
146+
#[test]
147+
fn seed_determinism() {
148+
let c = cfg();
149+
let mut pv1 = SolarPvAr1::new(5.0, 6, 18, 0.9, 0.2, &c, 42);
150+
let mut pv2 = SolarPvAr1::new(5.0, 6, 18, 0.9, 0.2, &c, 42);
151+
152+
for t in 0..48 {
153+
assert_eq!(pv1.power_kw(&ctx(t)), pv2.power_kw(&ctx(t)));
154+
}
155+
}
156+
157+
#[test]
158+
fn different_seeds_produce_different_sequences() {
159+
let c = cfg();
160+
let mut pv1 = SolarPvAr1::new(5.0, 6, 18, 0.9, 0.2, &c, 42);
161+
let mut pv2 = SolarPvAr1::new(5.0, 6, 18, 0.9, 0.2, &c, 99);
162+
163+
let mut any_differ = false;
164+
for t in 6..18 {
165+
if (pv1.power_kw(&ctx(t)) - pv2.power_kw(&ctx(t))).abs() > 1e-5 {
166+
any_differ = true;
167+
break;
168+
}
169+
}
170+
assert!(
171+
any_differ,
172+
"different seeds should produce different outputs"
173+
);
174+
}
175+
176+
#[test]
177+
fn multiplier_stays_within_bounds() {
178+
let c = SimConfig::new(24, 10, 0); // 10 days for more samples
179+
let mut pv = SolarPvAr1::new(5.0, 6, 18, 0.8, 0.5, &c, 42);
180+
181+
// Run many steps with high noise to stress-test clamping
182+
for t in 0..c.total_steps() {
183+
let kw = pv.power_kw(&ctx(t));
184+
// During daylight: power should be between -kw_peak*1.2 and 0
185+
// At night: exactly 0
186+
assert!(kw <= 0.0, "generation should be <= 0 at t={t}, got {kw}");
187+
assert!(
188+
kw >= -5.0 * MULTIPLIER_MAX,
189+
"power should not exceed peak * max_multiplier at t={t}, got {kw}"
190+
);
191+
}
192+
}
193+
194+
#[test]
195+
fn temporal_correlation_adjacent_steps_more_similar() {
196+
let c = SimConfig::new(96, 1, 0); // 15-min steps for smoother data
197+
let mut pv = SolarPvAr1::new(5.0, 24, 72, 0.9, 0.2, &c, 42);
198+
199+
let mut outputs = Vec::with_capacity(c.total_steps());
200+
for t in 0..c.total_steps() {
201+
outputs.push(pv.power_kw(&ctx(t)));
202+
}
203+
204+
// Compare adjacent-step differences vs 10-step-apart differences
205+
// during daylight only (steps 24..72)
206+
let mut adj_diff_sum = 0.0_f32;
207+
let mut adj_count = 0_u32;
208+
let mut far_diff_sum = 0.0_f32;
209+
let mut far_count = 0_u32;
210+
211+
for t in 25..72 {
212+
adj_diff_sum += (outputs[t] - outputs[t - 1]).abs();
213+
adj_count += 1;
214+
if t >= 34 {
215+
far_diff_sum += (outputs[t] - outputs[t - 10]).abs();
216+
far_count += 1;
217+
}
218+
}
219+
220+
let avg_adj = adj_diff_sum / adj_count as f32;
221+
let avg_far = far_diff_sum / far_count as f32;
222+
// Adjacent steps should on average be more similar (smaller difference)
223+
assert!(
224+
avg_adj < avg_far,
225+
"adjacent diff ({avg_adj:.4}) should be smaller than distant diff ({avg_far:.4})"
226+
);
227+
}
228+
229+
#[test]
230+
fn sign_convention_negative_during_daylight() {
231+
let c = cfg();
232+
let mut pv = SolarPvAr1::new(5.0, 6, 18, 0.9, 0.2, &c, 42);
233+
234+
for t in 0..24 {
235+
let kw = pv.power_kw(&ctx(t));
236+
assert!(kw <= 0.0, "power should be <= 0 at t={t}, got {kw}");
237+
// Strictly negative during mid-day (multiplier >= 0.2, frac > 0)
238+
if t >= 8 && t <= 16 {
239+
assert!(
240+
kw < 0.0,
241+
"power should be strictly negative during daylight at t={t}, got {kw}"
242+
);
243+
}
244+
}
245+
}
246+
247+
#[test]
248+
fn no_generation_at_night() {
249+
let c = cfg();
250+
let mut pv = SolarPvAr1::new(5.0, 6, 18, 0.9, 0.2, &c, 42);
251+
assert_eq!(pv.power_kw(&ctx(0)), 0.0);
252+
assert_eq!(pv.power_kw(&ctx(5)), 0.0);
253+
assert_eq!(pv.power_kw(&ctx(18)), 0.0);
254+
assert_eq!(pv.power_kw(&ctx(23)), 0.0);
255+
}
256+
257+
#[test]
258+
#[should_panic]
259+
fn sunset_before_sunrise_panics() {
260+
SolarPvAr1::new(5.0, 18, 6, 0.9, 0.2, &cfg(), 42);
261+
}
262+
263+
#[test]
264+
#[should_panic]
265+
fn sunset_exceeds_steps_panics() {
266+
SolarPvAr1::new(5.0, 6, 25, 0.9, 0.2, &cfg(), 42);
267+
}
268+
269+
#[test]
270+
fn alpha_clamped_to_unit_interval() {
271+
let c = cfg();
272+
let pv = SolarPvAr1::new(5.0, 6, 18, 1.5, 0.2, &c, 42);
273+
assert_eq!(pv.alpha, 1.0);
274+
let pv2 = SolarPvAr1::new(5.0, 6, 18, -0.5, 0.2, &c, 42);
275+
assert_eq!(pv2.alpha, 0.0);
276+
}
277+
}

0 commit comments

Comments
 (0)