wasm4pm 26.7.1

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
//! POWL to YAWL v6 XML conversion.
//!
//! Produces a valid YAWL specification document that can be imported into
//! the YAWL workflow engine.

use crate::powl_arena::{Operator, PowlArena, PowlNode};
use wasm_bindgen::prelude::*;

struct Ids {
    counter: u32,
}

impl Ids {
    fn new() -> Self {
        Ids { counter: 0 }
    }

    fn next(&mut self, prefix: &str) -> String {
        self.counter += 1;
        format!("{}_{}", prefix, self.counter)
    }
}

struct Builder {
    ids: Ids,
    elements: Vec<String>,
    flows: Vec<String>,
}

impl Builder {
    fn new() -> Self {
        Builder {
            ids: Ids::new(),
            elements: Vec::new(),
            flows: Vec::new(),
        }
    }

    fn flow(&mut self, source: &str, target: &str) {
        self.flows.push(format!(
            r#"        <edge source="{}" target="{}"/>"#,
            source, target
        ));
    }

    fn task(&mut self, id: &str, name: &str, join: &str, split: &str) {
        let escaped = xml_escape(name);
        self.elements.push(format!("        <task id=\"{}\">", id));
        self.elements
            .push(format!("          <name>{}</name>", escaped));
        self.elements
            .push(format!("          <decomposesTo id=\"dt_{}\"/>", id));
        self.elements
            .push(format!("          <join code=\"{}\"/>", join));
        self.elements
            .push(format!("          <split code=\"{}\"/>", split));
        self.elements.push("        </task>".to_string());
    }

    fn condition(&mut self, id: &str) {
        self.elements
            .push(format!("        <condition id=\"{}\"/>", id));
    }

    fn convert(&mut self, arena: &PowlArena, idx: u32, entry: &str, exit: &str) {
        match arena.get(idx) {
            None => {
                self.flow(entry, exit);
            }

            Some(PowlNode::Transition(tr)) => {
                if tr.label.is_none() {
                    self.flow(entry, exit);
                    return;
                }
                let label = tr.label.as_deref().unwrap();
                let id = sanitize_id(label);
                self.task(&id, label, "xor", "xor");
                self.flow(entry, &id);
                self.flow(&id, exit);
            }

            Some(PowlNode::FrequentTransition(ft)) => {
                let id = sanitize_id(&ft.activity);
                self.task(&id, &ft.activity, "xor", "xor");
                self.flow(entry, &id);
                self.flow(&id, exit);
            }

            Some(PowlNode::StrictPartialOrder(spo)) => {
                self.convert_spo(arena, &spo.children, &spo.order, entry, exit);
            }

            Some(PowlNode::OperatorPowl(op)) => match op.operator {
                Operator::Xor => {
                    self.convert_xor(arena, &op.children, entry, exit);
                }
                Operator::Loop => {
                    self.convert_loop(arena, &op.children, entry, exit);
                }
                Operator::PartialOrder => {
                    self.chain(arena, &op.children, entry, exit);
                }
            },

            Some(PowlNode::DecisionGraph(_)) => {
                self.flow(entry, exit);
            }

            Some(PowlNode::ChoiceGraph(_)) => {
                // ChoiceGraph → YAWL: approximate as a silent flow.
                self.flow(entry, exit);
            }
        }
    }

    fn convert_xor(&mut self, arena: &PowlArena, children: &[u32], entry: &str, exit: &str) {
        if children.is_empty() {
            self.flow(entry, exit);
            return;
        }
        let merge_c = self.ids.next("c");
        let fork_c = self.ids.next("c");
        self.condition(&merge_c);
        self.condition(&fork_c);
        self.flow(entry, &merge_c);
        self.flow(&fork_c, exit);
        let fork_c = fork_c.clone();
        let merge_c = merge_c.clone();
        for &child_idx in children {
            let ce = self.ids.next("c");
            self.condition(&ce);
            self.flow(&merge_c, &ce);
            self.flow(&ce, &fork_c);
            self.convert(arena, child_idx, &ce, &fork_c);
        }
    }

    fn convert_loop(&mut self, arena: &PowlArena, children: &[u32], entry: &str, exit: &str) {
        let merge_c = self.ids.next("c");
        let fork_c = self.ids.next("c");
        self.condition(&merge_c);
        self.condition(&fork_c);
        self.flow(entry, &merge_c);
        let do_entry = self.ids.next("c");
        let do_exit = self.ids.next("c");
        self.condition(&do_entry);
        self.condition(&do_exit);
        self.flow(&merge_c, &do_entry);
        self.convert(arena, children[0], &do_entry, &do_exit);
        self.flow(&do_exit, &fork_c);
        self.flow(&fork_c, exit);
        if children.len() > 1 {
            let redo_entry = self.ids.next("c");
            let redo_exit = self.ids.next("c");
            self.condition(&redo_entry);
            self.condition(&redo_exit);
            self.flow(&fork_c, &redo_entry);
            self.convert(arena, children[1], &redo_entry, &redo_exit);
            self.flow(&redo_exit, &merge_c);
        }
    }

    fn convert_spo(
        &mut self,
        arena: &PowlArena,
        children: &[u32],
        order: &crate::powl_arena::BinaryRelation,
        entry: &str,
        exit: &str,
    ) {
        if children.is_empty() {
            self.flow(entry, exit);
            return;
        }
        let n = children.len();
        let mut in_deg = vec![0; n];
        for i in 0..n {
            for j in 0..n {
                if order.is_edge(i, j) {
                    in_deg[j] += 1;
                }
            }
        }
        let mut level = vec![0usize; n];
        let mut queue = std::collections::VecDeque::new();
        for i in 0..n {
            if in_deg[i] == 0 {
                queue.push_back(i);
            }
        }
        while let Some(u) = queue.pop_front() {
            for v in 0..n {
                if order.is_edge(u, v) {
                    level[v] = level[v].max(level[u] + 1);
                    in_deg[v] -= 1;
                    if in_deg[v] == 0 {
                        queue.push_back(v);
                    }
                }
            }
        }
        let max_level = level.iter().copied().max().unwrap_or(0);
        let mut groups: Vec<Vec<u32>> = vec![Vec::new(); max_level + 1];
        for (node_i, &lv) in level.iter().enumerate() {
            groups[lv].push(children[node_i]);
        }
        let mut current = entry.to_string();
        for (gi, group) in groups.iter().enumerate() {
            let is_last = gi == groups.len() - 1;
            let next = if is_last {
                exit.to_string()
            } else {
                self.ids.next("c")
            };
            if group.len() == 1 {
                let ce = self.ids.next("c");
                self.condition(&ce);
                self.flow(&current, &ce);
                self.convert(arena, group[0], &ce, &next);
            } else {
                let merge_c = self.ids.next("c");
                let fork_c = self.ids.next("c");
                self.condition(&merge_c);
                self.condition(&fork_c);
                if !is_last {
                    self.condition(&next);
                }
                self.flow(&current, &merge_c);
                self.flow(&fork_c, &next);
                let fork_c = fork_c.clone();
                let merge_c = merge_c.clone();
                for &child_idx in group {
                    let ce = self.ids.next("c");
                    self.condition(&ce);
                    self.flow(&merge_c, &ce);
                    self.flow(&ce, &fork_c);
                    self.convert(arena, child_idx, &ce, &fork_c);
                }
            }
            current = next;
        }
    }

    fn chain(&mut self, arena: &PowlArena, children: &[u32], entry: &str, exit: &str) {
        if children.is_empty() {
            self.flow(entry, exit);
            return;
        }
        let mut prev = entry.to_string();
        for (i, &child) in children.iter().enumerate() {
            let is_last = i == children.len() - 1;
            let next = if is_last {
                exit.to_string()
            } else {
                let p = self.ids.next("c");
                self.condition(&p);
                p
            };
            self.convert(arena, child, &prev, &next);
            prev = next;
        }
    }
}

fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

fn sanitize_id(label: &str) -> String {
    let mut result = String::with_capacity(label.len());
    let mut prev_underscore = false;
    for ch in label.chars() {
        if ch.is_alphanumeric() || ch == '_' {
            if ch == '_' {
                if prev_underscore {
                    continue;
                }
                prev_underscore = true;
            } else {
                prev_underscore = false;
            }
            result.push(ch);
        } else {
            if !prev_underscore {
                result.push('_');
                prev_underscore = true;
            }
        }
    }
    let trimmed = result.trim_matches('_');
    if trimmed.is_empty() {
        "task".to_string()
    } else {
        trimmed.to_string()
    }
}

pub fn to_yawl_xml(arena: &PowlArena, root: u32) -> String {
    let mut builder = Builder::new();
    let ic = "IC".to_string();
    let oc = "OC".to_string();
    builder.convert(arena, root, &ic, &oc);
    let mut lines: Vec<String> = vec![
        r#"<?xml version="1.0" encoding="UTF-8"?>"#,
        r#"<specificationSet xmlns="http://www.yawlfoundation.org/yawlschema" version="6.0">"#,
        r#"  <specification uri="powl_workflow">"#,
        r#"    <meta>"#,
        r#"      <creator>wasm4pm</creator>"#,
        r#"      <description>Generated from POWL model</description>"#,
        r#"    </meta>"#,
        r#"    <net id="mainNet">"#,
        r#"      <processControlElements>"#,
        r#"        <inputCondition id="IC"/>"#,
        r#"        <outputCondition id="OC"/>"#,
    ]
    .into_iter()
    .map(String::from)
    .collect();
    for el in &builder.elements {
        lines.push(el.clone());
    }
    lines.push(r#"      </processControlElements>"#.to_string());
    lines.push(r#"      <flow>"#.to_string());
    for fl in &builder.flows {
        lines.push(fl.clone());
    }
    lines.push(r#"      </flow>"#.to_string());
    lines.push(r#"    </net>"#.to_string());
    lines.push(r#"  </specification>"#.to_string());
    lines.push(r#"</specificationSet>"#.to_string());
    lines.join("\n")
}

#[wasm_bindgen]
pub fn powl_to_yawl_string(powl_string: &str) -> Result<String, JsValue> {
    let mut arena = PowlArena::new();
    let root = crate::powl_parser::parse_powl_model_string(powl_string, &mut arena)
        .map_err(|e| crate::error::js_val(&format!("Parse error: {}", e)))?;
    Ok(to_yawl_xml(&arena, root))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::powl_arena::PowlArena;
    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)
    }

    fn has(xml: &str, needle: &str) -> bool {
        xml.contains(needle)
    }

    #[test]
    fn test_basic_yawl_conversion() {
        // Happy path: single task produces valid YAWL XML structure
        let (arena, root) = parse("A");
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<specificationSet"));
        assert!(has(&xml, "<name>A</name>"));
        assert!(has(&xml, "source=\"IC\""));
        assert!(has(&xml, "target=\"OC\""));

        // XOR produces conditions for branches
        let (arena, root) = parse("X ( A, B )");
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<name>A</name>"));
        assert!(has(&xml, "<name>B</name>"));

        // Silent transition is skipped (no task element)
        let (arena, root) = parse("tau");
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<specificationSet"));
        assert!(!has(&xml, "<task"));
    }

    #[test]
    fn test_partial_order_and_loop_conversion() {
        // Partial order (concurrent) produces AND flows
        let (arena, root) = parse("PO=(nodes={A, B}, order={})");
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<name>A</name>"));
        assert!(has(&xml, "<name>B</name>"));

        // Sequential PO (linear) flows directly without conditions
        let (arena, root) = parse("PO=(nodes={A, B}, order={A-->B})");
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<name>A</name>"));
        assert!(has(&xml, "<name>B</name>"));

        // Loop produces back flow from do body to redo
        let (arena, root) = parse("* ( A, B )");
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<name>A</name>"));
        assert!(has(&xml, "<name>B</name>"));
    }

    #[test]
    fn test_yawl_edge_cases_and_helpers() {
        // XML escaping in task names
        let mut arena = PowlArena::new();
        let root = arena.add_transition(Some("A<B>".into()));
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<name>A&lt;B&gt;</name>"));

        // ID sanitization helper
        assert_eq!(sanitize_id("A"), "A");
        assert_eq!(sanitize_id("hello world"), "hello_world");
        assert_eq!(sanitize_id(""), "task");

        // Frequent transition produces task element
        let root = arena.add_frequent_transition("Pay".into(), 1, Some(1));
        let xml = to_yawl_xml(&arena, root);
        assert!(has(&xml, "<name>Pay</name>"));
        assert!(has(&xml, "<task id=\"Pay\">"));
    }
}