Skip to content

Commit 977a965

Browse files
committed
Add example for Workflow Optimization Problem
1 parent 60ef73d commit 977a965

File tree

2 files changed

+215
-0
lines changed

2 files changed

+215
-0
lines changed

Diff for: README.md

+76
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,82 @@ print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.soluti
720720
```
721721

722722

723+
**Healthcare Workflow Optimization Problem**
724+
725+
Define a chromosome representation that encodes the allocation of resources and patient flow in the emergency
726+
department. This could be a binary matrix where each row represents a patient and each column represents a resource
727+
(room). If the element is 1, it means the patient is assigned to that particular room, and if the element is 0, it
728+
means the patient is not assigned to that room
729+
730+
Please note that this implementation is a basic template and may require further customization based on the specific
731+
objectives, constraints, and evaluation criteria of your healthcare workflow optimization problem. You'll need to
732+
define the specific fitness function and optimization objectives based on the factors you want to optimize, such as
733+
patient waiting times, resource utilization, and other relevant metrics in the healthcare workflow context.
734+
735+
736+
```python
737+
import numpy as np
738+
from mealpy import BinaryVar, WOA, Problem
739+
740+
# Define the problem parameters
741+
num_patients = 50 # Number of patients
742+
num_resources = 10 # Number of resources (room)
743+
744+
# Define the patient waiting time matrix (randomly generated for the example)
745+
# Why? May be, doctors need time to prepare tools,...
746+
waiting_matrix = np.random.randint(1, 10, size=(num_patients, num_resources))
747+
748+
data = {
749+
"num_patients": num_patients,
750+
"num_resources": num_resources,
751+
"waiting_matrix": waiting_matrix,
752+
"max_resource_capacity": 10, # Maximum capacity of each room
753+
"max_waiting_time": 60, # Maximum waiting time
754+
"penalty_value": 1e2, # Define a penalty value
755+
"penalty_patient": 1e10
756+
}
757+
758+
759+
class SupplyChainProblem(Problem):
760+
def __init__(self, bounds=None, minmax=None, data=None, **kwargs):
761+
self.data = data
762+
super().__init__(bounds, minmax, **kwargs)
763+
764+
def obj_func(self, x):
765+
x_decoded = self.decode_solution(x)
766+
x = x_decoded["placement_var"].reshape(self.data["num_patients"], self.data["num_resources"])
767+
768+
# If any row has all 0 value, it indicates that this patient is not allocated to any room.
769+
# If a patient a assigned to more than 3 room, not allow
770+
if np.any(np.all(x==0, axis=1)) or np.any(np.sum(x>3, axis=1)):
771+
return self.data["penalty_patient"]
772+
773+
# Calculate fitness based on optimization objectives
774+
room_used = np.sum(x, axis=0)
775+
wait_time = np.sum(x * self.data["waiting_matrix"], axis=1)
776+
violated_constraints = np.sum(room_used > self.data["max_resource_capacity"]) + np.sum(wait_time > self.data["max_waiting_time"])
777+
778+
# Calculate the fitness value based on the objectives
779+
resource_utilization_fitness = 1 - np.mean(room_used) / self.data["max_resource_capacity"]
780+
waiting_time_fitness = 1 - np.mean(wait_time) / self.data["max_waiting_time"]
781+
782+
fitness = resource_utilization_fitness + waiting_time_fitness + self.data['penalty_value'] * violated_constraints
783+
return fitness
784+
785+
786+
bounds = BinaryVar(n_vars=num_patients * num_resources, name="placement_var")
787+
problem = SupplyChainProblem(bounds=bounds, minmax="min", data=data)
788+
789+
model = WOA.OriginalWOA(epoch=50, pop_size=20)
790+
model.solve(problem)
791+
792+
print(f"Best agent: {model.g_best}") # Encoded solution
793+
print(f"Best solution: {model.g_best.solution}") # Encoded solution
794+
print(f"Best fitness: {model.g_best.target.fitness}")
795+
print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_patients, num_resources))}")
796+
```
797+
798+
723799

724800
**Employee Rostering Problem Using Woa Optimizer**
725801

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
#!/usr/bin/env python
2+
# Created by "Thieu" at 18:43, 07/11/2023 ----------%
3+
# Email: [email protected] %
4+
# Github: https://github.com/thieu1995 %
5+
# --------------------------------------------------%
6+
7+
# Workflow optimization refers to the process of improving the efficiency, productivity, and effectiveness of workflows within an organization
8+
# or system. A workflow represents a series of interconnected tasks or activities that are performed to achieve a specific outcome or goal.
9+
10+
# A workflow optimization problem involves analyzing and optimizing various aspects of a workflow, such as task allocation, task sequencing,
11+
# resource allocation, and process automation. The objective is to streamline the flow of work, eliminate bottlenecks, reduce delays,
12+
# minimize resource utilization, and enhance overall performance.
13+
14+
# Workflow optimization problems can arise in various domains and industries, including manufacturing, healthcare, logistics,
15+
# software development, finance, and many others. Here are a few examples of workflow optimization problems in different contexts:
16+
17+
# 1. Manufacturing Workflow Optimization:
18+
# + Optimizing the sequence of production tasks to minimize production time and maximize resource utilization.
19+
# + Allocating resources (e.g., machines, labor) to different production tasks to achieve the highest efficiency.
20+
# + Optimizing inventory management and supply chain processes to reduce lead times and minimize stockouts.
21+
22+
# 2. Healthcare Workflow Optimization:
23+
# + Optimizing patient scheduling and appointment sequencing to reduce waiting times and improve patient satisfaction.
24+
# + Allocating healthcare professionals and resources efficiently to different patient care tasks.
25+
# + Streamlining administrative processes, such as patient registration and documentation, to reduce paperwork and improve data accuracy.
26+
27+
# 3. Software Development Workflow Optimization:
28+
# + Optimizing the allocation of development tasks to software engineers to maximize productivity and minimize project delays.
29+
# + Streamlining the code review and testing processes to ensure high-quality software and faster delivery.
30+
# + Implementing agile methodologies and continuous integration/continuous delivery (CI/CD) practices to streamline development and deployment workflows.
31+
32+
# 4. Financial Workflow Optimization:
33+
# + Optimizing the approval and authorization processes for financial transactions to reduce processing time and improve accuracy.
34+
# + Automating routine financial tasks, such as invoice processing and expense management, to improve efficiency and reduce manual errors.
35+
# + Optimizing cash flow management and forecasting processes to ensure optimal utilization of financial resources.
36+
37+
# Workflow optimization problems can be addressed using various optimization techniques, such as mathematical programming, simulation,
38+
# machine learning, and process mining. The specific approach depends on the complexity of the workflow, available data, problem constraints,
39+
# and the desired optimization objectives.
40+
41+
42+
## Let's consider an example of healthcare workflow optimization in a hospital setting. One common challenge in healthcare is optimizing
43+
# the patient flow and resource allocation to ensure efficient and timely delivery of care. Here's an example scenario:
44+
45+
# Scenario: Emergency Department (ED) Workflow Optimization
46+
47+
# Problem: The emergency department of a hospital is experiencing high patient wait times, overcrowding, and inefficient
48+
# resource allocation. The goal is to optimize the workflow to reduce patient waiting times, improve resource utilization,
49+
# and enhance the overall efficiency of the emergency department.
50+
51+
# Solution Approach:
52+
# 1. Patient Triage: Implement an efficient patient triage system to categorize patients based on the severity of their condition.
53+
# This helps prioritize patients who require immediate attention, ensuring that critical cases are attended to promptly.
54+
# 2. Resource Allocation: Analyze the availability and utilization of resources, such as doctors, nurses, examination rooms, and medical equipment.
55+
# Optimize the allocation of resources based on patient demand and the severity of their conditions. This may involve adjusting staff schedules,
56+
# reallocating resources between different areas of the emergency department, or identifying bottlenecks in resource availability.
57+
# 3. Workflow Redesign: Analyze the current patient flow and identify bottlenecks or inefficiencies. Redesign the workflow to streamline
58+
# the patient journey from arrival to discharge. This may involve optimizing the sequence of activities, improving communication
59+
# between departments, and implementing standardized protocols for common procedures.
60+
# 4. Capacity Planning: Analyze historical data to understand patient arrival patterns, peak hours, and seasonal variations. Use this
61+
# information to plan for capacity adjustments, such as staffing levels and resource availability, during peak demand periods.
62+
# This helps ensure that sufficient resources are available to handle the expected patient volume.
63+
# 5. Process Automation: Identify routine administrative tasks that can be automated to reduce manual effort and improve efficiency.
64+
# For example, automate patient registration, data entry, and documentation processes to free up staff time for patient care activities.
65+
# 6. Data Analytics: Utilize data analytics techniques to monitor key performance indicators, track patient flow metrics, and identify
66+
# areas for further improvement. This includes analyzing patient wait times, length of stay, resource utilization rates, and patient
67+
# satisfaction scores. Data-driven insights can help identify trends, patterns, and potential areas of optimization.
68+
# 7. Continuous Improvement: Establish a culture of continuous improvement by regularly reviewing and evaluating the effectiveness of implemented changes.
69+
# Solicit feedback from staff, patients, and stakeholders to identify further opportunities for optimization and address any unforeseen challenges.
70+
71+
# Define a chromosome representation that encodes the allocation of resources and patient flow in the emergency department.
72+
# This could be a binary matrix where each row represents a patient and each column represents a resource (room).
73+
# If the element is 1, it means the patient is assigned to that particular room, and if the element is 0, it means the patient is not assigned to that room
74+
75+
# Please note that this implementation is a basic template and may require further customization based on the specific objectives, constraints,
76+
# and evaluation criteria of your healthcare workflow optimization problem. You'll need to define the specific fitness
77+
# function and optimization objectives based on the factors you want to optimize, such as patient waiting times, resource utilization, and
78+
# other relevant metrics in the healthcare workflow context.
79+
80+
81+
import numpy as np
82+
from mealpy import BinaryVar, WOA, Problem
83+
84+
# Define the problem parameters
85+
num_patients = 50 # Number of patients
86+
num_resources = 10 # Number of resources (room)
87+
88+
# Define the patient waiting time matrix (randomly generated for the example)
89+
# Why? May be, doctors need time to prepare tools,...
90+
waiting_matrix = np.random.randint(1, 10, size=(num_patients, num_resources))
91+
92+
data = {
93+
"num_patients": num_patients,
94+
"num_resources": num_resources,
95+
"waiting_matrix": waiting_matrix,
96+
"max_resource_capacity": 10, # Maximum capacity of each room
97+
"max_waiting_time": 60, # Maximum waiting time
98+
"penalty_value": 1e2, # Define a penalty value
99+
"penalty_patient": 1e10
100+
}
101+
102+
103+
class SupplyChainProblem(Problem):
104+
def __init__(self, bounds=None, minmax=None, data=None, **kwargs):
105+
self.data = data
106+
super().__init__(bounds, minmax, **kwargs)
107+
108+
def obj_func(self, x):
109+
x_decoded = self.decode_solution(x)
110+
x = x_decoded["placement_var"].reshape(self.data["num_patients"], self.data["num_resources"])
111+
112+
# If any row has all 0 value, it indicates that this patient is not allocated to any room.
113+
# If a patient a assigned to more than 3 room, not allow
114+
if np.any(np.all(x==0, axis=1)) or np.any(np.sum(x>3, axis=1)):
115+
return self.data["penalty_patient"]
116+
117+
# Calculate fitness based on optimization objectives
118+
room_used = np.sum(x, axis=0)
119+
wait_time = np.sum(x * self.data["waiting_matrix"], axis=1)
120+
violated_constraints = np.sum(room_used > self.data["max_resource_capacity"]) + np.sum(wait_time > self.data["max_waiting_time"])
121+
122+
# Calculate the fitness value based on the objectives
123+
resource_utilization_fitness = 1 - np.mean(room_used) / self.data["max_resource_capacity"]
124+
waiting_time_fitness = 1 - np.mean(wait_time) / self.data["max_waiting_time"]
125+
126+
fitness = resource_utilization_fitness + waiting_time_fitness + self.data['penalty_value'] * violated_constraints
127+
return fitness
128+
129+
130+
bounds = BinaryVar(n_vars=num_patients * num_resources, name="placement_var")
131+
problem = SupplyChainProblem(bounds=bounds, minmax="min", data=data)
132+
133+
model = WOA.OriginalWOA(epoch=50, pop_size=20)
134+
model.solve(problem)
135+
136+
print(f"Best agent: {model.g_best}") # Encoded solution
137+
print(f"Best solution: {model.g_best.solution}") # Encoded solution
138+
print(f"Best fitness: {model.g_best.target.fitness}")
139+
print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_patients, num_resources))}")

0 commit comments

Comments
 (0)