arldatastream.cc 12.9 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
88
89
90
91
  if (!p->stream->is_open())
  {
    radix_line("Failed to open ARL file: " << file);
  }
}

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[50];
131
  sprintf(recordHeader, "%2d%2d%2d%2d%2d%2d%2d%4s%4d%14.7E%14.7E", year,
132
133
134
          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);
135

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

139
  radix_line("  header as string:\n  " << recordHeader);
140

141
142
  result = true;
  return result;
143
}
144

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

  p->stream->skipBytes(bytesToSkip);

153
  return read_record_header(rheader);
154
155
}

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

161
  // Read main part of index header
162
  std::string headerString =
163
164
      p->stream->readString(ARLDataStream::PImpl::indexHeaderLength);
  expand(headerString, rheader, iheader);
165
166

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

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
  // Read variable description part of index header
  for (size_t level = 0; level < iheader.nz; ++level)
  {
    // Read levels information
    std::string levelString = p->stream->readString(6);
    iheader.levels.push_back(std::stof(levelString));
    std::string nVarsString = p->stream->readString(2);
    iheader.nVarsAtLevels.push_back(std::stoi(nVarsString));

    // Read names and checksums
    iheader.varNames.push_back(std::vector<std::string>());
    iheader.checkSums.push_back(std::vector<int>());
    for (size_t var = 0; var < iheader.nVarsAtLevels[level]; ++var)
    {
      std::string nameString = p->stream->readString(4);
      iheader.varNames[level].push_back(nameString);
      std::string sumString = p->stream->readString(3);
      iheader.checkSums[level].push_back(std::stoi(sumString));
      p->stream->skipBytes(1);
    }
  }

192
  radix_line("  Read index header: model = " << iheader.model_id);
193
194
195
  radix_line("                         nx = " << iheader.nx);
  radix_line("                         ny = " << iheader.ny);
  radix_line("                         nz = " << iheader.nz);
196
  radix_line("        Size of each record = " << p->recordSize);
197
  radix_line("    header as string:\n    " << headerString);
198
199
200

  result = true;
  return result;
201
202
}

203
204
bool ARLDataStream::write_index_header(const ARLRecordHeader& rheader,
                                       const ARLIndexHeader& iheader)
205
{
206
207
  bool result = false;

208
  // Calculate and save record size
209
  p->recordSize =
210
      (iheader.nx * iheader.ny) + ARLDataStream::PImpl::recordHeaderLength;
211

212
  radix_line("  Write index header: model = " << iheader.model_id);
213
214
215
  radix_line("                          nx = " << iheader.nx);
  radix_line("                          ny = " << iheader.ny);
  radix_line("                          nz = " << iheader.nz);
216
217
  radix_line("         Size of each record = " << p->recordSize);

218
  size_t MAX_HEADER_LENGTH = 10000;
219
220
  char indexHeaderMain[ARLDataStream::PImpl::indexHeaderLength],
      indexHeaderVars[MAX_HEADER_LENGTH];
221
222
223
224
225
226
227
228
229
  int pos = 0;

  // Write the variable description part of the header
  for (size_t level = 0; level < iheader.nz; ++level)
  {
    pos += sprintf(indexHeaderVars + pos, "%6.2f", iheader.levels[level]);
    pos += sprintf(indexHeaderVars + pos, "%2d", iheader.nVarsAtLevels[level]);
    for (size_t var = 0; var < iheader.nVarsAtLevels[level]; ++var)
    {
230
231
232
233
      pos += sprintf(indexHeaderVars + pos, "%4s",
                     iheader.varNames[level][var].c_str());
      pos +=
          sprintf(indexHeaderVars + pos, "%3d ", iheader.checkSums[level][var]);
234
235
236
237
    }
  }

  // Construct the main part of the header (inc. size calculation)
238
  int headerLength = ARLDataStream::PImpl::indexHeaderLength + pos;
239
  sprintf(indexHeaderMain,
240
241
          "%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",
242
243
244
245
          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,
246
          iheader.ny, iheader.nz, iheader.z_flag, headerLength);
247

248
  // Write the two elements of the header
249
250
  p->stream->writeString(std::string(indexHeaderMain),
                         ARLDataStream::PImpl::indexHeaderLength);
251
  p->stream->writeString(std::string(indexHeaderVars), pos);
252
253
254
255
256
257
258
259
260

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

  p->stream->writeString("", bytesToSkip);

261
  radix_line("    header as string:\n    " << indexHeaderVars);
262

263
264
  result = true;
  return result;
265
266
}

267
268
bool ARLDataStream::read_record(const ARLRecordHeader& rheader,
                                const ARLIndexHeader& iheader,
269
                                std::vector<std::vector<float> >& record)
270
{
271
272
  bool result = false;

273
  // Set up the vector size
Purves, Murray's avatar
Purves, Murray committed
274
  record.clear();
275
  record.resize(iheader.nx);
276
  for (std::vector<float>& vec : record)
277
  {
278
    vec.resize(iheader.ny);
279
280
281
  }

  // Calculate the scaling factor
282
  float scaleFactor = pow(2.0, 7.0 - (float)rheader.nexp), lastValue = 0.0;
283
284

  radix_line("    Reading record data:");
285
  for (int y = 0; y < iheader.ny; ++y)
286
  {
287
    for (int x = 0; x < iheader.nx; ++x)
288
289
290
291
292
293
    {
      // Read the raw value
      unsigned char ch = (unsigned char)p->stream->readChar();
      int packedValue  = ch - 127;

      // Calculate the unpacked value
294
      float unpackedValue = 0.0;
295
296
297
298
299
      // Get the correct 'last value' if we are at a 0 index
      if (x == 0)
      {
        if (y == 0)
        {
300
          lastValue = rheader.var1;
301
302
303
304
305
306
307
308
309
310
311
        }
        else
        {
          lastValue = record[x][y - 1];
        }
      }

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

312
      if ((x < 2 && y < 2) || ((iheader.nx - x < 3) && (iheader.ny - y < 3)))
313
314
315
316
317
318
319
      {
        radix_line("      [" << x << "," << y << "]: packed = " << packedValue
                             << ", unpacked = " << unpackedValue);
      }
    }
  }

320
321
  result = true;
  return result;
322
323
}

324
325
bool ARLDataStream::write_record(const ARLRecordHeader& rheader,
                                 const ARLIndexHeader& iheader,
326
                                 const std::vector<std::vector<float> >& record)
327
{
328
329
  bool result = false;

330
331
332
333
334
335
336
  if (record.size() == 0)
  {
    radix_line("No data here - returning false");
    return false;
  }

  // Calculate the scaling factor
337
  float scaleFactor = pow(2.0, 7.0 - (float)rheader.nexp), lastValue = 0.0;
338
339

  radix_line("    Writing record data:");
340
  for (int y = 0; y < iheader.ny; ++y)
341
  {
342
    for (int x = 0; x < iheader.nx; ++x)
343
344
345
346
347
348
    {
      // Get the correct 'last value' if we are at a 0 index
      if (x == 0)
      {
        if (y == 0)
        {
349
          lastValue = rheader.var1;
350
351
352
353
354
355
356
357
        }
        else
        {
          lastValue = record[x][y - 1];
        }
      }

      // Calculate the packed value
358
359
      float unpackedValue = record[x][y];
      int packedInt       = (int)((unpackedValue - lastValue) * scaleFactor);
360
361
362
363
364
365
366

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

      p->stream->writeChar(packedValue);

      lastValue = unpackedValue;

367
      if ((x < 2 && y < 2) || ((iheader.nx - x < 3) && (iheader.ny - y < 3)))
368
369
370
371
372
373
374
      {
        radix_line("      [" << x << "," << y << "]: packed = " << packedInt
                             << ", unpacked = " << unpackedValue);
      }
    }
  }

375
376
  result = true;
  return result;
377
378
}

379
380
void ARLDataStream::close_stream() { p->stream->close(); }

381
}  // namespace radix