use crate::configuration::GaConfiguration;
use crate::error::GaError;
use crate::population::Population;
use crate::stats::GenerationStats;
use crate::traits::ChromosomeT;
use serde::{Deserialize, Serialize};
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound(serialize = "U: Serialize", deserialize = "U: Deserialize<'de>"))]
pub struct Checkpoint<U>
where
U: ChromosomeT,
{
pub population: Population<U>,
pub configuration: GaConfiguration,
pub generation: usize,
pub stats: Vec<GenerationStats>,
}
pub fn save_checkpoint<U>(checkpoint: &Checkpoint<U>, path: &Path) -> Result<(), GaError>
where
U: ChromosomeT + Serialize,
{
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| {
GaError::CheckpointError(format!(
"Failed to create checkpoint directory '{}': {}",
parent.display(),
e
))
})?;
}
let json = serde_json::to_string_pretty(checkpoint)
.map_err(|e| GaError::CheckpointError(format!("Failed to serialize checkpoint: {}", e)))?;
std::fs::write(path, json).map_err(|e| {
GaError::CheckpointError(format!(
"Failed to write checkpoint to '{}': {}",
path.display(),
e
))
})?;
Ok(())
}
pub fn load_checkpoint<U>(path: &Path) -> Result<Checkpoint<U>, GaError>
where
U: ChromosomeT + for<'de> Deserialize<'de>,
{
let json = std::fs::read_to_string(path).map_err(|e| {
GaError::CheckpointError(format!(
"Failed to read checkpoint from '{}': {}",
path.display(),
e
))
})?;
let checkpoint: Checkpoint<U> = serde_json::from_str(&json).map_err(|e| {
GaError::CheckpointError(format!("Failed to deserialize checkpoint: {}", e))
})?;
Ok(checkpoint)
}