Coverage for sparkle/CLI/run_ablation.py: 81%
83 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-07 15:22 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-07 15:22 +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.configurator.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.structures import PerformanceDataFrame
16from sparkle.instance import Instance_Set
17from sparkle.CLI.help import argparse_custom as ac
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.ObjectivesArgument.names,
36 **ac.ObjectivesArgument.kwargs)
37 parser.add_argument(*ac.TargetCutOffTimeArgument.names,
38 **ac.TargetCutOffTimeArgument.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)
56 check_for_initialise()
58 # Define command line arguments
59 parser = parser_function()
61 # Process command line arguments
62 args = parser.parse_args(argv)
64 if ac.set_by_user(args, "settings_file"):
65 # Do first, so other command line options can override settings from the file
66 gv.settings().read_settings_ini(
67 args.settings_file, SettingState.CMD_LINE
68 )
69 if ac.set_by_user(args, "objectives"):
70 gv.settings().set_general_sparkle_objectives(
71 args.objectives, SettingState.CMD_LINE
72 )
73 if ac.set_by_user(args, "target_cutoff_time"):
74 gv.settings().set_general_target_cutoff_time(
75 args.target_cutoff_time, SettingState.CMD_LINE
76 )
77 if ac.set_by_user(args, "wallclock_time"):
78 gv.settings().set_smac2_wallclock_time(
79 args.wallclock_time, SettingState.CMD_LINE
80 )
81 if ac.set_by_user(args, "number_of_runs"):
82 gv.settings().set_configurator_number_of_runs(
83 args.number_of_runs, SettingState.CMD_LINE
84 )
85 if ac.set_by_user(args, "racing"):
86 gv.settings().set_ablation_racing_flag(
87 args.number_of_runs, SettingState.CMD_LINE
88 )
89 if args.run_on is not None:
90 gv.settings().set_run_on(
91 args.run_on.value, SettingState.CMD_LINE)
93 # Compare current settings to latest.ini
94 prev_settings = Settings(PurePath("Settings/latest.ini"))
95 Settings.check_settings_changes(gv.settings(), prev_settings)
97 run_on = gv.settings().get_run_on()
98 solver = resolve_object_name(args.solver,
99 gv.solver_nickname_mapping,
100 gv.settings().DEFAULT_solver_dir, Solver)
101 if solver is None:
102 print(f"Could not resolve Solver path/name {args.solver}!")
103 print([p for p in gv.settings().DEFAULT_solver_dir.iterdir()])
104 sys.exit(-1)
106 instance_set_train = resolve_object_name(
107 args.instance_set_train,
108 gv.file_storage_data_mapping[gv.instances_nickname_path],
109 gv.settings().DEFAULT_instance_dir, Instance_Set)
110 instance_set_test = resolve_object_name(
111 args.instance_set_test,
112 gv.file_storage_data_mapping[gv.instances_nickname_path],
113 gv.settings().DEFAULT_instance_dir, Instance_Set)
115 configurator = gv.settings().get_general_sparkle_configurator()
116 config_scenario = configurator.scenario_class().find_scenario(
117 configurator.output_path, solver, instance_set_train)
118 performance_data = PerformanceDataFrame(
119 gv.settings().DEFAULT_performance_data_path)
120 best_configuration, _ = performance_data.best_configuration(
121 str(config_scenario.solver.directory),
122 config_scenario.sparkle_objective,
123 instances=[str(p) for p in config_scenario.instance_set.instance_paths])
124 if config_scenario is None:
125 print("No configuration scenario found for combination:\n"
126 f"{configurator.name} {solver.name} {instance_set_train.name}")
127 sys.exit(-1)
128 if instance_set_test is None:
129 instance_set_test = instance_set_train
131 if not config_scenario.results_directory.is_dir():
132 print("Error: No configuration results found for the given solver and training"
133 " instance set. Ablation needs to have a target configuration. "
134 "Please finish configuration first.")
135 sys.exit(-1)
136 else:
137 print("Configuration exists!")
139 ablation_scenario = AblationScenario(
140 config_scenario,
141 instance_set_test,
142 gv.settings().DEFAULT_ablation_output,
143 override_dirs=True)
145 # Instances
146 ablation_scenario.create_instance_file()
147 ablation_scenario.create_instance_file(test=True)
149 # Configurations
150 ablation_scenario.create_configuration_file(
151 cutoff_time=gv.settings().get_general_target_cutoff_time(),
152 cutoff_length=gv.settings().get_smac2_target_cutoff_length(), # NOTE: SMAC2
153 concurrent_clis=gv.settings().get_slurm_max_parallel_runs_per_node(),
154 best_configuration=best_configuration,
155 ablation_racing=gv.settings().get_ablation_racing_flag(),
156 )
158 print("Submiting ablation run...")
159 runs = ablation_scenario.submit_ablation(
160 log_dir=sl.caller_log_dir,
161 sbatch_options=gv.settings().get_slurm_extra_options(as_args=True),
162 run_on=run_on)
164 if run_on == Runner.LOCAL:
165 print("Ablation analysis finished!")
166 else:
167 job_id_str = ",".join([run.run_id for run in runs])
168 print(f"Ablation analysis running. Waiting for Slurm job(s) with id(s): "
169 f"{job_id_str}")
170 sys.exit(0)
173if __name__ == "__main__":
174 main(sys.argv[1:])