sfttoolbox 0.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.
- sfttoolbox/DES/__init__.py +1 -0
- sfttoolbox/DES/_des.py +391 -0
- sfttoolbox/DES/examples/__init__.py +0 -0
- sfttoolbox/DES/examples/_example1.py +103 -0
- sfttoolbox/DES/examples/_example2.py +170 -0
- sfttoolbox/__init__.py +13 -0
- sfttoolbox/graphing.py +7 -0
- sfttoolbox/mapping/__init__.py +341 -0
- sfttoolbox/mapping/examples/__init__.py +0 -0
- sfttoolbox/mapping/examples/example1.py +133 -0
- sfttoolbox/mapping/examples/example2.py +35 -0
- sfttoolbox/mapping/isochrone_generator.py +322 -0
- sfttoolbox/plotting/__init__.py +1 -0
- sfttoolbox/plotting/_plotting.py +125 -0
- sfttoolbox-0.0.0.dist-info/METADATA +42 -0
- sfttoolbox-0.0.0.dist-info/RECORD +25 -0
- sfttoolbox-0.0.0.dist-info/WHEEL +5 -0
- sfttoolbox-0.0.0.dist-info/licenses/LICENSE.txt +437 -0
- sfttoolbox-0.0.0.dist-info/top_level.txt +2 -0
- test/DES/__init__.py +0 -0
- test/DES/test_des.py +152 -0
- test/__init__.py +0 -0
- test/mapping/__init__.py +0 -0
- test/mapping/test_isochrone_generator.py +79 -0
- test/mapping/test_somerset_map.py +83 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from ._des import *
|
sfttoolbox/DES/_des.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Simulation Module
|
|
3
|
+
|
|
4
|
+
This module provides a simulation framework for modeling patient flow through a directed graph representing a
|
|
5
|
+
healthcare system or any other system with similar dynamics.
|
|
6
|
+
The main class, `Simulation`, integrates with a patient generator interface to simulate the movement of patients through
|
|
7
|
+
the nodes of the graph, taking into account capacities and resource constraints at each node.
|
|
8
|
+
|
|
9
|
+
Classes:
|
|
10
|
+
- Simulation: Manages the simulation process, including patient generation, daily updates, and graph traversal.
|
|
11
|
+
- Patient: Represents a patient in the simulation, tracking their pathway through the system.
|
|
12
|
+
- PatientGeneratorInterface: An interface for generating new patients at each step of the simulation.
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
1. Import necessary libraries:
|
|
16
|
+
```
|
|
17
|
+
import networkx as nx
|
|
18
|
+
```
|
|
19
|
+
2. Define a directed graph (`nx.DiGraph`) with nodes representing different stages or units in the system.
|
|
20
|
+
Each node can have attributes like 'capacity' and 'resource'.
|
|
21
|
+
3. Implement a patient generator class that adheres to the `PatientGeneratorInterface`.
|
|
22
|
+
4. Initialize the `Simulation` class with the graph and the patient generator.
|
|
23
|
+
5. Run the simulation using the `run_simulation` method.
|
|
24
|
+
|
|
25
|
+
For examples, see files titled "_exampleX.py" in the examples directory.
|
|
26
|
+
|
|
27
|
+
This module is designed to be flexible and extensible, allowing users to customize the graph structure, patient
|
|
28
|
+
attributes, and generation logic according to their specific needs.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
__all__ = ["Simulation", "distribution_wrapper"]
|
|
32
|
+
|
|
33
|
+
import functools
|
|
34
|
+
import logging
|
|
35
|
+
from itertools import cycle
|
|
36
|
+
from typing import Any, Dict, List, Optional, Protocol
|
|
37
|
+
|
|
38
|
+
import networkx as nx
|
|
39
|
+
import numpy as np
|
|
40
|
+
|
|
41
|
+
logger = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class PatientInterface(Protocol):
|
|
45
|
+
def __init__(self, id: int) -> None:
|
|
46
|
+
"""
|
|
47
|
+
Initialize a patient interface with an ID and a pathway.
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
id (int): The patient's ID.
|
|
51
|
+
pathway (List[Any]): The patient's pathway through the system.
|
|
52
|
+
"""
|
|
53
|
+
self.id = id
|
|
54
|
+
self.pathway = []
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class PatientGeneratorInterface(Protocol):
|
|
58
|
+
def generate_patients(self, day_num: int, day: str) -> List[PatientInterface]:
|
|
59
|
+
"""
|
|
60
|
+
Generate a list of new patients for the given day.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
day_num (int): The current day number in the simulation.
|
|
64
|
+
day (str): The current day of the week.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
List[PatientInterface]: A list of newly generated patients.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class CapacityInterface(Protocol):
|
|
72
|
+
def get(
|
|
73
|
+
self, resource: Any, patient: PatientInterface, day_num: int, day: str
|
|
74
|
+
) -> bool:
|
|
75
|
+
"""
|
|
76
|
+
Check if the capacity allows the resource allocation for the given patient.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
resource (Any): The resource to check against capacity.
|
|
80
|
+
patient (PatientInterface): The patient for whom the resource allocation is checked.
|
|
81
|
+
day_num (int): The day number of the simulation.
|
|
82
|
+
day (str): The day of the week.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
bool: True if the capacity allows resource allocation, False otherwise.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def update_day(self, day_num: int, day: str) -> List[Any]:
|
|
89
|
+
"""
|
|
90
|
+
Update the capacity status for a given day.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
day_num (int): The current day number in the simulation.
|
|
94
|
+
day (str): The current day of the week.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
List[Any]: List of patients to be moved on the current day.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def distribution_wrapper(func: callable) -> callable:
|
|
102
|
+
"""
|
|
103
|
+
A decorator that wraps a distribution function to allow it fit the interface in Simulation.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
func (callable): The distribution function to be wrapped.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
callable: The wrapped function.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
@functools.wraps(func)
|
|
113
|
+
def wrapper(*args, **kwargs):
|
|
114
|
+
return func()
|
|
115
|
+
|
|
116
|
+
return wrapper
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Simulation:
|
|
120
|
+
def __init__(
|
|
121
|
+
self,
|
|
122
|
+
graph: nx.DiGraph,
|
|
123
|
+
patient_generator: PatientGeneratorInterface,
|
|
124
|
+
number_of_days: int,
|
|
125
|
+
start_day: str = "Mon",
|
|
126
|
+
):
|
|
127
|
+
"""
|
|
128
|
+
Initialize the simulation with a directed graph and a patient generator.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
graph (nx.DiGraph): The directed graph representing the system.
|
|
132
|
+
patient_generator (PatientGeneratorInterface): The patient generator interface for creating new patients.
|
|
133
|
+
number_of_days (int): The number of days to run the simulation.
|
|
134
|
+
"""
|
|
135
|
+
self.final_day_num = number_of_days
|
|
136
|
+
self.graph = graph
|
|
137
|
+
self.graph_checked = self.check_graph()
|
|
138
|
+
self.start_node = self.identify_start_node()
|
|
139
|
+
self.patient_generator = patient_generator
|
|
140
|
+
|
|
141
|
+
self.capacities = self.collect_capacities()
|
|
142
|
+
|
|
143
|
+
self.discharged_patients = []
|
|
144
|
+
|
|
145
|
+
days_of_the_week = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
|
146
|
+
start_index = days_of_the_week.index(start_day)
|
|
147
|
+
days_of_the_week = (
|
|
148
|
+
days_of_the_week[start_index:] + days_of_the_week[:start_index]
|
|
149
|
+
)
|
|
150
|
+
self.days_of_week = cycle(days_of_the_week)
|
|
151
|
+
|
|
152
|
+
self.day_num = None
|
|
153
|
+
self.day = None
|
|
154
|
+
|
|
155
|
+
def check_graph(self) -> True:
|
|
156
|
+
"""
|
|
157
|
+
Check the graph for interfaces, probabilities, etc.
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
bool: True if the graph passes all checks, False otherwise.
|
|
161
|
+
"""
|
|
162
|
+
# TODO: checks interfaces, probabilities etc...
|
|
163
|
+
# check if a capacity is present, a resource is also defined
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
def identify_start_node(self) -> Any:
|
|
167
|
+
"""
|
|
168
|
+
Identify the starting node in the graph.
|
|
169
|
+
|
|
170
|
+
Returns:
|
|
171
|
+
Any: The starting node.
|
|
172
|
+
|
|
173
|
+
Raises:
|
|
174
|
+
AttributeError: If no starting node is found.
|
|
175
|
+
"""
|
|
176
|
+
for node, degree in self.graph.in_degree:
|
|
177
|
+
if degree == 0:
|
|
178
|
+
starting_node = node
|
|
179
|
+
break
|
|
180
|
+
else:
|
|
181
|
+
# TODO: in a scenario where something is fed back to the start this won't work...
|
|
182
|
+
raise AttributeError("No starting node")
|
|
183
|
+
|
|
184
|
+
return starting_node
|
|
185
|
+
|
|
186
|
+
def collect_capacities(self) -> Dict[Any, Any]:
|
|
187
|
+
"""
|
|
188
|
+
Collect the capacities from the graph nodes.
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
Dict[Any, Any]: A dictionary of capacities for each node.
|
|
192
|
+
"""
|
|
193
|
+
return nx.get_node_attributes(self.graph, "capacity")
|
|
194
|
+
|
|
195
|
+
def run_simulation(self) -> None:
|
|
196
|
+
"""
|
|
197
|
+
Run the simulation for the specified number of days.
|
|
198
|
+
"""
|
|
199
|
+
# TODO: update day, go through all the patients on the books and run the relevant update days
|
|
200
|
+
# TODO: generate patients
|
|
201
|
+
# TODO: run each patient down the graph until assigned a capacity or discharged
|
|
202
|
+
|
|
203
|
+
for day_num, day in zip(range(0, self.final_day_num, 1), self.days_of_week):
|
|
204
|
+
self.day_num = day_num
|
|
205
|
+
self.day = day
|
|
206
|
+
logger.info(f"day number: {day_num}, day: {day}")
|
|
207
|
+
|
|
208
|
+
patients_to_move = {
|
|
209
|
+
node: capacity.update_day(day_num, day)
|
|
210
|
+
for node, capacity in self.capacities.items()
|
|
211
|
+
}
|
|
212
|
+
if any(patients_to_move.values()):
|
|
213
|
+
# TODO: use itertools here
|
|
214
|
+
for node, patients in patients_to_move.items():
|
|
215
|
+
for patient in patients:
|
|
216
|
+
logger.info(f"Moving previous patient: patient {patient.id}")
|
|
217
|
+
|
|
218
|
+
discharged_patient = self.traverse_graph(
|
|
219
|
+
node, patient, check_capacity=False
|
|
220
|
+
)
|
|
221
|
+
# TODO: abstract this out
|
|
222
|
+
if discharged_patient is not None:
|
|
223
|
+
self.discharged_patients.append(discharged_patient)
|
|
224
|
+
|
|
225
|
+
new_patients = self.patient_generator.generate_patients(day_num, day)
|
|
226
|
+
|
|
227
|
+
node = self.start_node
|
|
228
|
+
for patient in new_patients:
|
|
229
|
+
logger.info(f"New patient generated: patient {patient.id}")
|
|
230
|
+
|
|
231
|
+
discharged_patient = self.traverse_graph(node, patient)
|
|
232
|
+
if discharged_patient:
|
|
233
|
+
self.discharged_patients.append(discharged_patient)
|
|
234
|
+
|
|
235
|
+
def traverse_graph(
|
|
236
|
+
self, node: Any, patient: PatientInterface, check_capacity: bool = True
|
|
237
|
+
) -> Optional[PatientInterface]:
|
|
238
|
+
"""
|
|
239
|
+
Traverse the graph for a given patient starting from a specified node.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
node (Any): The current node in the graph.
|
|
243
|
+
patient (Patient): The patient being processed.
|
|
244
|
+
check_capacity (bool, optional): Whether to check capacity constraints. Defaults to True.
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Optional[Patient]: The patient if they are discharged, otherwise None.
|
|
248
|
+
"""
|
|
249
|
+
node_attrs = self.graph.nodes[node]
|
|
250
|
+
next_nodes_and_edge_attrs = [*zip(*self.graph[node].items())]
|
|
251
|
+
|
|
252
|
+
# Pathway required for terminal capacity node
|
|
253
|
+
if next_nodes_and_edge_attrs:
|
|
254
|
+
next_nodes, edge_attrs = next_nodes_and_edge_attrs
|
|
255
|
+
else:
|
|
256
|
+
next_nodes, edge_attrs = [], dict()
|
|
257
|
+
|
|
258
|
+
capacity = node_attrs.get("capacity")
|
|
259
|
+
if check_capacity and capacity:
|
|
260
|
+
resource = node_attrs["resource"]
|
|
261
|
+
|
|
262
|
+
if not capacity.get(
|
|
263
|
+
resource=resource, patient=patient, day_num=self.day_num, day=self.day
|
|
264
|
+
):
|
|
265
|
+
for edge_index, edge_attr in enumerate(edge_attrs):
|
|
266
|
+
if "capacity" in edge_attr:
|
|
267
|
+
break
|
|
268
|
+
next_node = next_nodes[edge_index]
|
|
269
|
+
else:
|
|
270
|
+
return
|
|
271
|
+
|
|
272
|
+
else:
|
|
273
|
+
patient.pathway.append(node)
|
|
274
|
+
|
|
275
|
+
if len(next_nodes) == 1:
|
|
276
|
+
next_node = next_nodes[0]
|
|
277
|
+
elif len(next_nodes) == 0:
|
|
278
|
+
# Final node reached - pathway for terminal nodes with capacity
|
|
279
|
+
return patient
|
|
280
|
+
else:
|
|
281
|
+
prob = node_attrs.get("distribution")(patient)
|
|
282
|
+
|
|
283
|
+
traverse_probs = np.cumsum(
|
|
284
|
+
[edge_attr.get("probability", 0) for edge_attr in edge_attrs]
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
if traverse_probs[-1] != 1:
|
|
288
|
+
bernoulli = [edge_attr.get("bernoulli") for edge_attr in edge_attrs]
|
|
289
|
+
|
|
290
|
+
if any(bernoulli):
|
|
291
|
+
assert (
|
|
292
|
+
len(bernoulli) == 2
|
|
293
|
+
), f"When using Bernoulli, there should only be 2 options, check node {node}"
|
|
294
|
+
next_node = (
|
|
295
|
+
next_nodes[0] if bernoulli[0] == prob else next_nodes[1]
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
else:
|
|
299
|
+
raise ValueError(
|
|
300
|
+
f"Probabilities of pathway must add up to 1 or contain a Bernoulli trial, check node {node}"
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
else:
|
|
304
|
+
next_node = next_nodes[np.searchsorted(traverse_probs, prob)]
|
|
305
|
+
|
|
306
|
+
logger.info(f"Moving to next node: {next_node}")
|
|
307
|
+
|
|
308
|
+
if self.graph.out_degree[next_node] > 0 or next_node in self.capacities:
|
|
309
|
+
return self.traverse_graph(next_node, patient)
|
|
310
|
+
else:
|
|
311
|
+
# Final node reached
|
|
312
|
+
patient.pathway.append(next_node)
|
|
313
|
+
return patient
|
|
314
|
+
|
|
315
|
+
def plot_graph(self, filename: str) -> None:
|
|
316
|
+
"""
|
|
317
|
+
Generate an HTML file to visualize the graph using Mermaid.js.
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
filename (str): The name of the file where the graph visualization will be saved.
|
|
321
|
+
"""
|
|
322
|
+
node_numbers = {v: k for k, v in dict(enumerate(self.graph.nodes)).items()}
|
|
323
|
+
|
|
324
|
+
graph_string = "\n".join(
|
|
325
|
+
[
|
|
326
|
+
self.__format_edge(edge, node_numbers)
|
|
327
|
+
for edge in self.graph.edges(data=True)
|
|
328
|
+
]
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
html_string = f"""
|
|
332
|
+
<html>
|
|
333
|
+
<body>
|
|
334
|
+
|
|
335
|
+
<style>
|
|
336
|
+
.node rect {{
|
|
337
|
+
fill: #edae49 !important;
|
|
338
|
+
stroke: #edae49 !important;
|
|
339
|
+
}}
|
|
340
|
+
</style>
|
|
341
|
+
<pre class="mermaid">
|
|
342
|
+
graph TD
|
|
343
|
+
{graph_string}
|
|
344
|
+
</pre>
|
|
345
|
+
<script type="module">
|
|
346
|
+
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
|
|
347
|
+
mermaid.initialize({{ startOnLoad: true }});
|
|
348
|
+
</script>
|
|
349
|
+
</body>
|
|
350
|
+
</html>
|
|
351
|
+
"""
|
|
352
|
+
|
|
353
|
+
with open(filename, "w") as fout:
|
|
354
|
+
fout.write(html_string)
|
|
355
|
+
|
|
356
|
+
def __format_node(self, node_name: str, attributes: Dict[str, Any]) -> str:
|
|
357
|
+
"""
|
|
358
|
+
Format the node information for graph visualization.
|
|
359
|
+
|
|
360
|
+
Args:
|
|
361
|
+
node_name (str): The name of the node.
|
|
362
|
+
attributes (Dict[str, Any]): The attributes of the node.
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
str: The formatted string representation of the node.
|
|
366
|
+
"""
|
|
367
|
+
atts = []
|
|
368
|
+
for k, v in attributes.items():
|
|
369
|
+
v = v.__name__ if hasattr(v, "__name__") else v
|
|
370
|
+
atts.append(f"{k}: {v}")
|
|
371
|
+
atts = "\n".join(atts)
|
|
372
|
+
return f"{node_name}\n{atts}"
|
|
373
|
+
|
|
374
|
+
def __format_edge(self, edge: Any, node_numbers: Dict[Any, int]) -> str:
|
|
375
|
+
"""
|
|
376
|
+
Format the edge information for graph visualization.
|
|
377
|
+
|
|
378
|
+
Args:
|
|
379
|
+
edge (Any): The edge in the graph, including source, target, and properties.
|
|
380
|
+
node_numbers (Dict[Any, int]): A mapping of node names to their corresponding numbers.
|
|
381
|
+
|
|
382
|
+
Returns:
|
|
383
|
+
str: The formatted string representation of the edge.
|
|
384
|
+
"""
|
|
385
|
+
src, tgt, props = edge
|
|
386
|
+
|
|
387
|
+
prop_string = ""
|
|
388
|
+
if props:
|
|
389
|
+
prop_string = "|" + "\n".join([f"{k}: {v}" for k, v in props.items()]) + "|"
|
|
390
|
+
|
|
391
|
+
return f"{node_numbers[src]}[{self.__format_node(src, self.graph.nodes[src])}] -->{prop_string} {node_numbers[tgt]}[{self.__format_node(tgt, self.graph.nodes[tgt])}]"
|
|
File without changes
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Simulation Example 1
|
|
3
|
+
|
|
4
|
+
This example demonstrates a simple simulation using a directed graph where patient movement is determined by
|
|
5
|
+
probabilities. This example does not take node capacity into account.
|
|
6
|
+
|
|
7
|
+
To run this example, use the following command in the terminal:
|
|
8
|
+
python _example1.py
|
|
9
|
+
|
|
10
|
+
Make sure you have the necessary dependencies installed, including the `networkx` library.
|
|
11
|
+
|
|
12
|
+
Dependencies:
|
|
13
|
+
- networkx
|
|
14
|
+
|
|
15
|
+
This example helps to illustrate the basic setup and execution of a simulation without capacity constraints, focusing
|
|
16
|
+
on probabilistic patient movement through the system.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
|
|
21
|
+
import networkx as nx
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
import sfttoolbox
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# This allows a standard distribution call to take in the patient object (and does nothing with it)
|
|
28
|
+
@sfttoolbox.DES.distribution_wrapper
|
|
29
|
+
def uniform():
|
|
30
|
+
return np.random.uniform()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Create a simple graph
|
|
34
|
+
G = nx.DiGraph()
|
|
35
|
+
G.add_edges_from(
|
|
36
|
+
[
|
|
37
|
+
("Patient arrives", "Patient triaged"),
|
|
38
|
+
# Probabilities determine the chance of moving
|
|
39
|
+
("Patient triaged", "Patient discharged", {"probability": 0.2}),
|
|
40
|
+
("Patient triaged", "Appointment made", {"probability": 0.8}),
|
|
41
|
+
("Appointment made", "Patient Treated"),
|
|
42
|
+
]
|
|
43
|
+
)
|
|
44
|
+
G.add_nodes_from(
|
|
45
|
+
[
|
|
46
|
+
# Defining a distribution to generate probabilities.
|
|
47
|
+
("Patient triaged", {"distribution": uniform})
|
|
48
|
+
]
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# id and pathway are required attributes to match the interface for the simulation
|
|
53
|
+
@dataclass
|
|
54
|
+
class Patient:
|
|
55
|
+
id: int
|
|
56
|
+
pathway: list[str] = field(default_factory=list)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# generate_patients is required to match the interface required for the simulation
|
|
60
|
+
class PatientGenerator:
|
|
61
|
+
def __init__(self):
|
|
62
|
+
self.id = 0
|
|
63
|
+
|
|
64
|
+
def generate_patients(self, day_num, day):
|
|
65
|
+
patients = []
|
|
66
|
+
if day == "Mon":
|
|
67
|
+
for _ in range(5):
|
|
68
|
+
patients.append(Patient(self.id))
|
|
69
|
+
self.id += 1
|
|
70
|
+
|
|
71
|
+
return patients
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
patient_generator = PatientGenerator()
|
|
76
|
+
|
|
77
|
+
number_of_simulation_days = 10
|
|
78
|
+
sim = sfttoolbox.DES.Simulation(G, patient_generator, number_of_simulation_days)
|
|
79
|
+
|
|
80
|
+
# Create an html file of the graph.
|
|
81
|
+
sim.plot_graph("sample_graph.html")
|
|
82
|
+
sim.run_simulation()
|
|
83
|
+
|
|
84
|
+
# We can then create a patient flow out of the discharged patients
|
|
85
|
+
G2 = nx.DiGraph()
|
|
86
|
+
|
|
87
|
+
for patient in sim.discharged_patients:
|
|
88
|
+
edges = [
|
|
89
|
+
(patient.pathway[i], patient.pathway[i + 1])
|
|
90
|
+
for i in range(len(patient.pathway) - 1)
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
# Create a graph out of the discharged patient pathway
|
|
94
|
+
G2.add_edges_from(edges)
|
|
95
|
+
|
|
96
|
+
# Add colour and value attributes to the edges
|
|
97
|
+
for edge in edges:
|
|
98
|
+
G2.edges[edge]["value"] = G2.edges[edge].get("value", 0) + 1
|
|
99
|
+
G2.edges[edge]["color"] = "blue"
|
|
100
|
+
|
|
101
|
+
# Use our convenient sankey generator to view the flow
|
|
102
|
+
sfttoolbox.plotting.generate_sankey(G2)
|
|
103
|
+
# %%
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Simulation Example 2
|
|
3
|
+
|
|
4
|
+
This example demonstrates a simulation using a directed graph where patient movement is determined by probabilities,
|
|
5
|
+
and nodes have capacity constraints based on available staff for appointments.
|
|
6
|
+
|
|
7
|
+
In this example, each node represents a unit where patients can have appointments. The capacity of each node is determined
|
|
8
|
+
by the available staff and the duration of the appointments. For instance, if a node has staff available for 8 hours in a day,
|
|
9
|
+
and each appointment requires 1 hour, the node can handle up to 8 appointments per day.
|
|
10
|
+
|
|
11
|
+
To run this example, use the following command in the terminal:
|
|
12
|
+
python _example2.py
|
|
13
|
+
|
|
14
|
+
Make sure you have the necessary dependencies installed, including the `networkx` library.
|
|
15
|
+
|
|
16
|
+
Dependencies:
|
|
17
|
+
- networkx
|
|
18
|
+
|
|
19
|
+
This example illustrates how to set up and execute a simulation that incorporates both probabilistic patient movement
|
|
20
|
+
and capacity constraints based on staff availability. It provides a more realistic scenario by considering resource
|
|
21
|
+
limitations in the healthcare system.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
|
|
26
|
+
import networkx as nx
|
|
27
|
+
import numpy as np
|
|
28
|
+
|
|
29
|
+
import sfttoolbox
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# This allows a standard distribution call to take in the patient object (and does nothing with it)
|
|
33
|
+
@sfttoolbox.DES.distribution_wrapper
|
|
34
|
+
def uniform():
|
|
35
|
+
return np.random.uniform()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class AppointmentDuration:
|
|
40
|
+
time_required: int
|
|
41
|
+
|
|
42
|
+
# This is required if using dataclasses and trying to plot the graph
|
|
43
|
+
def __post_init__(self):
|
|
44
|
+
self.__name__ = self.__class__.__name__
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# a capacity object must include a "get" method that takes the resource and patient objects
|
|
48
|
+
# and an update_day method.
|
|
49
|
+
class StaffCapacity:
|
|
50
|
+
def __init__(self):
|
|
51
|
+
self.weekly_capacity = {
|
|
52
|
+
"Mon": 2,
|
|
53
|
+
"Tues": 2,
|
|
54
|
+
"Weds": 2,
|
|
55
|
+
"Thurs": 2,
|
|
56
|
+
"Fri": 0,
|
|
57
|
+
"Sat": 0,
|
|
58
|
+
"Sun": 0,
|
|
59
|
+
}
|
|
60
|
+
self.current_weekly_capacity = self.weekly_capacity.copy()
|
|
61
|
+
self.waiting_list = []
|
|
62
|
+
self.treatment_list = []
|
|
63
|
+
|
|
64
|
+
self.wait_times = {}
|
|
65
|
+
|
|
66
|
+
self.hours_required = None
|
|
67
|
+
|
|
68
|
+
# Giving it a name makes the graph look nicer!
|
|
69
|
+
self.__name__ = self.__class__.__name__
|
|
70
|
+
|
|
71
|
+
def get(self, resource, patient, day_num, day):
|
|
72
|
+
self.hours_required = resource.time_required
|
|
73
|
+
self.treat_patient(patient, day_num, day)
|
|
74
|
+
# I'm returning true here because I'll keep adding patients to the waiting list.
|
|
75
|
+
return True
|
|
76
|
+
|
|
77
|
+
def treat_patient(self, patient, day_num, day):
|
|
78
|
+
if self.hours_required > self.current_weekly_capacity[day]:
|
|
79
|
+
self.waiting_list.append(patient)
|
|
80
|
+
self.wait_times[patient.id] = {"on": day_num}
|
|
81
|
+
else:
|
|
82
|
+
self.treatment_list.append(patient)
|
|
83
|
+
self.current_weekly_capacity[day] -= self.hours_required
|
|
84
|
+
|
|
85
|
+
def update_day(self, day_num, day):
|
|
86
|
+
self.current_weekly_capacity = self.weekly_capacity.copy()
|
|
87
|
+
|
|
88
|
+
patients_to_return = self.treatment_list
|
|
89
|
+
self.treatment_list = []
|
|
90
|
+
|
|
91
|
+
for idx, patient in enumerate(self.waiting_list):
|
|
92
|
+
if self.hours_required > self.current_weekly_capacity[day]:
|
|
93
|
+
break
|
|
94
|
+
else:
|
|
95
|
+
self.treatment_list.append(patient)
|
|
96
|
+
self.current_weekly_capacity[day] -= self.hours_required
|
|
97
|
+
self.waiting_list.pop(idx)
|
|
98
|
+
|
|
99
|
+
self.wait_times[patient.id]["off"] = day_num
|
|
100
|
+
|
|
101
|
+
return patients_to_return
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
staff_capacity = StaffCapacity()
|
|
105
|
+
|
|
106
|
+
G = nx.DiGraph()
|
|
107
|
+
G.add_edges_from(
|
|
108
|
+
[
|
|
109
|
+
("Patient arrives", "Patient triaged"),
|
|
110
|
+
("Patient triaged", "Patient discharged", {"probability": 0.2}),
|
|
111
|
+
("Patient triaged", "Appointment made", {"probability": 0.8}),
|
|
112
|
+
("Appointment made", "Patient Treated"),
|
|
113
|
+
]
|
|
114
|
+
)
|
|
115
|
+
G.add_nodes_from(
|
|
116
|
+
[
|
|
117
|
+
("Patient triaged", {"distribution": uniform}),
|
|
118
|
+
(
|
|
119
|
+
"Appointment made",
|
|
120
|
+
{"capacity": staff_capacity, "resource": AppointmentDuration(1)},
|
|
121
|
+
),
|
|
122
|
+
]
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# id and pathway are required attributes to match the interface for the simulation
|
|
127
|
+
@dataclass
|
|
128
|
+
class Patient:
|
|
129
|
+
id: int
|
|
130
|
+
pathway: list[str] = field(default_factory=list)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class PatientGenerator:
|
|
134
|
+
def __init__(self):
|
|
135
|
+
self.id = 0
|
|
136
|
+
|
|
137
|
+
# This is required to match the interface required for the simulation
|
|
138
|
+
def generate_patients(self, day_num, day):
|
|
139
|
+
patients = []
|
|
140
|
+
if day == "Mon":
|
|
141
|
+
for _ in range(50):
|
|
142
|
+
patients.append(Patient(self.id))
|
|
143
|
+
self.id += 1
|
|
144
|
+
|
|
145
|
+
return patients
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__":
|
|
149
|
+
patient_generator = PatientGenerator()
|
|
150
|
+
|
|
151
|
+
simulation_days = 10
|
|
152
|
+
sim = sfttoolbox.DES.Simulation(G, patient_generator, simulation_days)
|
|
153
|
+
|
|
154
|
+
sim.plot_graph("sample_graph.html")
|
|
155
|
+
|
|
156
|
+
sim.run_simulation()
|
|
157
|
+
|
|
158
|
+
# Because we stored the wait times in the capacity object, we can now retrieve them and look at some metrics!
|
|
159
|
+
number_of_patients_waiting = len(staff_capacity.wait_times)
|
|
160
|
+
mean_length_of_wait = np.mean(
|
|
161
|
+
[
|
|
162
|
+
patient["off"] - patient["on"]
|
|
163
|
+
for patient in staff_capacity.wait_times.values()
|
|
164
|
+
if patient.get("off")
|
|
165
|
+
]
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
print(
|
|
169
|
+
f"{number_of_patients_waiting} patients waited an average of {mean_length_of_wait :.2f} days"
|
|
170
|
+
)
|
sfttoolbox/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from . import DES, graphing, plotting
|
|
2
|
+
|
|
3
|
+
team_colours = {
|
|
4
|
+
"red": {"hex": "#d1495b", "rgb": "RGB(209, 73, 91)"},
|
|
5
|
+
"green": {"hex": "#66a182", "rgb": "RGB(102, 161, 130)"},
|
|
6
|
+
"yellow": {"hex": "#edae49", "rgb": "RGB(237, 174, 73)"},
|
|
7
|
+
"blue_grey": {"hex": "#9db2bf", "rgb": "RGB(157, 178, 191)"},
|
|
8
|
+
"grey": {"hex": "#dde6ed", "rgb": "RGB(221, 230, 237)"},
|
|
9
|
+
"blue": {"hex": "#00789c", "rgb": "RGB(0, 120, 156)"},
|
|
10
|
+
"dark_blue": {"hex": "#27374d", "rgb": "RGB(39, 55, 77)"},
|
|
11
|
+
"orange": {"hex": "#eb7956", "rgb": "RGB(235, 121, 86)"},
|
|
12
|
+
"white": {"hex": "#ffffff", "rgb": "RGB(255, 255, 255)"},
|
|
13
|
+
}
|