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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! Process discovery algorithms: DFG, OCEL, Declare, and related utilities.
//!
//! All WASM exports follow the **handle pattern**: call `load_eventlog_from_xes()`
//! to obtain an opaque handle string, then pass it to any `discover_*` function.
//!
//! [`discover_dfg_from_log`] is the pure-Rust variant (no WASM boundary) used
//! directly by integration tests in `wasm4pm/tests/`.
//!
//! ## Output shapes (JSON string — JS caller must `JSON.parse()`)
//!
//! | Function | Top-level keys |
//! |---|---|
//! | `discover_dfg` | `nodes[]`, `edges[]`, `start_activities[]`, `end_activities[]` |
//! | `discover_declare` | `constraints[]` |
//! | `discover_ocel_dfg` | per-type DFG maps |
use crate::error::{codes, wasm_err};
use crate::models::*;
use crate::state::{get_or_init_state, StoredObject};
use crate::utilities::to_js_str;
use rustc_hash::{FxHashMap, FxHashSet};
use serde_json::json;
use wasm_bindgen::prelude::*;
/// Pure-Rust DFG discovery without wasm-bindgen. Used by integration tests.
#[must_use]
pub fn discover_dfg_from_log<W>(log: &AdmittedEventLog<W>, activity_key: &str) -> DFG {
let mut dfg = DFG::new();
let col_owned = log.value.to_columnar_owned(activity_key);
let col = ColumnarLog::from_owned(&col_owned);
dfg.nodes.extend(col.vocab.iter().map(|&act| DFGNode {
id: act.to_owned(),
label: act.to_owned(),
frequency: 0,
}));
// Pre-size the edge map to n²/4 as a rough initial capacity — avoids most
// rehashes for typical logs where the DFG is sparse relative to n².
let n = col.vocab.len();
let mut edge_counts: FxHashMap<(u32, u32), usize> =
FxHashMap::with_capacity_and_hasher(n.saturating_mul(n) / 4 + 1, Default::default());
for t in 0..col.trace_offsets.len().saturating_sub(1) {
let start = col.trace_offsets[t];
let end = col.trace_offsets[t + 1];
if start >= end {
continue;
}
for &id in &col.events[start..end] {
dfg.nodes[id as usize].frequency += 1;
}
for i in start..end - 1 {
*edge_counts
.entry((col.events[i], col.events[i + 1]))
.or_insert(0) += 1;
}
*dfg.start_activities
.entry(col.vocab[col.events[start] as usize].to_owned())
.or_insert(0) += 1;
*dfg.end_activities
.entry(col.vocab[col.events[end - 1] as usize].to_owned())
.or_insert(0) += 1;
}
let mut sorted_edges: Vec<_> = edge_counts.into_iter().collect();
// Sort by source then target index to ensure deterministic order (Gap-1)
sorted_edges.sort_unstable_by_key(|&((f, t), _)| (f, t));
dfg.edges.extend(
sorted_edges
.into_iter()
.map(|((f, t), freq)| DirectlyFollowsRelation {
from: col.vocab[f as usize].to_owned(),
to: col.vocab[t as usize].to_owned(),
frequency: freq,
}),
);
dfg
}
/// Discover a Directly-Follows Graph (DFG) from an event log.
///
/// # Parameters
/// * `eventlog_handle` — Handle string returned by `load_eventlog_from_xes` or `load_eventlog_from_json`.
/// * `activity_key` — XES attribute name to use as activity label (e.g. `"concept:name"`).
///
/// # Returns
/// `Result<JsValue, JsValue>` — On success, a JS value (parse with `JSON.parse` if it is a
/// string) containing:
/// ```json
/// {
/// "nodes": [{"id": "...", "label": "...", "frequency": 42}],
/// "edges": [{"from": "A", "to": "B", "frequency": 17}],
/// "start_activities": {"A": 10},
/// "end_activities": {"C": 5}
/// }
/// ```
///
/// # Note
/// DFG construction is always successful for any valid event log (empty or otherwise).
/// The function never returns `None` and never panics.
/// For a sound process tree, use `discover_inductive_miner` instead.
#[wasm_bindgen]
pub fn discover_dfg(eventlog_handle: &str, activity_key: &str) -> Result<JsValue, JsValue> {
// Use with_object to borrow the log in place — avoids a full EventLog clone.
// discover_dfg_from_log builds its own columnar view internally, so we only
// need a shared reference, not an owned copy.
get_or_init_state().with_object(eventlog_handle, |obj| match obj {
Some(StoredObject::EventLog(log)) => {
let log_size = log.traces.len();
tracing::info!(
target: "wasm4pm.discovery.dfg",
algorithm = "dfg",
log_size = log_size,
activity_key = activity_key,
"DFG discovery started"
);
let admitted =
wasm4pm_compat::admission::Admission::<_, ()>::new(log.clone()).into_evidence();
let dfg = discover_dfg_from_log(&admitted, activity_key);
// Derive activity_count from the already-built DFG nodes — avoids
// a second full columnar pass that was previously done by get_activities().
let node_count = dfg.nodes.len();
let edge_count = dfg.edges.len();
let complexity = if node_count > 0 {
edge_count as f64 / node_count as f64
} else {
0.0
};
tracing::info!(
target: "wasm4pm.discovery.dfg",
checkpoint = "feature_extraction",
activity_count = node_count,
"Activity vocabulary extracted"
);
tracing::info!(
target: "wasm4pm.discovery.dfg",
checkpoint = "result_generation",
node_count = node_count,
edge_count = edge_count,
complexity = complexity,
"DFG discovery completed"
);
to_js_str(&dfg)
}
Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not an EventLog")),
None => Err(wasm_err(
codes::INVALID_HANDLE,
format!("EventLog '{}' not found", eventlog_handle),
)),
})
}
/// Pure-Rust OCEL DFG discovery: returns DFG without wasm-bindgen.
///
/// This is the testable core of `discover_ocel_dfg`. Integration tests
/// on native targets cannot call `#[wasm_bindgen]` functions, so they use
/// this instead.
#[must_use]
pub fn discover_ocel_dfg_pure(ocel: &OCEL) -> DFG {
let mut dfg = DFG::new();
// Get event types
for event_type in &ocel.event_types {
dfg.nodes.push(DFGNode {
id: event_type.clone(),
label: event_type.clone(),
frequency: 0,
});
}
// Count event type frequencies
for event in &ocel.events {
if let Some(node) = dfg.nodes.iter_mut().find(|n| n.id == event.event_type) {
node.frequency += 1;
}
}
// Get directly-follows relations within same objects
let mut events_by_object: FxHashMap<String, Vec<(usize, &str)>> = FxHashMap::default();
for (idx, event) in ocel.events.iter().enumerate() {
for obj_id in event.all_object_ids() {
events_by_object
.entry(obj_id.to_string())
.or_default()
.push((idx, event.event_type.as_str()));
}
}
// Sort events by timestamp (ISO 8601 sorts lexicographically without parsing).
// Use sort_unstable_by + str comparison to avoid allocating a String per comparison.
for events in events_by_object.values_mut() {
events.sort_unstable_by(|(ai, _), (bi, _)| {
ocel.events[*ai]
.timestamp
.as_str()
.cmp(ocel.events[*bi].timestamp.as_str())
});
}
// Build an edge map with &str keys — avoids one String allocation per DF pair.
// The strings are borrowed from the OCEL event_type fields which outlive this scope.
let mut edge_map: FxHashMap<(&str, &str), usize> = FxHashMap::default();
for events in events_by_object.values() {
for pair in events.windows(2) {
let from = pair[0].1;
let to = pair[1].1;
*edge_map.entry((from, to)).or_insert(0) += 1;
}
}
// Sort by the borrowed keys — no clone needed since (&str, &str) is Ord.
let mut sorted_edges: Vec<_> = edge_map.into_iter().collect();
sorted_edges.sort_unstable_by_key(|&((f, t), _)| (f, t));
for ((from, to), frequency) in sorted_edges {
dfg.edges.push(DirectlyFollowsRelation {
from: from.to_owned(),
to: to.to_owned(),
frequency,
});
}
// Collect start/end event types using .first()/.last() to eliminate
// manual bounds checks and the len()-1 index expression.
for obj_id in events_by_object.keys() {
if let Some(events) = events_by_object.get(obj_id) {
if let Some(first) = events.first() {
*dfg.start_activities.entry(first.1.to_string()).or_insert(0) += 1;
}
if let Some(last) = events.last() {
*dfg.end_activities.entry(last.1.to_string()).or_insert(0) += 1;
}
}
}
dfg
}
/// Discover a Directly-Follows Graph (DFG) from an OCEL
#[wasm_bindgen]
pub fn discover_ocel_dfg(ocel_handle: &str) -> Result<JsValue, JsValue> {
get_or_init_state().with_object(ocel_handle, |obj| match obj {
Some(StoredObject::OCEL(ocel)) => {
let dfg = discover_ocel_dfg_pure(ocel);
to_js_str(&dfg)
}
Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not an OCEL")),
None => Err(wasm_err(
codes::INVALID_HANDLE,
format!("OCEL '{}' not found", ocel_handle),
)),
})
}
#[inline(always)]
fn bitmask_mark(mask: &mut u64, id: usize) {
*mask |= 1u64 << id;
}
#[inline(always)]
fn bitmask_check(mask: u64, id: usize) -> bool {
(mask >> id) & 1 == 1
}
/// Discover a Directly-Follows Graph (DFG) per object type from an OCEL
#[wasm_bindgen]
pub fn discover_ocel_dfg_per_type(ocel_handle: &str) -> Result<JsValue, JsValue> {
get_or_init_state().with_object(ocel_handle, |obj| match obj {
Some(StoredObject::OCEL(ocel)) => {
let mut result: FxHashMap<String, DFG> = FxHashMap::default();
// Build sorted activity vocabulary for stable index assignment
let mut activity_vocab: Vec<String> = {
let mut seen: FxHashSet<&str> = FxHashSet::default();
ocel.events
.iter()
.filter_map(|e| {
if seen.insert(e.event_type.as_str()) {
Some(e.event_type.clone())
} else {
None
}
})
.collect()
};
activity_vocab.sort_unstable();
let activity_count = activity_vocab.len();
// Reverse lookup: activity name → index (used by bitmask fast path)
let activity_index: FxHashMap<&str, usize> = activity_vocab
.iter()
.enumerate()
.map(|(i, s)| (s.as_str(), i))
.collect();
let use_bitmask = activity_count <= 64;
// Fix C: pre-compute global activity frequencies once, outside the per-type loop
let global_activity_counts: FxHashMap<String, usize> = {
let mut m: FxHashMap<String, usize> = FxHashMap::default();
for event in &ocel.events {
*m.entry(event.event_type.clone()).or_insert(0) += 1;
}
m
};
// For each object type, discover a separate DFG
for obj_type in &ocel.object_types {
let mut dfg = DFG::new();
for name in &activity_vocab {
dfg.nodes.push(DFGNode {
id: name.clone(),
label: name.clone(),
frequency: 0,
});
}
// Get all events for objects of this type
let mut events_by_object: FxHashMap<String, Vec<(usize, &str)>> =
FxHashMap::default();
for obj in &ocel.objects {
if &obj.object_type == obj_type {
events_by_object.insert(obj.id.clone(), Vec::new());
}
}
// Collect events for each object of this type
for (idx, event) in ocel.events.iter().enumerate() {
for obj_id in event.all_object_ids() {
if let Some(events) = events_by_object.get_mut(obj_id) {
events.push((idx, event.event_type.as_str()));
}
}
}
// Sort events by timestamp (ISO 8601 sorts lexicographically without parsing).
// sort_unstable_by with str comparison avoids a String allocation per comparison.
for events in events_by_object.values_mut() {
events.sort_unstable_by(|(ai, _), (bi, _)| {
ocel.events[*ai]
.timestamp
.as_str()
.cmp(ocel.events[*bi].timestamp.as_str())
});
}
// Fix C: use pre-computed global activity frequencies
for node in &mut dfg.nodes {
if let Some(count) = global_activity_counts.get(&node.id) {
node.frequency = *count;
}
}
// Use &str keys to avoid one String allocation per DF pair in the hot loop.
let mut edge_map: FxHashMap<(&str, &str), usize> = FxHashMap::default();
for events in events_by_object.values() {
for pair in events.windows(2) {
let from = pair[0].1;
let to = pair[1].1;
*edge_map.entry((from, to)).or_insert(0) += 1;
}
}
for ((from, to), freq) in edge_map {
dfg.edges.push(DirectlyFollowsRelation {
from: from.to_owned(),
to: to.to_owned(),
frequency: freq,
});
}
// Collect start/end activities (now correctly using events_by_object.keys())
let mut trace_seen_bitmask: u64 = 0u64;
for obj_id in events_by_object.keys() {
if let Some(events) = events_by_object.get(obj_id) {
if let Some(first) = events.first() {
*dfg.start_activities.entry(first.1.to_string()).or_insert(0) += 1;
if use_bitmask {
if let Some(&id) = activity_index.get(first.1) {
bitmask_mark(&mut trace_seen_bitmask, id);
}
}
}
if let Some(last) = events.last() {
*dfg.end_activities.entry(last.1.to_string()).or_insert(0) += 1;
}
}
}
let _ = (trace_seen_bitmask, bitmask_check);
result.insert(obj_type.clone(), dfg);
}
// Return as JSON: { "Order": { ... DFG ... }, "Item": { ... } }
to_js_str(&result)
}
Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not an OCEL")),
None => Err(wasm_err(
codes::INVALID_HANDLE,
format!("OCEL '{}' not found", ocel_handle),
)),
})
}
struct TraceProfile {
/// Bitmask of present activities (A <= 128).
activity_mask: u128,
/// first_position[a] = index of first occurrence of activity a in trace
/// (or usize::MAX if not present).
first_positions: Vec<usize>,
/// last_position[a] = index of last occurrence of activity a in trace
/// (or usize::MAX if not present).
last_positions: Vec<usize>,
/// immediate_follows[(a,b)] = true if a is immediately followed by b at least once.
/// FxHashSet is ~2× faster than std HashSet for small integer tuple keys because
/// it skips the SipHash DoS-resistance overhead irrelevant for internal data.
immediate_follows: FxHashSet<(u32, u32)>,
}
impl TraceProfile {
fn new(n: usize) -> Self {
TraceProfile {
activity_mask: 0,
first_positions: vec![usize::MAX; n],
last_positions: vec![usize::MAX; n],
immediate_follows: FxHashSet::default(),
}
}
/// Mark activity as present at given position.
fn mark_activity(&mut self, activity_idx: usize, position: usize) {
if activity_idx < 128 {
self.activity_mask |= 1u128 << (activity_idx as u128);
}
if self.first_positions[activity_idx] == usize::MAX {
self.first_positions[activity_idx] = position;
}
self.last_positions[activity_idx] = position;
}
/// Check if activity a appeared before activity b in this trace.
#[inline(always)]
fn appears_before(&self, a: usize, b: usize) -> bool {
let fa = self.first_positions[a];
let fb = self.first_positions[b];
(fa != usize::MAX) & (fb != usize::MAX) & (fa < fb)
}
/// Check if activity a appeared after activity b in this trace.
#[allow(dead_code)]
#[inline(always)]
fn appears_after(&self, a: usize, b: usize) -> bool {
let la = self.last_positions[a];
let fb = self.first_positions[b];
(la != usize::MAX) & (fb != usize::MAX) & (la > fb)
}
}
/// Discover DECLARE constraints from an EventLog
#[wasm_bindgen]
pub fn discover_declare(eventlog_handle: &str, activity_key: &str) -> Result<JsValue, JsValue> {
tracing::info!(
target: "wasm4pm.discovery.declare",
algorithm = "declare",
activity_key = activity_key,
"DECLARE discovery started"
);
get_or_init_state().with_object(eventlog_handle, |obj| match obj {
Some(StoredObject::EventLog(log)) => {
let mut model = DeclareModel::new();
let col_owned = crate::cache::columnar_cache_get(eventlog_handle, activity_key)
.unwrap_or_else(|| {
let owned = log.to_columnar_owned(activity_key);
crate::cache::columnar_cache_insert(
eventlog_handle.to_string(),
activity_key.to_string(),
owned.clone(),
);
owned
});
let col = ColumnarLog::from_owned(&col_owned);
let n = col.vocab.len();
let total_cases = col.trace_offsets.len().saturating_sub(1);
tracing::info!(
target: "wasm4pm.discovery.declare",
checkpoint = "feature_extraction",
activity_count = n,
trace_count = total_cases,
"Activity vocabulary and case counts extracted"
);
model.activities = col.vocab.iter().map(|s| s.to_string()).collect();
if n == 0 || total_cases == 0 {
tracing::info!(
target: "wasm4pm.discovery.declare",
checkpoint = "empty_log",
activity_count = n,
trace_count = total_cases,
"Empty log detected"
);
return to_js_str(&model);
}
// Phase 1: Build TraceProfile for each trace
let mut traces_profiles: Vec<TraceProfile> = Vec::with_capacity(total_cases);
for t in 0..total_cases {
let start = col.trace_offsets[t];
let end = col.trace_offsets[t + 1];
let mut profile = TraceProfile::new(n);
if start < end {
for pos in 0..(end - start) {
let activity_id = col.events[start + pos];
profile.mark_activity(activity_id as usize, pos);
if pos < (end - start - 1) {
profile
.immediate_follows
.insert((activity_id, col.events[start + pos + 1]));
}
}
}
traces_profiles.push(profile);
}
tracing::info!(
target: "wasm4pm.discovery.declare",
checkpoint = "profile_building",
profiles_count = traces_profiles.len(),
"Trace profiles built"
);
// Phase 2: Iterate over activity pairs and count template matches
let mut activity_counts = vec![0u32; n];
for profile in &traces_profiles {
for (a, count) in activity_counts.iter_mut().enumerate() {
if profile.first_positions[a] != usize::MAX {
*count += 1;
}
}
}
let total_f64 = total_cases as f64;
let min_support = 0.1;
let min_confidence = 0.8;
for a in 0..n {
let support = activity_counts[a] as f64 / total_f64;
if support >= min_support {
model.constraints.push(DeclareConstraint {
template: "Existence".to_string(),
activities: vec![col.vocab[a].to_string()],
support,
confidence: 1.0,
});
} else if (1.0 - support) >= min_support {
model.constraints.push(DeclareConstraint {
template: "Absence".to_string(),
activities: vec![col.vocab[a].to_string()],
support: 1.0 - support,
confidence: 1.0,
});
}
for b in 0..n {
if a == b {
continue;
}
let mut both_count = 0;
let mut a_before_b_count = 0;
let mut a_immediately_before_b_count = 0;
for profile in &traces_profiles {
let has_a = profile.first_positions[a] != usize::MAX;
let has_b = profile.first_positions[b] != usize::MAX;
if has_a && has_b {
both_count += 1;
if profile.appears_before(a, b) {
a_before_b_count += 1;
}
if profile.immediate_follows.contains(&(a as u32, b as u32)) {
a_immediately_before_b_count += 1;
}
}
}
// CoExistence
if a < b {
let coex_support = both_count as f64 / total_f64;
if coex_support >= min_support {
model.constraints.push(DeclareConstraint {
template: "CoExistence".to_string(),
activities: vec![
col.vocab[a].to_string(),
col.vocab[b].to_string(),
],
support: coex_support,
confidence: 1.0,
});
}
// NotCoExistence
let not_coex_support = (total_cases - both_count) as f64 / total_f64;
if not_coex_support >= 0.9 {
model.constraints.push(DeclareConstraint {
template: "NotCoExistence".to_string(),
activities: vec![
col.vocab[a].to_string(),
col.vocab[b].to_string(),
],
support: not_coex_support,
confidence: 1.0,
});
}
}
// Response: A -> eventually B
if activity_counts[a] > 0 {
let conf = a_before_b_count as f64 / activity_counts[a] as f64;
if conf >= min_confidence {
model.constraints.push(DeclareConstraint {
template: "Response".to_string(),
activities: vec![
col.vocab[a].to_string(),
col.vocab[b].to_string(),
],
support: a_before_b_count as f64 / total_f64,
confidence: conf,
});
}
}
// Precedence: B -> always preceded by A
if activity_counts[b] > 0 {
let conf = a_before_b_count as f64 / activity_counts[b] as f64;
if conf >= min_confidence {
model.constraints.push(DeclareConstraint {
template: "Precedence".to_string(),
activities: vec![
col.vocab[a].to_string(),
col.vocab[b].to_string(),
],
support: a_before_b_count as f64 / total_f64,
confidence: conf,
});
}
}
// Succession: Response + Precedence
if activity_counts[a] > 0 && activity_counts[b] > 0 {
let conf_a = a_before_b_count as f64 / activity_counts[a] as f64;
let conf_b = a_before_b_count as f64 / activity_counts[b] as f64;
if conf_a >= min_confidence && conf_b >= min_confidence {
model.constraints.push(DeclareConstraint {
template: "Succession".to_string(),
activities: vec![
col.vocab[a].to_string(),
col.vocab[b].to_string(),
],
support: a_before_b_count as f64 / total_f64,
confidence: (conf_a + conf_b) / 2.0,
});
}
}
// ChainResponse: A -> immediately B
if activity_counts[a] > 0 {
let conf = a_immediately_before_b_count as f64 / activity_counts[a] as f64;
if conf >= min_confidence {
model.constraints.push(DeclareConstraint {
template: "ChainResponse".to_string(),
activities: vec![
col.vocab[a].to_string(),
col.vocab[b].to_string(),
],
support: a_immediately_before_b_count as f64 / total_f64,
confidence: conf,
});
}
}
// ChainPrecedence: B -> always immediately preceded by A
if activity_counts[b] > 0 {
let conf = a_immediately_before_b_count as f64 / activity_counts[b] as f64;
if conf >= min_confidence {
model.constraints.push(DeclareConstraint {
template: "ChainPrecedence".to_string(),
activities: vec![
col.vocab[a].to_string(),
col.vocab[b].to_string(),
],
support: a_immediately_before_b_count as f64 / total_f64,
confidence: conf,
});
}
}
}
}
let constraint_count = model.constraints.len();
tracing::info!(
target: "wasm4pm.discovery.declare",
checkpoint = "result_generation",
constraint_count = constraint_count,
activity_count = n,
"DECLARE discovery completed"
);
to_js_str(&model)
}
Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not an EventLog")),
None => Err(wasm_err(
codes::INVALID_HANDLE,
format!("EventLog '{}' not found", eventlog_handle),
)),
})
}
/// Get list of available discovery algorithms
#[wasm_bindgen]
pub fn available_discovery_algorithms() -> JsValue {
to_js_str(&json!({
"algorithms": [
{
"name": "dfg",
"description": "Directly-Follows Graph discovery from EventLog",
"input": "EventLog",
"parameters": ["activity_key"],
"status": "implemented"
},
{
"name": "ocel_dfg",
"description": "Object-Centric Directly-Follows Graph discovery",
"input": "OCEL",
"parameters": [],
"status": "implemented"
},
{
"name": "declare",
"description": "DECLARE constraint discovery",
"input": "EventLog",
"parameters": ["activity_key"],
"status": "implemented"
},
{
"name": "causal_alpha",
"description": "Causal graph discovery using alpha miner variant (binary causality)",
"input": "EventLog",
"parameters": ["activity_key"],
"status": "implemented"
},
{
"name": "causal_heuristic",
"description": "Causal graph discovery using heuristic variant (threshold-based)",
"input": "EventLog",
"parameters": ["activity_key", "threshold"],
"status": "implemented"
},
{
"name": "alpha_plus_plus",
"description": "Alpha++ algorithm for Petri net discovery",
"input": "EventLog",
"parameters": ["activity_key", "min_support"],
"status": "planned"
}
]
}))
.unwrap_or(JsValue::NULL)
}
/// Get discovery module info
#[wasm_bindgen]
pub fn discovery_info() -> JsValue {
to_js_str(&json!({
"status": "discovery_module_operational",
"implemented_algorithms": ["dfg", "ocel_dfg", "declare", "causal_alpha", "causal_heuristic"],
"note": "Core discovery algorithms implemented as WASM-native code"
}))
.unwrap_or(JsValue::NULL)
}