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
use std::error::Error;
use std::ops::{Index, IndexMut};

use indexed_vec::IndexVec;

use crate::net::NodeId;
use crate::timed::{Place, Transition};
use crate::{arc, standard, NetError, PlaceId, TransitionId};
use bimap::BiMap;

/// Timed Petri net, with produce, consume, condition and inhibitors arcs
///
/// This structure is indexed with [`PlaceId`] and [`TransitionId`] to allow easy access to places
/// and transitions.
///
/// As this kind of network is a superset of standard Petri net, we can create one from standard
/// Petri net without loosing any informations.
#[derive(Debug, Default)]
pub struct Net {
    /// Name of this network
    pub name: String,
    /// BiHashmap to get id from index and index from id
    id_index_map: BiMap<String, NodeId>,
    /// Prefix for new places and transitions
    automatic_prefix: String,
    /// Transitions of the network
    pub transitions: IndexVec<TransitionId, Transition>,
    /// Places of the network
    pub places: IndexVec<PlaceId, Place>,
}

impl Index<TransitionId> for Net {
    type Output = Transition;

    fn index(&self, index: TransitionId) -> &Self::Output {
        &self.transitions[index]
    }
}

impl Index<PlaceId> for Net {
    type Output = Place;

    fn index(&self, index: PlaceId) -> &Self::Output {
        &self.places[index]
    }
}

impl IndexMut<TransitionId> for Net {
    fn index_mut(&mut self, index: TransitionId) -> &mut Self::Output {
        self.transitions.index_mut(index)
    }
}

impl IndexMut<PlaceId> for Net {
    fn index_mut(&mut self, index: PlaceId) -> &mut Self::Output {
        self.places.index_mut(index)
    }
}

impl From<&standard::Net> for Net {
    fn from(standard: &standard::Net) -> Self {
        // Crate a new network
        let mut net = Net {
            name: standard.name.clone(),
            ..Net::default()
        };

        // Copy all places
        for place in &standard.places {
            let new_pl = net.create_place();
            net[new_pl].initial = place.initial;
            net[new_pl].label = place.label.clone();
        }

        // Copy transitions and arcs from timed Petri nets
        for transition in &standard.transitions {
            let new_tr = net.create_transition();
            net[new_tr].label = transition.label.clone();
            for &(pl, weight) in transition.consume.iter() {
                net.add_arc(arc::Kind::Consume(pl, net[new_tr].id, weight as usize))
                    .unwrap();
            }
            for &(pl, weight) in transition.produce.iter() {
                net.add_arc(arc::Kind::Produce(pl, net[new_tr].id, weight as usize))
                    .unwrap();
            }
        }
        net
    }
}

impl Net {
    /// Create a place with automatic name
    pub fn create_place(&mut self) -> PlaceId {
        self.places.push(Place {
            id: PlaceId::from(self.transitions.len()),
            ..Place::default()
        });
        self.id_index_map.insert(
            format!("{}-{}", self.automatic_prefix, self.id_index_map.len()),
            NodeId::Place(self.places.last_idx().unwrap()),
        );
        self.places.last_idx().unwrap()
    }

    /// Create a transition with an empty name
    pub fn create_transition(&mut self) -> TransitionId {
        self.transitions.push(Transition {
            id: TransitionId::from(self.transitions.len()),
            ..Transition::default()
        });
        self.id_index_map.insert(
            format!("{}-{}", self.automatic_prefix, self.id_index_map.len()),
            NodeId::Transition(self.transitions.last_idx().unwrap()),
        );
        self.transitions.last_idx().unwrap()
    }

    /// Get node name with its id
    pub fn get_name_by_index(&self, index: &NodeId) -> Option<String> {
        self.id_index_map.get_by_right(index).map(|v| v.clone())
    }

    /// Get node id with its name
    pub fn get_index_by_name(&self, name: &str) -> Option<NodeId> {
        self.id_index_map.get_by_left(name).map(|v| *v)
    }

    /// Rename node
    pub fn rename_node(&mut self, id: NodeId, name: &str) -> Result<(), NetError> {
        if name.starts_with(&self.automatic_prefix) {
            self.automatic_prefix.push('a');
        }
        match self.id_index_map.get_by_left(name) {
            None => {
                self.id_index_map.remove_by_right(&id);
                self.id_index_map.insert(name.to_string(), id);
                Ok(())
            }
            Some(_) => Err(NetError::DuplicatedName(name.to_string())),
        }
    }

    /// Add an arc in the network. This kind of network support only [`arc::Kind::Consume`],
    /// [`arc::Kind::Produce`], [`arc::Kind::Inhibitor`] and [`arc::Kind::Test`] arcs.
    ///
    /// # Errors
    /// Return [`NetError::UnsupportedArc`] when trying to add a kind of arc which is not supported
    pub fn add_arc(&mut self, arc: arc::Kind) -> Result<(), Box<dyn Error>> {
        match arc {
            arc::Kind::Consume(pl_id, tr_id, w) => {
                self.transitions[tr_id].consume.insert_or_add(pl_id, w);
                self.places[pl_id].consumed_by.insert_or_add(tr_id, w);
                Ok(())
            }
            arc::Kind::Produce(pl_id, tr_id, w) => {
                self.transitions[tr_id].produce.insert_or_add(pl_id, w);
                self.places[pl_id].produced_by.insert_or_add(tr_id, w);
                Ok(())
            }
            arc::Kind::Test(pl_id, tr_id, w) => {
                self.transitions[tr_id].conditions.insert_or_max(pl_id, w);
                self.places[pl_id].condition_for.insert_or_max(tr_id, w);
                Ok(())
            }
            arc::Kind::Inhibitor(pl_id, tr_id, w) => {
                self.transitions[tr_id].inhibitors.insert_or_min(pl_id, w);
                self.places[pl_id].inhibitor_for.insert_or_min(tr_id, w);
                Ok(())
            }
            a => Err(Box::new(NetError::UnsupportedArc(a))),
        }
    }

    /// Disconnect a place in the network
    ///
    /// The place is not really deleted to avoid memory relocation and extra information about
    /// this place such as name can be useful later.
    pub fn delete_place(&mut self, place: PlaceId) {
        for &(tr, _) in self.places[place].consumed_by.iter() {
            self.transitions[tr].consume.delete(place);
        }
        for &(tr, _) in self.places[place].condition_for.iter() {
            self.transitions[tr].conditions.delete(place);
        }
        for &(tr, _) in self.places[place].inhibitor_for.iter() {
            self.transitions[tr].inhibitors.delete(place);
        }
        for &(tr, _) in self.places[place].produced_by.iter() {
            self.transitions[tr].produce.delete(place);
        }
        self.places[place].consumed_by.clear();
        self.places[place].condition_for.clear();
        self.places[place].inhibitor_for.clear();
        self.places[place].produced_by.clear();
    }

    /// Disconnect a transition in the network
    ///
    /// The transition is not really deleted to avoid memory relocation and extra information about
    /// this transitions such as name can be useful later.
    pub fn delete_transition(&mut self, transition: TransitionId) {
        for &(pl, _) in self.transitions[transition].consume.iter() {
            self.places[pl].consumed_by.delete(transition);
        }

        for &(pl, _) in self.transitions[transition].produce.iter() {
            self.places[pl].produced_by.delete(transition);
        }

        for &(pl, _) in self.transitions[transition].inhibitors.iter() {
            self.places[pl].inhibitor_for.delete(transition);
        }

        for &(pl, _) in self.transitions[transition].conditions.iter() {
            self.places[pl].condition_for.delete(transition);
        }
        self.transitions[transition].consume.clear();
        self.transitions[transition].produce.clear();
        self.transitions[transition].priorities.clear();
        self.transitions[transition].inhibitors.clear();
        self.transitions[transition].conditions.clear();
    }

    /// Add a priority relation in the network
    pub fn add_priority(&mut self, tr_index: TransitionId, over: TransitionId) {
        match self.transitions[tr_index].priorities.binary_search(&over) {
            Ok(_) => {} // element already in vector @ `pos`
            Err(pos) => self.transitions[tr_index].priorities.insert(pos, over),
        }
    }

    /// Update all priorities to make a transitive closure
    ///
    /// # Errors
    /// `NetError::CyclicPriorities` is returned if there is a cyclic priority in the network
    pub fn update_priorities(&mut self) -> Result<(), Box<dyn Error>> {
        let mut done = IndexVec::<TransitionId, bool>::default();
        for tr in self.transitions.iter() {
            done.push(tr.priorities.is_empty());
        }

        if !done.iter().any(|&v| v) {
            return Err(Box::new(NetError::CyclicPriorities));
        }

        loop {
            if !done.iter().any(|&v| !v) {
                return Ok(());
            }
            let to_change: Vec<TransitionId> = done
                .iter()
                .enumerate()
                .filter_map(|(i, &v)| if v { None } else { Some(TransitionId::from(i)) })
                .collect();
            let mut changed = false;
            for current_index in to_change {
                done[current_index] = self.transitions[current_index]
                    .priorities
                    .iter()
                    .all(|&i| done[i]);
                if done[current_index] {
                    changed = true;
                    let mut to_extend = vec![];
                    for &sub_index in &self.transitions[current_index].priorities {
                        to_extend.extend(&self.transitions[sub_index].priorities);
                    }
                    for e in to_extend {
                        self.add_priority(current_index, e);
                    }
                }
            }
            if !changed {
                return Err(Box::new(NetError::CyclicPriorities));
            }
        }
    }
}