File: wgriddingmsgridder.cpp

package info (click to toggle)
wsclean 3.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,968 kB
  • sloc: cpp: 85,742; python: 3,526; sh: 245; makefile: 21
file content (607 lines) | stat: -rw-r--r-- 25,209 bytes parent folder | download
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
#include "wgriddingmsgridder.h"

#include "wgridder.h"

#include "../gridding/msgriddermanager.h"
#include "../msproviders/msreaders/msreader.h"

#include "../msproviders/msprovider.h"

#include "../system/buffered_lane.h"

#include "../structures/imageweights.h"

#include <aocommon/image.h>
#include <aocommon/logger.h>

#include <schaapcommon/math/resampler.h>

#include <casacore/ms/MeasurementSets/MeasurementSet.h>

using aocommon::Image;
using aocommon::Logger;

namespace wsclean {
namespace {
constexpr size_t kUvwSize = sizeof(double) * 3;
}  // namespace

WGriddingMSGridder::WGriddingMSGridder(
    const Settings& settings, const Resources& resources,
    MsProviderCollection& ms_provider_collection, bool use_tuned_wgridder)
    : MsGridder(settings, ms_provider_collection),
      resources_(resources),
      accuracy_(GetSettings().gridder_accuracy),
      use_tuned_wgridder_(use_tuned_wgridder) {
  // It may happen that several schaapcommon::fft::Resamplers are created
  // concurrently, so we must make sure that the FFTW planner can deal with
  // this.
  fftwf_make_planner_thread_safe();
}

WGriddingMSGridder::~WGriddingMSGridder() = default;

std::unique_ptr<WGridderBase> WGriddingMSGridder::MakeGridder(
    size_t width, size_t height) const {
  if (accuracy_ <= 1.01e-5) {
    return std::make_unique<WGridder<double>>(
        ActualInversionWidth(), ActualInversionHeight(), width, height,
        ActualPixelSizeX(), ActualPixelSizeY(), LShift(), MShift(),
        resources_.NCpus(), accuracy_, 0, use_tuned_wgridder_);
  } else {
    return std::make_unique<WGridder<float>>(
        ActualInversionWidth(), ActualInversionHeight(), width, height,
        ActualPixelSizeX(), ActualPixelSizeY(), LShift(), MShift(),
        resources_.NCpus(), accuracy_, 0, use_tuned_wgridder_);
  }
}

size_t WGriddingMSGridder::CalculateConstantMemory() const {
  size_t constant_mem = gridder_->ConstantMemoryUsage();
  constant_mem += GetVisibilityModifier().GetCacheParmResponseSize();
  return constant_mem;
}

size_t WGriddingMSGridder::CalculateMaxRowsInMemory(
    int64_t available_memory, size_t constant_memory,
    double additional_per_row_consumption, size_t per_row_uvw_consumption,
    size_t channel_count, size_t num_polarizations_stored) const {
  if (static_cast<int64_t>(constant_memory) >= available_memory) {
    // Assume that half the memory is necessary for the constant parts (like
    // image grid), and the other half remains available for the dynamic buffers
    constant_memory = available_memory / 2;
    Logger::Warn << "Not enough memory available for doing the gridding:\n"
                    "swapping might occur!\n";
  }

  const size_t per_visibility_ducc_overhead =
      gridder_->PerVisibilityMemoryUsage();
  // Internal DUCC size and size we might be storing in memory are different as
  // we collapse the visibilities before passing them in to DUCC
  const size_t per_row_visibility_memory =
      (per_visibility_ducc_overhead * channel_count) +
      (sizeof(std::complex<float>) * channel_count * num_polarizations_stored);
  // Keep computed number floating point to maintain precision.
  // This is because additional_per_row_consumption can be fractional in the
  // case of -shared-facet-writes; where gridders/facets share some per row
  // memory overheads with each other. In this instance we allocate a fractional
  // portion of this shared memory to each gridder to help compute maximum rows
  // more accurately.
  const double memory_per_row =
      additional_per_row_consumption  // external overheads
      + per_row_visibility_memory     // visibilities
      + per_row_uvw_consumption;      // uvw
  const uint64_t memory_for_buffers = available_memory - constant_memory;
  const size_t max_n_rows =
      std::max(uint64_t(memory_for_buffers / memory_per_row), uint64_t(100));
  if (max_n_rows < 1000) {
    Logger::Warn << "Less than 1000 data rows fit in memory: this probably "
                    "means performance is going to be very poor!\n";
  }

  return max_n_rows;
}

size_t WGriddingMSGridder::CalculateMaxVisibilitiesInMemory(
    int64_t available_memory, size_t constant_memory,
    double additional_per_visibility_consumption,
    size_t per_visibility_uvw_consumption,
    size_t num_polarizations_stored) const {
  // Function follows mostly the logic of CalculateMaxRowsInMemory().
  if (static_cast<int64_t>(constant_memory) >= available_memory) {
    constant_memory = available_memory / 2;
    Logger::Warn << "Not enough memory available for doing the gridding:\n"
                    "swapping might occur!\n";
  }

  const size_t per_visibility_ducc_overhead =
      gridder_->PerVisibilityMemoryUsage();
  const size_t per_visibility_memory =
      per_visibility_ducc_overhead +
      (sizeof(std::complex<float>) * num_polarizations_stored);
  const double memory_per_visibility =
      additional_per_visibility_consumption  // external overheads
      + per_visibility_memory                // visibilities
      + per_visibility_uvw_consumption;      // uvw
  const uint64_t memory_for_buffers = available_memory - constant_memory;
  // This value is a bit arbitrary, but gridding less than 10000 vis at a time
  // will be prohabitively slow...
  constexpr uint64_t kMinVisibilities = 10000;
  const size_t max_n_visibilities = std::max(
      uint64_t(memory_for_buffers / memory_per_visibility), kMinVisibilities);

  return max_n_visibilities;
}

void WGriddingMSGridder::GridSharedMeasurementSetChunk(
    bool apply_corrections, size_t n_polarizations, size_t n_rows,
    const double* uvws, const double* frequencies,
    const aocommon::BandData& selected_band, size_t data_desc_id,
    const std::pair<size_t, size_t>* antennas,
    const std::complex<float>* visibilities, const size_t* time_offsets,
    size_t n_antennas, const std::vector<std::complex<float>>& parm_response,
    const BeamResponseCacheChunk& beam_response) {
  // If there are no corrections to apply then we can bypass needing a callback
  // and just use the shared buffer directly
  if (!apply_corrections) {
    gridder_->AddInversionData(n_rows, selected_band.ChannelCount(), uvws,
                               frequencies, visibilities);
  } else {
    VisibilityCallbackData data(selected_band.ChannelCount(), selected_band,
                                data_desc_id, antennas, visibilities, uvws,
                                time_offsets, this, n_antennas,
                                parm_response.data(), beam_response);
    gridder_->AddInversionDataWithCorrectionCallback(
        GetGainMode(), n_polarizations, n_rows, uvws, frequencies, data);
  }
}

size_t WGriddingMSGridder::GridRegularMeasurementSet(
    const MsProviderCollection::MsData& ms_data) {
  // Regular data should always have one band per ms provider...
  const aocommon::MultiBandData& selected_bands(
      ms_data.ms_provider->SelectedBands());
  assert(selected_bands.BandCount() == 1);
  const aocommon::BandData& selected_band = *selected_bands.begin();
  const size_t n_vis_polarizations = ms_data.ms_provider->NPolarizations();

  const size_t data_size = selected_band.ChannelCount() * n_vis_polarizations;
  aocommon::UVector<std::complex<float>> model_buffer(data_size);
  aocommon::UVector<float> weight_buffer(data_size);
  aocommon::UVector<bool> selection_buffer(selected_band.ChannelCount(), true);

  aocommon::UVector<double> frequencies(selected_band.ChannelCount());
  for (size_t i = 0; i != frequencies.size(); ++i)
    frequencies[i] = selected_band.ChannelFrequency(i);

  size_t max_rows_per_chunk =
      CalculateMaxRowsInMemory(resources_.Memory(), CalculateConstantMemory(),
                               0, kUvwSize, selected_band.ChannelCount(), 1);

  aocommon::UVector<std::complex<float>> visibility_buffer(
      max_rows_per_chunk * selected_band.ChannelCount());
  aocommon::UVector<double> uvw_buffer(max_rows_per_chunk * 3);

  std::unique_ptr<MSReader> ms_reader = ms_data.ms_provider->MakeReader();
  aocommon::UVector<std::complex<float>> row_visibilities(data_size);
  InversionRow row_data;
  row_data.data = row_visibilities.data();

  const size_t n_parms = NumValuesPerSolution();

  // Iterate over chunks until all data has been gridded
  size_t n_total_rows_read = 0;
  Logger::Debug << "Max " << max_rows_per_chunk << " rows fit in memory.\n";
  while (ms_reader->CurrentRowAvailable()) {
    Logger::Info << "Loading data in memory...\n";

    size_t n_chunk_rows_read = 0;

    // Read / fill the chunk
    while (ms_reader->CurrentRowAvailable() &&
           n_chunk_rows_read < max_rows_per_chunk) {
      MSProvider::MetaData metadata;
      ms_reader->ReadMeta(metadata);
      row_data.uvw[0] = metadata.u_in_m;
      row_data.uvw[1] = metadata.v_in_m;
      row_data.uvw[2] = metadata.w_in_m;

      if (n_parms == 2) {
        GetCollapsedVisibilities<2>(*ms_reader, ms_data.antenna_names.size(),
                                    row_data, weight_buffer.data(),
                                    model_buffer.data(),
                                    selection_buffer.data(), metadata);
      } else {
        GetCollapsedVisibilities<4>(*ms_reader, ms_data.antenna_names.size(),
                                    row_data, weight_buffer.data(),
                                    model_buffer.data(),
                                    selection_buffer.data(), metadata);
      }

      std::copy_n(
          row_data.data, selected_band.ChannelCount(),
          &visibility_buffer[n_chunk_rows_read * selected_band.ChannelCount()]);
      std::copy_n(row_data.uvw, 3, &uvw_buffer[n_chunk_rows_read * 3]);

      ++n_chunk_rows_read;
      ms_reader->NextInputRow();
    }

    Logger::Info << "Gridding " << n_chunk_rows_read << " rows...\n";
    gridder_->AddInversionData(n_chunk_rows_read, selected_band.ChannelCount(),
                               uvw_buffer.data(), frequencies.data(),
                               visibility_buffer.data());

    n_total_rows_read += n_chunk_rows_read;
  }  // end of chunk
  return n_total_rows_read;
}

size_t WGriddingMSGridder::GridBdaMeasurementSet(
    const MsProviderCollection::MsData& ms_data) {
  const aocommon::MultiBandData& selected_bands(
      ms_data.ms_provider->SelectedBands());
  const size_t n_vis_polarizations = ms_data.ms_provider->NPolarizations();

  const size_t max_data_size =
      ms_data.ms_provider->NMaxChannels() * n_vis_polarizations;
  aocommon::UVector<std::complex<float>> model_buffer(max_data_size);
  aocommon::UVector<float> weight_buffer(max_data_size);
  aocommon::UVector<bool> selection_buffer(max_data_size, true);

  const size_t max_vis_per_chunk = CalculateMaxVisibilitiesInMemory(
      resources_.Memory(), CalculateConstantMemory(), 0, kUvwSize, 1);

  aocommon::UVector<std::complex<float>> visibility_buffer;
  visibility_buffer.reserve(max_vis_per_chunk);
  aocommon::UVector<double> uvw_buffer;
  uvw_buffer.reserve(3 * max_vis_per_chunk);

  std::unique_ptr<MSReader> ms_reader = ms_data.ms_provider->MakeReader();
  aocommon::UVector<std::complex<float>> row_visibilities(max_data_size);
  InversionRow row_data;
  row_data.data = row_visibilities.data();

  const size_t n_parms = NumValuesPerSolution();

  // Iterate over chunks until all data has been gridded
  size_t n_total_rows_read = 0;
  while (ms_reader->CurrentRowAvailable()) {
    Logger::Info << "Loading data in memory...\n";

    size_t n_chunk_rows_read = 0;
    visibility_buffer.clear();
    uvw_buffer.clear();

    // Read / fill the chunk
    while (ms_reader->CurrentRowAvailable()) {
      MSProvider::MetaData metadata;
      ms_reader->ReadMeta(metadata);
      row_data.uvw[0] = metadata.u_in_m;
      row_data.uvw[1] = metadata.v_in_m;
      row_data.uvw[2] = metadata.w_in_m;
      const aocommon::BandData& band = selected_bands[metadata.data_desc_id];
      if (visibility_buffer.size() + band.ChannelCount() >= max_vis_per_chunk)
        break;

      if (n_parms == 2) {
        GetCollapsedVisibilities<2>(*ms_reader, ms_data.antenna_names.size(),
                                    row_data, weight_buffer.data(),
                                    model_buffer.data(),
                                    selection_buffer.data(), metadata);
      } else {
        GetCollapsedVisibilities<4>(*ms_reader, ms_data.antenna_names.size(),
                                    row_data, weight_buffer.data(),
                                    model_buffer.data(),
                                    selection_buffer.data(), metadata);
      }

      for (size_t channel = 0; channel != band.ChannelCount(); ++channel) {
        // Because the gridder doesn't have an option to have different nr of
        // channels per row, the data is "flattened" into a single array and the
        // uvws are scaled so that they become frequency independent.
        visibility_buffer.emplace_back(row_data.data[channel]);
        for (size_t i = 0; i != 3; ++i)
          uvw_buffer.emplace_back(row_data.uvw[i] *
                                  band.ChannelFrequency(channel));
      }

      ++n_chunk_rows_read;
      ms_reader->NextInputRow();
    }

    Logger::Info << "Gridding " << n_chunk_rows_read
                 << " (irregular) rows...\n";

    // The Uvws have been scaled by the frequency already, hence use 1 here.
    constexpr double kDummyFrequency = 1.0;
    // Data has been flattened, so for the gridder there's only one channel:
    constexpr size_t kNGridderChannels = 1;
    gridder_->AddInversionData(visibility_buffer.size(), kNGridderChannels,
                               uvw_buffer.data(), &kDummyFrequency,
                               visibility_buffer.data());

    n_total_rows_read += n_chunk_rows_read;
  }  // end of chunk
  return n_total_rows_read;
}

void WGriddingMSGridder::PredictChunk(size_t n_rows, size_t n_channels,
                                      const double* frequencies,
                                      const double* uvws,
                                      std::complex<float>* visibilities) const {
  Logger::Info << "Predicting " + std::to_string(n_rows) + " rows...\n";
  gridder_->PredictVisibilities(n_rows, n_channels, uvws, frequencies,
                                visibilities);
}

size_t WGriddingMSGridder::PredictRegularMeasurementSet(
    const MsProviderCollection::MsData& ms_data) {
  const aocommon::MultiBandData& selected_bands(
      ms_data.ms_provider->SelectedBands());
  // Regular data should always have one band...
  assert(selected_bands.BandCount() == 1);
  const aocommon::BandData& selected_band = *selected_bands.begin();

  size_t n_total_rows_written = 0;

  aocommon::UVector<double> frequencies(selected_band.ChannelCount());
  for (size_t i = 0; i != frequencies.size(); ++i)
    frequencies[i] = selected_band.ChannelFrequency(i);

  const size_t max_rows_per_chunk =
      CalculateMaxRowsInMemory(resources_.Memory(), CalculateConstantMemory(),
                               0, kUvwSize, selected_band.ChannelCount(), 1);

  aocommon::UVector<double> uvw_buffer(max_rows_per_chunk * 3);
  // Iterate over chunks until all data has been gridded
  ms_data.ms_provider->ResetWritePosition();
  std::unique_ptr<MSReader> ms_reader = ms_data.ms_provider->MakeReader();
  while (ms_reader->CurrentRowAvailable()) {
    size_t n_chunk_rows_read = 0;

    // Read / fill the chunk
    Logger::Info << "Loading metadata...\n";
    // Read from metadata buffer
    std::vector<MSProvider::MetaData> metadata_buffer;
    while (ms_reader->CurrentRowAvailable() &&
           n_chunk_rows_read < max_rows_per_chunk) {
      MSProvider::MetaData metadata;
      ReadPredictMetaData(metadata);
      uvw_buffer[n_chunk_rows_read * 3] = metadata.u_in_m;
      uvw_buffer[n_chunk_rows_read * 3 + 1] = metadata.v_in_m;
      uvw_buffer[n_chunk_rows_read * 3 + 2] = metadata.w_in_m;
      metadata_buffer.emplace_back(std::move(metadata));
      n_chunk_rows_read++;

      ms_reader->NextInputRow();
    }

    Logger::Info << "Predicting " << n_chunk_rows_read << " rows...\n";
    aocommon::UVector<std::complex<float>> visibility_buffer(
        max_rows_per_chunk * selected_band.ChannelCount());
    gridder_->PredictVisibilities(
        n_chunk_rows_read, selected_band.ChannelCount(), uvw_buffer.data(),
        frequencies.data(), visibility_buffer.data());

    Logger::Info << "Writing...\n";
    for (size_t row = 0; row != n_chunk_rows_read; ++row) {
      WriteCollapsedVisibilities(
          *ms_data.ms_provider, ms_data.antenna_names.size(),
          metadata_buffer[row].data_desc_id,
          &visibility_buffer[row * selected_band.ChannelCount()],
          &uvw_buffer[row * 3], metadata_buffer[row].field_id,
          metadata_buffer[row].antenna1, metadata_buffer[row].antenna2,
          metadata_buffer[row].time);
    }
    n_total_rows_written += n_chunk_rows_read;
  }  // end of chunk
  return n_total_rows_written;
}

size_t WGriddingMSGridder::PredictBdaMeasurementSet(
    const MsProviderCollection::MsData& ms_data) {
  const aocommon::MultiBandData& selected_bands(
      ms_data.ms_provider->SelectedBands());

  size_t n_total_rows_written = 0;

  const size_t max_vis_per_chunk = CalculateMaxVisibilitiesInMemory(
      resources_.Memory(), CalculateConstantMemory(), 0, kUvwSize, 1);

  aocommon::UVector<double> uvw_buffer;
  uvw_buffer.reserve(3 * max_vis_per_chunk);

  // Iterate over chunks until all data has been gridded
  ms_data.ms_provider->ResetWritePosition();
  std::unique_ptr<MSReader> ms_reader = ms_data.ms_provider->MakeReader();
  std::vector<MSProvider::MetaData> metadata_buffer;
  while (ms_reader->CurrentRowAvailable()) {
    size_t n_chunk_rows_read = 0;

    // Read / fill the chunk
    Logger::Info << "Loading metadata...\n";
    metadata_buffer.clear();
    uvw_buffer.clear();
    size_t visibility_count = 0;
    while (ms_reader->CurrentRowAvailable()) {
      MSProvider::MetaData metadata;
      ReadPredictMetaData(metadata);
      const aocommon::BandData& band = selected_bands[metadata.data_desc_id];
      if (visibility_count + band.ChannelCount() >= max_vis_per_chunk) break;

      visibility_count += band.ChannelCount();
      for (size_t channel = 0; channel != band.ChannelCount(); ++channel) {
        const double frequency = band.ChannelFrequency(channel);
        uvw_buffer.emplace_back(metadata.u_in_m * frequency);
        uvw_buffer.emplace_back(metadata.v_in_m * frequency);
        uvw_buffer.emplace_back(metadata.w_in_m * frequency);
      }
      metadata_buffer.emplace_back(std::move(metadata));
      n_chunk_rows_read++;

      ms_reader->NextInputRow();
    }

    Logger::Info << "Predicting " << n_chunk_rows_read
                 << " (irregular) rows...\n";
    aocommon::UVector<std::complex<float>> visibility_buffer(visibility_count);
    // The Uvws have been scaled by the frequency already, hence use 1 here.
    constexpr double kDummyFrequency = 1.0;
    // Data has been flattened, so for the gridder there's only one channel:
    constexpr size_t kNGridderChannels = 1;
    gridder_->PredictVisibilities(visibility_count, kNGridderChannels,
                                  uvw_buffer.data(), &kDummyFrequency,
                                  visibility_buffer.data());

    Logger::Info << "Writing...\n";
    std::complex<float>* visibility_ptr = visibility_buffer.data();
    for (size_t row = 0; row != n_chunk_rows_read; ++row) {
      // The uvw_buffer has scaled uvws, so reload them from the metadata
      const double uvw[3] = {metadata_buffer[row].u_in_m,
                             metadata_buffer[row].v_in_m,
                             metadata_buffer[row].w_in_m};
      WriteCollapsedVisibilities(
          *ms_data.ms_provider, ms_data.antenna_names.size(),
          metadata_buffer[row].data_desc_id, visibility_ptr, uvw,
          metadata_buffer[row].field_id, metadata_buffer[row].antenna1,
          metadata_buffer[row].antenna2, metadata_buffer[row].time);
      const aocommon::BandData& band =
          selected_bands[metadata_buffer[row].data_desc_id];
      visibility_ptr += band.ChannelCount();
    }
    n_total_rows_written += n_chunk_rows_read;
  }  // end of chunk
  return n_total_rows_written;
}

size_t WGriddingMSGridder::GridMeasurementSet(
    const MsProviderCollection::MsData& ms_data) {
  // If the data isn't regular, the data is flattened before calling the
  // gridder. This costs more memory and may potentially be a bit slower or
  // cause more gridder calls, so flattening is done only when it is necessary.
  if (ms_data.ms_provider->IsRegular()) {
    return GridRegularMeasurementSet(ms_data);
  } else {
    return GridBdaMeasurementSet(ms_data);
  }
}

size_t WGriddingMSGridder::PredictMeasurementSet(
    const MsProviderCollection::MsData& ms_data) {
  ms_data.ms_provider->ReopenRW();

  // See comment in GridMeasurementSet().
  if (ms_data.ms_provider->IsRegular()) {
    return PredictRegularMeasurementSet(ms_data);
  } else {
    return PredictBdaMeasurementSet(ms_data);
  }
}

void WGriddingMSGridder::GetActualTrimmedSize(size_t& trimmedWidth,
                                              size_t& trimmedHeight) const {
  trimmedWidth = std::ceil(ActualInversionWidth() / ImagePadding());
  trimmedHeight = std::ceil(ActualInversionHeight() / ImagePadding());

  // In facet-based imaging, the alignment is 4, see wsclean.cpp. Also for
  // monolithic imaging - in which just an even number would suffice -
  // the trimmedWidth and trimmedHeight are defined to be divisable by 4.
  const size_t alignment = 4;
  if (trimmedWidth % alignment != 0) {
    trimmedWidth += alignment - (trimmedWidth % alignment);
  }
  if (trimmedHeight % alignment != 0) {
    trimmedHeight += alignment - (trimmedHeight % alignment);
  }
  trimmedWidth = std::min(trimmedWidth, ActualInversionWidth());
  trimmedHeight = std::min(trimmedHeight, ActualInversionHeight());
}

void WGriddingMSGridder::StartInversion() {
  size_t trimmed_width;
  size_t trimmed_height;
  GetActualTrimmedSize(trimmed_width, trimmed_height);

  gridder_ = MakeGridder(trimmed_width, trimmed_height);
  gridder_->InitializeInversion();

  ResetVisibilityCounters();
}

void WGriddingMSGridder::FinishInversion() {
  gridder_->FinalizeImage(1.0 / ImageWeight());

  std::string log_message =
      "Gridded visibility count: " + std::to_string(GriddedVisibilityCount());
  if (Weighting().IsNatural()) {
    log_message += ", effective count after weighting: " +
                   std::to_string(EffectiveGriddedVisibilityCount());
  }
  Logger::Info << log_message + '\n';

  image_ = Image(ActualInversionWidth(), ActualInversionHeight());
  {
    std::vector<float> image_float = gridder_->RealImage();
    std::copy(image_float.begin(), image_float.end(), image_.begin());
  }

  if (ImageWidth() != ActualInversionWidth() ||
      ImageHeight() != ActualInversionHeight()) {
    // Interpolate the image
    // The input is of size ActualInversionWidth() x ActualInversionHeight()
    schaapcommon::math::Resampler resampler(
        ActualInversionWidth(), ActualInversionHeight(), ImageWidth(),
        ImageHeight(), resources_.NCpus());

    Image resized(ImageWidth(), ImageHeight());
    resampler.Resample(image_.Data(), resized.Data());
    image_ = std::move(resized);
  }

  if (TrimWidth() != ImageWidth() || TrimHeight() != ImageHeight()) {
    Logger::Debug << "Trimming " + std::to_string(ImageWidth()) + " x " +
                         std::to_string(ImageHeight()) + " -> " +
                         std::to_string(TrimWidth()) + " x " +
                         std::to_string(TrimHeight()) + "\n";

    image_ = image_.Trim(TrimWidth(), TrimHeight());
  }
}

void WGriddingMSGridder::StartPredict(std::vector<Image>&& images) {
  size_t trimmed_width;
  size_t trimmed_height;
  GetActualTrimmedSize(trimmed_width, trimmed_height);

  gridder_ = MakeGridder(trimmed_width, trimmed_height);

  if (TrimWidth() != ImageWidth() || TrimHeight() != ImageHeight()) {
    Image untrimmed_image(ImageWidth(), ImageHeight());
    Logger::Debug << "Untrimming " + std::to_string(TrimWidth()) + " x " +
                         std::to_string(TrimHeight()) + " -> " +
                         std::to_string(ImageWidth()) + " x " +
                         std::to_string(ImageHeight()) + "\n";
    Image::Untrim(untrimmed_image.Data(), ImageWidth(), ImageHeight(),
                  images[0].Data(), TrimWidth(), TrimHeight());
    images[0] = std::move(untrimmed_image);
  }

  if (ImageWidth() != ActualInversionWidth() ||
      ImageHeight() != ActualInversionHeight()) {
    Image resampled_image(ActualInversionWidth(), ActualInversionHeight());
    schaapcommon::math::Resampler resampler(
        ImageWidth(), ImageHeight(), ActualInversionWidth(),
        ActualInversionHeight(), resources_.NCpus());

    resampler.Resample(images[0].Data(), resampled_image.Data());
    images[0] = std::move(resampled_image);
  }

  gridder_->InitializePrediction(images[0].Data());
  images[0].Reset();
}

void WGriddingMSGridder::FinishPredict() {}

}  // namespace wsclean