Skip to content

quast_decisiontree.nodes.root

quast_decisiontree.nodes.root

logger module-attribute

logger = logging.getLogger('dt_logger')

root_welcome module-attribute

root_welcome = "===============================================================================\nWelcome to the QuaST Decision Tree. You will be guided through the solution steps to construct\na quantum-assisted solution for optimization problems.\n\n ________  ___  ___  ________  ________  _________\n|\\   __  \\|\\  \\|\\  \\|\\   __  \\|\\   ____\\|\\___   ___\\\n\\ \\  \\|\\  \\ \\  \\\\\\  \\ \\  \\|\\  \\ \\  \\___|\\|___ \\  \\_|\n \\ \\  \\\\\\  \\ \\  \\\\\\  \\ \\   __  \\ \\_____  \\   \\ \\  \\\n  \\ \\  \\\\\\  \\ \\  \\\\\\  \\ \\  \\ \\  \\|____|\\  \\   \\ \\  \\\n   \\ \\_____  \\ \\_______\\ \\__\\ \\__\\____\\_\\  \\   \\ \\__\\\n    \\|___| \\__\\|_______|\\|__|\\|__|\\_________\\   \\|__|\n          \\|__|                  \\|_________|\n\nCurrently in beta stage: Features may be incomplete and subject to change. Feedback is welcome.\n========================"

rand_or_load_question module-attribute

rand_or_load_question = "Do you want to load a problem instance from file or generate a random one?"

instance_file_question module-attribute

instance_file_question = "Specify the problem file (JSON format) with the instance to be loaded."

problem_type_question module-attribute

problem_type_question = "Specify the class of the optimization problem you want to generate."

problem_size_question module-attribute

problem_size_question = "Specify the problem size (number of nodes in the underlying\nproblem graph) you wish to generate. This is not the number of binary variables in the resulting\nproblem, but an application-level quantity"

LoadProblemNode

Bases: 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.

Source code in src/quast_decisiontree/nodes/root.py
 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

queries instance-attribute

queries = self._build_queries()

__init__

__init__(children, exclude_problem_classes=None)
Source code in src/quast_decisiontree/nodes/root.py
 95
 96
 97
 98
 99
100
101
102
103
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()

execute

execute(problem_data, path_info)
Source code in src/quast_decisiontree/nodes/root.py
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
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"],
    )

add_feasibility_info

add_feasibility_info(
    result, problem_data, path_info, config
)
Source code in src/quast_decisiontree/nodes/root.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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

interpret_result

interpret_result(
    result, problem_data, next_node_info=None, config=None
)
Source code in src/quast_decisiontree/nodes/root.py
213
214
215
216
217
218
219
220
221
222
223
224
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

RootNode

Bases: MessageNode

the root node of the decisiontree

Source code in src/quast_decisiontree/nodes/root.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class RootNode(MessageNode):
    """the root node of the decisiontree"""

    _known_children = ["LoadProblemNode"]

    def __init__(self, message=root_welcome, children=None):
        if children is None:
            children = ["LoadProblemNode"]
        super().__init__(message=message, children=children)

    def log_result_summary(self, result: dict, problem_data: dict, config: dict):
        lines = [separator("=")]

        no_print = []
        try:
            lines.append(f"Quick result summary for run {config['run_name']}")
        except KeyError:
            no_print.append("run_name")

        try:
            lines.append(f"Problem class: {problem_data['problem_class']}")
        except KeyError:
            no_print.append("problem_class")

        try:
            lines.append(f"Instance file: {problem_data['instance_file']}")
        except KeyError:
            no_print.append("instance_file")

        try:
            lines.append(f"Best solution found: {result['solution_int_vector']}")
        except KeyError:
            no_print.append("solution_int_vector")

        try:
            lines.append(f"Cost function value: {result['solution_cost_value']}")
        except KeyError:
            no_print.append("solution_cost_value")

        lines.append(separator("="))

        if no_print:
            logger.info(
                "Some keys couldn't be found in quick result summary: %s\n"
                "Check result file manually.",
                no_print,
            )

        logger.info("\n".join(lines))

    def interpret_result(
        self,
        result: dict,
        problem_data: dict,
        next_node_info: dict | None = None,
        config: dict | None = None,
    ) -> dict:
        self.log_result_summary(result, problem_data, config)
        return result

__init__

__init__(message=root_welcome, children=None)
Source code in src/quast_decisiontree/nodes/root.py
232
233
234
235
def __init__(self, message=root_welcome, children=None):
    if children is None:
        children = ["LoadProblemNode"]
    super().__init__(message=message, children=children)

log_result_summary

log_result_summary(result, problem_data, config)
Source code in src/quast_decisiontree/nodes/root.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def log_result_summary(self, result: dict, problem_data: dict, config: dict):
    lines = [separator("=")]

    no_print = []
    try:
        lines.append(f"Quick result summary for run {config['run_name']}")
    except KeyError:
        no_print.append("run_name")

    try:
        lines.append(f"Problem class: {problem_data['problem_class']}")
    except KeyError:
        no_print.append("problem_class")

    try:
        lines.append(f"Instance file: {problem_data['instance_file']}")
    except KeyError:
        no_print.append("instance_file")

    try:
        lines.append(f"Best solution found: {result['solution_int_vector']}")
    except KeyError:
        no_print.append("solution_int_vector")

    try:
        lines.append(f"Cost function value: {result['solution_cost_value']}")
    except KeyError:
        no_print.append("solution_cost_value")

    lines.append(separator("="))

    if no_print:
        logger.info(
            "Some keys couldn't be found in quick result summary: %s\n"
            "Check result file manually.",
            no_print,
        )

    logger.info("\n".join(lines))

interpret_result

interpret_result(
    result, problem_data, next_node_info=None, config=None
)
Source code in src/quast_decisiontree/nodes/root.py
277
278
279
280
281
282
283
284
285
def interpret_result(
    self,
    result: dict,
    problem_data: dict,
    next_node_info: dict | None = None,
    config: dict | None = None,
) -> dict:
    self.log_result_summary(result, problem_data, config)
    return result

ask_for_file_if

ask_for_file_if(answers)
Source code in src/quast_decisiontree/nodes/root.py
60
61
def ask_for_file_if(answers):
    return answers["problem_generation"] == "load"

random_instance_if

random_instance_if(answers)
Source code in src/quast_decisiontree/nodes/root.py
64
65
def random_instance_if(answers):
    return answers["problem_generation"] == "random"