1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//! Layer 5b — correlation-domain semantic validation.
use super::super::{ErrorKind, ValidationContext, schema::ParsedData};
use super::CORR_TOLERANCE;
// ── Rules 14-16: Correlation matrix validation ────────────────────────────────
/// Validates correlation matrix symmetry, diagonal, and off-diagonal range for
/// all groups in all profiles of the correlation model.
///
/// Only runs when `data.correlation` is `Some`.
pub(super) fn check_correlation_matrices(data: &ParsedData, ctx: &mut ValidationContext) {
let Some(correlation) = &data.correlation else {
return;
};
for profile in correlation.profiles.values() {
for group in &profile.groups {
let n = group.entities.len();
let group_name = &group.name;
// Rules 14-16 require a square matrix; the matrix row count is guaranteed
// to match entity count by Layer 4 (dimensional check 4). Be defensive.
if group.matrix.len() != n {
continue;
}
for i in 0..n {
if group.matrix[i].len() != n {
continue;
}
for j in 0..n {
let val = group.matrix[i][j];
if i == j && (val - 1.0).abs() > CORR_TOLERANCE {
ctx.add_error(
ErrorKind::BusinessRuleViolation,
"scenarios/correlation.json",
Some(format!("CorrelationGroup {group_name}")),
format!(
"CorrelationGroup '{group_name}': diagonal entry matrix[{i}][{i}] \
is {val}, expected 1.0 (±{CORR_TOLERANCE}); \
correlation matrix diagonal must be 1.0"
),
);
}
if i != j && !((-1.0_f64)..=1.0).contains(&val) {
ctx.add_error(
ErrorKind::BusinessRuleViolation,
"scenarios/correlation.json",
Some(format!("CorrelationGroup {group_name}")),
format!(
"CorrelationGroup '{group_name}': off-diagonal entry \
matrix[{i}][{j}] is {val}, outside valid range [-1.0, 1.0]; \
correlation coefficients must be in [-1.0, 1.0]"
),
);
}
// Upper triangle only — avoids reporting each asymmetry twice.
if i < j {
let symmetric = group.matrix[j][i];
if (val - symmetric).abs() > CORR_TOLERANCE {
ctx.add_error(
ErrorKind::BusinessRuleViolation,
"scenarios/correlation.json",
Some(format!("CorrelationGroup {group_name}")),
format!(
"CorrelationGroup '{group_name}': correlation matrix is not \
symmetric at ({i},{j}): matrix[{i}][{j}]={val} but \
matrix[{j}][{i}]={symmetric}; tolerance is {CORR_TOLERANCE}"
),
);
}
}
}
}
}
}
}
// ── M4: Same-type enforcement within correlation groups ──────────────────────
/// Validates that all entities within each correlation group share the same
/// `entity_type` value. Mixed groups produce incorrect covariance matrices.
pub(super) fn check_correlation_same_type(data: &ParsedData, ctx: &mut ValidationContext) {
let Some(correlation) = &data.correlation else {
return;
};
for profile in correlation.profiles.values() {
for group in &profile.groups {
if group.entities.is_empty() {
continue;
}
let first_type = &group.entities[0].entity_type;
for entity in &group.entities[1..] {
if entity.entity_type != *first_type {
ctx.add_error(
ErrorKind::BusinessRuleViolation,
"scenarios/correlation.json",
Some(format!("CorrelationGroup '{}'", group.name)),
format!(
"CorrelationGroup '{}': entity {} has type '{}' but entity {} has \
type '{}'; all entities in a group must share the same entity_type",
group.name,
group.entities[0].id.0,
first_type,
entity.id.0,
entity.entity_type,
),
);
break;
}
}
}
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::panic,
clippy::too_many_lines,
clippy::doc_markdown,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
mod tests {
use super::super::test_support::*;
use super::super::validate_semantic_stages_penalties_scenarios;
use crate::validation::{ErrorKind, ValidationContext};
// ── Rule 14: Correlation matrix symmetry ──────────────────────────────────
/// Asymmetric matrix (matrix[0][1] != matrix[1][0]) produces a
/// `BusinessRuleViolation` with "symmetric" in the message.
#[test]
fn test_5b_correlation_asymmetric() {
let group = make_corr_group(
"Asymmetric",
vec![
vec![1.0, 0.8],
vec![0.5, 1.0], // asymmetric: should be 0.8
],
);
let corr = make_correlation(group);
let data = make_data_5b(
vec![make_hydro_ordered_penalties(1)],
make_stages_5b(vec![0]),
vec![make_bus_with_deficit(1, 10.0)],
vec![],
vec![],
Some(corr),
);
let mut ctx = ValidationContext::new();
validate_semantic_stages_penalties_scenarios(&data, &mut ctx);
assert!(ctx.has_errors());
let errors = ctx.errors();
let relevant: Vec<_> = errors
.iter()
.filter(|e| e.kind == ErrorKind::BusinessRuleViolation)
.collect();
assert!(
!relevant.is_empty(),
"asymmetric matrix should produce BusinessRuleViolation"
);
let msg = &relevant[0].message;
assert!(
msg.contains("symmetric"),
"message should contain 'symmetric', got: {msg}"
);
}
// ── Rule 15: Correlation matrix diagonal ──────────────────────────────────
/// Diagonal entry not equal to 1.0 produces a `BusinessRuleViolation`.
#[test]
fn test_5b_correlation_diagonal_not_one() {
let group = make_corr_group(
"BadDiag",
vec![
vec![0.9, 0.0], // diagonal entry 0.9 != 1.0
vec![0.0, 1.0],
],
);
let corr = make_correlation(group);
let data = make_data_5b(
vec![make_hydro_ordered_penalties(1)],
make_stages_5b(vec![0]),
vec![make_bus_with_deficit(1, 10.0)],
vec![],
vec![],
Some(corr),
);
let mut ctx = ValidationContext::new();
validate_semantic_stages_penalties_scenarios(&data, &mut ctx);
assert!(ctx.has_errors());
assert!(
ctx.errors()
.iter()
.any(|e| e.kind == ErrorKind::BusinessRuleViolation),
"diagonal != 1.0 should produce BusinessRuleViolation"
);
}
// ── Rule 16: Correlation coefficient range ────────────────────────────────
/// Off-diagonal entry > 1.0 produces a `BusinessRuleViolation`.
#[test]
fn test_5b_correlation_off_diagonal_out_of_range() {
let group = make_corr_group(
"BadRange",
vec![
vec![1.0, 1.5], // 1.5 > 1.0 — out of range
vec![1.5, 1.0],
],
);
let corr = make_correlation(group);
let data = make_data_5b(
vec![make_hydro_ordered_penalties(1)],
make_stages_5b(vec![0]),
vec![make_bus_with_deficit(1, 10.0)],
vec![],
vec![],
Some(corr),
);
let mut ctx = ValidationContext::new();
validate_semantic_stages_penalties_scenarios(&data, &mut ctx);
assert!(ctx.has_errors());
assert!(
ctx.errors()
.iter()
.any(|e| e.kind == ErrorKind::BusinessRuleViolation),
"off-diagonal > 1.0 should produce BusinessRuleViolation"
);
}
/// Valid symmetric correlation matrix produces no errors.
#[test]
fn test_5b_correlation_valid_symmetric() {
let group = make_corr_group("Valid", vec![vec![1.0, 0.6], vec![0.6, 1.0]]);
let corr = make_correlation(group);
let data = make_data_5b(
vec![make_hydro_ordered_penalties(1)],
make_stages_5b(vec![0]),
vec![make_bus_with_deficit(1, 10.0)],
vec![],
vec![],
Some(corr),
);
let mut ctx = ValidationContext::new();
validate_semantic_stages_penalties_scenarios(&data, &mut ctx);
assert!(
!ctx.has_errors(),
"valid symmetric matrix should produce no errors, got: {:?}",
ctx.errors()
);
}
// ── Edge case: no correlation data ────────────────────────────────────────
/// `correlation = None` produces no false-positive errors.
#[test]
fn test_5b_no_correlation_no_inflow_no_false_positives() {
let data = make_data_5b(
vec![make_hydro_ordered_penalties(1)],
make_stages_5b(vec![0]),
vec![make_bus_with_deficit(1, 10.0)],
vec![],
vec![],
None, // no correlation
);
let mut ctx = ValidationContext::new();
validate_semantic_stages_penalties_scenarios(&data, &mut ctx);
assert!(
!ctx.has_errors(),
"empty correlation and inflow should produce no errors, got: {:?}",
ctx.errors()
);
}
}