GALib-Parallel
Header-only C++ library for parallel evolutionary algorithms
Loading...
Searching...
No Matches
FileLogger.h
Go to the documentation of this file.
1#ifndef FILE_LOGGER_H
2#define FILE_LOGGER_H
3
4#pragma once
5
6#include <fstream>
7#include <string>
8#include <filesystem>
9#include <cstddef>
10#include "core/Population.h"
11
12namespace galib::utils {
21 template <typename GeneType>
22 class FileLogger {
23 private:
24 std::string path_m;
25 std::size_t interval_m;
26 bool header_written_m = false;
27
28 public:
34 FileLogger(const std::string& path, const std::size_t interval)
35 : path_m(path), interval_m(interval) {}
36
42 void log(std::size_t gen, const Population<GeneType>& pop) {
43 if (interval_m == 0 || (gen % interval_m != 0 && gen != 0)) {
44 return;
45 }
46
47 std::filesystem::path p(path_m);
48 if (!header_written_m) {
49 if (p.has_parent_path()) {
50 std::filesystem::create_directories(p.parent_path());
51 }
52 }
53
54 std::ofstream file;
55 if (!header_written_m) {
56 file.open(path_m, std::ios::out);
57 if (file.is_open()) {
58 file << "generation,individual_idx,fitness";
59 for (std::size_t j = 0; j < pop.getNumGenes(); ++j) {
60 file << ",gene_" << j;
61 }
62 file << ",genotype\n";
63 header_written_m = true;
64 }
65 } else {
66 file.open(path_m, std::ios::app);
67 }
68
69 if (!file.is_open()) {
70 return;
71 }
72
73 for (std::size_t i = 0; i < pop.size(); ++i) {
74 const auto& genotype = pop[i].getGenotype();
75 file << gen << "," << i << "," << pop[i].getFitness();
76
77 for (const auto& gene : genotype) {
78 file << "," << gene;
79 }
80 file << ",";
81
82 for (std::size_t j = 0; j < genotype.size(); ++j) {
83 file << genotype[j] << (j == genotype.size() - 1 ? "" : ";");
84 }
85 file << "\n";
86 }
87 file.close();
88 }
89 };
90} // namespace galib::utils
91
92#endif // FILE_LOGGER_H
A container for a group of individuals in the genetic algorithm.
Definition Population.h:24
std::size_t getNumGenes() const
Returns the number of genes for individuals in this population.
Definition Population.h:80
std::size_t size() const
Returns the total number of individuals in the population.
Definition Population.h:68
Logger for writing optimization progress to a CSV file.
Definition FileLogger.h:22
void log(std::size_t gen, const Population< GeneType > &pop)
Appends current population data to the CSV file.
Definition FileLogger.h:42
FileLogger(const std::string &path, const std::size_t interval)
Constructs a file logger.
Definition FileLogger.h:34