PetriNetInfo

Struct PetriNetInfo 

Source
pub struct PetriNetInfo(/* private fields */);
Expand description

A wrapper type representing petri net for simulation.

Methods from Deref<Target = Net>§

Source

pub fn save(&self, filename: &Path) -> Result<(), Error>

Save the petri net to a file. Result represents success.

Examples found in repository?
examples/example.rs (line 47)
14fn main() -> ExitCode {
15    let mut save = false;
16    let mut load = false;
17
18    let mut args = std::env::args();
19    args.next();
20    for arg in args {
21        match arg.as_ref() {
22            "save" => save = true,
23            "load" => load = true,
24            _ => eprintln!("Ignore invalid argument '{arg}'"),
25        }
26    }
27
28    let Ok(net) = Net::load("examples/example.pn".as_ref()) else {
29        eprintln!("Failed to load example net");
30        return ExitCode::FAILURE;
31    };
32    let mut net = MultiPetriNetSimulation::new(net);
33
34    let mut names = HashMap::new();
35    let Ok(file) = File::open("examples/example.pnk") else {
36        eprintln!("Failed to load example keys");
37        return ExitCode::FAILURE;
38    };
39    for (tid, line) in net.transition_ids().zip(BufReader::new(file).lines()) {
40        let Ok(line) = line else {
41            eprintln!("Failed to read key");
42            return ExitCode::FAILURE;
43        };
44        names.insert(tid, line);
45    }
46
47    if save && net.save("examples/example_copy.pns".as_ref()).is_err() {
48        eprintln!("Failed to save example net");
49    }
50
51    if load {
52        fn read_values(filename: &Path) -> std::io::Result<Vec<u32>> {
53            let size = (std::fs::metadata(filename)?.len() + 3) / 4;
54
55            let mut file = File::open(filename)?;
56
57            (0..size)
58                .map(|_| {
59                    let mut value = [0; 4];
60                    file.read_exact(&mut value)?;
61                    Ok(u32::from_le_bytes(value))
62                })
63                .collect()
64        }
65
66        let Ok(data) = read_values("examples/example.pns".as_ref()) else {
67            eprintln!("Reading state data failed");
68            return ExitCode::FAILURE;
69        };
70
71        if net.add_simulation_from_data(data).is_err() {
72            eprintln!("State initialization failed");
73            return ExitCode::FAILURE;
74        }
75    } else {
76        net.add_simulation();
77    }
78
79    enum StepAction {
80        Continue,
81        Reverse,
82        Save,
83        Quit,
84    }
85
86    let mut forward = true;
87    for mut simulation in &mut net {
88        fn step<D: PlayDirection>(
89            fire: CallState<PetriNetSimulationBorrowMut, D>,
90            names: &HashMap<Tid, String>,
91        ) -> StepAction {
92            if fire.callables.is_empty() {
93                return StepAction::Reverse;
94            }
95
96            for (i, tid) in fire.callables.iter().enumerate() {
97                println!("{}: {}", i + 1, names[tid]);
98            }
99            let stdin = io::stdin();
100            let mut string = String::new();
101            let Ok(size) = stdin.read_line(&mut string) else {
102                eprintln!("Input error");
103                return StepAction::Continue;
104            };
105            if size == 0 {
106                return StepAction::Continue;
107            }
108            match unsafe { string.chars().next().unwrap_unchecked() } {
109                'r' => return StepAction::Reverse,
110                'q' => return StepAction::Quit,
111                's' => return StepAction::Save,
112                _ => (),
113            }
114            match usize::from_str(&string[..(string.len() - 1)]) {
115                Ok(num) if num != 0 && num <= fire.callables.len() => {
116                    fire.call(num - 1);
117                }
118                _ => {
119                    println!(
120                        "You have to input a valid number from 1 to {}",
121                        fire.callables.len()
122                    );
123                    println!("You can also quit by writing \"q\", save the current state by writing \"s\" or reverse by writing \"r\"");
124                    return StepAction::Continue;
125                }
126            }
127
128            StepAction::Continue
129        }
130
131        loop {
132            let step_action = if forward {
133                step(simulation.prepare_call(), &names)
134            } else {
135                step(simulation.prepare_revert(), &names)
136            };
137
138            use StepAction::*;
139            match step_action {
140                Continue => (),
141                Reverse => {
142                    println!("Reverse play direction!");
143                    forward = !forward;
144                }
145                Save => {
146                    fn save(data: &[usize], filename: &Path) -> std::io::Result<()> {
147                        let mut file = File::create(filename)?;
148                        for &count in data {
149                            file.write_all(&(count as u32).to_le_bytes())?;
150                        }
151
152                        Ok(())
153                    }
154
155                    let data = simulation.data();
156
157                    println!(
158                        "{}",
159                        if save(data, "examples/example.pns".as_ref()).is_ok() {
160                            "Saving successful"
161                        } else {
162                            "Saving failed"
163                        }
164                    );
165                }
166                Quit => break,
167            }
168        }
169    }
170
171    ExitCode::SUCCESS
172}
Source

pub fn transition_count(&self) -> usize

The count of transitions of the petri net.

Source

pub fn transition_ids(&self) -> Ids<Transition>

An iterator over the ids of existing transitions.

Examples found in repository?
examples/example.rs (line 39)
14fn main() -> ExitCode {
15    let mut save = false;
16    let mut load = false;
17
18    let mut args = std::env::args();
19    args.next();
20    for arg in args {
21        match arg.as_ref() {
22            "save" => save = true,
23            "load" => load = true,
24            _ => eprintln!("Ignore invalid argument '{arg}'"),
25        }
26    }
27
28    let Ok(net) = Net::load("examples/example.pn".as_ref()) else {
29        eprintln!("Failed to load example net");
30        return ExitCode::FAILURE;
31    };
32    let mut net = MultiPetriNetSimulation::new(net);
33
34    let mut names = HashMap::new();
35    let Ok(file) = File::open("examples/example.pnk") else {
36        eprintln!("Failed to load example keys");
37        return ExitCode::FAILURE;
38    };
39    for (tid, line) in net.transition_ids().zip(BufReader::new(file).lines()) {
40        let Ok(line) = line else {
41            eprintln!("Failed to read key");
42            return ExitCode::FAILURE;
43        };
44        names.insert(tid, line);
45    }
46
47    if save && net.save("examples/example_copy.pns".as_ref()).is_err() {
48        eprintln!("Failed to save example net");
49    }
50
51    if load {
52        fn read_values(filename: &Path) -> std::io::Result<Vec<u32>> {
53            let size = (std::fs::metadata(filename)?.len() + 3) / 4;
54
55            let mut file = File::open(filename)?;
56
57            (0..size)
58                .map(|_| {
59                    let mut value = [0; 4];
60                    file.read_exact(&mut value)?;
61                    Ok(u32::from_le_bytes(value))
62                })
63                .collect()
64        }
65
66        let Ok(data) = read_values("examples/example.pns".as_ref()) else {
67            eprintln!("Reading state data failed");
68            return ExitCode::FAILURE;
69        };
70
71        if net.add_simulation_from_data(data).is_err() {
72            eprintln!("State initialization failed");
73            return ExitCode::FAILURE;
74        }
75    } else {
76        net.add_simulation();
77    }
78
79    enum StepAction {
80        Continue,
81        Reverse,
82        Save,
83        Quit,
84    }
85
86    let mut forward = true;
87    for mut simulation in &mut net {
88        fn step<D: PlayDirection>(
89            fire: CallState<PetriNetSimulationBorrowMut, D>,
90            names: &HashMap<Tid, String>,
91        ) -> StepAction {
92            if fire.callables.is_empty() {
93                return StepAction::Reverse;
94            }
95
96            for (i, tid) in fire.callables.iter().enumerate() {
97                println!("{}: {}", i + 1, names[tid]);
98            }
99            let stdin = io::stdin();
100            let mut string = String::new();
101            let Ok(size) = stdin.read_line(&mut string) else {
102                eprintln!("Input error");
103                return StepAction::Continue;
104            };
105            if size == 0 {
106                return StepAction::Continue;
107            }
108            match unsafe { string.chars().next().unwrap_unchecked() } {
109                'r' => return StepAction::Reverse,
110                'q' => return StepAction::Quit,
111                's' => return StepAction::Save,
112                _ => (),
113            }
114            match usize::from_str(&string[..(string.len() - 1)]) {
115                Ok(num) if num != 0 && num <= fire.callables.len() => {
116                    fire.call(num - 1);
117                }
118                _ => {
119                    println!(
120                        "You have to input a valid number from 1 to {}",
121                        fire.callables.len()
122                    );
123                    println!("You can also quit by writing \"q\", save the current state by writing \"s\" or reverse by writing \"r\"");
124                    return StepAction::Continue;
125                }
126            }
127
128            StepAction::Continue
129        }
130
131        loop {
132            let step_action = if forward {
133                step(simulation.prepare_call(), &names)
134            } else {
135                step(simulation.prepare_revert(), &names)
136            };
137
138            use StepAction::*;
139            match step_action {
140                Continue => (),
141                Reverse => {
142                    println!("Reverse play direction!");
143                    forward = !forward;
144                }
145                Save => {
146                    fn save(data: &[usize], filename: &Path) -> std::io::Result<()> {
147                        let mut file = File::create(filename)?;
148                        for &count in data {
149                            file.write_all(&(count as u32).to_le_bytes())?;
150                        }
151
152                        Ok(())
153                    }
154
155                    let data = simulation.data();
156
157                    println!(
158                        "{}",
159                        if save(data, "examples/example.pns".as_ref()).is_ok() {
160                            "Saving successful"
161                        } else {
162                            "Saving failed"
163                        }
164                    );
165                }
166                Quit => break,
167            }
168        }
169    }
170
171    ExitCode::SUCCESS
172}
Source

pub fn transition(&self, tid: Id<Transition>) -> &Node<Id<Place>>

A node representing a transition of the petri net.

Source

pub fn reusable_transition(&self) -> Option<Id<Transition>>

Returns the index of the next reusable transition.

Source

pub fn place_count(&self) -> usize

The count of places of the petri net.

Source

pub fn place_ids(&self) -> Ids<Place>

An iterator over the ids of existing places.

Source

pub fn place(&self, pid: Id<Place>) -> &Node<Id<Transition>>

A node representing a place of the petri net.

Source

pub fn reusable_place(&self) -> Option<Id<Place>>

Returns the index of the next reusable place.

Source

pub fn initial_token_count(&self, pid: Id<Place>) -> usize

The initial token count for a place of the petri net.

Source

pub fn add_place(&mut self) -> Id<Place>

Add a new place to the petri net and get the index.

Source

pub fn add_transition(&mut self) -> Id<Transition>

Add a new transition to the petri net and get the index.

Source

pub fn remove_place(&mut self, pid: Id<Place>)

Remove a place at index pid from petri net.

Source

pub fn remove_transition(&mut self, tid: Id<Transition>)

Remove a transition at index tid from petri net.

Source

pub fn connect_place_to_transition( &mut self, pid: Id<Place>, tid: Id<Transition>, ) -> bool

Make a connection in to the transition with index tid from place with index pid. Result represents success.

Source

pub fn connect_transition_to_place( &mut self, tid: Id<Transition>, pid: Id<Place>, ) -> bool

Make a connection out from the transition with index tid to place with index pid. Result represents success.

Source

pub fn disconnect_place_to_transition( &mut self, pid: Id<Place>, tid: Id<Transition>, )

Remove the connection in to transition with index tid from place with index pid.

Source

pub fn disconnect_transition_to_place( &mut self, tid: Id<Transition>, pid: Id<Place>, )

Remove the connection out from transition with index tid to place with index pid.

Source

pub fn add_initial_tokens(&mut self, pid: Id<Place>, count: usize) -> usize

Increase the initial token count in place indexed by pid.

Source

pub fn add_connected_place( &mut self, in_tids: &[Id<Transition>], out_tids: &[Id<Transition>], ) -> Id<Place>

Add a new place to the petri net, connct it to the specified transitions and get the index.

Source

pub fn add_connected_transition( &mut self, in_pids: &[Id<Place>], out_pids: &[Id<Place>], ) -> Id<Transition>

Add a new transition to the petri net, connct it to the specified places and get the index.

Source

pub fn duplicate_place(&mut self, pid: Id<Place>) -> Id<Place>

Duplicate the place and get the index of the clone.

Source

pub fn duplicate_transition(&mut self, tid: Id<Transition>) -> Id<Transition>

Duplicate the transition and get the index of the clone.

Trait Implementations§

Source§

impl Deref for PetriNetInfo

Source§

type Target = Net

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Net

Dereferences the value.
Source§

impl DerefMut for PetriNetInfo

Source§

fn deref_mut(&mut self) -> &mut Net

Mutably dereferences the value.
Source§

impl EditableSimulationInfo for PetriNetInfo

Source§

type Edit<'a> = EditNet<'a>

The type used for safe edits.
Source§

unsafe fn edit(&mut self) -> EditNet<'_>

Creates a type which allows safe edits to the info without invalidating the states. Read more
Source§

unsafe fn refresh_state(&self, state: &mut Self::State)

Refreshes the provided mutable state, assuming it is compatible with this SimulationInfo instance. Read more
Source§

impl From<Net> for PetriNetInfo

Source§

fn from(net: Net) -> Self

Converts to this type from the input type.
Source§

impl From<PetriNetInfo> for Net

Source§

fn from(val: PetriNetInfo) -> Self

Converts to this type from the input type.
Source§

impl SimulationInfo for PetriNetInfo

Source§

type StateLoadingError = StateInitializationError

The error type returned when loading the simulation state fails.
Source§

type State = State

The type of the simulation state.
Source§

type AccessData = [usize]

The type used to access the current state.
Source§

type LoadData = Vec<u32>

The type of data used to load the simulation state.
Source§

type Event = Id<Transition>

The type of events that can be called or reverted in the simulation.
Source§

type EventContainer<'a> = TransitionView<'a>

The type of container used to access the available events.
Source§

fn default_state(&self) -> State

Creates a new default state compatible with this SimulationInfo instance.
Source§

fn load_state(&self, data: Vec<u32>) -> Result<State, StateInitializationError>

Loads a state from the provided data, returning a Result with the loaded state or an error.
Source§

unsafe fn clone_state(&self, state: &State) -> State

Clones the provided state, assuming it is compatible with this SimulationInfo instance. Read more
Source§

unsafe fn data<'a>(&self, state: &'a State) -> &'a [usize]

Returns a reference to the data which repsesents the state. Read more
Source§

fn callables(state: &State) -> TransitionView<'_>

Returns the events that can be called for the provided state.
Source§

fn callable(state: &State, tid: Tid) -> bool

Checks if the provided event can be called for the given state.
Source§

unsafe fn call(&self, state: &mut State, tid: Tid)

Calls the provided event on the given mutable state. Read more
Source§

fn revertables(state: &State) -> TransitionView<'_>

Returns the events that can be reverted for the provided state.
Source§

fn revertable(state: &State, tid: Tid) -> bool

Checks if the provided event can be reverted for the given state.
Source§

unsafe fn revert(&self, state: &mut State, tid: Tid)

Reverts the provided event on the given mutable state. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.