arldatastream.cc 10.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
120
121
122
123
  radix_line("Write index 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);
124
125

  // Construct index header string
126
127
128
129
130
  char recordHeader[50];
  sprintf(recordHeader, "%2d%2d%2d%2d%2d%2d%2d%4s%4d%14.7E%14.7E", rheader.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);
131

132
  p->stream->writeString(std::string(recordHeader), 50);
133

134
  radix_line("  header as string:\n  " << recordHeader);
135

136
137
  result = true;
  return result;
138
}
139

140
bool ARLDataStream::read_next_record_header(ARLRecordHeader& rheader)
141
142
143
{
  int bytesToSkip = roundUpInt(p->stream->bytesRead(), p->recordSize) -
                    p->stream->bytesRead();
Purves, Murray's avatar
Purves, Murray committed
144
  radix_line("Skipping " << bytesToSkip << " bytes to the next index header");
145
146
147

  p->stream->skipBytes(bytesToSkip);

148
  return read_record_header(rheader);
149
150
}

151
152
bool ARLDataStream::read_index_header(const ARLRecordHeader& rheader,
                                      ARLIndexHeader& iheader)
153
{
154
155
  bool result = false;

156
  std::string headerString =
157
158
      p->stream->readString(ARLDataStream::PImpl::indexHeaderLength);
  expand(headerString, rheader, iheader);
159
160

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

164
165
166
167
  radix_line("  Read record header: model = " << iheader.model_id);
  radix_line("                         nx = " << iheader.nx);
  radix_line("                         ny = " << iheader.ny);
  radix_line("                         nz = " << iheader.nz);
168
  radix_line("        Size of each record = " << p->recordSize);
169
  radix_line("    header as string:\n    " << headerString);
170
171
172

  result = true;
  return result;
173
174
}

175
176
bool ARLDataStream::write_index_header(const ARLRecordHeader& rheader,
                                       const ARLIndexHeader& iheader)
177
{
178
179
  bool result = false;

180
  // Calculate and save record size
181
  p->recordSize =
182
      (iheader.nx * iheader.ny) + ARLDataStream::PImpl::recordHeaderLength;
183

184
185
186
187
  radix_line("  Write record header: model = " << iheader.model_id);
  radix_line("                          nx = " << iheader.nx);
  radix_line("                          ny = " << iheader.ny);
  radix_line("                          nz = " << iheader.nz);
188
189
  radix_line("         Size of each record = " << p->recordSize);

190
191
  char indexHeader[108];
  sprintf(indexHeader,
192
193
          "%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",
194
195
196
197
198
          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,
          iheader.ny, iheader.nz, iheader.z_flag, iheader.lenh);
199

200
  p->stream->writeString(std::string(indexHeader), 108);
201
202
203
204
205
206
207
208
209

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

210
  radix_line("    header as string:\n    " << indexHeader);
211

212
213
  result = true;
  return result;
214
215
}

216
217
bool ARLDataStream::read_record(const ARLRecordHeader& rheader,
                                const ARLIndexHeader& iheader,
218
                                std::vector<std::vector<float> >& record)
219
{
220
221
  bool result = false;

222
  // Set up the vector size
Purves, Murray's avatar
Purves, Murray committed
223
  record.clear();
224
  record.resize(iheader.nx);
225
  for (std::vector<float>& vec : record)
226
  {
227
    vec.resize(iheader.ny);
228
229
230
  }

  // Calculate the scaling factor
231
  float scaleFactor = pow(2.0, 7.0 - (float)rheader.nexp), lastValue = 0.0;
232
233

  radix_line("    Reading record data:");
234
  for (int y = 0; y < iheader.ny; ++y)
235
  {
236
    for (int x = 0; x < iheader.nx; ++x)
237
238
239
240
241
242
    {
      // Read the raw value
      unsigned char ch = (unsigned char)p->stream->readChar();
      int packedValue  = ch - 127;

      // Calculate the unpacked value
243
      float unpackedValue = 0.0;
244
245
246
247
248
      // Get the correct 'last value' if we are at a 0 index
      if (x == 0)
      {
        if (y == 0)
        {
249
          lastValue = rheader.var1;
250
251
252
253
254
255
256
257
258
259
260
        }
        else
        {
          lastValue = record[x][y - 1];
        }
      }

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

261
      if ((x < 2 && y < 2) || ((iheader.nx - x < 3) && (iheader.ny - y < 3)))
262
263
264
265
266
267
268
      {
        radix_line("      [" << x << "," << y << "]: packed = " << packedValue
                             << ", unpacked = " << unpackedValue);
      }
    }
  }

269
270
  result = true;
  return result;
271
272
}

273
274
bool ARLDataStream::write_record(const ARLRecordHeader& rheader,
                                 const ARLIndexHeader& iheader,
275
                                 const std::vector<std::vector<float> >& record)
276
{
277
278
  bool result = false;

279
280
281
282
283
284
285
  if (record.size() == 0)
  {
    radix_line("No data here - returning false");
    return false;
  }

  // Calculate the scaling factor
286
  float scaleFactor = pow(2.0, 7.0 - (float)rheader.nexp), lastValue = 0.0;
287
288

  radix_line("    Writing record data:");
289
  for (int y = 0; y < iheader.ny; ++y)
290
  {
291
    for (int x = 0; x < iheader.nx; ++x)
292
293
294
295
296
297
    {
      // Get the correct 'last value' if we are at a 0 index
      if (x == 0)
      {
        if (y == 0)
        {
298
          lastValue = rheader.var1;
299
300
301
302
303
304
305
306
        }
        else
        {
          lastValue = record[x][y - 1];
        }
      }

      // Calculate the packed value
307
308
      float unpackedValue = record[x][y];
      int packedInt       = (int)((unpackedValue - lastValue) * scaleFactor);
309
310
311
312
313
314
315

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

      p->stream->writeChar(packedValue);

      lastValue = unpackedValue;

316
      if ((x < 2 && y < 2) || ((iheader.nx - x < 3) && (iheader.ny - y < 3)))
317
318
319
320
321
322
323
      {
        radix_line("      [" << x << "," << y << "]: packed = " << packedInt
                             << ", unpacked = " << unpackedValue);
      }
    }
  }

324
325
  result = true;
  return result;
326
327
}

328
329
void ARLDataStream::close_stream() { p->stream->close(); }

330
}  // namespace radix