Untitled conversation
- Usercode
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import warnings
import numpy as np
from sko.GA import GA
from sko.tools import set_run_mode
import pandas as pd
import load_data as ld
# Some data for testing
N_POINTS = 4
TRAVEL_TIME_MATRIX = np.array([[0, 2, 3, 4], [2, 0, 5, 6], [3, 5, 0, 7], [4, 6, 7, 0]])
# Format:
# place_id: (load_time, unload_time)
LOAD_UNLOAD_TIME = {0: (0.5, 0.5), 1: (0.6, 0.6), 2: (0.7, 0.7), 3: (0.8, 0.8)}
# Format:
# (start_place, end_place, number_of_units, earliest_start_time, deadline)
RAW_TASKS = [
(0, 2, 6, 0, 20),
(1, 3, 5, 5, 30),
(2, 0, 4, 10, 40),
]
# Parameters for GA
SIZE_POP = 50
MAX_ITER = 200
PROB_MUT = 0.01
SEED = 42
class Task:
def __init__(
self, id, start_place, end_place, earliest_start, deadline, original_info
):
self.id = id
self.start_place = start_place
self.end_place = end_place
self.original_info = original_info
t_load = LOAD_UNLOAD_TIME[start_place][0]
t_travel = TRAVEL_TIME_MATRIX[self.start_place][self.end_place]
t_unload = LOAD_UNLOAD_TIME[end_place][1]
self.duration = t_load + t_travel + t_unload
self.time_window_start = earliest_start
self.time_window_end = deadline - self.duration
if self.time_window_start > self.time_window_end:
raise ValueError(f"Task {id} has an infeasible time window.")
def __repr__(self):
return f"Task(id={self.id}, from={self.start_place}, to={self.end_place}, window=[{self.time_window_start:.2f}, {self.time_window_end:.2f}])"
def split_task(raw_task, task_id):
start, end, num, t_start, t_deadline = raw_task
tasks = []
for sub_id in range(num):
original_info = {
"original_task_id": task_id,
"sub_task_id": sub_id,
"total_num": num,
"description": f"from P{start} to P{end}",
}
task = Task(task_id, start, end, t_start, t_deadline, original_info)
tasks.append(task)
return tasks
def split_tasks(raw_tasks):
all_tasks = []
for id, task in enumerate(raw_tasks):
all_tasks.extend(split_task(task, id))
return all_tasks, len(all_tasks)
print("Loading data...")
tasks, n_tasks = split_tasks(RAW_TASKS)
def objective_function(schedule):
schedule = np.argsort(schedule)
task_sequence = [tasks[i] for i in schedule]
truck_statuses = []
for task in task_sequence:
best_truck_idx = -1
earliest_finish_time = float("inf")
for i, (available_time, current_loc) in enumerate(truck_statuses):
travel_time = TRAVEL_TIME_MATRIX[current_loc][task.start_place]
arrival_time = available_time + travel_time
actual_start_time = max(arrival_time, task.time_window_start)
if actual_start_time <= task.time_window_end:
finish_time = actual_start_time + task.duration
if finish_time < earliest_finish_time:
earliest_finish_time = finish_time
best_truck_idx = i
if best_truck_idx == -1:
initial_loc = 0
initial_time = 0
travel_time = TRAVEL_TIME_MATRIX[initial_loc][task.start_place]
arrival_time = initial_time + travel_time
actual_start_time = max(arrival_time, task.time_window_start)
if actual_start_time > task.time_window_end:
return float("inf")
finish_time = actual_start_time + task.duration
truck_statuses.append((finish_time, task.end_place))
else:
truck_statuses[best_truck_idx] = (earliest_finish_time, task.end_place)
return len(truck_statuses)
def get_schedule_details(schedule):
schedule = np.argsort(schedule)
task_sequence = [tasks[i] for i in schedule]
truck_statuses = []
assignments_data = []
for task in task_sequence:
best_truck_idx = -1
earliest_finish_time = float("inf")
actual_start_time_for_best_truck = -1
for i, (available_time, current_loc) in enumerate(truck_statuses):
travel_time = TRAVEL_TIME_MATRIX[current_loc][task.start_place]
arrival_time = available_time + travel_time
actual_start_time = max(arrival_time, task.time_window_start)
if actual_start_time <= task.time_window_end:
finish_time = actual_start_time + task.duration
if finish_time < earliest_finish_time:
earliest_finish_time = finish_time
actual_start_time_for_best_truck = actual_start_time
best_truck_idx = i
if best_truck_idx == -1:
truck_id = len(truck_statuses) + 1
initial_loc = 0
initial_time = 0
travel_time = TRAVEL_TIME_MATRIX[initial_loc][task.start_place]
arrival_time = initial_time + travel_time
actual_start_time = max(arrival_time, task.time_window_start)
finish_time = actual_start_time + task.duration
truck_statuses.append((finish_time, task.end_place))
else:
truck_id = best_truck_idx + 1
actual_start_time = actual_start_time_for_best_truck
finish_time = earliest_finish_time
truck_statuses[best_truck_idx] = (finish_time, task.end_place)
assignments_data.append(
{
"original_task_id": task.original_info["original_task_id"],
"sub_task_id": task.original_info["sub_task_id"],
"truck_id": truck_id,
"start_time": actual_start_time,
"finish_time": finish_time,
"duration": task.duration,
"from_loc": task.start_place,
"to_loc": task.end_place,
}
)
df = pd.DataFrame(assignments_data)
return df
def print_schedule(schedule_df):
if schedule_df.empty:
print("No schedule to display.")
return
for original_id, group in schedule_df.groupby("original_task_id"):
start, end, num, _, _ = RAW_TASKS[original_id] # type: ignore
print(
f"\n▼ Original Task {original_id + 1}: {num} units from P{start} to P{end}"
)
sorted_group = group.sort_values(by="sub_task_id")
for row in sorted_group.itertuples(index=False):
print(
f" - Unit {row.sub_task_id + 1}/{num}: executed by Truck{row.truck_id}, "
f"started at {row.start_time:.2f}, finished at {row.finish_time:.2f}"
)
if __name__ == "__main__":
warnings.filterwarnings("ignore", category=SyntaxWarning)
np.random.seed(SEED)
# read data from CSV files
LOAD_UNLOAD_TIME = ld.load_load_unload_times("data/load_unload_times.csv")
TRAVEL_TIME_MATRIX = ld.load_distance_matrix("data/distance_matrix.csv")
RAW_TASKS = ld.load_tasks("data/tasks.csv")
RAW_TASKS = list(RAW_TASKS)
tasks, n_tasks = split_tasks(RAW_TASKS)
N_POINTS = TRAVEL_TIME_MATRIX.shape[0]
set_run_mode(objective_function, "multithreading")
ga = GA(
func=objective_function,
n_dim=n_tasks,
size_pop=SIZE_POP,
max_iter=MAX_ITER,
prob_mut=PROB_MUT,
lb=[0] * n_tasks, # type: ignore
ub=[n_tasks] * n_tasks, # type: ignore
precision=1e-7,
)
best_x, best_y = ga.run()
print("Least number of trucks needed:", int(best_y[0]))
print("---------- Schedule Details ----------")
schedule_df = get_schedule_details(best_x)
print_schedule(schedule_df)
schedule_df.to_csv("best_schedule_larger.csv", index=False, float_format="%.2f")
分析以上GA算法的时间复杂度,你需要写出:
Okay, let's break down the time complexity of the provided Genetic Algorithm (GA) implementation for the task scheduling problem.
n_tasks). This is the dimension of the GA's search space (n_dim).size_pop).max_iter).len(RAW_TASKS) initially).Data Preprocessing (split_tasks):
split_tasks function iterates through the RAW_TASKS ( tasks).split_task is called. This function iterates num times, where num is the number of units for that raw task.Task object takes roughly constant time (assuming matrix/dictionary lookups are ).The overall time complexity of the script is dominated by the execution of the Genetic Algorithm (ga.run()).
The time complexity is:
Where:
max_iter).size_pop).n_tasks).In the worst-case scenario where is proportional to , the complexity can be expressed as .
The initial data loading, task splitting, and final schedule generation have complexities ( and respectively) that are typically less than or equal to the complexity of the GA's main loop over generations. Multithreading optimizes the execution time per generation but does not change the overall theoretical complexity in terms of total operations.
split_tasks is proportional to the total number of tasks generated, .Objective Function (objective_function) Analysis:
schedule = np.argsort(schedule): Sorting the GA's chromosome representation (length ). Complexity: .task_sequence = [tasks[i] for i in schedule]: Creating the ordered task list. Complexity: .task_sequence ( tasks).
truck_statuses. The size of truck_statuses can grow up to (the number of trucks used).objective_function is dominated by the sorting and the nested loops: .Schedule Detail Function (get_schedule_details):
objective_function but stores detailed results.np.argsort (), the task sequence creation (), and the nested loops ().assignments_data takes time (appending items).pd.DataFrame(assignments_data) takes time proportional to the number of rows () and columns, roughly .get_schedule_details is .Genetic Algorithm (ga.run()) Analysis:
max_iter).objective_function for each of the individuals. Total evaluation cost per generation: .Multithreading (set_run_mode("multithreading")):
Worst-Case Scenario for : If each task requires a distinct truck due to timing and location constraints, could be as large as . In this case, the complexity becomes .