wasm4pm 26.6.13

High-performance process mining algorithms in WebAssembly for JavaScript/TypeScript
Documentation
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
use crate::models::{parse_timestamp_ms, *};
use crate::state::{get_or_init_state, StoredObject};
use crate::utilities::to_js;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use wasm_bindgen::prelude::*;

/// Check data quality of an EventLog for common issues
#[wasm_bindgen]
pub fn check_data_quality(
    log_handle: &str,
    activity_key: &str,
    timestamp_key: &str,
) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(log_handle, |obj| match obj {
        Some(StoredObject::EventLog(log)) => {
            let mut issues = Vec::new();
            let mut missing_attrs: HashMap<String, usize> = HashMap::new();
            let mut has_ordering_issues = false;
            let mut has_duplicates = false;

            // Scan all traces
            for trace in &log.traces {
                let trace_id = trace
                    .attributes
                    .get("case_id")
                    .or_else(|| trace.attributes.get("id"))
                    .and_then(|v| v.as_string())
                    .unwrap_or("unknown")
                    .to_string();

                // Check for empty traces
                if trace.events.is_empty() {
                    issues.push(json!({
                        "type": "empty_trace",
                        "trace_id": trace_id
                    }));
                    continue;
                }

                // Check for timestamp ordering and invalid timestamps
                let mut prev_timestamp: Option<i64> = None;
                let mut event_signatures: HashMap<(String, String, String), usize> = HashMap::new();

                for (idx, event) in trace.events.iter().enumerate() {
                    // Check for missing values
                    if !event.attributes.contains_key(activity_key) {
                        *missing_attrs.entry(activity_key.to_string()).or_insert(0) += 1;
                    }
                    if !event.attributes.contains_key(timestamp_key) {
                        *missing_attrs.entry(timestamp_key.to_string()).or_insert(0) += 1;
                    }

                    // Validate and parse timestamp
                    if let Some(ts_val) = event.attributes.get(timestamp_key) {
                        if let Some(ts_str) = ts_val.as_string() {
                            if let Some(ts_ms) = parse_timestamp_ms(ts_str) {
                                // Check ordering
                                if let Some(prev) = prev_timestamp {
                                    if ts_ms < prev && !has_ordering_issues {
                                        issues.push(json!({
                                            "type": "timestamp_ordering",
                                            "trace_id": trace_id,
                                            "event_indices": [idx - 1, idx]
                                        }));
                                        has_ordering_issues = true;
                                    }
                                }
                                prev_timestamp = Some(ts_ms);
                            } else {
                                issues.push(json!({
                                    "type": "invalid_timestamp",
                                    "trace_id": trace_id,
                                    "event_index": idx,
                                    "value": ts_str
                                }));
                            }
                        }
                    }

                    // Build signature for duplicate detection (activity + timestamp + key attributes)
                    let activity = event
                        .attributes
                        .get(activity_key)
                        .and_then(|v| v.as_string())
                        .unwrap_or("unknown");
                    let timestamp = event
                        .attributes
                        .get(timestamp_key)
                        .and_then(|v| v.as_string())
                        .unwrap_or("unknown");
                    // Sort attributes by key to ensure deterministic hashing
                    let mut sorted_attrs: Vec<_> = event.attributes.iter().collect();
                    sorted_attrs.sort_by_key(|(k, _)| k.as_str());
                    let sig = (
                        activity.to_string(),
                        timestamp.to_string(),
                        format!("{:?}", sorted_attrs),
                    );

                    *event_signatures.entry(sig).or_insert(0) += 1;
                }

                // Report duplicates
                for (_, count) in event_signatures {
                    if count > 1 && !has_duplicates {
                        issues.push(json!({
                            "type": "duplicate_events",
                            "trace_id": trace_id,
                            "count": count
                        }));
                        has_duplicates = true;
                    }
                }
            }

            // Add missing value issues
            for (attr, count) in missing_attrs.iter() {
                issues.push(json!({
                    "type": "missing_value",
                    "attribute": attr,
                    "event_count": count
                }));
            }

            let valid = issues.is_empty();
            let result = json!({
                "valid": valid,
                "issues": issues,
                "total_issues": issues.len()
            });

            to_js(&result)
        }
        Some(_) => Err(crate::error::js_val("Object is not an EventLog")),
        None => Err(crate::error::js_val("EventLog not found")),
    })
}

/// Check data quality of an OCEL
#[wasm_bindgen]
pub fn check_ocel_data_quality(ocel_handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(ocel_handle, |obj| match obj {
        Some(StoredObject::OCEL(ocel)) => {
            let mut issues = Vec::new();

            // Build set of valid object IDs
            let valid_object_ids: HashSet<String> =
                ocel.objects.iter().map(|o| o.id.clone()).collect();

            // Check referential integrity: events reference existing objects
            for event in &ocel.events {
                for obj_id in event.all_object_ids() {
                    if !valid_object_ids.contains(obj_id) {
                        issues.push(json!({
                            "type": "missing_object_reference",
                            "event_id": event.id,
                            "object_id": obj_id
                        }));
                    }
                }
            }

            // Check for orphan objects (objects not referenced by any event)
            let mut referenced_objects = HashSet::new();
            for event in &ocel.events {
                for obj_id in event.all_object_ids() {
                    referenced_objects.insert(obj_id.to_string());
                }
            }

            for object in &ocel.objects {
                if !referenced_objects.contains(&object.id) {
                    issues.push(json!({
                        "type": "orphan_object",
                        "object_id": object.id,
                        "object_type": object.object_type
                    }));
                }
            }

            // Check object relations: verify both source and target exist
            for relation in &ocel.object_relations {
                if !valid_object_ids.contains(&relation.source_id) {
                    issues.push(json!({
                        "type": "invalid_relation_source",
                        "source_id": relation.source_id,
                        "target_id": relation.target_id
                    }));
                }
                if !valid_object_ids.contains(&relation.target_id) {
                    issues.push(json!({
                        "type": "invalid_relation_target",
                        "source_id": relation.source_id,
                        "target_id": relation.target_id
                    }));
                }
            }

            // Check timestamp consistency: events and objects should have valid timestamps
            for event in &ocel.events {
                if parse_timestamp_ms(&event.timestamp).is_none() {
                    issues.push(json!({
                        "type": "invalid_event_timestamp",
                        "event_id": event.id,
                        "value": event.timestamp
                    }));
                }
            }

            for object in &ocel.objects {
                for change in &object.changes {
                    if parse_timestamp_ms(&change.timestamp).is_none() {
                        issues.push(json!({
                            "type": "invalid_object_timestamp",
                            "object_id": object.id,
                            "value": change.timestamp
                        }));
                    }
                }
            }

            let valid = issues.is_empty();
            let result = json!({
                "valid": valid,
                "issues": issues,
                "total_issues": issues.len()
            });

            to_js(&result)
        }
        Some(_) => Err(crate::error::js_val("Object is not an OCEL")),
        None => Err(crate::error::js_val("OCEL not found")),
    })
}

/// Infer schema from EventLog by analyzing attribute patterns
#[wasm_bindgen]
pub fn infer_eventlog_schema(log_handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(log_handle, |obj| match obj {
        Some(StoredObject::EventLog(log)) => {
            // Collect all attributes and their value distributions
            let mut attr_stats: HashMap<String, AttributeStats> = HashMap::new();

            // Process log-level attributes
            for (key, val) in &log.attributes {
                attr_stats.entry(key.clone()).or_default().observe(val);
            }

            // Process trace-level and event-level attributes
            for trace in &log.traces {
                for (key, val) in &trace.attributes {
                    attr_stats.entry(key.clone()).or_default().observe(val);
                }
                for event in &trace.events {
                    for (key, val) in &event.attributes {
                        attr_stats.entry(key.clone()).or_default().observe(val);
                    }
                }
            }

            // Infer keys based on patterns
            let activity_key = infer_activity_key(&attr_stats);
            let timestamp_key = infer_timestamp_key(&attr_stats);
            let resource_key = infer_resource_key(&attr_stats);
            let case_id_key = infer_case_id_key(log, &attr_stats);

            // Build attribute types map
            let mut attribute_types: HashMap<String, String> = HashMap::new();
            for (key, stats) in attr_stats {
                attribute_types.insert(key, stats.infer_type());
            }

            // Estimate confidence (high if we found strong candidates)
            let confidence = if activity_key.is_some() && timestamp_key.is_some() {
                0.95
            } else if activity_key.is_some() || timestamp_key.is_some() {
                0.70
            } else {
                0.40
            };

            let result = json!({
                "inferred_keys": {
                    "activity_key": activity_key.unwrap_or_else(|| "activity".to_string()),
                    "timestamp_key": timestamp_key.unwrap_or_else(|| "timestamp".to_string()),
                    "resource_key": resource_key.unwrap_or_else(|| "performer".to_string()),
                    "case_id_key": case_id_key.unwrap_or_else(|| "case_id".to_string())
                },
                "attribute_types": attribute_types,
                "confidence": confidence
            });

            to_js(&result)
        }
        Some(_) => Err(crate::error::js_val("Object is not an EventLog")),
        None => Err(crate::error::js_val("EventLog not found")),
    })
}

/// Infer schema from OCEL
#[wasm_bindgen]
pub fn infer_ocel_schema(ocel_handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(ocel_handle, |obj| match obj {
        Some(StoredObject::OCEL(ocel)) => {
            // Event type distribution
            let mut event_types: HashMap<String, usize> = HashMap::new();
            for event in &ocel.events {
                *event_types.entry(event.event_type.clone()).or_insert(0) += 1;
            }

            // Object type distribution
            let mut object_types: HashMap<String, usize> = HashMap::new();
            for object in &ocel.objects {
                *object_types.entry(object.object_type.clone()).or_insert(0) += 1;
            }

            // Relationship patterns (source_type -> target_type counts)
            let mut relationships: HashMap<(String, String), usize> = HashMap::new();
            for relation in &ocel.object_relations {
                // Find types of source and target objects
                let source_type = ocel
                    .objects
                    .iter()
                    .find(|o| o.id == relation.source_id)
                    .map(|o| o.object_type.clone());
                let target_type = ocel
                    .objects
                    .iter()
                    .find(|o| o.id == relation.target_id)
                    .map(|o| o.object_type.clone());

                if let (Some(st), Some(tt)) = (source_type, target_type) {
                    *relationships.entry((st, tt)).or_insert(0) += 1;
                }
            }

            // Build common_relationships list sorted by frequency
            let mut common_rels: Vec<_> = relationships.into_iter().collect();
            common_rels.sort_by_key(|b| std::cmp::Reverse(b.1));
            let common_relationships: Vec<Value> = common_rels
                .into_iter()
                .map(|((src, tgt), cnt)| {
                    json!({
                        "source_type": src,
                        "target_type": tgt,
                        "count": cnt
                    })
                })
                .collect();

            // Analyze event-object qualifiers (co-occurrence patterns)
            let mut qualifiers: HashMap<String, usize> = HashMap::new();
            for event in &ocel.events {
                for obj_ref in &event.object_refs {
                    *qualifiers.entry(obj_ref.qualifier.clone()).or_insert(0) += 1;
                }
            }

            let result = json!({
                "event_types": event_types,
                "object_types": object_types,
                "common_relationships": common_relationships,
                "event_object_qualifiers": qualifiers,
                "total_events": ocel.events.len(),
                "total_objects": ocel.objects.len(),
                "total_relations": ocel.object_relations.len()
            });

            to_js(&result)
        }
        Some(_) => Err(crate::error::js_val("Object is not an OCEL")),
        None => Err(crate::error::js_val("OCEL not found")),
    })
}

// === Helper Structures and Functions ===

/// Statistics about attribute values to support type inference
#[derive(Debug, Clone, Default)]
struct AttributeStats {
    count: usize,
    is_string: usize,
    is_numeric: usize,
    is_boolean: usize,
    is_date: usize,
    sample_values: Vec<String>,
}

impl AttributeStats {
    fn observe(&mut self, val: &AttributeValue) {
        self.count += 1;
        match val {
            AttributeValue::String(s) => {
                self.is_string += 1;
                if self.sample_values.len() < 3 {
                    self.sample_values.push(s.clone());
                }
            }
            AttributeValue::Int(_) => self.is_numeric += 1,
            AttributeValue::Float(_) => self.is_numeric += 1,
            AttributeValue::Date(s) => {
                self.is_date += 1;
                if self.sample_values.len() < 3 {
                    self.sample_values.push(s.clone());
                }
            }
            AttributeValue::Boolean(_) => self.is_boolean += 1,
            _ => {}
        }
    }

    fn infer_type(&self) -> String {
        if self.count == 0 {
            return "unknown".to_string();
        }

        // Determine type based on dominant value kind
        let total = self.count as f64;
        let pct_numeric = self.is_numeric as f64 / total;
        let pct_date = self.is_date as f64 / total;
        let pct_boolean = self.is_boolean as f64 / total;

        if pct_boolean > 0.8 {
            "boolean".to_string()
        } else if pct_date > 0.8 {
            "datetime".to_string()
        } else if pct_numeric > 0.8 {
            "numeric".to_string()
        } else {
            "string".to_string()
        }
    }
}

/// Infer activity key by looking for attributes with many unique values and common names
fn infer_activity_key(attr_stats: &HashMap<String, AttributeStats>) -> Option<String> {
    let activity_keywords = ["activity", "event", "action", "task", "event_type", "type"];

    // First try exact keyword matches
    for keyword in &activity_keywords {
        if attr_stats.contains_key(*keyword) {
            return Some(keyword.to_string());
        }
    }

    // Then try case-insensitive substring matches
    for key in attr_stats.keys() {
        for keyword in &activity_keywords {
            if key.to_lowercase().contains(keyword) {
                return Some(key.clone());
            }
        }
    }

    None
}

/// Infer timestamp key by looking for datetime attributes or common timestamp names
fn infer_timestamp_key(attr_stats: &HashMap<String, AttributeStats>) -> Option<String> {
    let timestamp_keywords = ["timestamp", "time", "date", "start_time", "end_time", "ts"];

    // First pass: look for attributes with high date type density
    let mut date_candidates: Vec<(String, usize)> = attr_stats
        .iter()
        .filter(|(_, stats)| stats.is_date > 0)
        .map(|(k, stats)| (k.clone(), stats.is_date))
        .collect();
    date_candidates.sort_by_key(|b| std::cmp::Reverse(b.1));

    if let Some((key, _)) = date_candidates.first() {
        return Some(key.clone());
    }

    // Second pass: try keyword matching
    for keyword in &timestamp_keywords {
        if attr_stats.contains_key(*keyword) {
            return Some(keyword.to_string());
        }
    }

    for key in attr_stats.keys() {
        for keyword in &timestamp_keywords {
            if key.to_lowercase().contains(keyword) {
                return Some(key.clone());
            }
        }
    }

    None
}

/// Infer resource key by looking for high-cardinality string attributes
fn infer_resource_key(attr_stats: &HashMap<String, AttributeStats>) -> Option<String> {
    let resource_keywords = [
        "resource",
        "performer",
        "user",
        "agent",
        "executor",
        "responsible",
    ];

    // First try exact keyword matches
    for keyword in &resource_keywords {
        if attr_stats.contains_key(*keyword) {
            return Some(keyword.to_string());
        }
    }

    // Then try case-insensitive substring matches
    for key in attr_stats.keys() {
        for keyword in &resource_keywords {
            if key.to_lowercase().contains(keyword) {
                return Some(key.clone());
            }
        }
    }

    // Fallback: find string attribute with moderate cardinality (not too few, not too many)
    let mut candidates: Vec<(String, usize)> = attr_stats
        .iter()
        .filter(|(_, stats)| stats.is_string > stats.count / 2)
        .map(|(k, stats)| (k.clone(), stats.is_string))
        .collect();
    candidates.sort_by_key(|b| std::cmp::Reverse(b.1));

    candidates.first().map(|(k, _)| k.clone())
}

/// Infer case ID key by matching trace attributes to log structure
fn infer_case_id_key(
    log: &EventLog,
    attr_stats: &HashMap<String, AttributeStats>,
) -> Option<String> {
    let case_keywords = [
        "case_id",
        "case",
        "trace_id",
        "id",
        "process_id",
        "instance",
    ];

    // First try exact keyword matches
    for keyword in &case_keywords {
        if attr_stats.contains_key(*keyword) {
            return Some(keyword.to_string());
        }
    }

    // Then try case-insensitive substring matches in trace attributes
    for trace in &log.traces {
        for key in trace.attributes.keys() {
            for keyword in &case_keywords {
                if key.to_lowercase().contains(keyword) {
                    return Some(key.clone());
                }
            }
        }
    }

    None
}