spinupdata.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. ///////////////////////////////////////////////////////////////////////////////////////
  2. /// \file spinupdata.cpp
  3. /// \brief Management of climate data for spinup
  4. ///
  5. /// $Date$
  6. ///
  7. ///////////////////////////////////////////////////////////////////////////////////////
  8. #include "config.h"
  9. #include "spinupdata.h"
  10. #include "shell.h"
  11. using std::vector;
  12. GenericSpinupData::GenericSpinupData()
  13. : thisyear(0) {
  14. }
  15. void GenericSpinupData::get_data_from(RawData& source) {
  16. data = source;
  17. if (source.empty()) {
  18. fail("No source data given to GenericSpinupData::get_data_from()");
  19. }
  20. for (size_t i = 0; i < source.size(); ++i) {
  21. if ((source[i].size() != 12 &&
  22. source[i].size() % DAYS_PER_YEAR != 0) ||
  23. source[i].empty()) {
  24. fail("Incorrect number of timesteps per year in data given to\n"\
  25. "GenericSpinupData (got %d)", source[i].size());
  26. }
  27. if (i > 0 && source[i].size() != source[i-1].size()) {
  28. fail("Different number of timesteps in different years in\n"\
  29. "data given to GenericSpinupData::get_data_from()");
  30. }
  31. }
  32. firstyear();
  33. }
  34. double GenericSpinupData::operator[](int ts) const {
  35. if (ts < 0 || ts >= int(data[thisyear].size())) {
  36. fail("Trying to access data for timestep %d during spinup\n"\
  37. "(should be 0-%d)", ts, data[thisyear].size());
  38. }
  39. return data[thisyear][ts];
  40. }
  41. void GenericSpinupData::nextyear() {
  42. thisyear = (thisyear + 1) % nbr_years();
  43. }
  44. void GenericSpinupData::firstyear() {
  45. thisyear = 0;
  46. }
  47. void GenericSpinupData::detrend_data() {
  48. vector<double> annual_mean(nbr_years(), 0);
  49. vector<double> year_number(nbr_years());
  50. for (size_t y = 0; y < nbr_years(); ++y) {
  51. for (size_t d = 0; d < data[y].size(); ++d) {
  52. annual_mean[y] += data[y][d];
  53. }
  54. annual_mean[y] /= data[y].size();
  55. year_number[y] = y;
  56. }
  57. double a, b;
  58. regress(&year_number.front(), &annual_mean.front(), (int) nbr_years(), a, b);
  59. for (size_t y = 0; y < nbr_years(); ++y) {
  60. double anomaly = b*y;
  61. for (size_t d = 0; d < data[y].size(); ++d) {
  62. data[y][d] -= anomaly;
  63. }
  64. }
  65. }
  66. size_t GenericSpinupData::nbr_years() const {
  67. return data.size();
  68. }