Coverage for sparkle/tools/solver_wrapper_parsing.py: 25%
32 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-29 10:17 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-29 10:17 +0000
1"""This module provides tools for the argument parsing for solver wrappers."""
3from pathlib import Path
4import ast
5from typing import Any
7from sparkle.types import resolve_objective
10def parse_commandline_dict(args: list[str]) -> dict:
11 """Parses a commandline dictionary to the object."""
12 dict_str = " ".join(args)
13 dict_str = dict_str[
14 dict_str.index("{") : dict_str.index("}") + 1
15 ] # Slurm script fix
16 return ast.literal_eval(dict_str)
19def parse_instance(instance_str: str) -> Path | list[Path]:
20 """Handles the parsing of multi file instances."""
21 instance_str = instance_str.removeprefix("[")
22 instance_str = instance_str.removesuffix("]")
23 instance_list = instance_str.split(",")
24 instance_list = [inst_str.strip(' "') for inst_str in instance_list]
25 return Path(instance_list[0]) if len(instance_list) == 1 else instance_list
28def parse_solver_wrapper_args(args: list[str]) -> dict[Any]:
29 """Parse the arguments passed to the solver wrapper.
31 Args:
32 args: a list of arguments passed via the command line. It is ensured by Sparkle
33 that this list contains certain keys such as `solver_dir`.
35 Returns:
36 A dictionary mapping argument names to their currently held values.
37 """
38 args_dict = parse_commandline_dict(args)
40 # Some data needs specific formatting
41 args_dict["solver_dir"] = Path(args_dict["solver_dir"])
42 instance = args_dict["instance"]
43 args_dict["instance"] = parse_instance(instance)
44 args_dict["seed"] = int(args_dict["seed"])
45 args_dict["objectives"] = [
46 resolve_objective(name) for name in args_dict["objectives"].split(",")
47 ]
48 args_dict["cutoff_time"] = float(args_dict["cutoff_time"])
49 return args_dict
52def get_solver_call_params(
53 args_dict: dict, prefix: str = "-", postfix: str = " "
54) -> list[str]:
55 """Gather the additional parameters for the solver call.
57 Args:
58 args_dict: Dictionary mapping argument names to their currently held values
59 prefix: Prefix of the command line options
60 postfix: Postfix of the command line options
62 Returns:
63 A list of parameters for the solver call
64 """
65 params = []
66 # Certain arguments are not relevant/have already been processed
67 ignore_args = {"solver_dir", "instance", "cutoff_time", "seed", "objectives"}
68 for key in args_dict:
69 if key not in ignore_args and args_dict[key] is not None:
70 if postfix == " ":
71 params.extend([prefix + str(key), str(args_dict[key])])
72 else:
73 params.extend([prefix + str(key) + postfix + str(args_dict[key])])
75 return params