pyjevsim 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyjevsim/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """
2
+ Author: Changbeom Choi (@cbchoi)
3
+ Copyright (c) 2014-2020 Handong Global University
4
+ Copyright (c) 2014-2020 Hanbat National University
5
+ License: MIT. The full license text is available at:
6
+ - https://github.com/eventsim/pyjevsim/blob/main/LICENSE
7
+ """
8
+ __author__ = "me@cbchoi.info"
9
+ __all__ = [
10
+ "behavior_model",
11
+ "behavior_executor",
12
+ "core_model",
13
+ "default_message_catcher",
14
+ "definition",
15
+ "executor_factory",
16
+ "executor",
17
+ "structural_model",
18
+ "structural_executor",
19
+ "executor_factory",
20
+ "system_executor",
21
+ "system_message",
22
+ "system_object",
23
+ "termination_manager",
24
+ "snapshot_manager"
25
+ ]
26
+
27
+ from .definition import (
28
+ AttributeType,
29
+ Infinite,
30
+ ModelType,
31
+ ExecutionType,
32
+ SimulationMode,
33
+ SingletonType,
34
+ )
35
+
36
+ from .system_executor import SysExecutor
37
+ from .system_message import SysMessage
38
+ from .behavior_model import BehaviorModel
39
+ from .structural_model import StructuralModel
40
+ from .snapshot_manager import SnapshotManager
41
+ from .restore_handler import RestoreHandler
@@ -0,0 +1,39 @@
1
+ """
2
+ Author: Changbeom Choi (@cbchoi)
3
+ Copyright (c) 2014-2020 Handong Global University
4
+ Copyright (c) 2021-2024 Hanbat National University
5
+ License: MIT. The full license text is available at:
6
+ https://github.com/eventsim/pyjevsim/blob/main/LICENSE
7
+
8
+ This module contains a BehaivorModel object that allows you to implement the Discrete Event System Specification AtomicModel.
9
+ """
10
+
11
+ from abc import abstractmethod
12
+ from collections import OrderedDict
13
+
14
+ from .behavior_model import BehaviorModel
15
+ from .definition import ModelType
16
+
17
+ class AtomicModel(BehaviorModel):
18
+ def __init__(self, _name=""):
19
+ super().__init__(_name)
20
+
21
+ @abstractmethod
22
+ def ext_trans(self, port, msg):
23
+ """Defines the external transition, to be implemented by subclasses"""
24
+ pass
25
+
26
+ @abstractmethod
27
+ def int_trans(self):
28
+ """Defines the internal transition, to be implemented by subclasses"""
29
+ pass
30
+
31
+ @abstractmethod
32
+ def output(self, msg_deliver):
33
+ """Defines the output function, to be implemented by subclasses"""
34
+ pass
35
+
36
+ @abstractmethod
37
+ def time_advance(self):
38
+ """Defines the output function, to be implemented by subclasses"""
39
+ return -1
@@ -0,0 +1,126 @@
1
+ """
2
+ Author: Changbeom Choi (@cbchoi)
3
+ Copyright (c) 2014-2020 Handong Global University
4
+ Copyright (c) 2021-2024 Hanbat National University
5
+ License: MIT. The full license text is available at:
6
+ https://github.com/eventsim/pyjevsim/blob/main/LICENSE
7
+
8
+ This module contains a BehaviorExecutor, an object for executing a BehaviorModel.
9
+ """
10
+
11
+ from .definition import Infinite
12
+ from .executor import Executor
13
+
14
+ class BehaviorExecutor(Executor):
15
+ """
16
+ A decorated form of the BehaviorModel, ready to be executed by the SysExecutor.
17
+ Manages the simulation time of the BehaviorModel and the information in the SysExecutor.
18
+
19
+ Args:
20
+ itime (int or Infinite): Time of instance creation
21
+ dtime (int or Infinite): Time of instance destruction
22
+ ename (str): SysExecutor name
23
+ behavior_model (ModelType.BEHAVIORAL): Behavior Model
24
+ """
25
+ def __init__(self, itime=Infinite, dtime=Infinite, ename="default", behavior_model=None, parent=None):
26
+ super().__init__(itime, dtime, ename, behavior_model, parent)
27
+
28
+ self._next_event_t = 0 # Next event time
29
+ self._cur_state = "" # Current state of the behavior executor
30
+ self.request_time = float("inf") # Request time initialized to infinity
31
+
32
+ self.behavior_model = behavior_model #Behavior Model
33
+ self._cancel_reschedule_f = False #cancel reschedule flag
34
+
35
+ def set_global_time(self, gtime):
36
+ """Sets the global time for the executor and behavior model"""
37
+ self.global_time = gtime
38
+ self.behavior_model.set_global_time(gtime)
39
+
40
+ def get_core_model(self):
41
+ """Returns the core behavior model"""
42
+ return self.behavior_model
43
+
44
+ def __str__(self):
45
+ """Returns a string representation of the executor"""
46
+ return f"[N]:{self.get_name()}, [S]:{self._cur_state}"
47
+
48
+ def get_name(self):
49
+ """Returns the name of the behavior model"""
50
+ return self.behavior_model.get_name()
51
+
52
+ def get_engine_name(self):
53
+ """Returns the name of the engine"""
54
+ return self.engine_name
55
+
56
+ def set_engine_name(self, engine_name):
57
+ """Sets the name of the engine"""
58
+ self.engine_name = engine_name
59
+
60
+ def get_create_time(self):
61
+ """Returns the instance creation time"""
62
+ return self._instance_t
63
+
64
+ def get_destruct_time(self):
65
+ """Returns the destruction time"""
66
+ return self._destruct_t
67
+
68
+ def get_obj_id(self):
69
+ """Returns the object ID of the behavior model"""
70
+ return self.behavior_model.get_obj_id()
71
+
72
+ # State management
73
+ def get_cur_state(self):
74
+ """Returns the current state of the executor"""
75
+ return self._cur_state
76
+
77
+ def init_state(self, state):
78
+ """Initializes the state of the executor"""
79
+ self._cur_state = state
80
+
81
+ # External Transition
82
+ def ext_trans(self, port, msg):
83
+ """Handles external transition based on port and message"""
84
+ if self.behavior_model.get_cancel_flag():
85
+ self._cancel_reschedule_f = True
86
+
87
+ self.behavior_model.ext_trans(port, msg)
88
+
89
+ # Internal Transition
90
+ def int_trans(self):
91
+ """Handles internal transition"""
92
+ self.behavior_model.int_trans()
93
+
94
+ # Output Function
95
+ def output(self, msg_deliver):
96
+ """Executes the output function of the behavior model"""
97
+ return self.behavior_model.output(msg_deliver)
98
+
99
+ # Time Advance Function
100
+ def time_advance(self):
101
+ """Returns the time advance value for the current state"""
102
+ if self.behavior_model._cur_state in self.behavior_model._states:
103
+ return self.behavior_model._states[self.behavior_model._cur_state]
104
+
105
+ return -1
106
+
107
+ def set_req_time(self, global_time):
108
+ """Sets the request time based on the global time and time advance"""
109
+ self.set_global_time(global_time)
110
+ if self.time_advance() == Infinite:
111
+ self._next_event_t = Infinite
112
+ self.request_time = Infinite
113
+ else:
114
+ if self._cancel_reschedule_f:
115
+ self.request_time = min(self._next_event_t, global_time + self.time_advance())
116
+ else:
117
+ self.request_time = global_time + self.time_advance()
118
+
119
+ def get_req_time(self):
120
+ """Returns the request time and resets the cancel flag if necessary"""
121
+ if self._cancel_reschedule_f:
122
+ self._cancel_reschedule_f = False
123
+ self.behavior_model.reset_cancel_flag()
124
+ self._next_event_t = self.request_time
125
+ return self.request_time
126
+
@@ -0,0 +1,260 @@
1
+ """
2
+ Author: Changbeom Choi (@cbchoi)
3
+ Copyright (c) 2014-2020 Handong Global University
4
+ Copyright (c) 2021-2024 Hanbat National University
5
+ License: MIT. The full license text is available at:
6
+ https://github.com/eventsim/pyjevsim/blob/main/LICENSE
7
+
8
+ This module contains a BehaivorModel object that allows you to implement the Discrete Event System Specification AtomicModel.
9
+ """
10
+
11
+ from abc import abstractmethod
12
+ from collections import OrderedDict
13
+
14
+ from .core_model import CoreModel
15
+ from .definition import ModelType
16
+
17
+ class BehaviorModel(CoreModel):
18
+ """BehaviorModel template to inherit when constructing a new Model.
19
+
20
+ Args:
21
+ _name (str): Unique model name
22
+ """
23
+ def __init__(self, _name=""):
24
+
25
+ super().__init__(_name, ModelType.BEHAVIORAL)
26
+ self._states = {}
27
+
28
+ # External transition map
29
+ self.external_transition_map_tuple = {}
30
+ self.external_transition_map_state = {}
31
+
32
+ # Internal transition map
33
+ self.internal_transition_map_tuple = {}
34
+ self.internal_transition_map_state = {}
35
+
36
+
37
+ self._cancel_reschedule_f = False
38
+ self._cur_state = ""
39
+ self.global_time = 0
40
+
41
+ def insert_state(self, name, deadline="inf"):
42
+ """
43
+ Insert "state" into the BehaviorModel
44
+
45
+ Args:
46
+ name (str): State name
47
+ deadline (str or Infinite): Time until the state is active. Defaults to Infinite.
48
+ """
49
+ self._states[name] = float(deadline)
50
+
51
+ def update_state(self, name, deadline="inf"):
52
+ """
53
+ Updates an existing state in the BehaviorModel
54
+
55
+ Args:
56
+ name (str): state name to update
57
+ deadline (str or Infinite): Time until the state is active. Defaults to Infinite.
58
+ """
59
+ self._states[name] = float(deadline)
60
+
61
+ def cancel_rescheduling(self):
62
+ """Canceled scheduling"""
63
+ self._cancel_reschedule_f = True
64
+
65
+
66
+ def init_state(self, state):
67
+ """
68
+ Sets the initial state
69
+
70
+ Args:
71
+ state (str): Initial state name
72
+ """
73
+ self._cur_state = state
74
+
75
+ def set_global_time(self, gtime):
76
+ """
77
+ Set gloabl time
78
+
79
+ Args:
80
+ gtime (float): Global time
81
+ """
82
+ self.global_time = gtime
83
+ pass
84
+
85
+ @abstractmethod
86
+ def ext_trans(self, port, msg):
87
+ """Defines the external transition, to be implemented by subclasses"""
88
+ pass
89
+
90
+ @abstractmethod
91
+ def int_trans(self):
92
+ """Defines the internal transition, to be implemented by subclasses"""
93
+ pass
94
+
95
+ @abstractmethod
96
+ def output(self, msg_deliver):
97
+ """Defines the output function, to be implemented by subclasses"""
98
+ pass
99
+
100
+ def get_cancel_flag(self):
101
+ """Returns the cancel reschedule flag"""
102
+ return self._cancel_reschedule_f
103
+
104
+ def reset_cancel_flag(self):
105
+ """Resets the cancel reschedule flag to False"""
106
+ self._cancel_reschedule_f = False
107
+
108
+ def retrieve_states(self):
109
+ """Returns the states dictionary"""
110
+ return self._states
111
+
112
+ def find_state(self, name):
113
+ """Checks if a state exists
114
+
115
+ Args:
116
+ name (str): State name
117
+
118
+ Returns:
119
+ bool: True if state exists, False otherwise
120
+ """
121
+ return name in self._states
122
+
123
+ def insert_external_transition(self, pre_state, event, post_state):
124
+ """Inserts an external transition
125
+
126
+ Args:
127
+ pre_state (str): Previous state
128
+ event (str): Event causing the transition
129
+ post_state (str): Next state
130
+ """
131
+ self.external_transition_map_tuple[(pre_state, event)] = post_state
132
+ if pre_state in self.external_transition_map_state:
133
+ self.external_transition_map_state[pre_state].append((event, post_state))
134
+ else:
135
+ self.external_transition_map_state[pre_state] = [(event, post_state)]
136
+
137
+ def retrieve_external_transition(self, pre_state):
138
+ """Retrieves external transitions for a given state
139
+
140
+ Args:
141
+ pre_state (str): Previous state
142
+
143
+ Returns:
144
+ list: List of external transitions
145
+ """
146
+ return self.external_transition_map_state[pre_state]
147
+
148
+ def retrieve_next_external_state(self, pre_state, event):
149
+ """Retrieves the next state for a given external transition
150
+
151
+ Args:
152
+ pre_state (str): Previous state
153
+ event (str): Event causing the transition
154
+
155
+ Returns:
156
+ str: Next state
157
+ """
158
+ return self.external_transition_map_tuple[(pre_state, event)]
159
+
160
+ def find_external_transition(self, pre_state):
161
+ """Checks if there are external transitions for a given state
162
+
163
+ Args:
164
+ pre_state (str): Previous state
165
+
166
+ Returns:
167
+ bool: True if transitions exist, False otherwise
168
+ """
169
+ return pre_state in self.external_transition_map_state
170
+
171
+ def insert_internal_transition(self, pre_state, event, post_state):
172
+ """Inserts an internal transition
173
+
174
+ Args:
175
+ pre_state (str): Previous state
176
+ event (str): Event causing the transition
177
+ post_state (str): Next state
178
+ """
179
+ self.internal_transition_map_tuple[(pre_state, event)] = post_state
180
+ if pre_state in self.internal_transition_map_state:
181
+ self.internal_transition_map_state[pre_state].append((event, post_state))
182
+ else:
183
+ self.internal_transition_map_state[pre_state] = [(event, post_state)]
184
+
185
+ def retrieve_internal_transition(self, pre_state):
186
+ """Retrieves internal transitions for a given state
187
+
188
+ Args:
189
+ pre_state (str): Previous state
190
+
191
+ Returns:
192
+ list: List of internal transitions
193
+ """
194
+ return self.internal_transition_map_state[pre_state]
195
+
196
+ def retrieve_next_internal_state(self, pre_state, event):
197
+ """Retrieves the next state for a given internal transition
198
+
199
+ Args:
200
+ pre_state (str): Previous state
201
+ event (str): Event causing the transition
202
+
203
+ Returns:
204
+ str: Next state
205
+ """
206
+ return self.internal_transition_map_tuple[(pre_state, event)]
207
+
208
+ def find_internal_transition(self, pre_state):
209
+ """Checks if there are internal transitions for a given state
210
+
211
+ Args:
212
+ pre_state (str): Previous state
213
+
214
+ Returns:
215
+ bool: True if transitions exist, False otherwise
216
+ """
217
+ return pre_state in self.internal_transition_map_state
218
+
219
+ def serialize(self):
220
+ """Serializes the behavior model to a JSON object
221
+
222
+ Returns:
223
+ OrderedDict: Serialized JSON object
224
+ """
225
+ json_obj = OrderedDict()
226
+ json_obj["name"] = self._name
227
+ json_obj["states"] = self._states
228
+ json_obj["input_ports"] = self.retrieve_input_ports()
229
+ json_obj["output_ports"] = self.retrieve_output_ports()
230
+ json_obj["external_trans"] = self.external_transition_map_state
231
+ json_obj["internal_trans"] = self.internal_transition_map_state
232
+ return json_obj
233
+
234
+ def deserialize(self, json):
235
+ """Deserializes the behavior model from a JSON object
236
+
237
+ Args:
238
+ json (dict): JSON object containing the model data
239
+ """
240
+ self._name = json["name"]
241
+ for key, value in json["states"].items():
242
+ self.insert_state(key, value)
243
+
244
+ # Handle input ports
245
+ for port in json["input_ports"]:
246
+ self.insert_input_port(port)
247
+
248
+ # Handle output ports
249
+ for port in json["output_ports"]:
250
+ self.insert_output_port(port)
251
+
252
+ # Handle external transitions
253
+ for key, value in json["external_trans"].items():
254
+ for ns in value:
255
+ self.insert_external_transition(key, ns[0], ns[1])
256
+
257
+ # Handle internal transitions
258
+ for key, value in json["internal_trans"].items():
259
+ for ns in value:
260
+ self.insert_internal_transition(key, ns[0], ns[1])
pyjevsim/core_model.py ADDED
@@ -0,0 +1,103 @@
1
+ """
2
+ Author: Changbeom Choi (@cbchoi)
3
+ Copyright (c) 2014-2020 Handong Global University
4
+ Copyright (c) 2021-2024 Hanbat National University
5
+ License: MIT. The full license text is available at:
6
+ https://github.com/eventsim/pyjevsim/blob/main/LICENSE
7
+
8
+ This module contains CoreModel, the parent class of all Model Types.
9
+ """
10
+ from .system_object import SystemObject
11
+
12
+ class CoreModel(SystemObject):
13
+ """
14
+ All forms of Models in Pyjevsim have a CoreModel as their foundation.
15
+ CoreModel class serves as a base model with basic functionalities for input and output ports.
16
+ """
17
+ def __init__(self, _name, _type):
18
+ """
19
+ Args:
20
+ _name (str): Model name
21
+ _type (ModelType.BEHAVIORAL or ModelType.STRUCTURAL or ModelType.UTILITY): Model type
22
+ """
23
+ super().__init__()
24
+ # Model Type
25
+ self.model_type = _type
26
+ self._name = _name
27
+
28
+ # Input Ports Declaration
29
+ self.external_input_ports = []
30
+ # Output Ports Declaration
31
+ self.external_output_ports = []
32
+
33
+ def set_name(self, _name):
34
+ """
35
+ Sets the name of the model.
36
+
37
+ Args:
38
+ _name (str): New name of the model
39
+ """
40
+ self._name = _name
41
+
42
+ def get_name(self):
43
+ """
44
+ Returns the name of the model.
45
+
46
+ Returns:
47
+ str: Name of the model
48
+ """
49
+ return self._name
50
+
51
+ def get_model_type(self):
52
+ """
53
+ Returns the type of the model.
54
+
55
+ Returns:
56
+ (ModelType.BEHAVIORAL or ModelType.STRUCTURAL or ModelType.UTILITY) : Type of the model
57
+ """
58
+ return self.model_type
59
+
60
+ def insert_input_port(self, port):
61
+ """Inserts an input port to the model.
62
+
63
+ Args:
64
+ port (str): Name of the input port
65
+ """
66
+ self.external_input_ports.append(port)
67
+
68
+ def retrieve_input_ports(self):
69
+ """
70
+ Retrieves all input ports of the model.
71
+
72
+ Returns:
73
+ list: List of input ports
74
+ """
75
+ return self.external_input_ports
76
+
77
+ def insert_output_port(self, port):
78
+ """
79
+ Inserts an output port to the model.
80
+
81
+ Args:
82
+ port (str): Name of the output port
83
+ """
84
+ self.external_output_ports.append(port)
85
+
86
+ def retrieve_output_ports(self):
87
+ """
88
+ Retrieves all output ports of the model.
89
+
90
+ Returns:
91
+ list: List of output ports
92
+ """
93
+ return self.external_output_ports
94
+
95
+ def model_snapshot(self):
96
+ """
97
+ Snapshot the information of the running model.
98
+
99
+ Returns:
100
+ dict: Dictionary containing model type, model name, and model data
101
+ """
102
+ model_info = {"type": self.model_type, "name": self._name, "data": self}
103
+ return model_info
@@ -0,0 +1,42 @@
1
+ """
2
+ Author: Changbeom Choi (@cbchoi)
3
+ Copyright (c) 2014-2020 Handong Global University
4
+ Copyright (c) 2021-2024 Hanbat National University
5
+ License: MIT. The full license text is available at:
6
+ https://github.com/eventsim/pyjevsim/blob/main/LICENSE
7
+
8
+ This module contains a default model, DefaultMessageCatcher, for catching uncaught messages.
9
+ """
10
+
11
+ from .behavior_model import BehaviorModel
12
+ from .definition import *
13
+
14
+ class DefaultMessageCatcher(BehaviorModel):
15
+ """
16
+ A default model for catching uncaught messages.
17
+ Receiving and not processing uncaught messages.
18
+ """
19
+
20
+ def __init__(self, _name):
21
+ super().__init__(_name)
22
+
23
+ self.init_state("IDLE") # Set initial state to 'IDLE'
24
+ self.insert_state("IDLE", Infinite) # Insert 'IDLE' state with infinite duration
25
+ self.insert_input_port("uncaught") # Insert 'uncaught' input port
26
+
27
+ def ext_trans(self, port, msg):
28
+ """
29
+ Received an uncaught message.
30
+
31
+ Args:
32
+ port (str): The port name
33
+ msg (SysMessage): The incoming message
34
+ """
35
+ data = msg.retrieve() # Retrieve message
36
+
37
+ def int_trans(self):
38
+ return
39
+
40
+ def output(self, msg_deliver):
41
+ return msg_deliver
42
+