recorder.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #ifndef _RECORDER
  2. #define _RECORDER
  3. #include <iostream>
  4. #include <fstream>
  5. #include <ostream>
  6. #include <istream>
  7. #include <streambuf>
  8. #include <filesystem>
  9. namespace fs = std::filesystem;
  10. template <typename T>
  11. struct Recorder
  12. {
  13. bool verbose;
  14. std::string name;
  15. T global_best_task;
  16. T current_best_task;
  17. long long global_best_score;
  18. long long current_best_score;
  19. Recorder(std::string name = "") : name(name)
  20. {
  21. verbose = false;
  22. global_best_score = 0;
  23. current_best_score = 0;
  24. }
  25. void set_verbose(bool verbose = true)
  26. {
  27. this->verbose = verbose;
  28. }
  29. void submit(T &task)
  30. {
  31. auto task_score = task.score();
  32. if (task_score > global_best_score)
  33. {
  34. std::cout << "Best improved: " << task_score << " <-- " << global_best_score << std::endl;
  35. current_best_score = global_best_score = task_score;
  36. current_best_task = global_best_task = task;
  37. if (name == "")
  38. {
  39. std::cout << "Warning: No name assigned for this recorder." << std::endl;
  40. return;
  41. }
  42. fs::path tasks = "tasks";
  43. std::fstream fs_score, fs_submit, fs_info;
  44. fs_score.open(tasks / (name + ".score"));
  45. fs_score << task_score << std::endl;
  46. fs_score.close();
  47. fs_submit.open(tasks / (name + ".out"));
  48. fs_info.open(tasks / (name + ".info"));
  49. task.save(fs_submit, fs_info);
  50. fs_submit.close();
  51. fs_info.close();
  52. }
  53. else if (task_score > current_best_score)
  54. {
  55. std::cout << "Current improved: " << task_score << " <-- " << current_best_score << std::endl;
  56. current_best_score = task_score;
  57. current_best_task = task;
  58. if (verbose)
  59. {
  60. task.save(std::cout, std::cerr);
  61. }
  62. }
  63. }
  64. void load(T &task)
  65. {
  66. fs::path tasks = "tasks";
  67. std::ifstream fs_score, fs_submit, fs_info;
  68. auto cur_name = tasks / (name + ".score");
  69. fs_score.open(tasks / (name + ".score"));
  70. fs_score >> global_best_score;
  71. fs_score.close();
  72. fs_submit.open(tasks / (name + ".out"));
  73. fs_info.open(tasks / (name + ".info"));
  74. task.load(fs_submit, fs_info);
  75. fs_submit.close();
  76. fs_info.close();
  77. std::cout << "Loaded Task: " << name << " Score: " << global_best_score << std::endl;
  78. }
  79. };
  80. template <typename T>
  81. void print(T &task)
  82. {
  83. task.save(std::cout, std::cerr);
  84. }
  85. #endif