Coverage for sparkle/tools/solver_wrapper_parsing.py: 25%

32 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-07-01 13:21 +0000

1"""This module provides tools for the argument parsing for solver wrappers.""" 

2from pathlib import Path 

3import ast 

4from typing import Any 

5 

6from sparkle.types import resolve_objective 

7 

8 

9def parse_commandline_dict(args: list[str]) -> dict: 

10 """Parses a commandline dictionary to the object.""" 

11 dict_str = " ".join(args) 

12 dict_str = dict_str[dict_str.index("{"):dict_str.index("}") + 1] # Slurm script fix 

13 return ast.literal_eval(dict_str) 

14 

15 

16def parse_instance(instance_str: str) -> Path | list[Path]: 

17 """Handles the parsing of multi file instances.""" 

18 instance_str = instance_str.removeprefix("[") 

19 instance_str = instance_str.removesuffix("]") 

20 instance_list = instance_str.split(",") 

21 instance_list = [inst_str.strip(' "') for inst_str in instance_list] 

22 return Path(instance_list[0]) if len(instance_list) == 1 else instance_list 

23 

24 

25def parse_solver_wrapper_args(args: list[str]) -> dict[Any]: 

26 """Parse the arguments passed to the solver wrapper. 

27 

28 Args: 

29 args: a list of arguments passed via the command line. It is ensured by Sparkle 

30 that this list contains certain keys such as `solver_dir`. 

31 

32 Returns: 

33 A dictionary mapping argument names to their currently held values. 

34 """ 

35 args_dict = parse_commandline_dict(args) 

36 

37 # Some data needs specific formatting 

38 args_dict["solver_dir"] = Path(args_dict["solver_dir"]) 

39 instance = args_dict["instance"] 

40 args_dict["instance"] = parse_instance(instance) 

41 args_dict["seed"] = int(args_dict["seed"]) 

42 args_dict["objectives"] = [resolve_objective(name) 

43 for name in args_dict["objectives"].split(",")] 

44 args_dict["cutoff_time"] = float(args_dict["cutoff_time"]) 

45 return args_dict 

46 

47 

48def get_solver_call_params(args_dict: dict, 

49 prefix: str = "-", 

50 postfix: str = " ") -> list[str]: 

51 """Gather the additional parameters for the solver call. 

52 

53 Args: 

54 args_dict: Dictionary mapping argument names to their currently held values 

55 prefix: Prefix of the command line options 

56 postfix: Postfix of the command line options 

57 

58 Returns: 

59 A list of parameters for the solver call 

60 """ 

61 params = [] 

62 # Certain arguments are not relevant/have already been processed 

63 ignore_args = {"solver_dir", "instance", "cutoff_time", "seed", "objectives"} 

64 for key in args_dict: 

65 if key not in ignore_args and args_dict[key] is not None: 

66 if postfix == " ": 

67 params.extend([prefix + str(key), str(args_dict[key])]) 

68 else: 

69 params.extend([prefix + str(key) + postfix + str(args_dict[key])]) 

70 

71 return params