|
| 1 | +""" |
| 2 | +JSON Summary Reporter for generating unified results.json files. |
| 3 | +""" |
| 4 | + |
| 5 | +import json |
| 6 | +import os |
| 7 | +import datetime |
| 8 | +from typing import Any, Dict, List, Optional |
| 9 | + |
| 10 | +from krkn_ai.models.app import CommandRunResult |
| 11 | +from krkn_ai.models.config import ConfigFile |
| 12 | +from krkn_ai.utils.logger import get_logger |
| 13 | + |
| 14 | +logger = get_logger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class JSONSummaryReporter: |
| 18 | + """ |
| 19 | + Reporter class for generating and saving unified JSON summary files. |
| 20 | +
|
| 21 | + This class consolidates all run statistics into a single results.json file |
| 22 | + for easier analysis and programmatic access. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + run_uuid: str, |
| 28 | + config: ConfigFile, |
| 29 | + seen_population: Dict[Any, CommandRunResult], |
| 30 | + best_of_generation: List[CommandRunResult], |
| 31 | + start_time: Optional[datetime.datetime] = None, |
| 32 | + end_time: Optional[datetime.datetime] = None, |
| 33 | + completed_generations: int = 0, |
| 34 | + seed: Optional[int] = None, |
| 35 | + ): |
| 36 | + """ |
| 37 | + Initialize the JSON summary reporter. |
| 38 | +
|
| 39 | + Args: |
| 40 | + run_uuid: Unique identifier for this run. |
| 41 | + config: Configuration used for this run. |
| 42 | + seen_population: Map of scenarios to their execution results. |
| 43 | + best_of_generation: List of best results per generation. |
| 44 | + start_time: When the run started. |
| 45 | + end_time: When the run ended. |
| 46 | + completed_generations: Number of generations completed. |
| 47 | + seed: Random seed used for the run (if any). |
| 48 | + """ |
| 49 | + self.run_uuid = run_uuid |
| 50 | + self.config = config |
| 51 | + self.seen_population = seen_population |
| 52 | + self.best_of_generation = best_of_generation |
| 53 | + self.start_time = start_time |
| 54 | + self.end_time = end_time |
| 55 | + self.completed_generations = completed_generations |
| 56 | + self.seed = seed |
| 57 | + |
| 58 | + def generate_summary(self) -> Dict[str, Any]: |
| 59 | + """ |
| 60 | + Generate a unified results summary containing all run statistics. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + Dict containing run metadata, config summary, best scenarios, |
| 64 | + and fitness progression over generations. |
| 65 | + """ |
| 66 | + # Calculate duration |
| 67 | + duration_seconds = 0.0 |
| 68 | + if self.start_time and self.end_time: |
| 69 | + duration_seconds = (self.end_time - self.start_time).total_seconds() |
| 70 | + |
| 71 | + # Get all fitness scores for statistics |
| 72 | + all_fitness_scores = [ |
| 73 | + result.fitness_result.fitness_score |
| 74 | + for result in self.seen_population.values() |
| 75 | + ] |
| 76 | + |
| 77 | + # Calculate average fitness score |
| 78 | + average_fitness_score = 0.0 |
| 79 | + if all_fitness_scores: |
| 80 | + average_fitness_score = sum(all_fitness_scores) / len(all_fitness_scores) |
| 81 | + |
| 82 | + # Get best fitness score |
| 83 | + best_fitness_score = 0.0 |
| 84 | + if all_fitness_scores: |
| 85 | + best_fitness_score = max(all_fitness_scores) |
| 86 | + |
| 87 | + # Count unique scenarios by their string representation |
| 88 | + unique_scenarios = set() |
| 89 | + for result in self.seen_population.values(): |
| 90 | + unique_scenarios.add(str(result.scenario)) |
| 91 | + |
| 92 | + # Generate fitness progression from best_of_generation |
| 93 | + fitness_progression = self._build_fitness_progression() |
| 94 | + |
| 95 | + # Generate best scenarios list (sorted by fitness score, top 10) |
| 96 | + best_scenarios = self._build_best_scenarios() |
| 97 | + |
| 98 | + # Build the results summary |
| 99 | + results_summary: Dict[str, Any] = { |
| 100 | + "run_id": self.run_uuid, |
| 101 | + "seed": self.seed, |
| 102 | + "start_time": self.start_time.isoformat() if self.start_time else None, |
| 103 | + "end_time": self.end_time.isoformat() if self.end_time else None, |
| 104 | + "duration_seconds": round(duration_seconds, 2), |
| 105 | + "config": { |
| 106 | + "generations": self.config.generations, |
| 107 | + "population_size": self.config.population_size, |
| 108 | + "mutation_rate": self.config.mutation_rate, |
| 109 | + "scenario_mutation_rate": self.config.scenario_mutation_rate, |
| 110 | + "crossover_rate": self.config.crossover_rate, |
| 111 | + "composition_rate": self.config.composition_rate, |
| 112 | + }, |
| 113 | + "summary": { |
| 114 | + "total_scenarios_executed": len(self.seen_population), |
| 115 | + "unique_scenarios": len(unique_scenarios), |
| 116 | + "generations_completed": self.completed_generations, |
| 117 | + "best_fitness_score": round(best_fitness_score, 4), |
| 118 | + "average_fitness_score": round(average_fitness_score, 4), |
| 119 | + }, |
| 120 | + "best_scenarios": best_scenarios, |
| 121 | + "fitness_progression": fitness_progression, |
| 122 | + } |
| 123 | + |
| 124 | + return results_summary |
| 125 | + |
| 126 | + def _build_fitness_progression(self) -> List[Dict[str, Any]]: |
| 127 | + """Build fitness progression data from best_of_generation.""" |
| 128 | + fitness_progression = [] |
| 129 | + for i, result in enumerate(self.best_of_generation): |
| 130 | + # Calculate average fitness for this generation from seen_population |
| 131 | + gen_fitness_scores = [ |
| 132 | + r.fitness_result.fitness_score |
| 133 | + for r in self.seen_population.values() |
| 134 | + if r.generation_id == i |
| 135 | + ] |
| 136 | + gen_average = 0.0 |
| 137 | + if gen_fitness_scores: |
| 138 | + gen_average = sum(gen_fitness_scores) / len(gen_fitness_scores) |
| 139 | + |
| 140 | + fitness_progression.append( |
| 141 | + { |
| 142 | + "generation": i, |
| 143 | + "best": result.fitness_result.fitness_score, |
| 144 | + "average": round(gen_average, 4), |
| 145 | + } |
| 146 | + ) |
| 147 | + return fitness_progression |
| 148 | + |
| 149 | + def _build_best_scenarios(self) -> List[Dict[str, Any]]: |
| 150 | + """Build ranked list of best scenarios (top 10).""" |
| 151 | + sorted_results = sorted( |
| 152 | + self.seen_population.values(), |
| 153 | + key=lambda x: x.fitness_result.fitness_score, |
| 154 | + reverse=True, |
| 155 | + ) |
| 156 | + best_scenarios = [] |
| 157 | + for rank, result in enumerate(sorted_results[:10], start=1): |
| 158 | + scenario_params = {} |
| 159 | + if hasattr(result.scenario, "parameters"): |
| 160 | + scenario_params = { |
| 161 | + param.get_name(): param.get_value() |
| 162 | + for param in result.scenario.parameters |
| 163 | + } |
| 164 | + |
| 165 | + best_scenarios.append( |
| 166 | + { |
| 167 | + "rank": rank, |
| 168 | + "scenario_id": result.scenario_id, |
| 169 | + "generation": result.generation_id, |
| 170 | + "fitness_score": result.fitness_result.fitness_score, |
| 171 | + "scenario_type": result.scenario.name, |
| 172 | + "parameters": scenario_params, |
| 173 | + } |
| 174 | + ) |
| 175 | + return best_scenarios |
| 176 | + |
| 177 | + def save(self, output_dir: str): |
| 178 | + """ |
| 179 | + Generate and save the results summary to a JSON file. |
| 180 | +
|
| 181 | + Args: |
| 182 | + output_dir: Directory where results.json will be saved. |
| 183 | + """ |
| 184 | + summary = self.generate_summary() |
| 185 | + output_path = os.path.join(output_dir, "results.json") |
| 186 | + with open(output_path, "w", encoding="utf-8") as f: |
| 187 | + json.dump(summary, f, indent=2) |
| 188 | + logger.info("Results summary saved to %s", output_path) |
0 commit comments