ebi_bpmn 0.0.41

A BPMN parser, writer and executor
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
use crate::{
    BusinessProcessModelAndNotation,
    element::{BPMNElement, BPMNElementTrait},
    marking::{BPMNRootMarking, BPMNSubMarking, Token},
    parser::parser_state::GlobalIndex,
    semantics::TransitionIndex,
    sequence_flow::BPMNSequenceFlow,
    structure_checker::verify_structural_correctness_initiation_mode,
    traits::{
        objectable::{BPMNObject, EMPTY_FLOWS},
        processable::Processable,
        searchable::Searchable,
        startable::{InitiationMode, Startable},
        transitionable::{
            Transitionable, enabledness_xor_join_only, execute_transition_parallel_split,
            execute_transition_xor_join_consume, number_of_transitions_xor_join_only,
        },
    },
};
use anyhow::{Context, Result, anyhow};
use bitvec::{bitvec, vec::BitVec};
use ebi_activity_key::Activity;
use ebi_arithmetic::{Fraction, One};

#[derive(Debug, Clone)]
pub struct BPMNExpandedSubProcess {
    pub(crate) global_index: GlobalIndex,
    pub(crate) id: String,
    pub(crate) local_index: usize,
    pub(crate) name: Option<String>,
    pub(crate) elements: Vec<BPMNElement>,
    ///internal sequence flows
    pub(crate) sequence_flows: Vec<BPMNSequenceFlow>,

    //external sequence flows
    pub(crate) incoming_sequence_flows: Vec<usize>,
    pub(crate) outgoing_sequence_flows: Vec<usize>,
}

impl BPMNExpandedSubProcess {
    pub(crate) fn start_process_instance(
        &self,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<BPMNSubMarking> {
        let initiation_mode = self.initiation_mode(bpmn)?;
        self.to_sub_marking(&initiation_mode)
    }
}

impl BPMNElementTrait for BPMNExpandedSubProcess {
    fn add_incoming_sequence_flow(&mut self, flow_index: usize) -> Result<()> {
        self.incoming_sequence_flows.push(flow_index);
        Ok(())
    }

    fn add_outgoing_sequence_flow(&mut self, flow_index: usize) -> anyhow::Result<()> {
        self.outgoing_sequence_flows.push(flow_index);
        Ok(())
    }

    fn add_incoming_message_flow(&mut self, _flow_index: usize) -> Result<()> {
        Err(anyhow!(
            "expanded sub-processes cannot have incoming message flows"
        ))
    }

    fn add_outgoing_message_flow(&mut self, _flow_index: usize) -> Result<()> {
        Err(anyhow!(
            "expanded sub-processes cannot have outgoing message flows"
        ))
    }

    fn verify_structural_correctness(
        &self,
        _parent: &dyn Processable,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<()> {
        //recurse on elements
        for element in &self.elements {
            element.verify_structural_correctness(self, bpmn)?
        }

        //verify initiation and termination
        verify_structural_correctness_initiation_mode!(self, bpmn);

        Ok(())
    }
}

impl BPMNObject for BPMNExpandedSubProcess {
    fn global_index(&self) -> GlobalIndex {
        self.global_index
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn activity(&self) -> Option<Activity> {
        None
    }

    fn local_index(&self) -> usize {
        self.local_index
    }

    fn is_unconstrained_start_event(
        &self,
        _bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<bool> {
        Ok(false)
    }

    fn is_end_event(&self) -> bool {
        false
    }

    fn incoming_sequence_flows(&self) -> &[usize] {
        &self.incoming_sequence_flows
    }

    fn outgoing_sequence_flows(&self) -> &[usize] {
        &self.outgoing_sequence_flows
    }

    fn incoming_message_flows(&self) -> &[usize] {
        &EMPTY_FLOWS
    }

    fn outgoing_message_flows(&self) -> &[usize] {
        &EMPTY_FLOWS
    }

    fn can_start_process_instance(&self, _bpmn: &BusinessProcessModelAndNotation) -> Result<bool> {
        Ok(self.incoming_sequence_flows().len() == 0)
    }

    fn outgoing_message_flows_always_have_tokens(&self) -> bool {
        false
    }

    fn outgoing_messages_cannot_be_removed(&self) -> bool {
        false
    }

    fn incoming_messages_are_ignored(&self) -> bool {
        false
    }

    fn can_have_incoming_sequence_flows(&self) -> bool {
        true
    }

    fn can_have_outgoing_sequence_flows(&self) -> bool {
        true
    }
}

impl Transitionable for BPMNExpandedSubProcess {
    fn number_of_transitions(&self, marking: &BPMNSubMarking) -> usize {
        //behaves like an XOR-join to start
        let mut result = number_of_transitions_xor_join_only!(self);

        for sub_marking in &marking.element_index_2_sub_markings[self.local_index] {
            // one transition to end the instantiation
            result += 1;
            // and the transitions within us
            result += self.elements.number_of_transitions(sub_marking);
        }

        result
    }

    fn enabled_transitions(
        &self,
        root_marking: &BPMNRootMarking,
        sub_marking: &BPMNSubMarking,
        _parent: &dyn Processable,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<BitVec> {
        //start transitions: like an xor join
        let mut result = enabledness_xor_join_only!(self, sub_marking);

        //gather sub-process instantations transitions
        for sub_marking in &sub_marking.element_index_2_sub_markings[self.local_index] {
            let sub_marking_enabled_transitions =
                self.elements
                    .enabled_transitions(root_marking, sub_marking, self, bpmn)?;

            //end transition
            if sub_marking_enabled_transitions.not_any() {
                result.push(true);
            } else {
                result.push(false);
            }

            //transitions from this instantiation
            result.extend(sub_marking_enabled_transitions);
        }

        Ok(result)
    }

    fn execute_transition(
        &self,
        mut transition_index: TransitionIndex,
        root_marking: &mut BPMNRootMarking,
        sub_marking: &mut BPMNSubMarking,
        _parent: &dyn Processable,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<()> {
        if transition_index < number_of_transitions_xor_join_only!(self) {
            //behaves like an XOR-join to start

            //consume
            execute_transition_xor_join_consume!(self, sub_marking, transition_index);

            //produce -> start a new sub-process instance
            sub_marking.element_index_2_sub_markings[self.local_index]
                .push(self.start_process_instance(bpmn)?);
            return Ok(());
        }
        transition_index -= number_of_transitions_xor_join_only!(self);

        //find the sub-marking that contains the transition index
        let mut remove_instantiation = None;
        for (instantiation_index, sub_sub_marking) in sub_marking.element_index_2_sub_markings
            [self.local_index]
            .iter_mut()
            .enumerate()
        {
            // one transition to end the instantiation
            if transition_index == 0 {
                //end the process instance
                remove_instantiation = Some(instantiation_index);
                //produce tokens
                execute_transition_parallel_split!(self, sub_marking);
                break;
            }
            transition_index -= 1;

            // and the transitions within us
            let number_of_sub_transitions = self.elements.number_of_transitions(sub_sub_marking);
            if transition_index < number_of_sub_transitions {
                self.elements
                    .execute_transition(transition_index, root_marking, sub_sub_marking, self, bpmn)
                    .with_context(|| format!("Execute transition in sub-process `{}`.", self.id))?;
                return Ok(());
            }
            transition_index -= number_of_sub_transitions;
        }

        if let Some(remove_instantiation_index) = remove_instantiation {
            sub_marking.element_index_2_sub_markings[self.local_index]
                .remove(remove_instantiation_index);
        }

        Ok(())
    }

    fn transition_activity(
        &self,
        mut transition_index: TransitionIndex,
        marking: &BPMNSubMarking,
    ) -> Option<Activity> {
        //start transition
        if transition_index < number_of_transitions_xor_join_only!(self) {
            return None;
        }
        transition_index -= number_of_transitions_xor_join_only!(self);

        for sub_marking in &marking.element_index_2_sub_markings[self.local_index] {
            if transition_index == 0 {
                //end transition
                return None;
            }
            transition_index -= 1;

            //own transitions
            let sub_number_of_transitions = self.elements.number_of_transitions(&sub_marking);
            if transition_index < sub_number_of_transitions {
                return self
                    .elements
                    .transition_activity(transition_index, &sub_marking);
            }
            transition_index -= sub_number_of_transitions;
        }
        None
    }

    fn transition_debug(
        &self,
        mut transition_index: TransitionIndex,
        marking: &BPMNSubMarking,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> Option<String> {
        //start transition
        if transition_index < self.incoming_sequence_flows.len().max(1) {
            return Some(format!(
                "expanded sub-process `{}`; start internal transition {}",
                self.id, transition_index
            ));
        }
        transition_index -= self.incoming_sequence_flows.len().max(1);

        //instantiations
        for (i, sub_marking) in marking.element_index_2_sub_markings[self.local_index]
            .iter()
            .enumerate()
        {
            if transition_index == 0 {
                //end transition
                return Some(format!(
                    "expanded sub-process `{}`; instantiation {}, end transition",
                    self.id, i
                ));
            }
            transition_index -= 1;

            //own transitions
            let sub_number_of_transitions = self.elements.number_of_transitions(&sub_marking);
            if transition_index < sub_number_of_transitions {
                return self
                    .elements
                    .transition_debug(transition_index, &sub_marking, bpmn);
            }
            transition_index -= sub_number_of_transitions;
        }
        None
    }

    fn transition_probabilistic_penalty(
        &self,
        mut transition_index: TransitionIndex,
        marking: &BPMNSubMarking,
        _parent: &dyn Processable,
    ) -> Option<ebi_arithmetic::Fraction> {
        //start transition
        if transition_index < self.incoming_sequence_flows.len().max(1) {
            return Some(Fraction::one());
        }
        transition_index -= self.incoming_sequence_flows.len().max(1);

        //instantiations
        for sub_marking in marking.element_index_2_sub_markings[self.local_index].iter() {
            if transition_index == 0 {
                //end transition
                return Some(Fraction::one());
            }
            transition_index -= 1;

            //own transitions
            let sub_number_of_transitions = self.elements.number_of_transitions(&sub_marking);
            if transition_index < sub_number_of_transitions {
                return self.elements.transition_probabilistic_penalty(
                    transition_index,
                    &sub_marking,
                    self,
                );
            }
            transition_index -= sub_number_of_transitions;
        }
        None
    }

    fn transition_2_consumed_tokens(
        &self,
        _transition_index: TransitionIndex,
        _root_marking: &BPMNRootMarking,
        _sub_marking: &BPMNSubMarking,
        _parent: &dyn Processable,
        _bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<Vec<Token>> {
        Err(anyhow!("Sub-processes are not yet supported here."))
    }

    fn transition_2_produced_tokens(
        &self,
        _transition_index: TransitionIndex,
        _root_marking: &BPMNRootMarking,
        _sub_marking: &BPMNSubMarking,
        _parent: &dyn Processable,
        _bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<Vec<Token>> {
        Err(anyhow!("Sub-processes are not yet supported here."))
    }
}

impl Startable for BPMNExpandedSubProcess {
    fn unconstrained_start_events_without_recursing(
        &self,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<Vec<&BPMNElement>> {
        self.elements
            .unconstrained_start_events_without_recursing(bpmn)
    }

    fn end_events_without_recursing(&self) -> Vec<&BPMNElement> {
        self.elements.end_events_without_recursing()
    }

    fn start_elements_without_recursing(
        &self,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> Result<Vec<&BPMNElement>> {
        self.elements.start_elements_without_recursing(bpmn)
    }
}

impl Searchable for BPMNExpandedSubProcess {
    fn id_2_pool_and_global_index(&self, id: &str) -> Option<(Option<usize>, GlobalIndex)> {
        if self.id == id {
            Some((Some(self.local_index), self.global_index))
        } else {
            if let Some((_, index)) = self.elements.id_2_pool_and_global_index(id) {
                Some((Some(self.local_index), index))
            } else {
                None
            }
        }
    }

    fn global_index_2_sequence_flow_and_parent(
        &self,
        sequence_flow_global_index: GlobalIndex,
    ) -> Option<(&BPMNSequenceFlow, &dyn Processable)> {
        for sequence_flow in &self.sequence_flows {
            if sequence_flow.global_index == sequence_flow_global_index {
                return Some((sequence_flow, self));
            }
        }
        None
    }

    fn id_2_local_index(&self, id: &str) -> Option<usize> {
        self.elements.id_2_local_index(id)
    }

    fn all_elements_ref(&self) -> Vec<&BPMNElement> {
        self.elements.all_elements_ref()
    }

    fn parent_of(&self, global_index: GlobalIndex) -> (Option<&dyn Processable>, bool) {
        if self.global_index == global_index {
            (None, true)
        } else {
            let x = self.elements.parent_of(global_index);
            if x.1 && x.0.is_none() {
                (Some(self), true)
            } else if x.1 {
                x
            } else {
                (None, false)
            }
        }
    }

    fn all_sequence_flows_ref(&self) -> Vec<&BPMNSequenceFlow> {
        let mut result: Vec<&BPMNSequenceFlow> = self.sequence_flows.iter().collect();
        result.extend(self.elements.all_sequence_flows_ref());
        result
    }

    fn global_index_2_sequence_flow_mut(
        &mut self,
        sequence_flow_global_index: GlobalIndex,
    ) -> Option<&mut BPMNSequenceFlow> {
        let x = self
            .sequence_flows
            .iter_mut()
            .filter_map(|sequence_flow| {
                if sequence_flow.global_index == sequence_flow_global_index {
                    Some(sequence_flow)
                } else {
                    None
                }
            })
            .next();
        if x.is_some() {
            return x;
        }

        //recurse
        self.elements
            .global_index_2_sequence_flow_mut(sequence_flow_global_index)
    }

    fn global_index_2_element(&self, index: GlobalIndex) -> Option<&BPMNElement> {
        self.elements.global_index_2_element(index)
    }

    fn global_index_2_element_mut(&mut self, index: GlobalIndex) -> Option<&mut BPMNElement> {
        self.elements.global_index_2_element_mut(index)
    }

    fn local_index_2_element(&self, index: usize) -> Option<&BPMNElement> {
        self.elements.local_index_2_element(index)
    }

    fn local_index_2_element_mut(&mut self, index: usize) -> Option<&mut BPMNElement> {
        self.elements.local_index_2_element_mut(index)
    }
}

macro_rules! to_sub_marking {
    ($self:ident, $initiation_mode:ident) => {
        match $initiation_mode {
            InitiationMode::ChoiceBetweenStartEvents() => {
                //initiation mode 1: through one or more start events
                Ok(BPMNSubMarking {
                    sequence_flow_2_tokens: vec![0; $self.sequence_flows_non_recursive().len()],
                    initial_choice_token: true,
                    element_index_2_tokens: vec![0; $self.elements_non_recursive().len()],
                    element_index_2_sub_markings: vec![
                        vec![];
                        $self.elements_non_recursive().len()
                    ],
                })
            }
            InitiationMode::ParallelElements(elements) => {
                let mut element_index_2_tokens = vec![0; $self.elements_non_recursive().len()];
                for element in elements {
                    element_index_2_tokens[element.local_index()] = 1;
                }

                Ok(BPMNSubMarking {
                    sequence_flow_2_tokens: vec![0; $self.sequence_flows_non_recursive().len()],
                    initial_choice_token: false,
                    element_index_2_tokens,
                    element_index_2_sub_markings: vec![
                        vec![];
                        $self.elements_non_recursive().len()
                    ],
                })
            }
        }
    };
}
pub(crate) use to_sub_marking;

impl Processable for BPMNExpandedSubProcess {
    fn elements_non_recursive(&self) -> &Vec<BPMNElement> {
        &self.elements
    }

    fn sequence_flows_non_recursive(&self) -> &Vec<BPMNSequenceFlow> {
        &self.sequence_flows
    }

    fn to_sub_marking(&self, initiation_mode: &InitiationMode) -> Result<BPMNSubMarking> {
        to_sub_marking!(self, initiation_mode)
    }

    fn is_sub_process(&self) -> bool {
        true
    }
}