globalco2file.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. ///////////////////////////////////////////////////////////////////////////////////////
  2. /// \file globalco2file.cpp
  3. /// \brief A class for reading in CO2 values from a text file
  4. ///
  5. /// \author Joe Siltberg
  6. /// $Date: 2013-10-10 10:20:33 +0200 (Thu, 10 Oct 2013) $
  7. ///
  8. ///////////////////////////////////////////////////////////////////////////////////////
  9. #include "config.h"
  10. #include "globalco2file.h"
  11. #include "guess.h"
  12. #include <stdio.h>
  13. #include <limits>
  14. #include "gutil.h"
  15. namespace {
  16. // Constant to indicate that the file hasn't been properly loaded
  17. const int BAD_YEAR = std::numeric_limits<int>::min();
  18. }
  19. GlobalCO2File::GlobalCO2File()
  20. : first_year(BAD_YEAR) {
  21. }
  22. void GlobalCO2File::load_file(const char* path) {
  23. // Reads in atmospheric CO2 concentrations for historical period
  24. // from ascii text file with records in format: <year> <co2-value>
  25. // Have we already loaded a file?
  26. if (first_year != BAD_YEAR) {
  27. // Go back to initial state
  28. first_year = BAD_YEAR;
  29. co2.clear();
  30. }
  31. int calender_year;
  32. double next_co2;
  33. FILE* in = fopen(path, "rt");
  34. if (!in) {
  35. fail("GlobalCO2File::load_file: could not open CO2 file %s for input",
  36. path);
  37. }
  38. // Read in the values from the file
  39. while (readfor(in,"i,f",&calender_year,&next_co2)) {
  40. if (first_year == BAD_YEAR) {
  41. first_year = calender_year;
  42. }
  43. else if (calender_year != first_year+int(co2.size())) {
  44. fail("GlobalCO2File::load_file: %s, line %d - bad year specified",
  45. path,co2.size()+1);
  46. }
  47. co2.push_back(next_co2);
  48. }
  49. if (first_year == BAD_YEAR) {
  50. fail("GlobalCO2File::load_file: failed to load from file %s", path);
  51. }
  52. fclose(in);
  53. }
  54. double GlobalCO2File::operator[](int year) const {
  55. if (first_year == BAD_YEAR) {
  56. fail("GlobalCO2File::operator[]: "\
  57. "Tried to get CO2 value before loading from file!");
  58. }
  59. if (year < first_year) {
  60. return co2.front();
  61. }
  62. else if (year >= first_year+static_cast<int>(co2.size())) {
  63. fail("GlobalCO2File::operator[]: "\
  64. "Tried to get CO2 value after last year in file\n"\
  65. "Last year: %d, tried to get CO2 for: %d",
  66. first_year+co2.size()-1, year);
  67. return 0.0; // to avoid compiler warning
  68. }
  69. else {
  70. return co2[year-first_year];
  71. }
  72. }