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)
Norby, Tom's avatar
Norby, Tom committed
81
    : p(new PImpl())
82
{
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
  }
}

Norby, Tom's avatar
Norby, Tom committed
92
93
ARLDataStream::~ARLDataStream() { delete p; }

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

98
  std::string headerString =
99
100
101
102
103
104
105
106
107
108
      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);
109
  radix_line("  header as string:\n  " << headerString);
110
111
112

  result = true;
  return result;
113
114
}

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

119
120
121
  // Remove century from year
  int year = rheader.year % 100;

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

  // Construct index header string
132
  char recordHeader[51];
Norby, Tom's avatar
Norby, Tom committed
133
134
135
136
137
138
  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
139

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

143
  radix_line("  header as string:\n  " << recordHeader);
144

145
146
  result = true;
  return result;
147
}
148

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

  p->stream->skipBytes(bytesToSkip);

157
  return read_record_header(rheader);
158
159
}

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

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

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

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

    // Read names and checksums
187
188
189
190
191
    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)
192
193
    {
      std::string nameString = p->stream->readString(4);
194
      iheader.var_names[level].push_back(nameString);
195
      std::string sumString = p->stream->readString(3);
196
      iheader.check_sums[level].push_back(std::stoi(sumString));
197
198
199
200
      p->stream->skipBytes(1);
    }
  }

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

  result = true;
  return result;
210
211
}

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

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

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

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

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

  // Construct the main part of the header (inc. size calculation)
248
  int headerLength = ARLDataStream::PImpl::indexHeaderLength + pos;
249
  sprintf(indexHeaderMain,
250
251
          "%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",
252
253
254
255
          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,
256
          iheader.ny, iheader.nz, iheader.z_flag, headerLength);
Norby, Tom's avatar
Norby, Tom committed
257
258
  indexHeaderMain[ARLDataStream::PImpl::indexHeaderLength] =
      '\0';  // null-terminate
259

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

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

  // 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");

272
  p->stream->writeString("", size_t(bytesToSkip));
273

274
275
  radix_line("    header as string:\n    " << indexHeaderMain
                                           << indexHeaderVars);
276

277
278
  result = true;
  return result;
279
280
}

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

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

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

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

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

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

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

335
336
  result = true;
  return result;
337
338
}

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

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

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

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

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

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

      p->stream->writeChar(packedValue);

      lastValue = unpackedValue;

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

391
392
  result = true;
  return result;
393
394
}

395
396
void ARLDataStream::close_stream() { p->stream->close(); }

397
}  // namespace radix