-
Notifications
You must be signed in to change notification settings - Fork 25
/
instance_factory.py
190 lines (143 loc) · 6.07 KB
/
instance_factory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""
This file provides functions to generate scheduling problem instances.
Using this file requires a data_generation config. For example, it is necessary to specify
the type of the scheduling problem.
"""
# OS imports
import random
from multiprocessing import Process, Manager
import warnings
import argparse
# Config and data handling imports
from src.utils.file_handler.config_handler import ConfigHandler
from src.utils.file_handler.data_handler import DataHandler
# Functional imports
import copy
import tqdm
import numpy as np
from typing import List
from src.data_generator.task import Task
from src.data_generator.sp_factory import SPFactory
from src.agents.heuristic.heuristic_agent import HeuristicSelectionAgent
from src.environments.env_tetris_scheduling import Env
# constants
DEADLINE_HEURISTIC = 'rand'
SEED = 0
def generate_instances_from_config(config: dict, print_info: bool = False) -> List[List[Task]]:
"""
Generates a list of raw scheduling instances according to the console
:param config: Data_generation config
:param print_info: True if the created instances should be output to the console
:return: List of raw scheduling problem instances
"""
# Generate instances
instances = SPFactory.generate_instances(**config)
if print_info:
print(f"Setups: {len(instances)}")
return instances
def compute_initial_instance_solution(instances: List[List[Task]], config: dict) -> List[List[Task]]:
"""
Initializes multiple processes (optional) to generate deadlines for the raw scheduling problem instances
:param instances: List of raw scheduling problem instances
:param config: Data_generation config
:return: List of scheduling problems instances with set deadlines
"""
# Get configured number of processes
num_processes: int = config.get('num_processes', 1)
if num_processes > len(instances):
num_processes = len(instances)
warnings.warn('num_processes was set to num_instances.'
'The number of processes may not exceed the number of instances which need to be generated.',
category=RuntimeWarning)
# Multiprocess case
manager = Manager()
instance_list = manager.list()
make_span_list = manager.list()
processes = []
# split instances for multiprocessing
features_dataset = np.array_split(instances, num_processes)
for process_id in tqdm.tqdm(range(num_processes), desc="Compute deadlines"):
args = (features_dataset[process_id], instance_list, make_span_list, config)
p = Process(target=generate_deadlines, args=args)
p.start()
processes.append(p)
for p in processes:
p.join()
return list(instance_list)
def generate_deadlines(instances: List[List[Task]], instance_with_dead_lines: List[List[Task]],
make_span_list: List[List[int]], config: dict) -> None:
"""
Generates suitable deadlines for the input instances
:param instances: List of raw scheduling problem instances
:param instance_with_dead_lines: manager.list() (Only in Multi-process case)
:param make_span_list: manager.list() (Only in Multi-process case)
:param config: Data_generation config
:return: None
"""
heuristic_agent = HeuristicSelectionAgent()
make_span = []
np.random.seed(config.get('seed', SEED))
for i, instance in enumerate(instances):
# create env
env = Env(config, [instance])
done = False
total_reward = 0
t = 0
runtimes = [task.runtime for task in instance]
# run agent on environment and collect rewards until done
while not done:
tasks = env.tasks
task_mask = env.get_action_mask()
action = heuristic_agent(tasks, task_mask, DEADLINE_HEURISTIC)
b = env.step(action)
total_reward += b[1]
done = b[2]
t += 1
tasks = env.tasks
# start_times = env.scheduling
make_span.append(env.get_makespan())
# actions.sort()
for task_j, task in enumerate(tasks):
task.deadline = task.finished
task._deadline = task.finished
task.runtime = runtimes[task_j]
task._run_time_left = runtimes[task_j]
task.running = 0
task.done = 0
task._started_in_generation = copy.copy(task.started)
task.started = 0
task.finished = 0
task._optimal_machine = int(task.selected_machine)
instance_with_dead_lines.append(tasks)
make_span_list.append(make_span)
def main(config_file_name=None, external_config=None):
# get config
current_config: dict = ConfigHandler.get_config(config_file_name, external_config)
# set seeds
seed = current_config.get('seed', SEED)
np.random.seed(seed)
random.seed(seed)
# Generate instances
generated_instances: List[List[Task]] = generate_instances_from_config(current_config)
# Create instance list
instance_list: List[List[Task]] = compute_initial_instance_solution(generated_instances, current_config)
# Assign deadlines in-place
SPFactory.set_deadlines_to_max_deadline_per_job(instance_list, current_config.get('num_jobs', None))
# compute individual hash for each instance
SPFactory.compute_and_set_hashes(instance_list)
# Write resulting instance data to file
if current_config.get('write_to_file', False):
DataHandler.save_instances_data_file(current_config, instance_list)
def get_parser_args():
"""Get arguments from command line."""
# Arguments for function
parser = argparse.ArgumentParser(description='Instance generation for scheduling optimization')
parser.add_argument('-fp', '--config_file_path', type=str, required=True,
help='Path to config file you want to use for training')
args = parser.parse_args()
return args
if __name__ == '__main__':
# get config_file from terminal input
parse_args = get_parser_args()
config_file_path = parse_args.config_file_path
main(config_file_name=config_file_path)