Coverage for sparkle/CLI/run_ablation.py: 83%
78 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-05 14:48 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-05 14:48 +0000
1#!/usr/bin/env python3
2"""Sparkle command to execute ablation analysis."""
4import argparse
5import sys
6from pathlib import PurePath
8from runrunner.base import Runner
10from sparkle.solver.ablation import AblationScenario
11from sparkle.CLI.help import global_variables as gv
12from sparkle.CLI.help import logging as sl
13from sparkle.platform.settings_objects import Settings, SettingState
14from sparkle.solver import Solver
15from sparkle.instance import Instance_Set
16from sparkle.CLI.help import argparse_custom as ac
17from sparkle.platform import CommandName, COMMAND_DEPENDENCIES
18from sparkle.CLI.initialise import check_for_initialise
19from sparkle.CLI.help.nicknames import resolve_object_name
22def parser_function() -> argparse.ArgumentParser:
23 """Define the command line arguments."""
24 parser = argparse.ArgumentParser(
25 description="Runs parameter importance between the default and configured "
26 "parameters with ablation. This command requires a finished "
27 "configuration for the solver instance pair.",
28 epilog="Note that if no test instance set is given, the validation is performed"
29 " on the training set.")
30 parser.add_argument("--solver", required=False, type=str, help="path to solver")
31 parser.add_argument(*ac.InstanceSetTrainAblationArgument.names,
32 **ac.InstanceSetTrainAblationArgument.kwargs)
33 parser.add_argument(*ac.InstanceSetTestAblationArgument.names,
34 **ac.InstanceSetTestAblationArgument.kwargs)
35 parser.add_argument(*ac.SparkleObjectiveArgument.names,
36 **ac.SparkleObjectiveArgument.kwargs)
37 parser.add_argument(*ac.TargetCutOffTimeAblationArgument.names,
38 **ac.TargetCutOffTimeAblationArgument.kwargs)
39 parser.add_argument(*ac.WallClockTimeArgument.names,
40 **ac.WallClockTimeArgument.kwargs)
41 parser.add_argument(*ac.NumberOfRunsAblationArgument.names,
42 **ac.NumberOfRunsAblationArgument.kwargs)
43 parser.add_argument(*ac.RacingArgument.names,
44 **ac.RacingArgument.kwargs)
45 parser.add_argument(*ac.SettingsFileArgument.names,
46 **ac.SettingsFileArgument.kwargs)
47 parser.add_argument(*ac.RunOnArgument.names,
48 **ac.RunOnArgument.kwargs)
49 parser.set_defaults(ablation_settings_help=False)
50 return parser
53def main(argv: list[str]) -> None:
54 """Main function to run ablation analysis."""
55 sl.log_command(sys.argv)
57 # Define command line arguments
58 parser = parser_function()
60 # Process command line arguments
61 args = parser.parse_args(argv)
63 check_for_initialise(COMMAND_DEPENDENCIES[CommandName.RUN_ABLATION])
65 if ac.set_by_user(args, "settings_file"):
66 # Do first, so other command line options can override settings from the file
67 gv.settings().read_settings_ini(
68 args.settings_file, SettingState.CMD_LINE
69 )
70 if ac.set_by_user(args, "objectives"):
71 gv.settings().set_general_sparkle_objectives(
72 args.objectives, SettingState.CMD_LINE
73 )
74 if ac.set_by_user(args, "target_cutoff_time"):
75 gv.settings().set_general_target_cutoff_time(
76 args.target_cutoff_time, SettingState.CMD_LINE
77 )
78 if ac.set_by_user(args, "wallclock_time"):
79 gv.settings().set_smac2_wallclock_time(
80 args.wallclock_time, SettingState.CMD_LINE
81 )
82 if ac.set_by_user(args, "number_of_runs"):
83 gv.settings().set_configurator_number_of_runs(
84 args.number_of_runs, SettingState.CMD_LINE
85 )
86 if ac.set_by_user(args, "racing"):
87 gv.settings().set_ablation_racing_flag(
88 args.number_of_runs, SettingState.CMD_LINE
89 )
90 if args.run_on is not None:
91 gv.settings().set_run_on(
92 args.run_on.value, SettingState.CMD_LINE)
94 # Compare current settings to latest.ini
95 prev_settings = Settings(PurePath("Settings/latest.ini"))
96 Settings.check_settings_changes(gv.settings(), prev_settings)
98 run_on = gv.settings().get_run_on()
99 solver_path = resolve_object_name(args.solver,
100 gv.solver_nickname_mapping,
101 gv.settings().DEFAULT_solver_dir)
102 solver = Solver(solver_path)
103 instance_set_train = resolve_object_name(
104 args.instance_set_train,
105 gv.file_storage_data_mapping[gv.instances_nickname_path],
106 gv.settings().DEFAULT_instance_dir, Instance_Set)
107 instance_set_test = resolve_object_name(
108 args.instance_set_test,
109 gv.file_storage_data_mapping[gv.instances_nickname_path],
110 gv.settings().DEFAULT_instance_dir, Instance_Set)
112 configurator = gv.settings().get_general_sparkle_configurator()
113 config_scenario = configurator.scenario_class.find_scenario(
114 configurator.output_path, solver, instance_set_train)
115 if config_scenario is None:
116 print("No configuration scenario found for combination:\n"
117 f"{configurator.name} {solver.name} {instance_set_train.name}")
118 sys.exit(-1)
119 if instance_set_test is None:
120 instance_set_test = instance_set_train
122 if not config_scenario.results_directory.is_dir():
123 print("Error: No configuration results found for the given solver and training"
124 " instance set. Ablation needs to have a target configuration. "
125 "Please finish configuration first.")
126 sys.exit(-1)
127 else:
128 print("Configuration exists!")
130 ablation_scenario = AblationScenario(
131 solver, instance_set_train, instance_set_test,
132 gv.settings().DEFAULT_ablation_output,
133 gv.settings().DEFAULT_ablation_exec,
134 gv.settings().DEFAULT_ablation_validation_exec, override_dirs=True)
136 # Instances
137 ablation_scenario.create_instance_file()
138 ablation_scenario.create_instance_file(test=True)
140 # Configurations
141 ablation_scenario.create_configuration_file()
142 print("Submiting ablation run...")
143 runs = ablation_scenario.submit_ablation(run_on=run_on)
145 if run_on == Runner.LOCAL:
146 print("Ablation analysis finished!")
147 else:
148 job_id_str = ",".join([run.run_id for run in runs])
149 print(f"Ablation analysis running. Waiting for Slurm job(s) with id(s): "
150 f"{job_id_str}")
151 sys.exit(0)
154if __name__ == "__main__":
155 main(sys.argv[1:])