arldatastream.cc 13.6 KB
Newer Older
1
2
3
4
#include "radixio/arldatastream.hh"

#include "radixbug/bug.hh"
#include "radixcore/stringfunctions.hh"
5
6
#include "radixio/eafstream.hh"
#include "radixmath/util.hh"
7
8
9
10
11
12
13
14

#include <fstream>
namespace radix
{
class ARLDataStream::PImpl
{
 public:
  std::string file;
15
  std::shared_ptr<radix::eafstream> stream;
16
17
  int recordSize                      = 0;
  static const int recordHeaderLength = 50, indexHeaderLength = 108;
18
19
};

20
void ARLDataStream::expand(const std::string& val, ARLRecordHeader& rheader)
21
{
22
  if (val.size() < ARLDataStream::PImpl::recordHeaderLength)
23
24
  {
    throw std::runtime_error(
25
        "Incorrect size for string expansion to ARLRecordHeader.");
26
  }
27
28
29
30
31
32
33
34
35
36
37
  rheader.year  = std::atoi(val.substr(0, 2).c_str());
  rheader.month = std::atoi(val.substr(2, 2).c_str());
  rheader.day   = std::atoi(val.substr(4, 2).c_str());
  rheader.hour  = std::atoi(val.substr(6, 2).c_str());
  rheader.ic    = std::atoi(val.substr(8, 2).c_str());
  rheader.il    = std::atoi(val.substr(10, 2).c_str());
  rheader.cgrid = val.substr(12, 2).c_str();
  rheader.kvar  = val.substr(14, 4);
  rheader.nexp  = std::atoi(val.substr(18, 4).c_str());
  rheader.prec  = float(std::atof(val.substr(22, 14).c_str()));
  rheader.var1  = float(std::atof(val.substr(36, 14).c_str()));
38
}
39
40
41
void ARLDataStream::expand(const std::string& val,
                           const ARLRecordHeader& rheader,
                           ARLIndexHeader& iheader)
42
{
43
  if (val.size() < ARLDataStream::PImpl::indexHeaderLength)
44
45
46
47
  {
    throw std::runtime_error(
        "Incorrect size for string expansion to ARLHeader.");
  }
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  iheader.model_id = val.substr(0, 4);
  iheader.icx      = std::atoi(val.substr(4, 3).c_str());
  iheader.mn       = std::atoi(val.substr(7, 2).c_str());
  iheader.pole_lat = float(std::atof(val.substr(9, 7).c_str()));
  iheader.pole_lon = float(std::atof(val.substr(16, 7).c_str()));
  iheader.ref_lat  = float(std::atof(val.substr(23, 7).c_str()));
  iheader.ref_lon  = float(std::atof(val.substr(30, 7).c_str()));
  iheader.size     = float(std::atof(val.substr(37, 7).c_str()));
  iheader.orient   = float(std::atof(val.substr(44, 7).c_str()));
  iheader.tang_lat = float(std::atof(val.substr(51, 7).c_str()));
  iheader.sync_xp  = float(std::atof(val.substr(58, 7).c_str()));
  iheader.sync_yp  = float(std::atof(val.substr(65, 7).c_str()));
  iheader.sync_lat = float(std::atof(val.substr(72, 7).c_str()));
  iheader.sync_lon = float(std::atof(val.substr(79, 7).c_str()));
  iheader.dummy    = float(std::atof(val.substr(86, 7).c_str()));
  iheader.nx       = std::atoi(val.substr(93, 3).c_str());
  iheader.ny       = std::atoi(val.substr(96, 3).c_str());
  iheader.nz       = std::atoi(val.substr(99, 3).c_str());
  iheader.z_flag   = std::atoi(val.substr(102, 2).c_str());
  iheader.lenh     = std::atoi(val.substr(104, 4).c_str());

  int knx = ordinal(rheader.cgrid[0]);
  int kny = ordinal(rheader.cgrid[1]);
71
72
73
  // Check for the grid domain extending beyond 3 digits
  if (knx >= 64 || kny >= 64)
  {
74
75
    iheader.nx = (knx - 64) * 1000 + iheader.nx;
    iheader.ny = (kny - 64) * 1000 + iheader.ny;
76
77
78
  }
}

79
80
ARLDataStream::ARLDataStream(const std::string& file,
                             std::ios_base::openmode mode)
81
82
    : p(new PImpl(), [](PImpl* impl) { delete impl; })
{
83
  p->file   = file;
84
85
  p->stream = std::make_shared<radix::eafstream>(p->file.c_str(),
                                                 mode | std::ios::binary);
86
87
  if (!p->stream->is_open())
  {
88
    throw std::runtime_error("Error opening file '" + p->file + "'");
89
90
91
  }
}

92
bool ARLDataStream::read_record_header(ARLRecordHeader& rheader)
93
{
94
95
  bool result = false;

96
  std::string headerString =
97
98
99
100
101
102
103
104
105
106
      p->stream->readString(ARLDataStream::PImpl::recordHeaderLength);
  expand(headerString, rheader);

  radix_line("Read record header: year = " << rheader.year);
  radix_line("                   month = " << rheader.month);
  radix_line("                     day = " << rheader.day);
  radix_line("                    hour = " << rheader.hour);
  radix_line("                variable = " << rheader.kvar);
  radix_line("        scaling exponent = " << rheader.nexp);
  radix_line("           initial value = " << rheader.var1);
107
  radix_line("  header as string:\n  " << headerString);
108
109
110

  result = true;
  return result;
111
112
}

113
bool ARLDataStream::write_record_header(const ARLRecordHeader& rheader)
114
{
115
116
  bool result = false;

117
118
119
  // Remove century from year
  int year = rheader.year % 100;

120
  radix_line("Write record header: year = " << year);
121
122
123
124
  radix_line("                   month = " << rheader.month);
  radix_line("                     day = " << rheader.day);
  radix_line("                    hour = " << rheader.hour);
  radix_line("                variable = " << rheader.kvar);
125
  radix_line("                   level = " << rheader.il);
126
127
  radix_line("        scaling exponent = " << rheader.nexp);
  radix_line("           initial value = " << rheader.var1);
128
129

  // Construct index header string
130
  char recordHeader[51];
Norby, Tom's avatar
Norby, Tom committed
131
132
133
134
135
136
  snprintf(recordHeader, sizeof(recordHeader),
           "%2d%2d%2d%2d%2d%2d%2d%4s%4d%14.7E%14.7E", year, rheader.month,
           rheader.day, rheader.hour, rheader.ic, rheader.il,
           std::stoi(rheader.cgrid.c_str()), rheader.kvar.c_str(), rheader.nexp,
           rheader.prec, rheader.var1);
  recordHeader[50] = '\0';  // null-terminate
137

138
139
  p->stream->writeString(std::string(recordHeader),
                         ARLDataStream::PImpl::recordHeaderLength);
140

141
  radix_line("  header as string:\n  " << recordHeader);
142

143
144
  result = true;
  return result;
145
}
146

147
bool ARLDataStream::read_next_record_header(ARLRecordHeader& rheader)
148
149
150
{
  int bytesToSkip = roundUpInt(p->stream->bytesRead(), p->recordSize) -
                    p->stream->bytesRead();
151
  radix_line("Skipping " << bytesToSkip << " bytes to the next record header");
152
153
154

  p->stream->skipBytes(bytesToSkip);

155
  return read_record_header(rheader);
156
157
}

158
159
bool ARLDataStream::read_index_header(const ARLRecordHeader& rheader,
                                      ARLIndexHeader& iheader)
160
{
161
162
  bool result = false;

163
  // Read main part of index header
164
  radix_line("  Reading main part of index header...");
165
  std::string headerString =
166
167
      p->stream->readString(ARLDataStream::PImpl::indexHeaderLength);
  expand(headerString, rheader, iheader);
168
169

  // Calculate and save record size
170
  p->recordSize =
171
      (iheader.nx * iheader.ny) + ARLDataStream::PImpl::recordHeaderLength;
172

173
  // Read variable description part of index header
174
175
  radix_line("  Reading variable part of index header... " << iheader.nz
                                                           << " levels");
176
  for (size_t level = 0; level < size_t(iheader.nz); ++level)
177
178
179
180
181
  {
    // Read levels information
    std::string levelString = p->stream->readString(6);
    iheader.levels.push_back(std::stof(levelString));
    std::string nVarsString = p->stream->readString(2);
182
    iheader.num_vars_at_levels.push_back(std::stoi(nVarsString));
183
184

    // Read names and checksums
185
186
187
188
189
    iheader.var_names.push_back(std::vector<std::string>());
    iheader.check_sums.push_back(std::vector<int>());
    radix_line("    Level " << level << "... "
                            << iheader.num_vars_at_levels[level] << " vars");
    for (int var = 0; var < iheader.num_vars_at_levels[level]; ++var)
190
191
    {
      std::string nameString = p->stream->readString(4);
192
      iheader.var_names[level].push_back(nameString);
193
      std::string sumString = p->stream->readString(3);
194
      iheader.check_sums[level].push_back(std::stoi(sumString));
195
196
197
198
      p->stream->skipBytes(1);
    }
  }

199
  radix_line("  Read index header: model = " << iheader.model_id);
200
201
202
  radix_line("                         nx = " << iheader.nx);
  radix_line("                         ny = " << iheader.ny);
  radix_line("                         nz = " << iheader.nz);
203
  radix_line("        Size of each record = " << p->recordSize);
204
  radix_line("    header as string:\n    " << headerString);
205
206
207

  result = true;
  return result;
208
209
}

210
211
bool ARLDataStream::write_index_header(const ARLRecordHeader& rheader,
                                       const ARLIndexHeader& iheader)
212
{
213
214
  bool result = false;

215
  // Calculate and save record size
216
  p->recordSize =
217
      (iheader.nx * iheader.ny) + ARLDataStream::PImpl::recordHeaderLength;
218

219
  radix_line("  Write index header: model = " << iheader.model_id);
220
221
222
  radix_line("                          nx = " << iheader.nx);
  radix_line("                          ny = " << iheader.ny);
  radix_line("                          nz = " << iheader.nz);
223
224
  radix_line("         Size of each record = " << p->recordSize);

Purves, Murray's avatar
Purves, Murray committed
225
  const size_t MAX_HEADER_LENGTH = 10000;
Norby, Tom's avatar
Norby, Tom committed
226
  char indexHeaderMain[ARLDataStream::PImpl::indexHeaderLength + 1],
227
      indexHeaderVars[MAX_HEADER_LENGTH];
228
229
230
  int pos = 0;

  // Write the variable description part of the header
231
  for (size_t level = 0; level < size_t(iheader.nz); ++level)
232
  {
233
    pos += sprintf(indexHeaderVars + pos, "%6.1f", iheader.levels[level]);
234
235
236
    pos += sprintf(indexHeaderVars + pos, "%2d",
                   iheader.num_vars_at_levels[level]);
    for (size_t var = 0; var < size_t(iheader.num_vars_at_levels[level]); ++var)
237
    {
238
      pos += sprintf(indexHeaderVars + pos, "%4s",
239
240
241
                     iheader.var_names[level][var].c_str());
      pos += sprintf(indexHeaderVars + pos, "%3d ",
                     iheader.check_sums[level][var]);
242
243
244
245
    }
  }

  // Construct the main part of the header (inc. size calculation)
246
  int headerLength = ARLDataStream::PImpl::indexHeaderLength + pos;
247
  sprintf(indexHeaderMain,
248
249
          "%4s%3d%2d%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7."
          "2f%3d%3d%3d%2d%4d",
250
251
252
253
          iheader.model_id.c_str(), iheader.icx, iheader.mn, iheader.pole_lat,
          iheader.pole_lon, iheader.ref_lat, iheader.ref_lon, iheader.size,
          iheader.orient, iheader.tang_lat, iheader.sync_xp, iheader.sync_yp,
          iheader.sync_lat, iheader.sync_lon, iheader.dummy, iheader.nx,
254
          iheader.ny, iheader.nz, iheader.z_flag, headerLength);
Norby, Tom's avatar
Norby, Tom committed
255
256
  indexHeaderMain[ARLDataStream::PImpl::indexHeaderLength] =
      '\0';  // null-terminate
257

258
  // Write the two elements of the header
259
260
  p->stream->writeString(std::string(indexHeaderMain),
                         ARLDataStream::PImpl::indexHeaderLength);
261

262
  p->stream->writeString(std::string(indexHeaderVars), pos);
263
264
265
266
267
268
269

  // Skip enough bytes to get to the next index header
  int bytesToSkip = roundUpInt(p->stream->bytesWritten(), p->recordSize) -
                    p->stream->bytesWritten();
  radix_line("    Write complete: skipping "
             << bytesToSkip << " bytes to the next index header");

270
  p->stream->writeString("", size_t(bytesToSkip));
271

272
273
  radix_line("    header as string:\n    " << indexHeaderMain
                                           << indexHeaderVars);
274

275
276
  result = true;
  return result;
277
278
}

279
280
bool ARLDataStream::read_record(const ARLRecordHeader& rheader,
                                const ARLIndexHeader& iheader,
281
                                std::vector<std::vector<float> >& record)
282
{
283
284
  bool result = false;

285
  // Set up the vector size
Purves, Murray's avatar
Purves, Murray committed
286
  record.clear();
287
  record.resize(iheader.nx);
288
  for (std::vector<float>& vec : record)
289
  {
290
    vec.resize(size_t(iheader.ny));
291
292
293
  }

  // Calculate the scaling factor
294
295
  float scaleFactor = std::pow(2.0f, 7.0f - float(rheader.nexp)),
        lastValue   = 0.f;
296
297

  radix_line("    Reading record data:");
298
  for (int y = 0; y < iheader.ny; ++y)
299
  {
300
    for (int x = 0; x < iheader.nx; ++x)
301
302
    {
      // Read the raw value
303
      unsigned char ch = (unsigned char)(p->stream->readChar());
304
305
306
      int packedValue  = ch - 127;

      // Calculate the unpacked value
307
      float unpackedValue = 0.0;
308
309
310
311
312
      // Get the correct 'last value' if we are at a 0 index
      if (x == 0)
      {
        if (y == 0)
        {
313
          lastValue = rheader.var1;
314
315
316
317
318
319
320
321
322
323
324
        }
        else
        {
          lastValue = record[x][y - 1];
        }
      }

      unpackedValue = (packedValue / scaleFactor) + lastValue;
      record[x][y]  = unpackedValue;
      lastValue     = unpackedValue;

325
      if ((x < 2 && y < 2) || ((iheader.nx - x < 3) && (iheader.ny - y < 3)))
326
327
328
329
330
331
332
      {
        radix_line("      [" << x << "," << y << "]: packed = " << packedValue
                             << ", unpacked = " << unpackedValue);
      }
    }
  }

333
334
  result = true;
  return result;
335
336
}

337
338
bool ARLDataStream::write_record(const ARLRecordHeader& rheader,
                                 const ARLIndexHeader& iheader,
339
                                 const std::vector<std::vector<float> >& record)
340
{
341
342
  bool result = false;

343
344
345
346
347
348
349
  if (record.size() == 0)
  {
    radix_line("No data here - returning false");
    return false;
  }

  // Calculate the scaling factor
350
351
  float scaleFactor = std::pow(2.0f, 7.0f - float(rheader.nexp)),
        lastValue   = 0.f;
352
353

  radix_line("    Writing record data:");
354
  for (int y = 0; y < iheader.ny; ++y)
355
  {
356
    for (int x = 0; x < iheader.nx; ++x)
357
358
359
360
361
362
    {
      // Get the correct 'last value' if we are at a 0 index
      if (x == 0)
      {
        if (y == 0)
        {
363
          lastValue = rheader.var1;
364
365
366
        }
        else
        {
367
          lastValue = record[size_t(x)][size_t(y - 1)];
368
369
370
371
        }
      }

      // Calculate the packed value
372
      float unpackedValue = record[x][y];
373
      int packedInt       = int((unpackedValue - lastValue) * scaleFactor);
374
375
376
377
378
379
380

      unsigned char packedValue = (unsigned char)(packedInt + 127);

      p->stream->writeChar(packedValue);

      lastValue = unpackedValue;

381
      if ((x < 2 && y < 2) || ((iheader.nx - x < 3) && (iheader.ny - y < 3)))
382
383
384
385
386
387
388
      {
        radix_line("      [" << x << "," << y << "]: packed = " << packedInt
                             << ", unpacked = " << unpackedValue);
      }
    }
  }

389
390
  result = true;
  return result;
391
392
}

393
394
void ARLDataStream::close_stream() { p->stream->close(); }

395
}  // namespace radix