gridder_cxx.h 41.5 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
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
#ifndef GRIDDER_CXX_H
#define GRIDDER_CXX_H

/*
 *  This file is part of nifty_gridder.
 *
 *  nifty_gridder is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  nifty_gridder is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with nifty_gridder; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

/* Copyright (C) 2019 Max-Planck-Society
   Author: Martin Reinecke */

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <vector>

#include "pocketfft_hdronly.h"
#include <array>
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
33
#define NOINLINE __attribute__((noinline))
Martin Reinecke's avatar
Martin Reinecke committed
34

Martin Reinecke's avatar
Martin Reinecke committed
35
36
namespace gridder {

37
38
namespace detail {

Martin Reinecke's avatar
Martin Reinecke committed
39
40
41
using namespace std;

template<typename T, size_t ndim> class mav
Martin Reinecke's avatar
Martin Reinecke committed
42
43
44
45
46
  {
  static_assert((ndim>0) && (ndim<3), "only supports 1D and 2D arrays");

  private:
    T *d;
Martin Reinecke's avatar
Martin Reinecke committed
47
48
    array<size_t, ndim> shp;
    array<ptrdiff_t, ndim> str;
Martin Reinecke's avatar
Martin Reinecke committed
49
50

  public:
Martin Reinecke's avatar
Martin Reinecke committed
51
52
53
54
    mav(T *d_, const array<size_t,ndim> &shp_,
        const array<ptrdiff_t,ndim> &str_)
      : d(d_), shp(shp_), str(str_) {}
    mav(T *d_, const array<size_t,ndim> &shp_)
Martin Reinecke's avatar
Martin Reinecke committed
55
56
57
58
59
60
      : d(d_), shp(shp_)
      {
      str[ndim-1]=1;
      for (size_t d=2; d<=ndim; ++d)
        str[ndim-d] = str[ndim-d+1]*shp[ndim-d+1];
      }
Martin Reinecke's avatar
Martin Reinecke committed
61
62
    operator mav<const T, ndim>() const
      { return mav<const T, ndim>(d,shp,str); }
Martin Reinecke's avatar
Martin Reinecke committed
63
64
65
66
    T &operator[](size_t i)
      { return operator()(i); }
    const T &operator[](size_t i) const
      { return operator()(i); }
67
    T &operator()(size_t i) const
Martin Reinecke's avatar
Martin Reinecke committed
68
69
      {
      static_assert(ndim==1, "ndim must be 1");
Martin Reinecke's avatar
Martin Reinecke committed
70
      return d[str[0]*i];
Martin Reinecke's avatar
Martin Reinecke committed
71
      }
72
    T &operator()(size_t i, size_t j) const
Martin Reinecke's avatar
Martin Reinecke committed
73
74
      {
      static_assert(ndim==2, "ndim must be 2");
Martin Reinecke's avatar
Martin Reinecke committed
75
      return d[str[0]*i + str[1]*j];
Martin Reinecke's avatar
Martin Reinecke committed
76
77
      }
    size_t shape(size_t i) const { return shp[i]; }
Martin Reinecke's avatar
Martin Reinecke committed
78
    const array<size_t,ndim> &shape() const { return shp; }
Martin Reinecke's avatar
Martin Reinecke committed
79
80
81
82
83
84
    size_t size() const
      {
      size_t res=1;
      for (auto v: shp) res*=v;
      return res;
      }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
85
    ptrdiff_t stride(size_t i) const { return str[i]; }
Martin Reinecke's avatar
Martin Reinecke committed
86
    T *data()
Martin Reinecke's avatar
Martin Reinecke committed
87
      { return d; }
Martin Reinecke's avatar
Martin Reinecke committed
88
    const T *data() const
Martin Reinecke's avatar
Martin Reinecke committed
89
      { return d; }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
90
91
92
93
94
95
96
97
98
99
    bool contiguous() const
      {
      ptrdiff_t stride=1;
      for (size_t i=0; i<ndim; ++i)
        {
        if (str[ndim-1-i]!=stride) return false;
        stride *= shp[ndim-1-i];
        }
      return true;
      }
Martin Reinecke's avatar
Martin Reinecke committed
100
101
  };

Martin Reinecke's avatar
updates    
Martin Reinecke committed
102
103
template<typename T, size_t ndim> using const_mav = mav<const T, ndim>;

Martin Reinecke's avatar
Martin Reinecke committed
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
template<typename T, size_t ndim> class tmpStorage
  {
  private:
    vector<T> d;
    mav<T,ndim> mav_;

    static size_t prod(const array<size_t,ndim> &shp)
      {
      size_t res=1;
      for (auto v: shp) res*=v;
      return res;
      }

  public:
    tmpStorage(const array<size_t,ndim> &shp)
      : d(prod(shp)), mav_(d.data(), shp) {}
    mav<T,ndim> &getMav() { return mav_; };
    void fill(const T & val)
      { std::fill(d.begin(), d.end(), val); }
  };
Martin Reinecke's avatar
Martin Reinecke committed
124
125
126
127
128
129
130
//
// basic utilities
//

void myassert(bool cond, const char *msg)
  {
  if (cond) return;
Martin Reinecke's avatar
Martin Reinecke committed
131
  throw runtime_error(msg);
Martin Reinecke's avatar
Martin Reinecke committed
132
133
134
  }

template<size_t ndim> void checkShape
Martin Reinecke's avatar
Martin Reinecke committed
135
  (const array<size_t, ndim> &shp1, const array<size_t, ndim> &shp2)
Martin Reinecke's avatar
Martin Reinecke committed
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
  {
  for (size_t i=0; i<ndim; ++i)
    myassert(shp1[i]==shp2[i], "shape mismatch");
  }

/*! Returns the remainder of the division \a v1/v2.
    The result is non-negative.
    \a v1 can be positive or negative; \a v2 must be positive. */
template<typename T> inline T fmodulo (T v1, T v2)
  {
  if (v1>=0)
    return (v1<v2) ? v1 : fmod(v1,v2);
  T tmp=fmod(v1,v2)+v2;
  return (tmp==v2) ? T(0) : tmp;
  }

static size_t nthreads = 1;

void set_nthreads(size_t nthreads_)
  {
  myassert(nthreads_>=1, "nthreads must be >= 1");
  nthreads = nthreads_;
  }

size_t get_nthreads()
  { return nthreads; }

//
// Utilities for Gauss-Legendre quadrature
//

static inline double one_minus_x2 (double x)
  { return (fabs(x)>0.1) ? (1.+x)*(1.-x) : 1.-x*x; }

Martin Reinecke's avatar
Martin Reinecke committed
170
void legendre_prep(int n, vector<double> &x, vector<double> &w)
Martin Reinecke's avatar
Martin Reinecke committed
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
  {
  constexpr double pi = 3.141592653589793238462643383279502884197;
  constexpr double eps = 3e-14;
  int m = (n+1)>>1;
  x.resize(m);
  w.resize(m);

  double t0 = 1 - (1-1./n) / (8.*n*n);
  double t1 = 1./(4.*n+2.);

#pragma omp parallel num_threads(nthreads)
{
  int i;
#pragma omp for schedule(dynamic,100)
  for (i=1; i<=m; ++i)
    {
    double x0 = cos(pi * ((i<<2)-1) * t1) * t0;

    int dobreak=0;
    int j=0;
    double dpdx;
    while(1)
      {
      double P_1 = 1.0;
      double P0 = x0;
      double dx, x1;

      for (int k=2; k<=n; k++)
        {
        double P_2 = P_1;
        P_1 = P0;
//        P0 = ((2*k-1)*x0*P_1-(k-1)*P_2)/k;
        P0 = x0*P_1 + (k-1.)/k * (x0*P_1-P_2);
        }

      dpdx = (P_1 - x0*P0) * n / one_minus_x2(x0);

      /* Newton step */
      x1 = x0 - P0/dpdx;
      dx = x0-x1;
      x0 = x1;
      if (dobreak) break;

      if (abs(dx)<=eps) dobreak=1;
      myassert(++j<100, "convergence problem");
      }

    x[m-i] = x0;
    w[m-i] = 2. / (one_minus_x2(x0) * dpdx * dpdx);
    }
} // end of parallel region
  }

//
// Start of real gridder functionality
//

size_t get_supp(double epsilon)
  {
Martin Reinecke's avatar
Martin Reinecke committed
230
  static const vector<double> maxmaperr { 1e8, 0.32, 0.021, 6.2e-4,
Martin Reinecke's avatar
Martin Reinecke committed
231
232
233
234
235
236
237
    1.08e-5, 1.25e-7, 8.25e-10, 5.70e-12, 1.22e-13, 2.48e-15, 4.82e-17,
    6.74e-19, 5.41e-21, 4.41e-23, 7.88e-25, 3.9e-26 };

  double epssq = epsilon*epsilon;

  for (size_t i=1; i<maxmaperr.size(); ++i)
    if (epssq>maxmaperr[i]) return i;
Martin Reinecke's avatar
Martin Reinecke committed
238
  throw runtime_error("requested epsilon too small - minimum is 2e-13");
Martin Reinecke's avatar
Martin Reinecke committed
239
240
  }

Martin Reinecke's avatar
Martin Reinecke committed
241
242
243
244
245
struct RowChan
  {
  size_t row, chan;
  };

Martin Reinecke's avatar
Martin Reinecke committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
template<typename T> class EC_Kernel
  {
  protected:
    size_t supp;
    T beta, emb_;

  public:
    EC_Kernel(size_t supp_)
      : supp(supp_), beta(2.3*supp_), emb_(exp(-beta)) {}
    T operator()(T v) const { return exp(beta*(sqrt(T(1)-v*v)-T(1))); }
    T val_no_emb(T v) const { return exp(beta*sqrt(T(1)-v*v)); }
    T emb() const { return emb_; }
  };

template<typename T> class EC_Kernel_with_correction: public EC_Kernel<T>
  {
  protected:
    static constexpr T pi = T(3.141592653589793238462643383279502884197L);
    int p;
265
    vector<double> x, wgt, psi;
Martin Reinecke's avatar
Martin Reinecke committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
    using EC_Kernel<T>::supp;

  public:
    using EC_Kernel<T>::operator();
    EC_Kernel_with_correction(size_t supp_)
      : EC_Kernel<T>(supp_), p(int(1.5*supp_+2))
      {
      legendre_prep(2*p,x,wgt);
      psi=x;
      for (auto &v:psi)
        v=operator()(v);
      }
    /* Compute correction factors for the ES gridding kernel
       This implementation follows eqs. (3.8) to (3.10) of Barnett et al. 2018 */
    T corfac(T v) const
      {
      T tmp=0;
      for (int i=0; i<p; ++i)
        tmp += wgt[i]*psi[i]*cos(pi*supp*v*x[i]);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
285
      return T(1./(supp*tmp));
Martin Reinecke's avatar
Martin Reinecke committed
286
287
288
289
      }
  };
/* Compute correction factors for the ES gridding kernel
   This implementation follows eqs. (3.8) to (3.10) of Barnett et al. 2018 */
Martin Reinecke's avatar
Martin Reinecke committed
290
vector<double> correction_factors (size_t n, size_t nval, size_t supp)
Martin Reinecke's avatar
Martin Reinecke committed
291
292
  {
  EC_Kernel_with_correction<double> kernel(supp);
Martin Reinecke's avatar
Martin Reinecke committed
293
  vector<double> res(nval);
Martin Reinecke's avatar
Martin Reinecke committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
  double xn = 1./n;
#pragma omp parallel for schedule(static) num_threads(nthreads)
  for (size_t k=0; k<nval; ++k)
    res[k] = kernel.corfac(k*xn);
  return res;
  }

template<typename T> struct UVW
  {
  T u, v, w;
  UVW () {}
  UVW (T u_, T v_, T w_) : u(u_), v(v_), w(w_) {}
  UVW operator* (T fct) const
    { return UVW(u*fct, v*fct, w*fct); }
  };

template<typename T> class Baselines
  {
  protected:
Martin Reinecke's avatar
Martin Reinecke committed
313
314
    vector<UVW<T>> coord;
    vector<T> f_over_c;
Martin Reinecke's avatar
Martin Reinecke committed
315
316
317
    size_t nrows, nchan;

  public:
Martin Reinecke's avatar
updates    
Martin Reinecke committed
318
    Baselines(const const_mav<T,2> &coord_, const const_mav<T,1> &freq)
Martin Reinecke's avatar
Martin Reinecke committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
      {
      constexpr double speedOfLight = 299792458.;
      myassert(coord_.shape(1)==3, "dimension mismatch");
      nrows = coord_.shape(0);
      nchan = freq.shape(0);
      myassert(nrows*nchan<(size_t(1)<<32), "too many entries in MS");
      f_over_c.resize(nchan);
      for (size_t i=0; i<nchan; ++i)
        f_over_c[i] = freq(i)/speedOfLight;
      coord.resize(nrows);
      for (size_t i=0; i<coord.size(); ++i)
        coord[i] = UVW<T>(coord_(i,0), coord_(i,1), coord_(i,2));
      }

Martin Reinecke's avatar
Martin Reinecke committed
333
    RowChan getRowChan(uint32_t index) const
Martin Reinecke's avatar
Martin Reinecke committed
334
335
336
      {
      size_t irow = index/nchan;
      size_t ichan = index-nchan*irow;
Martin Reinecke's avatar
Martin Reinecke committed
337
      return RowChan{irow, ichan};
Martin Reinecke's avatar
Martin Reinecke committed
338
      }
Martin Reinecke's avatar
Martin Reinecke committed
339
340
341
342
343

    UVW<T> effectiveCoord(const RowChan &rc) const
      { return coord[rc.row]*f_over_c[rc.chan]; }
    UVW<T> effectiveCoord(uint32_t index) const
      { return effectiveCoord(getRowChan(index)); }
Martin Reinecke's avatar
Martin Reinecke committed
344
345
346
    size_t Nrows() const { return nrows; }
    size_t Nchannels() const { return nchan; }

Martin Reinecke's avatar
Martin Reinecke committed
347
    void effectiveUVW(const mav<const uint32_t,1> &idx, mav<T,2> &res) const
Martin Reinecke's avatar
Martin Reinecke committed
348
349
350
351
352
353
354
355
356
357
358
359
360
      {
      size_t nvis = idx.shape(0);
      myassert(res.shape(0)==nvis, "shape mismatch");
      myassert(res.shape(1)==3, "shape mismatch");
      for (size_t i=0; i<nvis; i++)
        {
        auto uvw = effectiveCoord(idx(i));
        res(i,0) = uvw.u;
        res(i,1) = uvw.v;
        res(i,2) = uvw.w;
        }
      }

Martin Reinecke's avatar
Martin Reinecke committed
361
362
    template<typename T2> void ms2vis(const mav<const T2,2> &ms,
      const mav<const uint32_t,1> &idx, mav<T2,1> &vis) const
Martin Reinecke's avatar
Martin Reinecke committed
363
364
365
366
367
368
369
370
      {
      myassert(ms.shape(0)==nrows, "shape mismatch");
      myassert(ms.shape(1)==nchan, "shape mismatch");
      size_t nvis = idx.shape(0);
      myassert(vis.shape(0)==nvis, "shape mismatch");
#pragma omp parallel for num_threads(nthreads)
      for (size_t i=0; i<nvis; ++i)
        {
Martin Reinecke's avatar
Martin Reinecke committed
371
372
        auto rc = getRowChan(idx(i));
        vis[i] = ms(rc.row, rc.chan);
Martin Reinecke's avatar
Martin Reinecke committed
373
374
375
        }
      }

Martin Reinecke's avatar
Martin Reinecke committed
376
377
    template<typename T2> void vis2ms(const mav<const T2,1> &vis,
      const mav<const uint32_t,1> &idx, mav<T2,2> &ms) const
Martin Reinecke's avatar
Martin Reinecke committed
378
379
380
381
382
383
384
385
      {
      size_t nvis = vis.shape(0);
      myassert(idx.shape(0)==nvis, "shape mismatch");
      myassert(ms.shape(0)==nrows, "shape mismatch");
      myassert(ms.shape(1)==nchan, "shape mismatch");
#pragma omp parallel for num_threads(nthreads)
      for (size_t i=0; i<nvis; ++i)
        {
Martin Reinecke's avatar
Martin Reinecke committed
386
387
        auto rc = getRowChan(idx(i));
        ms(rc.row, rc.chan) += vis(i);
Martin Reinecke's avatar
Martin Reinecke committed
388
389
390
391
392
393
394
395
        }
      }
  };

template<typename T> class GridderConfig
  {
  protected:
    size_t nx_dirty, ny_dirty;
396
    T eps, psx, psy;
Martin Reinecke's avatar
Martin Reinecke committed
397
398
    size_t supp, nsafe, nu, nv;
    T beta;
Martin Reinecke's avatar
Martin Reinecke committed
399
    vector<T> cfu, cfv;
Martin Reinecke's avatar
Martin Reinecke committed
400

Martin Reinecke's avatar
Martin Reinecke committed
401
    complex<T> wscreen(double x, double y, double w, bool adjoint) const
Martin Reinecke's avatar
Martin Reinecke committed
402
403
      {
      constexpr double pi = 3.141592653589793238462643383279502884197;
404
405
406
      double tmp = 1-x-y;
      if (tmp<0) return 0.;
      double nm1 = (-x-y)/(sqrt(tmp)+1); // more accurate form of sqrt(1-x-y)
Martin Reinecke's avatar
Martin Reinecke committed
407
408
409
410
411
412
413
414
415
416
417
418
      double n = nm1+1., xn = 1./n;
      double phase = 2*pi*w*nm1;
      if (adjoint) phase *= -1;
      return complex<T>(cos(phase)*xn, sin(phase)*xn);
      }

  public:
    GridderConfig(size_t nxdirty, size_t nydirty, double epsilon,
      double pixsize_x, double pixsize_y)
      : nx_dirty(nxdirty), ny_dirty(nydirty), eps(epsilon),
        psx(pixsize_x), psy(pixsize_y),
        supp(get_supp(epsilon)), nsafe((supp+1)/2),
Martin Reinecke's avatar
Martin Reinecke committed
419
        nu(max(2*nsafe,2*nx_dirty)), nv(max(2*nsafe,2*ny_dirty)),
Martin Reinecke's avatar
Martin Reinecke committed
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
        beta(2.3*supp),
        cfu(nx_dirty), cfv(ny_dirty)
      {
      myassert((nx_dirty&1)==0, "nx_dirty must be even");
      myassert((ny_dirty&1)==0, "ny_dirty must be even");
      myassert(epsilon>0, "epsilon must be positive");
      myassert(pixsize_x>0, "pixsize_x must be positive");
      myassert(pixsize_y>0, "pixsize_y must be positive");

      auto tmp = correction_factors(nu, nx_dirty/2+1, supp);
      cfu[nx_dirty/2]=tmp[0];
      cfu[0]=tmp[nx_dirty/2];
      for (size_t i=1; i<nx_dirty/2; ++i)
        cfu[nx_dirty/2-i] = cfu[nx_dirty/2+i] = tmp[i];
      tmp = correction_factors(nv, ny_dirty/2+1, supp);
      cfv[ny_dirty/2]=tmp[0];
      cfv[0]=tmp[ny_dirty/2];
      for (size_t i=1; i<ny_dirty/2; ++i)
        cfv[ny_dirty/2-i] = cfv[ny_dirty/2+i] = tmp[i];
      }
    size_t Nxdirty() const { return nx_dirty; }
    size_t Nydirty() const { return ny_dirty; }
    double Epsilon() const { return eps; }
    double Pixsize_x() const { return psx; }
    double Pixsize_y() const { return psy; }
    size_t Nu() const { return nu; }
    size_t Nv() const { return nv; }
    size_t Supp() const { return supp; }
    size_t Nsafe() const { return nsafe; }
    T Beta() const { return beta; }

Martin Reinecke's avatar
Martin Reinecke committed
451
    void apply_taper(const mav<const T,2> &img, mav<T,2> &img2, bool divide) const
Martin Reinecke's avatar
Martin Reinecke committed
452
      {
Martin Reinecke's avatar
Martin Reinecke committed
453
454
      checkShape(img.shape(), {nx_dirty, ny_dirty});
      checkShape(img2.shape(), {nx_dirty, ny_dirty});
Martin Reinecke's avatar
Martin Reinecke committed
455
456
457
      if (divide)
        for (size_t i=0; i<nx_dirty; ++i)
          for (size_t j=0; j<ny_dirty; ++j)
Martin Reinecke's avatar
Martin Reinecke committed
458
            img2(i,j) = img(i,j)/(cfu[i]*cfv[j]);
Martin Reinecke's avatar
Martin Reinecke committed
459
460
461
      else
        for (size_t i=0; i<nx_dirty; ++i)
          for (size_t j=0; j<ny_dirty; ++j)
Martin Reinecke's avatar
Martin Reinecke committed
462
            img2(i,j) = img(i,j)*cfu[i]*cfv[j];
Martin Reinecke's avatar
Martin Reinecke committed
463
464
      }

Martin Reinecke's avatar
Martin Reinecke committed
465
    void grid2dirty_c(const mav<const complex<T>,2> &grid, mav<complex<T>,2> &dirty) const
Martin Reinecke's avatar
Martin Reinecke committed
466
      {
Martin Reinecke's avatar
Martin Reinecke committed
467
468
469
      checkShape(grid.shape(), {nu,nv});
      checkShape(dirty.shape(), {nx_dirty,ny_dirty});
      vector<complex<T>> tmpdat(nu*nv);
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
470
471
      auto tmp=mav<complex<T>,2>(tmpdat.data(),{nu,nv},{ptrdiff_t(nv),ptrdiff_t(1)});
      constexpr auto sc = ptrdiff_t(sizeof(complex<T>));
Martin Reinecke's avatar
Martin Reinecke committed
472
473
474
      pocketfft::c2c({nu,nv},{grid.stride(0)*sc,grid.stride(1)*sc},
        {tmp.stride(0)*sc, tmp.stride(1)*sc}, {0,1}, pocketfft::BACKWARD,
        grid.data(), tmp.data(), T(1), nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
475
476
477
478
479
480
481
      for (size_t i=0; i<nx_dirty; ++i)
        for (size_t j=0; j<ny_dirty; ++j)
          {
          size_t i2 = nu-nx_dirty/2+i;
          if (i2>=nu) i2-=nu;
          size_t j2 = nv-ny_dirty/2+j;
          if (j2>=nv) j2-=nv;
Martin Reinecke's avatar
Martin Reinecke committed
482
          dirty(i,j) = tmp(i2,j2)*cfu[i]*cfv[j];
Martin Reinecke's avatar
Martin Reinecke committed
483
484
          }
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
485
486
487

    void dirty2grid_c(const const_mav<complex<T>,2> &dirty,
      mav<complex<T>,2> &grid) const
Martin Reinecke's avatar
Martin Reinecke committed
488
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
489
490
491
492
493
      checkShape(dirty.shape(), {nx_dirty, ny_dirty});
      checkShape(grid.shape(), {nu, nv});
      for (size_t i=0; i<nu; ++i)
        for (size_t j=0; j<nv; ++j)
          grid(i,j)=0.;
Martin Reinecke's avatar
Martin Reinecke committed
494
495
496
497
498
499
500
      for (size_t i=0; i<nx_dirty; ++i)
        for (size_t j=0; j<ny_dirty; ++j)
          {
          size_t i2 = nu-nx_dirty/2+i;
          if (i2>=nu) i2-=nu;
          size_t j2 = nv-ny_dirty/2+j;
          if (j2>=nv) j2-=nv;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
501
          grid(i2,j2) = dirty(i,j)*cfu[i]*cfv[j];
Martin Reinecke's avatar
Martin Reinecke committed
502
          }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
503
      constexpr auto sc = ptrdiff_t(sizeof(complex<T>));
Martin Reinecke's avatar
updates    
Martin Reinecke committed
504
      pocketfft::stride_t strides{grid.stride(0)*sc,grid.stride(1)*sc};
Martin Reinecke's avatar
Martin Reinecke committed
505
      pocketfft::c2c({nu,nv}, strides, strides, {0,1}, pocketfft::FORWARD,
Martin Reinecke's avatar
updates    
Martin Reinecke committed
506
        grid.data(), grid.data(), T(1), nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
507
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
508

Martin Reinecke's avatar
Martin Reinecke committed
509
510
511
512
513
514
515
516
517
    inline void getpix(T u_in, T v_in, T &u, T &v, int &iu0, int &iv0) const
      {
      u=fmodulo(u_in*psx, T(1))*nu,
      iu0 = int(u-supp*0.5 + 1 + nu) - nu;
      if (iu0+supp>nu+nsafe) iu0 = nu+nsafe-supp;
      v=fmodulo(v_in*psy, T(1))*nv;
      iv0 = int(v-supp*0.5 + 1 + nv) - nv;
      if (iv0+supp>nv+nsafe) iv0 = nv+nsafe-supp;
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
518
519
520

    void apply_wscreen(const const_mav<complex<T>,2> &dirty,
      mav<complex<T>,2> &dirty2, double w, bool adjoint) const
Martin Reinecke's avatar
Martin Reinecke committed
521
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
522
523
      checkShape(dirty.shape(), {nx_dirty, ny_dirty});
      checkShape(dirty2.shape(), {nx_dirty, ny_dirty});
Martin Reinecke's avatar
Martin Reinecke committed
524
525
      double x0 = -0.5*nx_dirty*psx,
             y0 = -0.5*ny_dirty*psy;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
526
#pragma omp parallel for num_threads(nthreads) schedule(static)
Martin Reinecke's avatar
Martin Reinecke committed
527
528
529
530
531
532
533
534
      for (size_t i=0; i<=nx_dirty/2; ++i)
        {
        double fx = x0+i*psx;
        fx *= fx;
        for (size_t j=0; j<=ny_dirty/2; ++j)
          {
          double fy = y0+j*psy;
          auto ws = wscreen(fx, fy*fy, w, adjoint);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
535
          dirty2(i,j) = dirty(i,j)*ws; // lower left
Martin Reinecke's avatar
Martin Reinecke committed
536
537
538
          size_t i2 = nx_dirty-i, j2 = ny_dirty-j;
          if ((i>0)&&(i<i2))
            {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
539
            dirty2(i2,j) = dirty(i2,j)*ws; // lower right
Martin Reinecke's avatar
Martin Reinecke committed
540
            if ((j>0)&&(j<j2))
Martin Reinecke's avatar
updates    
Martin Reinecke committed
541
              dirty2(i2,j2) = dirty(i2,j2)*ws; // upper right
Martin Reinecke's avatar
Martin Reinecke committed
542
543
            }
          if ((j>0)&&(j<j2))
Martin Reinecke's avatar
updates    
Martin Reinecke committed
544
            dirty2(i,j2) = dirty(i,j2)*ws; // upper left
Martin Reinecke's avatar
Martin Reinecke committed
545
546
547
          }
        }
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
548

Martin Reinecke's avatar
Martin Reinecke committed
549
550
551
552
  };

constexpr int logsquare=4;

Martin Reinecke's avatar
Martin Reinecke committed
553
template<typename T, typename T2=complex<T>> class Helper
Martin Reinecke's avatar
Martin Reinecke committed
554
555
556
557
558
559
560
561
562
563
564
  {
  private:
    const GridderConfig<T> &gconf;
    int nu, nv, nsafe, supp;
    T beta;
    const T2 *grid_r;
    T2 *grid_w;
    int su, sv;
    int iu0, iv0; // start index of the current visibility
    int bu0, bv0; // start index of the current buffer

Martin Reinecke's avatar
Martin Reinecke committed
565
    vector<T2> rbuf, wbuf;
Martin Reinecke's avatar
Martin Reinecke committed
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

    void dump() const
      {
      if (bu0<-nsafe) return; // nothing written into buffer yet

#pragma omp critical (gridder_writing_to_grid)
{
      int idxu = (bu0+nu)%nu;
      int idxv0 = (bv0+nv)%nv;
      for (int iu=0; iu<su; ++iu)
        {
        int idxv = idxv0;
        for (int iv=0; iv<sv; ++iv)
          {
          grid_w[idxu*nv + idxv] += wbuf[iu*sv + iv];
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
}
      }

    void load()
      {
      int idxu = (bu0+nu)%nu;
      int idxv0 = (bv0+nv)%nv;
      for (int iu=0; iu<su; ++iu)
        {
        int idxv = idxv0;
        for (int iv=0; iv<sv; ++iv)
          {
          rbuf[iu*sv + iv] = grid_r[idxu*nv + idxv];
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
      }

  public:
    const T2 *p0r;
    T2 *p0w;
Martin Reinecke's avatar
Martin Reinecke committed
607
    vector<T> kernel;
Martin Reinecke's avatar
Martin Reinecke committed
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650

    Helper(const GridderConfig<T> &gconf_, const T2 *grid_r_, T2 *grid_w_)
      : gconf(gconf_), nu(gconf.Nu()), nv(gconf.Nv()), nsafe(gconf.Nsafe()),
        supp(gconf.Supp()), beta(gconf.Beta()), grid_r(grid_r_),
        grid_w(grid_w_), su(2*nsafe+(1<<logsquare)), sv(2*nsafe+(1<<logsquare)),
        bu0(-1000000), bv0(-1000000),
        rbuf(su*sv*(grid_r!=nullptr),T(0)),
        wbuf(su*sv*(grid_w!=nullptr),T(0)),
        kernel(2*supp)
      {}
    ~Helper() { if (grid_w) dump(); }

    int lineJump() const { return sv; }

    void prep(T u_in, T v_in)
      {
      T u, v;
      gconf.getpix(u_in, v_in, u, v, iu0, iv0);
      T xsupp=T(2)/supp;
      auto x0 = xsupp*(iu0-u);
      auto y0 = xsupp*(iv0-v);
      for (int i=0; i<supp; ++i)
        {
        auto x = x0+i*xsupp;
        kernel[i  ] = beta*sqrt(T(1)-x*x);
        auto y = y0+i*xsupp;
        kernel[i+supp] = beta*sqrt(T(1)-y*y);
        }
      for (auto &k : kernel)
        k = exp(k);

      if ((iu0<bu0) || (iv0<bv0) || (iu0+supp>bu0+su) || (iv0+supp>bv0+sv))
        {
        if (grid_w) { dump(); fill(wbuf.begin(), wbuf.end(), T(0)); }
        bu0=((((iu0+nsafe)>>logsquare)<<logsquare))-nsafe;
        bv0=((((iv0+nsafe)>>logsquare)<<logsquare))-nsafe;
        if (grid_r) load();
        }
      p0r = grid_r ? rbuf.data() + sv*(iu0-bu0) + iv0-bv0 : nullptr;
      p0w = grid_w ? wbuf.data() + sv*(iu0-bu0) + iv0-bv0 : nullptr;
      }
  };

651
template<class T, class T2, class T3> class VisServ
Martin Reinecke's avatar
updates    
Martin Reinecke committed
652
  {
653
654
655
656
657
658
659
  private:
    const Baselines<T> &baselines;
    const const_mav<uint32_t,1> &idx;
    T2 vis;
    const T3 &wgt;
    size_t nvis;
    bool have_wgt;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
660

661
662
663
664
665
666
667
668
669
670
671
  public:
    VisServ(const Baselines<T> &baselines_,
      const const_mav<uint32_t,1> &idx_, T2 vis_, const T3 &wgt_)
      : baselines(baselines_), idx(idx_), vis(vis_), wgt(wgt_)
      {
      nvis = vis.shape(0);
      checkShape(idx.shape(), {nvis});
      have_wgt = wgt.size()!=0;
      if (have_wgt) checkShape(wgt.shape(), {nvis});
      }
    size_t Nvis() const { return nvis; }
672
    const Baselines<T> &getBaselines() const { return baselines; }
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
    UVW<T> getCoord(size_t i) const
      { return baselines.effectiveCoord(idx[i]); }
    complex<T> getVis(size_t i) const
      { return have_wgt ? vis(i)*wgt(i) : vis(i); }
    uint32_t getIdx(size_t i) const { return idx[i]; }
    void setVis (size_t i, const complex<T> &v) const
      { vis(i) = have_wgt ? v*wgt(i) : v; }
    void addVis (size_t i, const complex<T> &v) const
      { vis(i) += have_wgt ? v*wgt(i) : v; }
  };
template<class T, class T2, class T3> class MsServ
  {
  private:
    const Baselines<T> &baselines;
    const const_mav<uint32_t,1> &idx;
    T2 ms;
    const T3 &wgt;
    size_t nvis;
    bool have_wgt;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
692

693
694
695
696
  public:
    MsServ(const Baselines<T> &baselines_,
    const const_mav<uint32_t,1> &idx_, T2 ms_, const T3 &wgt_)
      : baselines(baselines_), idx(idx_), ms(ms_), wgt(wgt_)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
697
      {
698
699
700
701
702
703
      auto nrows = baselines.Nrows();
      auto nchan = baselines.Nchannels();
      nvis = idx.shape(0);
      checkShape(ms.shape(), {nrows, nchan});
      have_wgt = wgt.size()!=0;
      if (have_wgt) checkShape(wgt.shape(), {nrows, nchan});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
704
      }
705
    size_t Nvis() const { return nvis; }
706
    const Baselines<T> &getBaselines() const { return baselines; }
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
    UVW<T> getCoord(size_t i) const
      { return baselines.effectiveCoord(idx(i)); }
    complex<T> getVis(size_t i) const
      {
      auto rc = baselines.getRowChan(idx(i));
      return have_wgt ? ms(rc.row, rc.chan)*wgt(rc.row, rc.chan)
                      : ms(rc.row, rc.chan);
      }
    uint32_t getIdx(size_t i) const { return idx[i]; }
    void setVis (size_t i, const complex<T> &v) const
      {
      auto rc = baselines.getRowChan(idx(i));
      ms(rc.row, rc.chan) = have_wgt ? v*wgt(rc.row, rc.chan) : v;
      }
    void addVis (size_t i, const complex<T> &v) const
      {
      auto rc = baselines.getRowChan(idx(i));
      ms(rc.row, rc.chan) += have_wgt ? v*wgt(rc.row, rc.chan) : v;
      }
  };
Martin Reinecke's avatar
updates    
Martin Reinecke committed
727

728
729
template<typename T, typename Serv> void x2grid_c
  (const GridderConfig<T> &gconf, const Serv &srv, mav<complex<T>,2> &grid)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
730
731
732
733
734
735
736
737
738
739
740
741
742
743
  {
  size_t nu=gconf.Nu(), nv=gconf.Nv();
  checkShape(grid.shape(), {nu, nv});
  myassert(grid.contiguous(), "grid is not contiguous");
  T beta = gconf.Beta();
  size_t supp = gconf.Supp();

#pragma omp parallel num_threads(nthreads)
{
  Helper<T> hlp(gconf, nullptr, grid.data());
  T emb = exp(-2*beta);
  int jump = hlp.lineJump();
  const T * ku = hlp.kernel.data();
  const T * kv = hlp.kernel.data()+supp;
744
  size_t np = srv.Nvis();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
745
746
747

  // Loop over sampling points
#pragma omp for schedule(guided,100)
748
  for (size_t ipart=0; ipart<np; ++ipart)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
749
    {
750
    UVW<T> coord = srv.getCoord(ipart);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
751
752
    hlp.prep(coord.u, coord.v);
    auto * ptr = hlp.p0w;
753
    auto v(srv.getVis(ipart)*emb);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
754
755
756
757
758
759
760
761
762
763
764
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(v*ku[cu]);
      for (size_t cv=0; cv<supp; ++cv)
        ptr[cv] += tmp*kv[cv];
      ptr+=jump;
      }
    }
} // end of parallel region
  }

765
template<typename T> void vis2grid_c
Martin Reinecke's avatar
updates    
Martin Reinecke committed
766
  (const Baselines<T> &baselines, const GridderConfig<T> &gconf,
767
768
  const const_mav<uint32_t,1> &idx, const const_mav<complex<T>,1> &vis,
  mav<complex<T>,2> &grid, const const_mav<T,1> &wgt)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
769
  {
770
771
772
773
774
775
776
777
778
779
  x2grid_c(gconf, VisServ<T,const_mav<complex<T>,1>,const_mav<T,1>> (baselines, idx, vis, wgt), grid);
  }

template<typename T> void ms2grid_c
  (const Baselines<T> &baselines, const GridderConfig<T> &gconf,
  const const_mav<uint32_t,1> &idx, const const_mav<complex<T>,2> &ms,
  mav<complex<T>,2> &grid, const const_mav<T,2> &wgt)
  {
  x2grid_c(gconf, MsServ<T,const_mav<complex<T>,2>,const_mav<T,2>> (baselines, idx, ms, wgt), grid);
  }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
780

781
782
783
template<typename T, typename Serv> void grid2x_c
  (const GridderConfig<T> &gconf, const const_mav<complex<T>,2> &grid, const Serv &srv)
  {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
784
785
786
787
788
789
790
791
792
793
794
795
796
797
  size_t nu=gconf.Nu(), nv=gconf.Nv();
  checkShape(grid.shape(), {nu, nv});
  myassert(grid.contiguous(), "grid is not contiguous");
  T beta = gconf.Beta();
  size_t supp = gconf.Supp();

  // Loop over sampling points
#pragma omp parallel num_threads(nthreads)
{
  Helper<T> hlp(gconf, grid.data(), nullptr);
  T emb = exp(-2*beta);
  int jump = hlp.lineJump();
  const T * ku = hlp.kernel.data();
  const T * kv = hlp.kernel.data()+supp;
798
  size_t np = srv.Nvis();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
799
800

#pragma omp for schedule(guided,100)
801
  for (size_t ipart=0; ipart<np; ++ipart)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
802
    {
803
    UVW<T> coord = srv.getCoord(ipart);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
804
805
806
807
808
809
810
811
812
813
814
    hlp.prep(coord.u, coord.v);
    complex<T> r = 0;
    const auto * ptr = hlp.p0r;
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(0);
      for (size_t cv=0; cv<supp; ++cv)
        tmp += ptr[cv] * kv[cv];
      r += tmp*ku[cu];
      ptr += jump;
      }
815
    srv.setVis(ipart, r*emb);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
816
817
818
    }
}
  }
819
820
821
822
823
824
825
template<typename T> void grid2vis_c
  (const Baselines<T> &baselines, const GridderConfig<T> &gconf,
  const const_mav<uint32_t,1> &idx, const const_mav<complex<T>,2> &grid,
  mav<complex<T>,1> &vis, const const_mav<T,1> &wgt)
  {
  grid2x_c(gconf, grid, VisServ<T,mav<complex<T>,1>,const_mav<T,1>> (baselines, idx, vis, wgt));
  }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
826
827
828
829
830
831

template<typename T> void grid2ms_c
  (const Baselines<T> &baselines, const GridderConfig<T> &gconf,
  const const_mav<uint32_t,1> &idx, const const_mav<complex<T>,2> &grid,
  mav<complex<T>,2> &ms, const const_mav<T,2> &wgt)
  {
832
  grid2x_c(gconf, grid, MsServ<T,mav<complex<T>,2>,const_mav<T,2>> (baselines, idx, ms, wgt));
Martin Reinecke's avatar
updates    
Martin Reinecke committed
833
834
  }

Martin Reinecke's avatar
Martin Reinecke committed
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
template<typename T> void apply_holo
  (const Baselines<T> &baselines, const GridderConfig<T> &gconf,
  const const_mav<uint32_t,1> &idx, const const_mav<complex<T>,2> &grid,
  mav<complex<T>,2> &ogrid, const const_mav<T,1> &wgt)
  {
  size_t nu=gconf.Nu(), nv=gconf.Nv();
  checkShape(grid.shape(), {nu, nv});
  size_t nvis = idx.shape(0);
  bool have_wgt = wgt.size()!=0;
  if (have_wgt) checkShape(wgt.shape(), {nvis});
  checkShape(ogrid.shape(), {nu, nv});

  for (size_t i=0; i<nu; ++i)
    for (size_t j=0; j<nv; ++j)
      ogrid(i,j) = T(0);

  T beta = gconf.Beta();
  size_t supp = gconf.Supp();

  // Loop over sampling points
#pragma omp parallel num_threads(nthreads)
{
  Helper<T> hlp(gconf, grid.data(), ogrid.data());
  T emb = exp(-2*beta);
  int jump = hlp.lineJump();
  const T * ku = hlp.kernel.data();
  const T * kv = hlp.kernel.data()+supp;

#pragma omp for schedule(guided,100)
  for (size_t ipart=0; ipart<nvis; ++ipart)
    {
866
    UVW<T> coord = baselines.effectiveCoord(idx(ipart));
Martin Reinecke's avatar
Martin Reinecke committed
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
    hlp.prep(coord.u, coord.v);
    complex<T> r = 0;
    const auto * ptr = hlp.p0r;
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(0);
      for (size_t cv=0; cv<supp; ++cv)
        tmp += ptr[cv] * kv[cv];
      r += tmp*ku[cu];
      ptr += jump;
      }
    r*=emb*emb;
    if (have_wgt)
      {
      auto twgt = wgt(ipart);
      r*=twgt*twgt;
      }
    auto * wptr = hlp.p0w;
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(r*ku[cu]);
      for (size_t cv=0; cv<supp; ++cv)
        wptr[cv] += tmp*kv[cv];
      wptr += jump;
      }
    }
}
  }

template<typename T> void get_correlations
  (const Baselines<T> &baselines, const GridderConfig<T> &gconf,
  const const_mav<uint32_t,1> &idx, int du, int dv,
  mav<T,2> &ogrid, const const_mav<T,1> &wgt)
  {
  size_t nu=gconf.Nu(), nv=gconf.Nv();
  size_t nvis = idx.shape(0);
  bool have_wgt = wgt.size()!=0;
  if (have_wgt) checkShape(wgt.shape(), {nvis});
  checkShape(ogrid.shape(), {nu, nv});
  size_t supp = gconf.Supp();
  myassert(size_t(abs(du))<supp, "|du| must be smaller than Supp");
  myassert(size_t(abs(dv))<supp, "|dv| must be smaller than Supp");

  T beta = gconf.Beta();
  for (size_t i=0; i<nu; ++i)
    for (size_t j=0; j<nv; ++j)
      ogrid(i,j) = T(0);

  size_t u0, u1, v0, v1;
  if (du>=0)
    { u0=0; u1=supp-du; }
  else
    { u0=-du; u1=supp; }
  if (dv>=0)
    { v0=0; v1=supp-dv; }
  else
    { v0=-dv; v1=supp; }

  // Loop over sampling points
#pragma omp parallel num_threads(nthreads)
{
  Helper<T,T> hlp(gconf, nullptr, ogrid.data());
  T emb = exp(-2*beta);
  int jump = hlp.lineJump();
  const T * ku = hlp.kernel.data();
  const T * kv = hlp.kernel.data()+supp;

#pragma omp for schedule(guided,100)
  for (size_t ipart=0; ipart<nvis; ++ipart)
    {
    UVW<T> coord = baselines.effectiveCoord(idx(ipart));
    hlp.prep(coord.u, coord.v);
    auto * wptr = hlp.p0w + u0*jump;
    auto f0 = emb*emb;
    if (have_wgt)
      {
      auto twgt = wgt(ipart);
      f0*=twgt*twgt;
      }
    for (size_t cu=u0; cu<u1; ++cu)
      {
      auto f1=ku[cu]*ku[cu+du]*f0;
      for (size_t cv=v0; cv<v1; ++cv)
        wptr[cv] += f1*kv[cv]*kv[cv+dv];
      wptr += jump;
      }
    }
}
  }


958
template<typename T, typename T2> void apply_wcorr(const GridderConfig<T> &gconf,
Martin Reinecke's avatar
Martin Reinecke committed
959
  const mav<T2,2> &dirty, const EC_Kernel_with_correction<T> &kernel, double dw)
Martin Reinecke's avatar
Martin Reinecke committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
  {
  auto nx_dirty=gconf.Nxdirty();
  auto ny_dirty=gconf.Nydirty();
  auto psx=gconf.Pixsize_x();
  auto psy=gconf.Pixsize_y();
  double x0 = -0.5*nx_dirty*psx,
         y0 = -0.5*ny_dirty*psy;
#pragma omp parallel for schedule(static) num_threads(nthreads)
  for (size_t i=0; i<=nx_dirty/2; ++i)
    {
    double fx = x0+i*psx;
    fx *= fx;
    for (size_t j=0; j<=ny_dirty/2; ++j)
      {
      double fy = y0+j*psy;
      fy*=fy;
976
977
978
979
980
981
982
      T fct = 0;
      double tmp = 1.-fx-fy;
      if (tmp>=0)
        {
        auto nm1 = (-fx-fy)/(sqrt(1.-fx-fy)+1.); // accurate form of sqrt(1-x-y)
        fct = (nm1<=-1) ? 0. : kernel.corfac(nm1*dw);
        }
Martin Reinecke's avatar
Martin Reinecke committed
983
984
985
986
987
988
989
990
991
992
993
994
995
996
      size_t i2 = nx_dirty-i, j2 = ny_dirty-j;
      dirty(i,j)*=fct;
      if ((i>0)&&(i<i2))
        {
        dirty(i2,j)*=fct;
        if ((j>0)&&(j<j2))
          dirty(i2,j2)*=fct;
        }
      if ((j>0)&&(j<j2))
        dirty(i,j2)*=fct;
      }
    }
  }

Martin Reinecke's avatar
Martin Reinecke committed
997
998
template<typename T, typename Serv> void wstack_common(
  const GridderConfig<T> &gconf, const Serv &srv, T &wmin, vector<T> &wval,
Martin Reinecke's avatar
Martin Reinecke committed
999
  double &dw, size_t &nplanes, vector<size_t> &nvis_plane, vector<int> &minplane, size_t verbosity)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1000
1001
1002
1003
1004
  {
  auto nx_dirty=gconf.Nxdirty();
  auto ny_dirty=gconf.Nydirty();
  auto psx=gconf.Pixsize_x();
  auto psy=gconf.Pixsize_y();
1005
  size_t nvis = srv.Nvis();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1006
1007

  // determine w values for every visibility, and min/max w;
Martin Reinecke's avatar
Martin Reinecke committed
1008
1009
1010
  wmin=T(1e38);
  T wmax=T(-1e38);
  wval.resize(nvis);
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1011
1012

#pragma omp parallel for num_threads(nthreads) reduction(min:wmin) reduction(max:wmax)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1013
1014
  for (size_t ipart=0; ipart<nvis; ++ipart)
    {
1015
    wval[ipart] = srv.getCoord(ipart).w;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1016
1017
1018
    wmin = min(wmin,wval[ipart]);
    wmax = max(wmax,wval[ipart]);
    }
Martin Reinecke's avatar
Martin Reinecke committed
1019
  if (verbosity>0) cout << "W range: " << wmin << " to " << wmax << endl;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1020
1021
1022
  double x0 = -0.5*nx_dirty*psx,
         y0 = -0.5*ny_dirty*psy;
  double nmin = sqrt(max(1.-x0*x0-y0*y0,0.))-1.;
Martin Reinecke's avatar
Martin Reinecke committed
1023
1024
  dw = 0.25/abs(nmin);
  nplanes = max<size_t>(2,((wmax-wmin)/dw+2));
1025
  dw=(wmax-wmin)/(nplanes-1);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1026

Martin Reinecke's avatar
Martin Reinecke committed
1027
  auto w_supp = gconf.Supp();
1028
1029
1030
  wmin -= (0.5*w_supp-1)*dw;
  wmax += (0.5*w_supp-1)*dw;
  nplanes += w_supp-2;
Martin Reinecke's avatar
Martin Reinecke committed
1031
1032
  if (verbosity>0) cout << "Kernel support: " << w_supp << endl;
  if (verbosity>0) cout << "nplanes: " << nplanes << endl;
Martin Reinecke's avatar
Martin Reinecke committed
1033
1034
  nvis_plane.resize(nplanes,0);
  minplane.resize(nvis);
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1035
1036
1037
1038
#pragma omp parallel num_threads(nthreads)
{
  vector<size_t> nvploc(nplanes,0);
#pragma omp for
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1039
1040
1041
1042
1043
  for (size_t ipart=0; ipart<nvis; ++ipart)
    {
    int plane0 = int((wval[ipart]-wmin)/dw+0.5*w_supp)-int(w_supp-1);
    minplane[ipart]=plane0;
    for (int i=max<int>(0,plane0); i<min<int>(nplanes,plane0+w_supp); ++i)
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1044
      ++nvploc[i];
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1045
    }
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1046
1047
1048
1049
#pragma omp critical
  for (size_t i=0; i<nplanes; ++i)
    nvis_plane[i]+=nvploc[i];
}
Martin Reinecke's avatar
Martin Reinecke committed
1050
1051
  }

1052
template<typename T, typename Serv> void x2dirty_wstack(
Martin Reinecke's avatar
Martin Reinecke committed
1053
  const GridderConfig<T> &gconf, const Serv &srv, const mav<complex<T>,2> &dirty, size_t verbosity=0)
Martin Reinecke's avatar
Martin Reinecke committed
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
  {
  auto nx_dirty=gconf.Nxdirty();
  auto ny_dirty=gconf.Nydirty();
  auto nu=gconf.Nu();
  auto nv=gconf.Nv();
  size_t nvis = srv.Nvis();
  auto w_supp = gconf.Supp();
  EC_Kernel_with_correction<T> kernel(w_supp);
  T wmin;
  vector<T> wval;
  double dw;
  size_t nplanes;
  vector<size_t> nvis_plane;
  vector<int> minplane;
Martin Reinecke's avatar
Martin Reinecke committed
1068
  wstack_common(gconf, srv, wmin, wval, dw, nplanes, nvis_plane, minplane, verbosity);
Martin Reinecke's avatar
Martin Reinecke committed
1069

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
1070
1071
  for (size_t i=0; i<nx_dirty; ++i)
    for (size_t j=0; j<ny_dirty; ++j)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1072
      dirty(i,j) = 0.;
Martin Reinecke's avatar
Martin Reinecke committed
1073
1074
1075
  {
  vector<complex<T>> vis_loc_;
  vector<uint32_t> idx_loc_;
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1076
  vector<uint32_t> mapper;
Martin Reinecke's avatar
Martin Reinecke committed
1077
1078
1079
1080
  tmpStorage<complex<T>,2> grid_({nu,nv});
  auto grid=grid_.getMav();
  tmpStorage<complex<T>,2> tdirty_({nx_dirty,ny_dirty});
  auto tdirty=tdirty_.getMav();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1081
1082
1083
  for (size_t iw=0; iw<nplanes; ++iw)
    {
    if (nvis_plane[iw]==0) continue;
Martin Reinecke's avatar
Martin Reinecke committed
1084
1085
1086
    if (verbosity>1)
      cout << "Working on plane " << iw << " containing " << nvis_plane[iw]
           << " visibilities" << endl;
1087
    T wcur = wmin+iw*dw;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1088
    size_t cnt=0;
Martin Reinecke's avatar
Martin Reinecke committed
1089
    vis_loc_.resize(nvis_plane[iw]);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1090
    auto vis_loc = mav<complex<T>,1>(vis_loc_.data(), {nvis_plane[iw]});
Martin Reinecke's avatar
Martin Reinecke committed
1091
    idx_loc_.resize(nvis_plane[iw]);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1092
    auto idx_loc = mav<uint32_t,1>(idx_loc_.data(), {nvis_plane[iw]});
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1093
    mapper.resize(nvis_plane[iw]);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1094
    for (size_t ipart=0; ipart<nvis; ++ipart)
Martin Reinecke's avatar
Martin Reinecke committed
1095
      if ((int(iw)>=minplane[ipart]) && (iw<minplane[ipart]+w_supp))
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1096
1097
        mapper[cnt++] = ipart;

1098
    T tmpval=T(2)/(w_supp*dw);
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1099
1100
1101
1102
#pragma omp parallel for num_threads(nthreads)
    for (size_t i=0; i<nvis_plane[iw]; ++i)
      {
      auto ipart = mapper[i];
1103
      T x=min(T(1), tmpval*abs(wcur-wval[ipart]));
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1104
1105
1106
      vis_loc[i] = srv.getVis(ipart)*kernel(x);
      idx_loc[i] = srv.getIdx(ipart);
      }
Martin Reinecke's avatar
Martin Reinecke committed
1107
    grid_.fill(0.);
1108
    vis2grid_c(srv.getBaselines(), gconf, const_mav<uint32_t,1>(idx_loc), const_mav<complex<T>,1>(vis_loc), grid, const_mav<T,1>(nullptr,{0}));
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1109
1110
    gconf.grid2dirty_c(grid, tdirty);
    gconf.apply_wscreen(tdirty, tdirty, wcur, false);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
1111
#pragma omp parallel for num_threads(nthreads)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
1112
1113
    for (size_t i=0; i<nx_dirty; ++i)
      for (size_t j=0; j<ny_dirty; ++j)
1114
        dirty(i,j) += tdirty(i,j);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1115
    }
Martin Reinecke's avatar
Martin Reinecke committed
1116
  }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1117
  // correct for w gridding
Martin Reinecke's avatar
Martin Reinecke committed
1118
  apply_wcorr(gconf, dirty, kernel, dw);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1119
  }
1120
template<typename T> void vis2dirty_wstack(const Baselines<T> &baselines,
1121
  const GridderConfig<T> &gconf, const const_mav<uint32_t,1> &idx,
1122
1123
  const const_mav<complex<T>,1> &vis, mav<complex<T>,2> &dirty)
  {
1124
  x2dirty_wstack(gconf, VisServ<T,const_mav<complex<T>,1>,const_mav<T,1>>(baselines, idx, vis, const_mav<T,1>(nullptr,{0})), dirty);
1125
1126
  }

1127
template<typename T, typename Serv> void dirty2x_wstack(
1128
  const GridderConfig<T> &gconf,  const const_mav<complex<T>,2> &dirty,
Martin Reinecke's avatar
Martin Reinecke committed
1129
  const Serv &srv, size_t verbosity=0)
1130
1131
1132
1133
1134
  {
  auto nx_dirty=gconf.Nxdirty();
  auto ny_dirty=gconf.Nydirty();
  auto nu=gconf.Nu();
  auto nv=gconf.Nv();
1135
  size_t nvis = srv.Nvis();
1136
1137
  auto w_supp = gconf.Supp();
  EC_Kernel_with_correction<T> kernel(w_supp);
Martin Reinecke's avatar
Martin Reinecke committed
1138
1139
1140
1141
1142
1143
  T wmin;
  vector<T> wval;
  double dw;
  size_t nplanes;
  vector<size_t> nvis_plane;
  vector<int> minplane;
Martin Reinecke's avatar
Martin Reinecke committed
1144
  wstack_common(gconf, srv, wmin, wval, dw, nplanes, nvis_plane, minplane, verbosity);
1145
1146

  for (size_t i=0; i<nvis; ++i)
1147
    srv.setVis(i, 0.);
1148
1149
1150
1151
1152
1153
1154
1155
1156

  tmpStorage<complex<T>,2> tdirty_({nx_dirty,ny_dirty});
  auto tdirty=tdirty_.getMav();
  for (size_t i=0; i<nx_dirty; ++i)
    for (size_t j=0; j<ny_dirty; ++j)
      tdirty(i,j) = dirty(i,j);
  // correct for w gridding
  apply_wcorr(gconf, tdirty, kernel, dw);

Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1157
1158
1159
  vector<complex<T>> vis_loc_;
  vector<uint32_t> idx_loc_;
  vector<uint32_t> mapper;
1160
1161
1162
1163
1164
1165
1166
  tmpStorage<complex<T>,2> grid_({nu,nv});
  auto grid=grid_.getMav();
  tmpStorage<complex<T>,2> tdirty2_({nx_dirty,ny_dirty});
  auto tdirty2=tdirty2_.getMav();
  for (size_t iw=0; iw<nplanes; ++iw)
    {
    if (nvis_plane[iw]==0) continue;
Martin Reinecke's avatar
Martin Reinecke committed
1167
1168
1169
    if (verbosity>1)
      cout << "Working on plane " << iw << " containing " << nvis_plane[iw]
           << " visibilities" << endl;
1170
    T wcur = wmin+iw*dw;
1171
1172
1173
1174
1175
    size_t cnt=0;
    vis_loc_.resize(nvis_plane[iw]);
    auto vis_loc = mav<complex<T>,1>(vis_loc_.data(), {nvis_plane[iw]});
    idx_loc_.resize(nvis_plane[iw]);
    auto idx_loc = mav<uint32_t,1>(idx_loc_.data(), {nvis_plane[iw]});
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1176
    mapper.resize(nvis_plane[iw]);
1177
    for (size_t ipart=0; ipart<nvis; ++ipart)
Martin Reinecke's avatar
Martin Reinecke committed
1178
      if ((int(iw)>=minplane[ipart]) && (iw<minplane[ipart]+w_supp))
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1179
1180
1181
1182
1183
1184
1185
        mapper[cnt++] = ipart;
#pragma omp parallel for num_threads(nthreads)
    for (size_t i=0; i<nvis_plane[iw]; ++i)
        idx_loc[i] = srv.getIdx(mapper[i]);

    gconf.apply_wscreen(tdirty, tdirty2, wcur, true);
    gconf.dirty2grid_c(tdirty2, grid);
1186
    grid2vis_c(srv.getBaselines(), gconf, const_mav<uint32_t,1>(idx_loc), const_mav<complex<T>,2>(grid), vis_loc, const_mav<T,1>(nullptr,{0}));
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1187

1188
    T tmpval=T(2)/(w_supp*dw);
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1189
1190
1191
1192
#pragma omp parallel for num_threads(nthreads)
    for (size_t i=0; i<nvis_plane[iw]; ++i)
      {
      auto ipart = mapper[i];
1193
      T x=min(T(1), tmpval*abs(wcur-wval[ipart]));
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
1194
1195
      srv.addVis(ipart, vis_loc[i]*kernel(x));
      }
1196
1197
    }
  }
1198
1199
1200
1201
template<typename T> void dirty2vis_wstack(const Baselines<T> &baselines,
  const GridderConfig<T> &gconf, const const_mav<uint32_t,1> &idx,
  const const_mav<complex<T>,2> &dirty, mav<complex<T>,1> &vis)
  {
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
  dirty2x_wstack(gconf, dirty, VisServ<T,mav<complex<T>,1>,const_mav<T,1>>(baselines, idx, vis, const_mav<T,1>(nullptr,{0})));
  }


template<typename T> size_t getIdxSize(const Baselines<T> &baselines,
  const const_mav<bool,2> &flags, int chbegin, int chend, T wmin, T wmax)
  {
  size_t nrow=baselines.Nrows(), nchan=baselines.Nchannels();
  if (chbegin<0) chbegin=0;
  if (chend<0) chend=nchan;
  myassert(chend>chbegin, "empty channel range selected");
  myassert(chend<=int(nchan), "chend too large");
  myassert(wmax>wmin, "empty w range selected");
  checkShape(flags.shape(), {nrow, nchan});
  size_t res=0;
#pragma omp parallel for num_threads(nthreads) reduction(+:res)
  for (size_t irow=0; irow<nrow; ++irow)
    for (int ichan=chbegin; ichan<chend; ++ichan)
      if (!flags(irow,ichan))
        {
        auto uvw = baselines.effectiveCoord(RowChan{irow,size_t(ichan)});
        if ((uvw.w>=wmin) && (uvw.w<wmax))
          ++res;
        }
  return res;
  }

template<typename T> void fillIdx(const Baselines<T> &baselines,
  const GridderConfig<T> &gconf, const const_mav<bool,2> &flags, int chbegin,
  int chend, T wmin, T wmax, mav<uint32_t,1> &res)
  {
  size_t nrow=baselines.Nrows(),
         nchan=baselines.Nchannels(),
         nsafe=gconf.Nsafe();
  if (chbegin<0) chbegin=0;
  if (chend<0) chend=nchan;
  myassert(chend>chbegin, "empty channel range selected");
  myassert(chend<=int(nchan), "chend too large");
  myassert(wmax>wmin, "empty w range selected");
  checkShape(flags.shape(), {nrow, nchan});
  constexpr int side=1<<logsquare;
  size_t nbu = (gconf.Nu()+1+side-1) >> logsquare,
         nbv = (gconf.Nv()+1+side-1) >> logsquare;
  vector<uint32_t> acc(nbu*nbv+1, 0);
  vector<uint32_t> tmp(nrow*(chend-chbegin));
  for (size_t irow=0, idx=0; irow<nrow; ++irow)
    for (int ichan=chbegin; ichan<chend; ++ichan)
      if (!flags(irow, ichan))
        {
        auto uvw = baselines.effectiveCoord(RowChan{irow,size_t(ichan)});
        if ((uvw.w>=wmin) && (uvw.w<wmax))
          {
          T u, v;
          int iu0, iv0;
          gconf.getpix(uvw.u, uvw.v, u, v, iu0, iv0);
          iu0 = (iu0+nsafe)>>logsquare;
          iv0 = (iv0+nsafe)>>logsquare;
          ++acc[nbv*iu0 + iv0 + 1];
          tmp[idx++] = nbv*iu0 + iv0;
          }
        }

  for (size_t i=1; i<acc.size(); ++i)
    acc[i] += acc[i-1];
  myassert(res.shape(0)==acc.back(), "array size mismatch");
  for (size_t irow=0, idx=0; irow<nrow; ++irow)
    for (int ichan=chbegin; ichan<chend; ++ichan)
      if (!flags(irow, ichan))
        {
        auto uvw = baselines.effectiveCoord(RowChan{irow,size_t(ichan)});
        if ((uvw.w>=wmin) && (uvw.w<wmax))
          res[acc[tmp[idx++]]++] = irow*nchan+ichan;
        }
1275
  }
1276

Martin Reinecke's avatar
Martin Reinecke committed
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
template<typename T> vector<uint32_t> getWgtIndices(const Baselines<T> &baselines,
  const GridderConfig<T> &gconf, const const_mav<T,2> &wgt)
  {
  size_t nrow=baselines.Nrows(),
         nchan=baselines.Nchannels(),
         nsafe=gconf.Nsafe();
  bool have_wgt=wgt.size()!=0;
  if (have_wgt) checkShape(wgt.shape(),{nrow,nchan});
  constexpr int side=1<<logsquare;
  size_t nbu = (gconf.Nu()+1+side-1) >> logsquare,
         nbv = (gconf.Nv()+1+side-1) >> logsquare;
  vector<uint32_t> acc(nbu*nbv+1, 0);
  vector<uint32_t> tmp(nrow*nchan);

  for (size_t irow=0, idx=0; irow<nrow; ++irow)
    for (size_t ichan=0; ichan<nchan; ++ichan)
      if ((!have_wgt) || (wgt(irow,ichan)!=0))
        {
        auto uvw = baselines.effectiveCoord(RowChan{irow,size_t(ichan)});
        T u, v;
        int iu0, iv0;
        gconf.getpix(uvw.u, uvw.v, u, v, iu0, iv0);
        iu0 = (iu0+nsafe)>>logsquare;
        iv0 = (iv0+nsafe)>>logsquare;
        ++acc[nbv*iu0 + iv0 + 1];
        tmp[idx++] = nbv*iu0 + iv0;
        }

  for (size_t i=1; i<acc.size(); ++i)
    acc[i] += acc[i-1];

  vector<uint32_t> res(acc.back());
  for (size_t irow=0, idx=0; irow<nrow; ++irow)
    for (size_t ichan=0; ichan<nchan; ++ichan)
      if ((!have_wgt) || (wgt(irow,ichan)!=0))
        res[acc[tmp[idx++]]++] = irow*nchan+ichan;
  return res;
  }

template<typename T> void full_gridding(const const_mav<T,2> &uvw,
  const const_mav<T,1> &freq, const const_mav<complex<T>,2> &ms,
  const const_mav<T,2> &wgt, T pixsize_x, T pixsize_y, double epsilon,
Martin Reinecke's avatar
Martin Reinecke committed
1319
  size_t nthreads, const mav<complex<T>,2> &dirty, size_t verbosity)
Martin Reinecke's avatar
Martin Reinecke committed
1320
  {
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
1321
  set_nthreads(nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
1322
1323