Skip to main content

DynamicNetEdit

Enum DynamicNetEdit 

Source
pub enum DynamicNetEdit<'a, Edit: Deref<Target = EditNet<'a>> + 'a> {
    Default(&'a mut PetriNetInfo),
    Simulated(Edit),
}
Expand description

A type for editing a dynamic net safely.

Variants§

§

Default(&'a mut PetriNetInfo)

A editable reference to a default net.

§

Simulated(Edit)

A editable reference to a simulated net.

Implementations§

Source§

impl<'a, Edit: DerefMut<Target = EditNet<'a>> + 'a> DynamicNetEdit<'a, Edit>

Source

pub fn new<E: Editable<Edit<'a> = Edit>>(net: &'a mut DynamicNet<E>) -> Self

Creates a new dynamic net edit for editing the simulated net safely.

Source

pub fn add_place(&mut self) -> Pid

Add a new place to the petri net and get the index and refresh states if necessary.

Source

pub fn add_transition(&mut self) -> Tid

Add a new transition to the petri net and get the index and refresh states if necessary.

Source

pub fn add_connected_transition( &mut self, in_pids: &[Pid], out_pids: &[Pid], ) -> Tid

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

Source

pub fn remove_place(&mut self, pid: Pid)

Remove a place at index pid from petri net and refresh states if necessary.

Source

pub fn connect_place_to_transition(&mut self, pid: Pid, tid: Tid) -> bool

Make a connection in to the transition with index tid from place with index pid and refresh states if necessary. Result represents success.

Source

pub fn connect_transition_to_place(&mut self, tid: Tid, pid: Pid) -> bool

Make a connection out from the transition with index tid to place with index pid and refresh states if necessary. Result represents success.

Source

pub fn duplicate_transition(&mut self, tid: Tid) -> Tid

Duplicate the transition and get the index of the clone and refresh states if necessary.

Source

pub fn duplicate_place(&mut self, pid: Pid) -> Pid

Duplicate the place and get the index of the clone and refresh states if necessary.

Source

pub fn add_initial_tokens(&mut self, pid: Pid, count: usize) -> usize

Increase the initial token count in place indexed by pid and refresh states if necessary.

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

Source§

type Target = PetriNetInfo

The resulting type after dereferencing.
Source§

fn deref(&self) -> &PetriNetInfo

Dereferences the value.

Auto Trait Implementations§

§

impl<'a, Edit> !Send for DynamicNetEdit<'a, Edit>

§

impl<'a, Edit> !Sync for DynamicNetEdit<'a, Edit>

§

impl<'a, Edit> !UnwindSafe for DynamicNetEdit<'a, Edit>

§

impl<'a, Edit> Freeze for DynamicNetEdit<'a, Edit>
where Edit: Freeze,

§

impl<'a, Edit> RefUnwindSafe for DynamicNetEdit<'a, Edit>
where Edit: RefUnwindSafe,

§

impl<'a, Edit> Unpin for DynamicNetEdit<'a, Edit>
where Edit: Unpin,

§

impl<'a, Edit> UnsafeUnpin for DynamicNetEdit<'a, Edit>
where Edit: UnsafeUnpin,

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.