File: rspreader.cpp

package info (click to toggle)
aoflagger 3.4.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,960 kB
  • sloc: cpp: 83,076; python: 10,187; sh: 260; makefile: 178
file content (347 lines) | stat: -rw-r--r-- 13,681 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#include <stdexcept>
#include <set>
#include <sstream>

#include "rspreader.h"
#include "../structures/image2d.h"
#include "../structures/mask2d.h"
#include "../structures/samplerow.h"

#include "../util/logger.h"
#include "../util/ffttools.h"

const unsigned char RSPReader::BitReverseTable256[256] = {
#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
    R6(0), R6(2), R6(1), R6(3)};

const unsigned long RSPReader::STATION_INTEGRATION_STEPS = 1024;

const unsigned int RSPReader::RCPBeamletData::SIZE = 8;

const unsigned int RSPReader::RCPApplicationHeader::SIZE = 16;

std::pair<TimeFrequencyData, TimeFrequencyMetaDataPtr>
RSPReader::ReadChannelBeamlet(unsigned long timestepStart,
                              unsigned long timestepEnd, unsigned beamletCount,
                              unsigned beamletIndex) {
  const unsigned width = timestepEnd - timestepStart;

  std::pair<TimeFrequencyData, TimeFrequencyMetaDataPtr> data =
      ReadSingleBeamlet(timestepStart * (unsigned long)256,
                        timestepEnd * (unsigned long)256, beamletCount,
                        beamletIndex);

  const TimeFrequencyData allX = data.first.Make(aocommon::Polarization::XX);
  const TimeFrequencyData allY = data.first.Make(aocommon::Polarization::YY);
  const Image2DCPtr xr = allX.GetRealPart();
  const Image2DCPtr xi = allX.GetImaginaryPart();
  const Image2DCPtr yr = allY.GetRealPart();
  const Image2DCPtr yi = allY.GetImaginaryPart();
  const Mask2DCPtr mask = data.first.GetSingleMask();

  Image2DPtr outXR = Image2D::CreateUnsetImagePtr(width, 256),
             outXI = Image2D::CreateUnsetImagePtr(width, 256),
             outYR = Image2D::CreateUnsetImagePtr(width, 256),
             outYI = Image2D::CreateUnsetImagePtr(width, 256);
  const Mask2DPtr outMask = Mask2D::CreateUnsetMaskPtr(width, 256);

  std::vector<double> observationTimes;
  for (unsigned long timestep = 0; timestep < timestepEnd - timestepStart;
       ++timestep) {
    const unsigned long timestepIndex = timestep * 256;
    SampleRow realX = SampleRow::MakeFromRow(xr.get(), timestepIndex, 256, 0),
              imaginaryX =
                  SampleRow::MakeFromRow(xi.get(), timestepIndex, 256, 0),
              realY = SampleRow::MakeFromRow(yr.get(), timestepIndex, 256, 0),
              imaginaryY =
                  SampleRow::MakeFromRow(yi.get(), timestepIndex, 256, 0);

    FFTTools::FFT(realX, imaginaryX);
    FFTTools::FFT(realY, imaginaryY);

    realX.SetVerticalImageValues(outXR.get(), timestep);
    imaginaryX.SetVerticalImageValues(outXI.get(), timestep);
    realY.SetVerticalImageValues(outYR.get(), timestep);
    imaginaryY.SetVerticalImageValues(outYI.get(), timestep);

    observationTimes.push_back(
        data.second->ObservationTimes()[timestepIndex + 256 / 2]);

    size_t validValues = 0;
    for (unsigned y = 0; y < 256; ++y) {
      if (!mask->Value(timestepIndex + y, 0)) ++validValues;
    }
    for (unsigned y = 0; y < 256; ++y) {
      outMask->SetValue(timestep, y, validValues == 0);
    }
  }

  data.first = TimeFrequencyData(aocommon::Polarization::XX, outXR, outXI,
                                 aocommon::Polarization::YY, outYR, outYI);
  data.first.SetGlobalMask(outMask);
  BandInfo band = data.second->Band();
  band.channels.clear();
  for (unsigned i = 0; i < 256; ++i) {
    ChannelInfo channel;
    channel.frequencyHz = i + 1;
    channel.frequencyIndex = i;
    band.channels.push_back(channel);
  }
  data.second->SetBand(band);
  data.second->SetObservationTimes(observationTimes);
  return data;
}

std::pair<TimeFrequencyData, TimeFrequencyMetaDataPtr>
RSPReader::ReadSingleBeamlet(unsigned long timestepStart,
                             unsigned long timestepEnd, unsigned beamletCount,
                             unsigned beamletIndex) {
  std::pair<TimeFrequencyData, TimeFrequencyMetaDataPtr> data =
      ReadAllBeamlets(timestepStart, timestepEnd, beamletCount);

  const unsigned width = timestepEnd - timestepStart;
  const Image2DPtr realX = Image2D::CreateZeroImagePtr(width, 1);
  const Image2DPtr imaginaryX = Image2D::CreateZeroImagePtr(width, 1);
  const Image2DPtr realY = Image2D::CreateZeroImagePtr(width, 1);
  const Image2DPtr imaginaryY = Image2D::CreateZeroImagePtr(width, 1);
  const Mask2DPtr mask = Mask2D::CreateUnsetMaskPtr(width, 1);

  const TimeFrequencyData allX = data.first.Make(aocommon::Polarization::XX);
  const TimeFrequencyData allY = data.first.Make(aocommon::Polarization::YY);
  const Image2DCPtr xr = allX.GetRealPart();
  const Image2DCPtr xi = allX.GetImaginaryPart();
  const Image2DCPtr yr = allY.GetRealPart();
  const Image2DCPtr yi = allY.GetImaginaryPart();
  const Mask2DCPtr maskWithBeamlets = data.first.GetSingleMask();

  for (unsigned x = 0; x < width; ++x) {
    realX->SetValue(x, 0, xr->Value(x, beamletIndex));
    imaginaryX->SetValue(x, 0, xi->Value(x, beamletIndex));
    realY->SetValue(x, 0, yr->Value(x, beamletIndex));
    imaginaryY->SetValue(x, 0, yi->Value(x, beamletIndex));
    mask->SetValue(x, 0, maskWithBeamlets->Value(x, beamletIndex));
  }
  data.first = TimeFrequencyData(aocommon::Polarization::XX, realX, imaginaryX,
                                 aocommon::Polarization::YY, realY, imaginaryY);
  data.first.SetGlobalMask(mask);
  BandInfo band = data.second->Band();
  band.channels[0] = data.second->Band().channels[beamletIndex];
  band.channels.resize(1);
  data.second->SetBand(band);
  return data;
}

unsigned long RSPReader::TimeStepCount(size_t beamletCount) const {
  std::ifstream stream(_rawFile.c_str(),
                       std::ios_base::binary | std::ios_base::in);
  stream.seekg(0, std::ios_base::end);
  const unsigned long fileSize = stream.tellg();

  stream.seekg(0, std::ios_base::beg);
  RCPApplicationHeader firstHeader;
  firstHeader.Read(stream);
  const unsigned long bytesPerFrame =
      beamletCount * firstHeader.nofBlocks * RCPBeamletData::SIZE +
      RCPApplicationHeader::SIZE;
  const unsigned long frames = fileSize / bytesPerFrame;

  Logger::Debug << "File has " << frames << " number of frames ("
                << ((double)(frames * firstHeader.nofBlocks *
                             STATION_INTEGRATION_STEPS) /
                    _clockSpeed)
                << "s of data)\n";

  return frames * firstHeader.nofBlocks;
}

std::pair<TimeFrequencyData, TimeFrequencyMetaDataPtr>
RSPReader::ReadAllBeamlets(unsigned long timestepStart,
                           unsigned long timestepEnd, unsigned beamletCount) {
  const unsigned width = timestepEnd - timestepStart;
  const Image2DPtr realX = Image2D::CreateZeroImagePtr(width, beamletCount);
  const Image2DPtr imaginaryX =
      Image2D::CreateZeroImagePtr(width, beamletCount);
  const Image2DPtr realY = Image2D::CreateZeroImagePtr(width, beamletCount);
  const Image2DPtr imaginaryY =
      Image2D::CreateZeroImagePtr(width, beamletCount);
  const Mask2DPtr mask = Mask2D::CreateSetMaskPtr<true>(width, beamletCount);

  std::ifstream file(_rawFile.c_str(),
                     std::ios_base::binary | std::ios_base::in);
  size_t frame = 0;
  std::set<short> stations;

  const TimeFrequencyMetaDataPtr metaData =
      TimeFrequencyMetaDataPtr(new TimeFrequencyMetaData());
  BandInfo band;
  for (size_t i = 0; i < beamletCount; ++i) {
    ChannelInfo channel;
    channel.frequencyHz = i + 1;
    channel.frequencyIndex = i;
    band.channels.push_back(channel);
  }
  metaData->SetBand(band);

  std::vector<double> observationTimes;

  // Read a header and determine the reading start position
  // Because timestepStart might fall within a block, the
  RCPApplicationHeader firstHeader;
  firstHeader.Read(file);
  const unsigned long bytesPerFrame =
      beamletCount * firstHeader.nofBlocks * RCPBeamletData::SIZE +
      RCPApplicationHeader::SIZE;
  const unsigned long startFrame =
      timestepStart / (unsigned long)firstHeader.nofBlocks;
  const unsigned long startByte = startFrame * bytesPerFrame;
  const unsigned long offsetFromStart =
      timestepStart - (startFrame * firstHeader.nofBlocks);
  // Logger::Debug << "Seeking to " << startByte << " (timestepStart=" <<
  // timestepStart << ", offsetFromStart=" << offsetFromStart << ", startFrame="
  // << startFrame << ",bytesPerFrame=" << bytesPerFrame << ")\n";
  file.seekg(startByte, std::ios_base::beg);

  // Read the frames
  unsigned long x = 0;
  while (x < width + offsetFromStart && file.good()) {
    RCPApplicationHeader header;
    header.Read(file);
    if (header.versionId != 2) {
      std::stringstream s;
      s << "Corrupted header found in frame " << frame << "!";
      throw std::runtime_error(s.str());
    }
    if (stations.count(header.stationId) == 0) {
      stations.insert(header.stationId);
      AntennaInfo antenna;
      std::stringstream s;
      s << "LOFAR station with index " << header.stationId;
      antenna.name = s.str();
      metaData->SetAntenna1(antenna);
      metaData->SetAntenna2(antenna);
    }
    for (size_t j = 0; j < beamletCount; ++j) {
      for (size_t i = 0; i < header.nofBlocks; ++i) {
        RCPBeamletData data;
        data.Read(file);
        if (i + x < width + offsetFromStart && i + x >= offsetFromStart) {
          const unsigned long pos = i + x - offsetFromStart;
          realX->SetValue(pos, j, data.xr);
          imaginaryX->SetValue(pos, j, data.xi);
          realY->SetValue(pos, j, data.yr);
          imaginaryY->SetValue(pos, j, data.yi);
          mask->SetValue(pos, j, false);
        }
      }
    }
    x += header.nofBlocks;
    ++frame;
  }
  // Logger::Debug << "Read " << frame << " frames.\n";

  for (unsigned long i = 0; i < width; ++i) {
    const unsigned long pos = i + timestepStart;
    const double time =
        (double)pos * (double)STATION_INTEGRATION_STEPS / (double)_clockSpeed;
    observationTimes.push_back(time);
  }

  metaData->SetObservationTimes(observationTimes);

  std::pair<TimeFrequencyData, TimeFrequencyMetaDataPtr> data;
  data.first = TimeFrequencyData(aocommon::Polarization::XX, realX, imaginaryX,
                                 aocommon::Polarization::YY, realY, imaginaryY);
  data.first.SetGlobalMask(mask);
  data.second = metaData;
  return data;
}

void RSPReader::ReadForStatistics(unsigned beamletCount) {
  const long unsigned timesteps = TimeStepCount(beamletCount);
  const long unsigned stepSize = 1024;
  std::vector<BeamletStatistics> statistics(beamletCount),
      timeStartStatistics(beamletCount);

  std::vector<std::ofstream*> statFile(beamletCount);
  for (unsigned i = 0; i < beamletCount; ++i) {
    std::ostringstream str;
    str << "rsp-statistics" << i << ".txt";
    statFile[i] = new std::ofstream(str.str().c_str());
  }

  double startTime = -1.0, periodStartTime = -1.0;

  for (unsigned long timestepIndex = 0; timestepIndex < timesteps;
       timestepIndex += stepSize) {
    // Read the data
    unsigned long end = timestepIndex + stepSize;
    if (end > timesteps) end = timesteps;
    const std::pair<TimeFrequencyData, TimeFrequencyMetaDataPtr> dataPair =
        ReadAllBeamlets(timestepIndex, end, beamletCount);
    const TimeFrequencyData& data = dataPair.first;
    if (startTime == -1.0) {
      startTime = dataPair.second->ObservationTimes()[0];
      periodStartTime = startTime;
    }

    // Count the statistics
    for (unsigned imageIndex = 0; imageIndex < data.ImageCount();
         ++imageIndex) {
      const Image2DCPtr image = data.GetImage(imageIndex);
      for (unsigned y = 0; y < image->Height(); ++y) {
        for (unsigned x = 0; x < image->Width(); ++x) {
          int value = (int)image->Value(x, y);
          if (value < 0) {
            value = -value;
            ++(statistics[y].bitUseCount[15]);
          }
          unsigned highestBit = (value != 0) ? 1 : 0;
          for (unsigned bit = 0; bit < 15; ++bit) {
            if ((value & (2 << bit)) != 0) {
              highestBit = bit + 1;
            }
          }
          for (unsigned bit = 0; bit < highestBit; ++bit)
            ++(statistics[y].bitUseCount[bit]);
          ++(statistics[y].totalCount);
        }
      }
    }
    if ((timestepIndex / stepSize) % 100000 == 0 ||
        timestepIndex + stepSize >= timesteps) {
      for (unsigned i = 0; i < beamletCount; ++i) {
        Logger::Info << "Beamlet index " << i << ":\n";
        statistics[i].Print();
      }
    }
    if ((dataPair.second->ObservationTimes()[0] - periodStartTime) > 60.0) {
      Logger::Debug << "Processed 1 minute of data ("
                    << (dataPair.second->ObservationTimes()[0] - startTime)
                    << "s)\n";
      for (unsigned i = 0; i < beamletCount; ++i) {
        (*statFile[i]) << (periodStartTime - startTime) << '\t'
                       << (statistics[i].totalCount -
                           timeStartStatistics[i].totalCount);
        statistics[i].totalCount = timeStartStatistics[i].totalCount;
        for (unsigned bit = 0; bit < 15; ++bit) {
          (*statFile[i]) << '\t'
                         << (statistics[i].bitUseCount[bit] -
                             timeStartStatistics[i].bitUseCount[bit]);
          timeStartStatistics[i].bitUseCount[bit] =
              statistics[i].bitUseCount[bit];
        }
        (*statFile[i]) << '\n';
      }

      periodStartTime = dataPair.second->ObservationTimes()[0];
    }
  }

  for (unsigned i = 0; i < beamletCount; ++i) {
    Logger::Info << "Beamlet index " << i << ":\n";
    statistics[i].Print();
    delete statFile[i];
  }
}