File: baselineiterator.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 (335 lines) | stat: -rw-r--r-- 11,258 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
#include "baselineiterator.h"

#include "../lua/luathreadgroup.h"
#include "../lua/scriptdata.h"

#include "../structures/antennainfo.h"

#include "../util/logger.h"
#include "../util/progress/dummyprogresslistener.h"
#include "../util/stopwatch.h"

#include "../imagesets/bhfitsimageset.h"
#include "../imagesets/fitsimageset.h"
#include "../imagesets/imageset.h"
#include "../imagesets/msimageset.h"
#include "../imagesets/filterbankset.h"
#include "../imagesets/qualitystatimageset.h"
#include "../imagesets/rfibaselineset.h"

#include "writethread.h"

#include <aocommon/system.h>

#include <sstream>
#include <vector>

BaselineIterator::BaselineIterator(std::mutex* ioMutex, const Options& options)
    : _options(options),
      _sequenceCount(0),
      _nextIndex(0),
      _threadCount(4),
      _loopIndex(),
      _ioMutex(ioMutex),
      _finishedBaselines(false),
      _exceptionOccured(false),
      _baselineProgress(0) {}

BaselineIterator::~BaselineIterator() {}

void BaselineIterator::Run(imagesets::ImageSet& imageSet, LuaThreadGroup& lua,
                           ScriptData& scriptData) {
  _lua = &lua;
  _imageSet = &imageSet;
  _threadCount = _options.CalculateThreadCount();

  _writeThread.reset(new WriteThread(imageSet, _threadCount, _ioMutex));
  _globalScriptData = &scriptData;

  imagesets::MSImageSet* msImageSet =
      dynamic_cast<imagesets::MSImageSet*>(&imageSet);
  if (msImageSet) {
    // Check memory usage
    const imagesets::ImageSetIndex tempIndex = msImageSet->StartIndex();
    const size_t timeStepCount =
        msImageSet->ObservationTimesVector(tempIndex).size();
    const size_t channelCount = msImageSet->GetBandInfo(0).channels.size();
    const double estMemorySizePerThread =
        8.0 /*bp complex*/ * 4.0 /*polarizations*/ * double(timeStepCount) *
        double(channelCount) *
        3.0 /* approx copies of the data that will be made in memory*/;
    Logger::Debug << "Estimate of memory each thread will use: "
                  << memToStr(estMemorySizePerThread) << ".\n";
    size_t compThreadCount = _threadCount;
    if (compThreadCount > 0) --compThreadCount;

    const int64_t memSize = aocommon::system::TotalMemory();
    Logger::Debug << "Detected " << memToStr(memSize) << " of system memory.\n";

    if (estMemorySizePerThread * double(compThreadCount) > memSize) {
      size_t maxThreads = size_t(memSize / estMemorySizePerThread);
      if (maxThreads < 1) maxThreads = 1;
      Logger::Warn << "This measurement set is TOO LARGE to be processed with "
                   << _threadCount << " threads!\n"
                   << _threadCount << " threads would require "
                   << memToStr(estMemorySizePerThread * compThreadCount)
                   << " of memory approximately.\n"
                      "Number of threads that will actually be used: "
                   << maxThreads
                   << "\n"
                      "This might hurt performance a lot!\n\n";
      _threadCount = maxThreads;
    }
  }
  if (dynamic_cast<imagesets::FilterBankSet*>(&imageSet) != nullptr &&
      _threadCount != 1) {
    Logger::Info << "This is a Filterbank set -- disabling multi-threading\n";
    _threadCount = 1;
  }
  if (!_options.antennaeToSkip.empty()) {
    Logger::Debug << "The following antennas will be skipped: ";
    for (const size_t a : _options.antennaeToSkip) Logger::Debug << a << ' ';
    Logger::Debug << '\n';
  }
  if (!_options.antennaeToInclude.empty()) {
    Logger::Debug << "Only the following antennas will be included: ";
    for (const size_t a : _options.antennaeToInclude) Logger::Debug << a << ' ';
    Logger::Debug << '\n';
  }

  _finishedBaselines = false;
  _sequenceCount = 0;
  _baselineProgress = 0;
  _nextIndex = 0;

  // Count the sequences that are to be processed
  imagesets::ImageSetIndex iteratorIndex = imageSet.StartIndex();
  while (!iteratorIndex.HasWrapped()) {
    if (IsSequenceSelected(iteratorIndex)) ++_sequenceCount;
    iteratorIndex.Next();
  }
  Logger::Debug << "Will process " << _sequenceCount << " sequences.\n";

  // Initialize thread data and threads
  _loopIndex = imageSet.StartIndex();

  std::vector<std::thread> threadGroup;
  const ReaderThread reader(*this);
  threadGroup.emplace_back(reader);

  for (unsigned i = 0; i < _threadCount; ++i) {
    const ProcessingThread function(*this, i);
    threadGroup.emplace_back(function);
  }

  for (std::thread& t : threadGroup) t.join();

  _writeThread.reset();

  if (_exceptionOccured)
    throw std::runtime_error(
        "An exception occured in the parallel (multi-threaded) processing of "
        "the baselines: the RFI strategy will not continue.");
}

bool BaselineIterator::IsSequenceSelected(imagesets::ImageSetIndex& index) {
  imagesets::IndexableSet* idImageSet =
      dynamic_cast<imagesets::IndexableSet*>(_imageSet);
  size_t a1id, a2id;
  if (idImageSet != nullptr) {
    a1id = idImageSet->GetAntenna1(index);
    a2id = idImageSet->GetAntenna2(index);
    if (!_options.bands.empty() &&
        _options.bands.count(idImageSet->GetBand(index)) == 0)
      return false;
    if (!_options.fields.empty() &&
        _options.fields.count(idImageSet->GetField(index)) == 0)
      return false;
  } else {
    a1id = 0;
    a2id = 0;
  }
  if (_options.antennaeToSkip.count(a1id) != 0 ||
      _options.antennaeToSkip.count(a2id) != 0)
    return false;
  if (!_options.antennaeToInclude.empty() &&
      (_options.antennaeToInclude.count(a1id) == 0 &&
       _options.antennaeToInclude.count(a2id) == 0))
    return false;

  // For SD/BHFits/QS/rfibl files, we want to select everything -- it's
  // confusing if the default option "only flag cross correlations" would also
  // hold for single-"baseline" files.
  if (!_imageSet->HasCrossCorrelations()) return true;

  switch (_options.baselineSelection.value_or(
      BaselineSelection::CrossCorrelations)) {
    case BaselineSelection::All:
      return true;
    case BaselineSelection::CrossCorrelations: {
      return a1id != a2id;
    }
    case BaselineSelection::AutoCorrelations:
      return a1id == a2id;
    case BaselineSelection::Current:
    case BaselineSelection::EqualToCurrent:
    case BaselineSelection::AutoCorrelationsOfCurrentAntennae:
      throw std::runtime_error("Not implemented");
  }
  return false;
}

imagesets::ImageSetIndex BaselineIterator::GetNextIndex() {
  const std::lock_guard<std::mutex> lock(_mutex);
  while (!_loopIndex.HasWrapped()) {
    if (IsSequenceSelected(_loopIndex)) {
      imagesets::ImageSetIndex newIndex(_loopIndex);
      _loopIndex.Next();

      return newIndex;
    }
    _loopIndex.Next();
  }
  return imagesets::ImageSetIndex();
}

void BaselineIterator::SetExceptionOccured() {
  const std::lock_guard<std::mutex> lock(_mutex);
  _exceptionOccured = true;
  _dataProcessed.notify_all();
  _dataAvailable.notify_all();
}

void BaselineIterator::SetFinishedBaselines() {
  const std::lock_guard<std::mutex> lock(_mutex);
  _finishedBaselines = true;
}

void BaselineIterator::ProcessingThread::operator()() {
  ScriptData scriptData;
  const std::string executeFunctionName =
      _parent._options.executeFunctionName.empty()
          ? "execute"
          : _parent._options.executeFunctionName;

  try {
    std::unique_ptr<imagesets::BaselineData> baseline =
        _parent.GetNextBaseline();

    while (baseline != nullptr) {
      /* TODO
      std::ostringstream progressStr;
      if(baseline->MetaData()->HasAntenna1() &&
      baseline->MetaData()->HasAntenna2()) progressStr << "Processing baseline "
      << baseline->MetaData()->Antenna1().name << " x " <<
      baseline->MetaData()->Antenna2().name; else progressStr << "Processing
      next baseline";

      _parent.SetProgress(_progress, _parent.BaselineProgress(),
      _parent._baselineCount, progressStr.str(), _threadIndex);
      */

      TimeFrequencyData data(baseline->Data());
      _parent._lua->Execute(_threadIndex, data, baseline->MetaData(),
                            scriptData, executeFunctionName);

      _parent._writeThread->SaveFlags(data, baseline->Index());

      baseline = _parent.GetNextBaseline();
      _parent.IncBaselineProgress();
    }

  } catch (std::exception& e) {
    Logger::Error << e.what() << '\n';
    _parent.SetExceptionOccured();
  }

  {
    const std::unique_lock<std::mutex> ioLock(*_parent._ioMutex);
    _parent._globalScriptData->Combine(std::move(scriptData));
  }

  Logger::Debug << "Processing thread finished.\n";
}

void BaselineIterator::ReaderThread::operator()() {
  Stopwatch watch(true);
  bool finished = false;
  const size_t threadCount = _parent._threadCount;
  size_t minRecommendedBufferSize, maxRecommendedBufferSize;
  imagesets::MSImageSet* msImageSet =
      dynamic_cast<imagesets::MSImageSet*>(_parent._imageSet);
  if (msImageSet != nullptr) {
    minRecommendedBufferSize =
        msImageSet->Reader()->GetMinRecommendedBufferSize(threadCount);
    maxRecommendedBufferSize =
        msImageSet->Reader()->GetMaxRecommendedBufferSize(threadCount) -
        _parent.GetBaselinesInBufferCount();
  } else {
    minRecommendedBufferSize = 1;
    maxRecommendedBufferSize = 2;
  }

  do {
    watch.Pause();
    _parent.WaitForReadBufferAvailable(minRecommendedBufferSize);
    if (!_parent._exceptionOccured) {
      const size_t wantedCount =
          maxRecommendedBufferSize - _parent.GetBaselinesInBufferCount();
      size_t requestedCount = 0;

      std::unique_lock<std::mutex> lock(*_parent._ioMutex);
      watch.Start();

      for (size_t i = 0; i < wantedCount; ++i) {
        const imagesets::ImageSetIndex index = _parent.GetNextIndex();
        if (!index.Empty()) {
          _parent._imageSet->AddReadRequest(index);
          ++requestedCount;
        } else {
          finished = true;
          break;
        }
      }

      if (requestedCount > 0) {
        DummyProgressListener dummy;
        _parent._imageSet->PerformReadRequests(dummy);
        watch.Pause();

        for (size_t i = 0; i < requestedCount; ++i) {
          std::unique_ptr<imagesets::BaselineData> baseline =
              _parent._imageSet->GetNextRequested();

          const std::lock_guard<std::mutex> bufferLock(_parent._mutex);
          _parent._baselineBuffer.emplace(std::move(baseline));
        }
      }

      lock.unlock();

      _parent._dataAvailable.notify_all();
    }
    watch.Start();
  } while (!finished && !_parent._exceptionOccured);
  _parent.SetFinishedBaselines();
  _parent._dataAvailable.notify_all();
  watch.Pause();
  Logger::Debug << "Time spent on reading: " << watch.ToString() << '\n';
}

std::string BaselineIterator::memToStr(double memSize) {
  std::ostringstream str;
  if (memSize > 1024.0 * 1024.0 * 1024.0 * 1024.0)
    str << round(memSize * 10.0 / (1024.0 * 1024.0 * 1024.0 * 1024.0)) / 10.0
        << " TB";
  else if (memSize > 1024.0 * 1024.0 * 1024.0)
    str << round(memSize * 10.0 / (1024.0 * 1024.0 * 1024.0)) / 10.0 << " GB";
  else if (memSize > 1024.0 * 1024.0)
    str << round(memSize * 10.0 / (1024.0 * 1024.0)) / 10.0 << " MB";
  else if (memSize > 1024.0)
    str << round(memSize * 10.0 / (1024.0)) / 10.0 << " KB";
  else
    str << memSize << " B";
  return str.str();
}