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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Process model complexity metrics.
//!
//! Five complementary metrics that practitioners use for governance,
//! model comparison, and cognitive load estimation:
//!
//! | Metric | What it measures |
//! |--------------------|---------------------------------------|
//! | `cyclomatic` | Decision paths (McCabe analog) |
//! | `cfc` | Control-flow complexity (Cardoso) |
//! | `cognitive` | Nesting-weighted structural load |
//! | `halstead` | Information-theoretic volume/effort |
//! | `nesting_depth` | Maximum nesting depth |
//! | `branching_factor` | Average children per operator node |
use wasm4pm_compat::powl::{ChoiceGraph, ChoiceGraphNode};
use crate::powl_arena::{PowlArena, PowlNode};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
// ─── Output types ─────────────────────────────────────────────────────────────
/// Halstead software science metrics adapted for process models.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HalsteadMetrics {
/// Unique operator types (XOR, LOOP, SPO, DG, ...).
pub n1: usize,
/// Unique operand tokens (distinct activity labels + tau).
pub n2: usize,
/// Total operator occurrences.
pub capital_n1: usize,
/// Total operand occurrences.
pub capital_n2: usize,
/// Vocabulary: n1 + n2.
pub vocabulary: usize,
/// Length: N1 + N2.
pub length: usize,
/// Volume: length * log2(vocabulary).
pub volume: f64,
/// Difficulty: (n1/2) * (N2/n2).
pub difficulty: f64,
/// Effort: difficulty * volume.
pub effort: f64,
}
/// All complexity metrics for a POWL model.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ComplexityReport {
/// McCabe cyclomatic complexity analog.
/// Base = 1; each XOR adds (branches - 1); each LOOP adds 1.
pub cyclomatic: usize,
/// Cardoso Control-Flow Complexity.
/// XOR(n) -> sum of children's CFC; LOOP -> 2*CFC(do); AND/SPO -> max; leaf -> 1.
pub cfc: usize,
/// Cognitive complexity (nesting-weighted).
/// Each structural node adds its nesting depth to the score.
pub cognitive: usize,
/// Maximum nesting depth (0 = flat leaf).
pub nesting_depth: usize,
/// Average number of children across all operator/SPO/DG nodes.
pub branching_factor: f64,
/// Total number of distinct activity labels.
pub activity_count: usize,
/// Total node count in the arena.
pub node_count: usize,
/// Halstead metrics.
pub halstead: HalsteadMetrics,
}
// ─── Computation ──────────────────────────────────────────────────────────────
struct Collector {
cyclomatic: usize,
cognitive: usize,
max_depth: usize,
operator_types: HashSet<String>,
operator_total: usize,
activity_set: HashSet<String>,
activity_total: usize,
operator_children_counts: Vec<usize>,
}
impl Collector {
fn new() -> Self {
Self {
cyclomatic: 1,
cognitive: 0,
max_depth: 0,
operator_types: HashSet::new(),
operator_total: 0,
activity_set: HashSet::new(),
activity_total: 0,
operator_children_counts: Vec::new(),
}
}
}
/// Recursively compute CFC (returned) and side-effect all other metrics.
fn visit(arena: &PowlArena, idx: u32, depth: usize, col: &mut Collector) -> usize {
col.max_depth = col.max_depth.max(depth);
match arena.get(idx) {
None => 1,
Some(PowlNode::Transition(t)) => {
let label = t.label.clone().unwrap_or_else(|| "tau".to_string());
col.activity_set.insert(label);
col.activity_total += 1;
1 // CFC of a leaf
}
Some(PowlNode::FrequentTransition(ft)) => {
col.activity_set.insert(ft.activity.clone());
col.activity_total += 1;
// FrequentTransition is implicitly optional -- contributes 1 choice
col.cyclomatic += 1;
col.cognitive += depth + 1;
2 // leaf + optional path
}
Some(PowlNode::OperatorPowl(op)) => {
let operator: &'static str = op.operator.as_str();
let children = op.children.clone();
let n = children.len();
col.operator_types.insert(operator.to_string());
col.operator_total += 1;
col.operator_children_counts.push(n);
match operator {
"X" => {
// cyclomatic: each extra branch
col.cyclomatic += n.saturating_sub(1);
col.cognitive += depth + 1;
// CFC(XOR) = sum of children CFCs
let child_cfcs: Vec<usize> = children
.iter()
.map(|&c| visit(arena, c, depth + 1, col))
.collect();
child_cfcs.iter().sum()
}
"*" => {
col.cyclomatic += 1; // redo path
col.cognitive += depth + 1;
// children[0] = do, children[1] = redo
let do_cfc = if !children.is_empty() {
visit(arena, children[0], depth + 1, col)
} else {
1
};
if children.len() > 1 {
visit(arena, children[1], depth + 1, col);
}
2 * do_cfc // CFC(LOOP) = 2 * CFC(do)
}
_ => {
// Any other operator (PartialOrder inline, Sequence, etc.)
col.cognitive += depth + 1;
let child_cfcs: Vec<usize> = children
.iter()
.map(|&c| visit(arena, c, depth + 1, col))
.collect();
child_cfcs.iter().copied().max().unwrap_or(1)
}
}
}
Some(PowlNode::StrictPartialOrder(spo)) => {
let children = spo.children.clone();
let n = children.len();
col.operator_types.insert("SPO".to_string());
col.operator_total += 1;
col.operator_children_counts.push(n);
col.cognitive += depth + 1;
// CFC(AND/SPO) = max of children CFCs
let child_cfcs: Vec<usize> = children
.iter()
.map(|&c| visit(arena, c, depth + 1, col))
.collect();
child_cfcs.iter().copied().max().unwrap_or(1)
}
Some(PowlNode::DecisionGraph(dg)) => {
// Treat as StrictPartialOrder for complexity measurement
let children = dg.children.clone();
let n = children.len();
col.operator_types.insert("DG".to_string());
col.operator_total += 1;
col.operator_children_counts.push(n);
col.cognitive += depth + 1;
// CFC(AND/SPO/DG) = max of children CFCs
let child_cfcs: Vec<usize> = children
.iter()
.map(|&c| visit(arena, c, depth + 1, col))
.collect();
child_cfcs.iter().copied().max().unwrap_or(1)
}
Some(PowlNode::ChoiceGraph(cg)) => {
// CG: like DG, recurse into SubModel children for CFC.
let mut sub_indices: Vec<u32> = Vec::new();
for n in cg.graph.nodes() {
if let ChoiceGraphNode::SubModel(idx) = n {
sub_indices.push(*idx);
}
}
let n = sub_indices.len();
col.operator_types.insert("CG".to_string());
col.operator_total += 1;
col.operator_children_counts.push(n);
col.cognitive += depth + 1;
let child_cfcs: Vec<usize> = sub_indices
.iter()
.map(|&c| visit(arena, c, depth + 1, col))
.collect();
child_cfcs.iter().copied().max().unwrap_or(1)
}
}
}
/// Compute all complexity metrics for a POWL model rooted at `root`.
pub fn measure(arena: &PowlArena, root: u32) -> ComplexityReport {
let mut col = Collector::new();
let cfc = visit(arena, root, 0, &mut col);
let n1 = col.operator_types.len();
let n2 = col.activity_set.len();
let cap_n1 = col.operator_total;
let cap_n2 = col.activity_total;
let vocab = n1 + n2;
let length = cap_n1 + cap_n2;
let volume = if vocab > 1 {
length as f64 * (vocab as f64).log2()
} else {
0.0
};
let difficulty = if n2 > 0 {
(n1 as f64 / 2.0) * (cap_n2 as f64 / n2 as f64)
} else {
0.0
};
let branching_factor = if col.operator_children_counts.is_empty() {
0.0
} else {
col.operator_children_counts.iter().sum::<usize>() as f64
/ col.operator_children_counts.len() as f64
};
ComplexityReport {
cyclomatic: col.cyclomatic,
cfc,
cognitive: col.cognitive,
nesting_depth: col.max_depth,
branching_factor,
activity_count: col.activity_set.len(),
node_count: arena.len(),
halstead: HalsteadMetrics {
n1,
n2,
capital_n1: cap_n1,
capital_n2: cap_n2,
vocabulary: vocab,
length,
volume,
difficulty,
effort: difficulty * volume,
},
}
}
/// Compute simplicity metric for a Petri net.
///
/// Simplicity measures how "simple" a model is based on its structure.
/// The arc_degree variant uses: 1 - (arcs / (places * transitions))
/// where a value closer to 1.0 indicates a simpler model.
///
/// This mirrors `pm4py.analysis.simplicity_petri_net()` with variant="arc_degree".
///
/// # Arguments
/// * `num_places` - Number of places in the Petri net
/// * `num_transitions` - Number of transitions in the Petri net
/// * `num_arcs` - Number of arcs in the Petri net
///
/// # Returns
/// Simplicity score in [0.0, 1.0] where 1.0 is simplest.
pub fn simplicity_arc_degree(num_places: usize, num_transitions: usize, num_arcs: usize) -> f64 {
// Maximum possible arcs in a bipartite graph: places * transitions.
// Use saturating multiplication to guard against usize overflow on
// pathological inputs (catches missing-NaN-class bug where overflow
// produced a tiny max_arcs and made simplicity look near 0).
let max_arcs = num_places.saturating_mul(num_transitions);
if max_arcs == 0 {
return 1.0;
}
// Iter-10 hardening: clamp to [0, 1] to enforce the documented
// postcondition "Simplicity score in [0.0, 1.0] where 1.0 is simplest".
// The old expression `1.0 - actual/max` can go negative when num_arcs
// exceeds max_arcs (multi-arcs between the same place/transition pair,
// or weighted arcs counted by weight). Documented domain is [0, 1].
let raw = 1.0 - (num_arcs as f64 / max_arcs as f64);
raw.clamp(0.0, 1.0)
}
// ─── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use crate::powl_parser::parse_powl_model_string;
fn parse(s: &str) -> (PowlArena, u32) {
let mut arena = PowlArena::new();
let root = parse_powl_model_string(s, &mut arena).unwrap();
(arena, root)
}
#[test]
fn leaf_has_base_complexity() {
let (arena, root) = parse("A");
let r = measure(&arena, root);
assert_eq!(r.cyclomatic, 1);
assert_eq!(r.cfc, 1);
assert_eq!(r.nesting_depth, 0);
assert_eq!(r.activity_count, 1);
}
#[test]
fn xor_adds_branches() {
let (arena, root) = parse("X(A, B, C)");
let r = measure(&arena, root);
assert_eq!(r.cyclomatic, 3); // 1 base + 2 extra branches
assert_eq!(r.cfc, 3); // sum of 3 leaf CFCs
assert_eq!(r.branching_factor, 3.0);
}
#[test]
fn loop_adds_one() {
let (arena, root) = parse("*(A, B)");
let r = measure(&arena, root);
assert_eq!(r.cyclomatic, 2); // 1 base + 1 redo
assert_eq!(r.cfc, 2); // 2 * CFC(A)
}
#[test]
fn spo_uses_max_cfc() {
let (arena, root) = parse("PO=(nodes={A, B, C}, order={A-->B, A-->C})");
let r = measure(&arena, root);
assert_eq!(r.cfc, 1); // max(1,1,1)
assert_eq!(r.activity_count, 3);
}
#[test]
fn nested_increases_depth() {
let (arena, root) = parse("X(A, X(B, C))");
let r = measure(&arena, root);
assert!(r.nesting_depth >= 2);
assert!(r.cognitive >= 2);
}
#[test]
fn halstead_volume_positive_for_complex_model() {
let (arena, root) = parse("X(A, *(B, C))");
let r = measure(&arena, root);
assert!(r.halstead.volume > 0.0);
assert!(r.halstead.effort > 0.0);
}
#[test]
fn decision_graph_complexity() {
let (arena, root) =
parse("DG=(nodes={A, B}, order={A-->B}, starts=[A], ends=[B], empty=false)");
let r = measure(&arena, root);
// DG treated like SPO: CFC = max(1,1) = 1
assert_eq!(r.cfc, 1);
assert_eq!(r.activity_count, 2);
}
#[test]
fn simplicity_perfect_bipartite() {
// 2 places, 2 transitions, 4 arcs = fully connected
let s = simplicity_arc_degree(2, 2, 4);
assert!((s - 0.0).abs() < f64::EPSILON);
}
#[test]
fn simplicity_no_arcs() {
let s = simplicity_arc_degree(2, 2, 0);
assert!((s - 1.0).abs() < f64::EPSILON);
}
#[test]
fn simplicity_empty_net() {
let s = simplicity_arc_degree(0, 0, 0);
assert!((s - 1.0).abs() < f64::EPSILON);
}
/// Iter-10 Rank-1: Range invariant. The documented postcondition of
/// `simplicity_arc_degree` is "Simplicity score in [0.0, 1.0]". The
/// pre-fix expression `1.0 - num_arcs/max_arcs` returns a NEGATIVE
/// value whenever `num_arcs > max_arcs` — easy to trigger with
/// multi-arcs between the same place/transition pair, or weighted
/// arcs that the caller summed by weight before passing in.
#[test]
fn iter10_simplicity_clamped_when_arcs_exceed_max() {
// 2 places * 2 transitions = max_arcs = 4. Pass num_arcs = 100
// (would be possible if caller counted parallel arcs).
let s = simplicity_arc_degree(2, 2, 100);
assert!(s >= 0.0, "simplicity {} must not be negative", s);
assert!(s <= 1.0, "simplicity {} must not exceed 1.0", s);
}
/// Iter-10 Rank-2: Domain contract. Even on overflow-class inputs
/// (saturating_mul keeps max_arcs finite) the score stays in [0, 1].
#[test]
fn iter10_simplicity_saturates_on_overflow() {
// num_places * num_transitions would overflow usize without the
// saturating_mul guard — assert the function does not panic and
// returns a value in the documented range.
let huge = usize::MAX / 2 + 1;
let s = simplicity_arc_degree(huge, huge, 7);
assert!((0.0..=1.0).contains(&s), "score out of range: {}", s);
assert!(s.is_finite(), "score must be finite");
}
}