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
//! High-ROI WASM utility exports for caching, hashing, and drift analysis.
//!
//! This module provides 6 carefully-selected wasm_bindgen exports that unlock
//! downstream tools without introducing design changes:
//!
//! 1. **cache_stats()** — Return JSON {hits, misses, evictions, total_bytes}
//! 2. **get_activity_frequencies()** — Return Vec<{activity, count}> as JSON
//! 3. **hash_xes_content()** — Return BLAKE3 hex string (FNV-1a in Rust)
//! 4. **jaccard_distance()** — Convert HashSet to JSON array wrapper, compute distance
//! 5. **ewma_series()** — Exponential weighted moving average smoothing
//! 6. **identify_high_variance_activities()** — Optional variance-based activity profiling
use crate::cache::{cache_stats as internal_cache_stats, hash_xes_content as internal_hash_xes};
use crate::models::AttributeValue;
use crate::prediction_drift::{
ewma_series as internal_ewma_series, jaccard_distance as internal_jaccard_distance,
};
use crate::state::{get_or_init_state, StoredObject};
use crate::utilities::to_js_str;
use serde_json::json;
use std::collections::HashSet;
use wasm_bindgen::prelude::*;
/// Return JSON { hits, misses, evictions, total_bytes } with cache statistics.
///
/// # Returns
/// ```json
/// {
/// "hits": 42,
/// "misses": 8,
/// "evictions": 2,
/// "total_bytes": 65536,
/// "parse_entries": 3,
/// "columnar_entries": 5,
/// "interner_entries": 1
/// }
/// ```
#[wasm_bindgen]
pub fn cache_stats() -> Result<JsValue, JsValue> {
let stats = internal_cache_stats();
to_js_str(&json!({
"parse_hits": stats.parse_hits,
"parse_misses": stats.parse_misses,
"parse_evictions": stats.parse_evictions,
"parse_entries": stats.parse_entries,
"columnar_entries": stats.columnar_entries,
"interner_entries": stats.interner_entries,
}))
}
/// Return BLAKE3 (FNV-1a) hex hash of XES content string.
///
/// # Arguments
/// * `xes_content` — XES event log as string
///
/// # Returns
/// 16-character lowercase hex string
///
/// # Example
/// ```
/// use wasm4pm::wasm_utils::hash_xes_content;
/// let hash = hash_xes_content("<log></log>");
/// assert_eq!(hash.len(), 16);
/// ```
#[wasm_bindgen]
pub fn hash_xes_content(xes_content: &str) -> String {
internal_hash_xes(xes_content)
}
/// Compute Jaccard distance between two JSON-serialized activity sets.
///
/// # Arguments
/// * `set1_json` — JSON string: `["A", "B", "C"]`
/// * `set2_json` — JSON string: `["B", "C", "D"]`
///
/// # Returns
/// Distance in [0.0, 1.0]:
/// - `0.0` = identical or both empty
/// - `1.0` = completely disjoint
///
/// # Example
/// ```
/// use wasm4pm::wasm_utils::jaccard_distance;
/// let dist = jaccard_distance(r#"["A", "B"]"#, r#"["B", "C"]"#).unwrap();
/// assert!((dist - 0.6666666666666667).abs() < 1e-10);
/// ```
#[wasm_bindgen]
pub fn jaccard_distance(set1_json: &str, set2_json: &str) -> Result<f64, JsValue> {
let set1: HashSet<String> = serde_json::from_str(set1_json)
.map_err(|e| crate::error::js_val(&format!("Invalid set1 JSON: {}", e)))?;
let set2: HashSet<String> = serde_json::from_str(set2_json)
.map_err(|e| crate::error::js_val(&format!("Invalid set2 JSON: {}", e)))?;
let distance = internal_jaccard_distance(&set1, &set2);
Ok(distance)
}
/// Compute exponential weighted moving average over a numeric series.
///
/// # Arguments
/// * `values_json` — JSON string: `[1.0, 2.0, 3.0, ...]`
/// * `alpha` — Smoothing factor in (0.0, 1.0]; clamped if out of range
///
/// # Returns
/// JSON string: `[1.0, 1.5, 2.25, ...]` (EWMA series)
///
/// # Example
/// ```
/// use wasm4pm::wasm_utils::ewma_series;
/// let smoothed = ewma_series(r#"[1.0, 2.0, 3.0, 4.0, 5.0]"#, 0.5).unwrap();
/// ```
///
/// # Theory
/// `s[i] = α · x[i] + (1 - α) · s[i-1]` with `s[0] = x[0]`
#[wasm_bindgen]
pub fn ewma_series(values_json: &str, alpha: f64) -> Result<JsValue, JsValue> {
let values: Vec<f64> = serde_json::from_str(values_json)
.map_err(|e| crate::error::js_val(&format!("Invalid values JSON: {}", e)))?;
let smoothed = internal_ewma_series(&values, alpha);
to_js_str(&smoothed)
}
/// Identify activities with high variance (low frequency consistency).
///
/// Scans the event log and flags activities where:
/// - Occurrence count per trace varies widely (variance > threshold)
/// - Activity is sparse or bursty
///
/// # Arguments
/// * `eventlog_handle` — Handle from `load_eventlog_from_xes()`
/// * `activity_key` — Activity attribute name (e.g., "concept:name")
/// * `threshold` — Variance threshold; activities with variance > threshold are returned
///
/// # Returns
/// ```json
/// {
/// "high_variance_activities": [
/// {
/// "activity": "Inspect",
/// "variance": 2.45,
/// "min_per_trace": 0,
/// "max_per_trace": 5,
/// "mean_per_trace": 1.2,
/// "occurrence_count": 48
/// }
/// ],
/// "total_activities": 15
/// }
/// ```
#[wasm_bindgen]
pub fn identify_high_variance_activities(
eventlog_handle: &str,
activity_key: &str,
threshold: f64,
) -> Result<JsValue, JsValue> {
get_or_init_state().with_object(eventlog_handle, |obj| match obj {
Some(StoredObject::EventLog(log)) => {
use std::collections::HashMap;
// Count occurrences per trace
let mut activity_per_trace: HashMap<String, Vec<usize>> = HashMap::new();
for trace in &log.traces {
let mut trace_counts: HashMap<String, usize> = HashMap::new();
for event in &trace.events {
if let Some(AttributeValue::String(activity)) =
event.attributes.get(activity_key)
{
*trace_counts.entry(activity.clone()).or_insert(0) += 1;
}
}
for (activity, count) in trace_counts {
activity_per_trace.entry(activity).or_default().push(count);
}
}
// Compute variance and statistics for each activity
let mut high_variance: Vec<serde_json::Value> = Vec::new();
for (activity, counts) in &activity_per_trace {
if counts.is_empty() {
continue;
}
let mean = counts.iter().sum::<usize>() as f64 / counts.len() as f64;
let variance: f64 = counts
.iter()
.map(|&c| {
let diff = c as f64 - mean;
diff * diff
})
.sum::<f64>()
/ counts.len() as f64;
if variance > threshold {
let min_per_trace = *counts.iter().min().unwrap_or(&0);
let max_per_trace = *counts.iter().max().unwrap_or(&0);
let occurrence_count = counts.iter().sum::<usize>();
high_variance.push(json!({
"activity": activity,
"variance": variance,
"min_per_trace": min_per_trace,
"max_per_trace": max_per_trace,
"mean_per_trace": mean,
"occurrence_count": occurrence_count,
}));
}
}
high_variance.sort_by(|a, b| {
let var_a = a.get("variance").and_then(|v| v.as_f64()).unwrap_or(0.0);
let var_b = b.get("variance").and_then(|v| v.as_f64()).unwrap_or(0.0);
var_b
.partial_cmp(&var_a)
.unwrap_or(std::cmp::Ordering::Equal)
});
to_js_str(&json!({
"high_variance_activities": high_variance,
"total_activities": activity_per_trace.len(),
}))
}
Some(_) => Err(crate::error::js_val("Not an EventLog")),
None => Err(crate::error::js_val("EventLog not found")),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hash_xes_content_deterministic() {
let xes = r#"<?xml version="1.0" encoding="UTF-8"?><log></log>"#;
let h1 = internal_hash_xes(xes);
let h2 = internal_hash_xes(xes);
assert_eq!(h1, h2, "Hash must be deterministic");
}
#[test]
fn test_hash_xes_content_length() {
let xes = r#"<?xml version="1.0" encoding="UTF-8"?><log></log>"#;
let hash = internal_hash_xes(xes);
assert_eq!(hash.len(), 16, "FNV-1a hash should be 16 hex chars");
}
#[test]
fn test_jaccard_distance_identical_sets() {
let set = vec!["A", "B", "C"];
let json_set = serde_json::to_string(&set).unwrap();
let dist = internal_jaccard_distance(
&set.iter().map(|s| s.to_string()).collect(),
&set.iter().map(|s| s.to_string()).collect(),
);
assert_eq!(dist, 0.0, "Identical sets have distance 0");
}
#[test]
fn test_jaccard_distance_disjoint_sets() {
let set1: HashSet<String> = vec!["A", "B"].into_iter().map(|s| s.to_string()).collect();
let set2: HashSet<String> = vec!["C", "D"].into_iter().map(|s| s.to_string()).collect();
let dist = internal_jaccard_distance(&set1, &set2);
assert_eq!(dist, 1.0, "Disjoint sets have distance 1");
}
#[test]
fn test_jaccard_distance_empty_sets() {
let empty1: HashSet<String> = HashSet::new();
let empty2: HashSet<String> = HashSet::new();
let dist = internal_jaccard_distance(&empty1, &empty2);
assert_eq!(dist, 0.0, "Empty sets have distance 0 (no change)");
}
#[test]
fn test_ewma_series_constant_values() {
let values = vec![3.0, 3.0, 3.0, 3.0];
let smoothed = internal_ewma_series(&values, 0.5);
assert_eq!(smoothed.len(), 4);
for &val in &smoothed {
assert!((val - 3.0).abs() < 1e-10, "Constant series → constant EWMA");
}
}
#[test]
fn test_ewma_series_empty() {
let smoothed = internal_ewma_series(&[], 0.5);
assert!(smoothed.is_empty(), "Empty input → empty output");
}
#[test]
fn test_cache_stats_returns_valid_json() {
// This test only verifies the function doesn't crash
// Actual cache state depends on prior test execution
let _stats = internal_cache_stats();
// If we got here, the function succeeded
}
#[test]
fn test_ewma_series_single_value() {
let smoothed = internal_ewma_series(&[42.0], 0.5);
assert_eq!(smoothed.len(), 1);
assert_eq!(smoothed[0], 42.0, "Single value is identity");
}
#[test]
fn test_jaccard_distance_partial_overlap() {
let set1: HashSet<String> = vec!["A", "B", "C"]
.into_iter()
.map(|s| s.to_string())
.collect();
let set2: HashSet<String> = vec!["B", "C", "D"]
.into_iter()
.map(|s| s.to_string())
.collect();
let dist = internal_jaccard_distance(&set1, &set2);
// Union: {A, B, C, D} = 4, Intersection: {B, C} = 2
// Distance = 1 - (2/4) = 0.5
assert!(
(dist - 0.5).abs() < 1e-10,
"Partial overlap distance calculation"
);
}
}