Optimizes nodes in the given list of cases. Args: case_list (list[Case]): The list of cases to be optimized. solution (Solution): The solution to be optimized. save_dir (Path): The directory to save the results. parallel_max_num (int)
(
self,
case_list: list[Case],
solution: Solution,
save_dir: Path,
parallel_max_num,
)
| 64 | self.logger = logging.getLogger(logger_name) if logger_name else logging.getLogger(__name__) |
| 65 | |
| 66 | def optimize( |
| 67 | self, |
| 68 | case_list: list[Case], |
| 69 | solution: Solution, |
| 70 | save_dir: Path, |
| 71 | parallel_max_num, |
| 72 | ): |
| 73 | """ |
| 74 | Optimizes nodes in the given list of cases. |
| 75 | |
| 76 | Args: |
| 77 | case_list (list[Case]): The list of cases to be optimized. |
| 78 | solution (Solution): The solution to be optimized. |
| 79 | save_dir (Path): The directory to save the results. |
| 80 | parallel_max_num (int): The maximum number of parallel processes. |
| 81 | |
| 82 | Returns: |
| 83 | tuple: The updated solution and optimization status. |
| 84 | """ |
| 85 | self.logger.info("Start Node Optimization") |
| 86 | saved_ori_solution = copy.deepcopy(solution) |
| 87 | |
| 88 | # backward |
| 89 | backward_save_dir = save_dir / "case_after_backward" |
| 90 | partial_funcs = [partial(self.backward, case, solution, backward_save_dir) for case in case_list] |
| 91 | OptimUtils.parallel_execution(partial_funcs, max_workers=parallel_max_num) |
| 92 | |
| 93 | # optimization (based on the suggestions) |
| 94 | op_info = self.optimize_node(case_list, solution) |
| 95 | |
| 96 | # Determine the optimization status based on the success of any node optimization |
| 97 | op_status = any(info["optim_status"] for info in op_info.values()) |
| 98 | |
| 99 | # if optimized successfully, update the AgentTeam |
| 100 | if op_status: |
| 101 | all_node_roles_description = {} |
| 102 | for node_name, node in solution.sop.nodes.items(): |
| 103 | all_node_roles_description[node_name] = node.node_roles_description |
| 104 | agent_team_config = AgentTeamConfig.generate_config( |
| 105 | solution.task.task_description, all_node_roles_description) |
| 106 | solution.agent_team = AgentTeam(agent_team_config) |
| 107 | |
| 108 | # save new solution and op_info |
| 109 | try: |
| 110 | with open(save_dir / "node_optim_info.json", "w", encoding="utf-8") as f: |
| 111 | json.dump(op_info, f, ensure_ascii=False, indent=4) |
| 112 | solution.dump(save_dir) |
| 113 | solution = Solution(config=SolutionConfig(str(save_dir / "solution.json"))) |
| 114 | except Exception as e: |
| 115 | self.logger.error(f"Error in saving solution: {e}") |
| 116 | solution = saved_ori_solution |
| 117 | solution.dump(save_dir / "accepted_solution") |
| 118 | |
| 119 | return solution, op_status |
| 120 | |
| 121 | def backward(self, case: Case, solution: Solution, save_dir: str): |
| 122 | """ |
nothing calls this directly
no test coverage detected