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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224 | class LoadProblemNode(Node):
"""the node that loads or generates the optimization problem to solve
Modifications at runtime:
- generate
- {bool} : whether to generate the problem at random
- problem_instance
- {str} : file path of problem instance to load. Overwrites generate if applicable, and
raises a warning if generate was True.
- problem_class:
- {str} : if generate is True, sets the problem class
- problem_size:
- {int} : if generate is True, sets the problem size
Available problem classes are discovered at construction time. Pass
``exclude_problem_classes`` (e.g. via the node ``init_args`` in the tree config) to hide
classes from the interactive selection.
"""
_known_children = ["FormulationSelectNode"]
_path_keys = dict(
generate=PathKey(bool),
problem_instance=PathKey(str),
problem_class=PathKey(str),
problem_size=PathKey(int),
)
def __init__(self, children: list, exclude_problem_classes: list | None = None):
super().__init__(
requires=[],
creates=["instance_file", "problem_instance", "problem_class", "problem_size"],
children=children,
)
self._exclude_problem_classes = tuple(exclude_problem_classes or ())
self._problem_classes = discover_types()
self.queries = self._build_queries()
def _build_queries(self) -> QueryTree:
rand_or_load = MultiChoiceQuery(
question=rand_or_load_question,
answers={
"load": "Load from file",
"random": "Generate random instance",
},
name="problem_generation",
)
existing_file_path = PathQuery(question=instance_file_question, name="instance_file")
problem_class = MultiChoiceQuery(
question=problem_type_question,
answers={
pc.__name__: getdoc(pc) or pc.__name__
for pc in self._problem_classes
if pc.__name__ not in self._exclude_problem_classes
},
name="problem_class",
)
problem_size = IntQuery(question=problem_size_question, name="problem_size")
return QueryTree(
queries=[rand_or_load, existing_file_path, problem_class, problem_size],
conditions=[None, ask_for_file_if, random_instance_if, random_instance_if],
)
def _class_from_name(self, name: str):
for pc in self._problem_classes:
if pc.__name__ == name:
return pc
raise InvalidConfigValueError(f"Unknown problem class {name!r}.")
def execute(self, problem_data: dict, path_info: dict):
instance_file = path_info.get("problem_instance")
if instance_file is not None:
logger.debug("Loading problem instance from file %r.", instance_file)
problem_instance = from_json(instance_file)
answers = {}
else:
if path_info.get("generate"):
answers = dict(
problem_generation="random",
instance_file=None,
problem_class=path_info.get("problem_class"),
problem_size=path_info.get("problem_size"),
)
else:
answers = self.queries.input()
if answers["problem_generation"] == "load":
instance_file = answers["instance_file"]
logger.debug("Loading problem instance from file %r.", instance_file)
problem_instance = from_json(instance_file)
path_info["generate"] = False
path_info["instance_file"] = instance_file
elif answers["problem_generation"] == "random":
problem_class = self._class_from_name(answers["problem_class"])
size = answers["problem_size"]
logger.debug(
"Generating random %s instance of size %s.", problem_class.__name__, size
)
problem_instance = problem_class.create_random_instance(size)
path_info["generate"] = True
path_info["problem_size"] = size
path_info["problem_class"] = answers["problem_class"]
experiment_path = os.environ.get("QDT_EXPERIMENT_FOLDER")
if experiment_path is not None:
instance_file = save_problem_instance(problem_instance, experiment_path)
else:
logger.warning(
"Couldn't find environment variable QDT_EXPERIMENT_FOLDER to save "
"problem instance."
)
problem_data["instance_file"] = instance_file
if answers.get("problem_generation") == "random":
problem_data["problem_size"] = answers["problem_size"]
problem_data["problem_instance"] = problem_instance
problem_data["problem_class"] = problem_instance.__class__.__name__
return dict(
random_problem=(answers.get("problem_generation") == "random"),
problem_instance=problem_data["problem_instance"],
)
def add_feasibility_info(
self, result: dict, problem_data: dict, path_info: dict, config: dict
) -> dict:
bitstring_keys = ["best_bitstring", "solution_bitstring"]
for key in bitstring_keys:
try:
result[key + "_feasible"] = problem_data["problem_instance"].is_feasible(
solution_string=result[key], encoding=problem_data["encoding"]
)
except (KeyError, AttributeError):
pass
try:
result["feasibility_ratio"] = feasibility_ratio(
result["eigenstate"],
problem_data["problem_instance"].is_feasible,
int(problem_data["discrete_problem"].n),
problem_data["encoding"],
)
except (KeyError, AttributeError):
pass
return result
def interpret_result(
self,
result: dict,
problem_data: dict,
next_node_info: dict | None = None,
config: dict | None = None,
) -> dict:
try:
result = self.add_feasibility_info(result, problem_data, next_node_info, config)
except Exception:
logger.warning("Failed to add feasibility info to result.", exc_info=True)
return result
|