gridder_cxx.h 52.7 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
#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>
Martin Reinecke's avatar
Martin Reinecke committed
30
#include <array>
Martin Reinecke's avatar
Martin Reinecke committed
31
32

#include "pocketfft_hdronly.h"
Martin Reinecke's avatar
Martin Reinecke committed
33
34

#if defined(__GNUC__)
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
35
#define NOINLINE __attribute__((noinline))
Martin Reinecke's avatar
Martin Reinecke committed
36
#define ALIGNED(align) __attribute__ ((aligned(align)))
Martin Reinecke's avatar
Martin Reinecke committed
37
#define RESTRICT __restrict__
Martin Reinecke's avatar
Martin Reinecke committed
38
39
40
#else
#define NOINLINE
#define ALIGNED(align)
Martin Reinecke's avatar
Martin Reinecke committed
41
#define RESTRICT
Martin Reinecke's avatar
Martin Reinecke committed
42
#endif
Martin Reinecke's avatar
Martin Reinecke committed
43

Martin Reinecke's avatar
Martin Reinecke committed
44
45
namespace gridder {

46
47
namespace detail {

Martin Reinecke's avatar
Martin Reinecke committed
48
49
using namespace std;

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
template<typename T> struct VLEN { static constexpr size_t val=1; };

#if (defined(__AVX512F__))
template<> struct VLEN<float> { static constexpr size_t val=16; };
template<> struct VLEN<double> { static constexpr size_t val=8; };
#elif (defined(__AVX__))
template<> struct VLEN<float> { static constexpr size_t val=8; };
template<> struct VLEN<double> { static constexpr size_t val=4; };
#elif (defined(__SSE2__))
template<> struct VLEN<float> { static constexpr size_t val=4; };
template<> struct VLEN<double> { static constexpr size_t val=2; };
#elif (defined(__VSX__))
template<> struct VLEN<float> { static constexpr size_t val=4; };
template<> struct VLEN<double> { static constexpr size_t val=2; };
#endif

Martin Reinecke's avatar
Martin Reinecke committed
66
67

// "mav" stands for "multidimensional array view"
Martin Reinecke's avatar
Martin Reinecke committed
68
template<typename T, size_t ndim> class mav
Martin Reinecke's avatar
Martin Reinecke committed
69
70
71
72
73
  {
  static_assert((ndim>0) && (ndim<3), "only supports 1D and 2D arrays");

  private:
    T *d;
Martin Reinecke's avatar
Martin Reinecke committed
74
75
    array<size_t, ndim> shp;
    array<ptrdiff_t, ndim> str;
Martin Reinecke's avatar
Martin Reinecke committed
76
77

  public:
Martin Reinecke's avatar
Martin Reinecke committed
78
79
80
81
    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
82
83
84
85
86
87
      : 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];
      }
88
    T &operator[](size_t i) const
Martin Reinecke's avatar
Martin Reinecke committed
89
      { return operator()(i); }
90
    T &operator()(size_t i) const
Martin Reinecke's avatar
Martin Reinecke committed
91
92
      {
      static_assert(ndim==1, "ndim must be 1");
Martin Reinecke's avatar
Martin Reinecke committed
93
      return d[str[0]*i];
Martin Reinecke's avatar
Martin Reinecke committed
94
      }
95
    T &operator()(size_t i, size_t j) const
Martin Reinecke's avatar
Martin Reinecke committed
96
97
      {
      static_assert(ndim==2, "ndim must be 2");
Martin Reinecke's avatar
Martin Reinecke committed
98
      return d[str[0]*i + str[1]*j];
Martin Reinecke's avatar
Martin Reinecke committed
99
100
      }
    size_t shape(size_t i) const { return shp[i]; }
Martin Reinecke's avatar
Martin Reinecke committed
101
    const array<size_t,ndim> &shape() const { return shp; }
Martin Reinecke's avatar
Martin Reinecke committed
102
103
104
105
106
107
    size_t size() const
      {
      size_t res=1;
      for (auto v: shp) res*=v;
      return res;
      }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
108
    ptrdiff_t stride(size_t i) const { return str[i]; }
109
    T *data() const
Martin Reinecke's avatar
Martin Reinecke committed
110
      { return d; }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
111
112
113
114
115
116
117
118
119
120
    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
121
122
    void fill(const T &val) const
      {
Martin Reinecke's avatar
Martin Reinecke committed
123
      // FIXME: special cases for contiguous arrays and/or zeroing?
Martin Reinecke's avatar
Martin Reinecke committed
124
125
126
127
128
129
130
131
      if (ndim==1)
        for (size_t i=0; i<shp[0]; ++i)
          d[str[0]*i]=val;
      else if (ndim==2)
        for (size_t i=0; i<shp[0]; ++i)
          for (size_t j=0; j<shp[1]; ++j)
            d[str[0]*i + str[1]*j] = val;
      }
Martin Reinecke's avatar
Martin Reinecke committed
132
133
  };

Martin Reinecke's avatar
updates    
Martin Reinecke committed
134
template<typename T, size_t ndim> using const_mav = mav<const T, ndim>;
Martin Reinecke's avatar
Martin Reinecke committed
135
136
137
138
139
140
141
142
template<typename T, size_t ndim> const_mav<T, ndim> cmav (const mav<T, ndim> &mav)
  { return const_mav<T, ndim>(mav.data(), mav.shape()); }
template<typename T, size_t ndim> const_mav<T, ndim> nullmav()
  {
  array<size_t,ndim> shp;
  shp.fill(0);
  return const_mav<T, ndim>(nullptr, shp);
  }
Martin Reinecke's avatar
Martin Reinecke committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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) {}
Martin Reinecke's avatar
Martin Reinecke committed
159
160
    mav<T,ndim> &getMav() { return mav_; }
    const_mav<T,ndim> getCmav() { return cmav(mav_); }
Martin Reinecke's avatar
Martin Reinecke committed
161
162
163
    void fill(const T & val)
      { std::fill(d.begin(), d.end(), val); }
  };
Martin Reinecke's avatar
Martin Reinecke committed
164

Martin Reinecke's avatar
Martin Reinecke committed
165
166
167
//
// basic utilities
//
Martin Reinecke's avatar
Martin Reinecke committed
168
169
170
171
172
#if defined (__GNUC__)
#define LOC_ CodeLocation(__FILE__, __LINE__, __PRETTY_FUNCTION__)
#else
#define LOC_ CodeLocation(__FILE__, __LINE__)
#endif
Martin Reinecke's avatar
Martin Reinecke committed
173

Martin Reinecke's avatar
Martin Reinecke committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#define myfail(...) \
  do { \
    std::ostringstream os; \
    streamDump__(os, LOC_, "\n", ##__VA_ARGS__, "\n"); \
    throw std::runtime_error(os.str()); \
    } while(0)

#define myassert(cond,...) \
  do { \
    if (cond); \
    else { myfail("Assertion failure\n", ##__VA_ARGS__); } \
    } while(0)

template<typename T>
inline void streamDump__(std::ostream &os, const T& value)
  { os << value; }

template<typename T, typename ... Args>
inline void streamDump__(std::ostream &os, const T& value,
  const Args& ... args)
Martin Reinecke's avatar
Martin Reinecke committed
194
  {
Martin Reinecke's avatar
Martin Reinecke committed
195
196
  os << value;
  streamDump__(os, args...);
Martin Reinecke's avatar
Martin Reinecke committed
197
  }
Martin Reinecke's avatar
Martin Reinecke committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// to be replaced with std::source_location once available
class CodeLocation
  {
  private:
    const char *file, *func;
    int line;

  public:
    CodeLocation(const char *file_, int line_, const char *func_=nullptr)
      : file(file_), func(func_), line(line_) {}

    ostream &print(ostream &os) const
      {
      os << "file: " << file <<  ", line: " <<  line;
      if (func) os << ", function: " << func;
      return os;
      }
  };

inline std::ostream &operator<<(std::ostream &os, const CodeLocation &loc)
  { return loc.print(os); }
Martin Reinecke's avatar
Martin Reinecke committed
219
220

template<size_t ndim> void checkShape
Martin Reinecke's avatar
Martin Reinecke committed
221
  (const array<size_t, ndim> &shp1, const array<size_t, ndim> &shp2)
Martin Reinecke's avatar
Martin Reinecke committed
222
223
224
225
226
  {
  for (size_t i=0; i<ndim; ++i)
    myassert(shp1[i]==shp2[i], "shape mismatch");
  }

Martin Reinecke's avatar
Martin Reinecke committed
227
228
template<typename T> inline T fmod1 (T v)
  { return v-floor(v); }
Martin Reinecke's avatar
Martin Reinecke committed
229
230
231
232
233
234
235
236

//
// 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
237
void legendre_prep(int n, vector<double> &x, vector<double> &w, size_t nthreads)
Martin Reinecke's avatar
Martin Reinecke committed
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
  {
  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
//

Martin Reinecke's avatar
Martin Reinecke committed
295
296
297
298
299
struct RowChan
  {
  size_t row, chan;
  };

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
template<typename T> void complex2hartley
  (const const_mav<complex<T>, 2> &grid, const mav<T,2> &grid2, size_t nthreads)
  {
  myassert(grid.shape()==grid2.shape(), "shape mismatch");
  size_t nu=grid.shape(0), nv=grid.shape(1);

#pragma omp parallel for num_threads(nthreads)
  for (size_t u=0; u<nu; ++u)
    {
    size_t xu = (u==0) ? 0 : nu-u;
    for (size_t v=0; v<nv; ++v)
      {
      size_t xv = (v==0) ? 0 : nv-v;
      grid2(u,v) += T(0.5)*(grid( u, v).real()+grid( u, v).imag()+
                            grid(xu,xv).real()-grid(xu,xv).imag());
      }
    }
  }

template<typename T> void hartley2complex
  (const const_mav<T,2> &grid, const mav<complex<T>,2> &grid2, size_t nthreads)
  {
  myassert(grid.shape()==grid2.shape(), "shape mismatch");
  size_t nu=grid.shape(0), nv=grid.shape(1);

#pragma omp parallel for num_threads(nthreads)
  for (size_t u=0; u<nu; ++u)
    {
    size_t xu = (u==0) ? 0 : nu-u;
    for (size_t v=0; v<nv; ++v)
      {
      size_t xv = (v==0) ? 0 : nv-v;
      T v1 = T(0.5)*grid( u, v);
      T v2 = T(0.5)*grid(xu,xv);
      grid2(u,v) = std::complex<T>(v1+v2, v1-v2);
      }
    }
  }

Martin Reinecke's avatar
Martin Reinecke committed
339
340
template<typename T> void hartley2_2D(const const_mav<T,2> &in,
  const mav<T,2> &out, size_t nthreads)
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
  {
  myassert(in.shape()==out.shape(), "shape mismatch");
  size_t nu=in.shape(0), nv=in.shape(1);
  ptrdiff_t sz=ptrdiff_t(sizeof(T));
  pocketfft::stride_t stri{sz*in.stride(0), sz*in.stride(1)};
  pocketfft::stride_t stro{sz*out.stride(0), sz*out.stride(1)};
  auto d_i = in.data();
  auto ptmp = out.data();
  pocketfft::r2r_separable_hartley({nu, nv}, stri, stro, {0,1}, d_i, ptmp, T(1),
    nthreads);
#pragma omp parallel for num_threads(nthreads)
  for(size_t i=1; i<(nu+1)/2; ++i)
    for(size_t j=1; j<(nv+1)/2; ++j)
       {
       T a = ptmp[i*nv+j];
       T b = ptmp[(nu-i)*nv+j];
       T c = ptmp[i*nv+nv-j];
       T d = ptmp[(nu-i)*nv+nv-j];
       ptmp[i*nv+j] = T(0.5)*(a+b+c-d);
       ptmp[(nu-i)*nv+j] = T(0.5)*(a+b+d-c);
       ptmp[i*nv+nv-j] = T(0.5)*(a+c+d-b);
       ptmp[(nu-i)*nv+nv-j] = T(0.5)*(b+c+d-a);
       }
  }


Martin Reinecke's avatar
Martin Reinecke committed
367
class ES_Kernel
Martin Reinecke's avatar
Martin Reinecke committed
368
369
  {
  protected:
Martin Reinecke's avatar
Martin Reinecke committed
370
    double beta;
Martin Reinecke's avatar
Martin Reinecke committed
371
372

  public:
Martin Reinecke's avatar
Martin Reinecke committed
373
    ES_Kernel(size_t supp) : beta(2.3*supp) {}
Martin Reinecke's avatar
Martin Reinecke committed
374
    double operator()(double v) const { return exp(beta*(sqrt(1.-v*v)-1.)); }
Martin Reinecke's avatar
Martin Reinecke committed
375
376
377
378
379
380
381
382
383
384
385
    static size_t get_supp(double epsilon)
      {
      static const vector<double> maxmaperr { 1e8, 0.32, 0.021, 6.2e-4,
        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;
      myfail("requested epsilon too small - minimum is 2e-13");
      }
Martin Reinecke's avatar
Martin Reinecke committed
386
387
  };

Martin Reinecke's avatar
Martin Reinecke committed
388
class ES_Kernel_with_correction: public ES_Kernel
Martin Reinecke's avatar
Martin Reinecke committed
389
390
  {
  protected:
Martin Reinecke's avatar
Martin Reinecke committed
391
    static constexpr double pi = 3.141592653589793238462643383279502884197;
Martin Reinecke's avatar
Martin Reinecke committed
392
    int p;
393
    vector<double> x, wgt, psi;
Martin Reinecke's avatar
Martin Reinecke committed
394
    size_t supp;
Martin Reinecke's avatar
Martin Reinecke committed
395
396

  public:
Martin Reinecke's avatar
Martin Reinecke committed
397
398
    ES_Kernel_with_correction(size_t supp_, size_t nthreads)
      : ES_Kernel(supp_), p(int(1.5*supp_+2)), supp(supp_)
Martin Reinecke's avatar
Martin Reinecke committed
399
      {
Martin Reinecke's avatar
Martin Reinecke committed
400
      legendre_prep(2*p,x,wgt,nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
401
402
403
404
405
406
      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 */
Martin Reinecke's avatar
Martin Reinecke committed
407
    double corfac(double v) const
Martin Reinecke's avatar
Martin Reinecke committed
408
      {
Martin Reinecke's avatar
Martin Reinecke committed
409
      double tmp=0;
Martin Reinecke's avatar
Martin Reinecke committed
410
411
      for (int i=0; i<p; ++i)
        tmp += wgt[i]*psi[i]*cos(pi*supp*v*x[i]);
Martin Reinecke's avatar
Martin Reinecke committed
412
      return 1./(supp*tmp);
Martin Reinecke's avatar
Martin Reinecke committed
413
414
415
416
      }
  };
/* 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
417
vector<double> correction_factors(size_t n, size_t nval, size_t supp,
Martin Reinecke's avatar
Martin Reinecke committed
418
  size_t nthreads)
Martin Reinecke's avatar
Martin Reinecke committed
419
  {
Martin Reinecke's avatar
Martin Reinecke committed
420
  ES_Kernel_with_correction kernel(supp, nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
421
  vector<double> res(nval);
Martin Reinecke's avatar
Martin Reinecke committed
422
423
424
425
426
427
428
429
430
431
432
433
434
435
  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); }
436
437
438
439
440
441
442
  void Flip() { u=-u; v=-v; w=-w; }
  bool FixW()
    {
    bool flip = w<0;
    if (flip) Flip();
    return flip;
    }
Martin Reinecke's avatar
Martin Reinecke committed
443
444
445
446
447
  };

template<typename T> class Baselines
  {
  protected:
Martin Reinecke's avatar
Martin Reinecke committed
448
449
    vector<UVW<T>> coord;
    vector<T> f_over_c;
Martin Reinecke's avatar
Martin Reinecke committed
450
    size_t nrows, nchan;
451
    size_t shift, mask;
Martin Reinecke's avatar
Martin Reinecke committed
452
453

  public:
Martin Reinecke's avatar
updates    
Martin Reinecke committed
454
    Baselines(const const_mav<T,2> &coord_, const const_mav<T,1> &freq)
Martin Reinecke's avatar
Martin Reinecke committed
455
456
457
458
459
      {
      constexpr double speedOfLight = 299792458.;
      myassert(coord_.shape(1)==3, "dimension mismatch");
      nrows = coord_.shape(0);
      nchan = freq.shape(0);
460
461
462
      shift=0;
      while((size_t(1)<<shift)<nchan) ++shift;
      mask=(size_t(1)<<shift)-1;
Martin Reinecke's avatar
Martin Reinecke committed
463
464
465
      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)
466
467
        {
        myassert(freq[i]>0, "negative channel frequency encountered");
Martin Reinecke's avatar
Martin Reinecke committed
468
        f_over_c[i] = freq(i)/speedOfLight;
469
        }
Martin Reinecke's avatar
Martin Reinecke committed
470
471
472
473
474
      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
475
    RowChan getRowChan(uint32_t index) const
476
      { return RowChan{index>>shift, index&mask}; }
Martin Reinecke's avatar
Martin Reinecke committed
477
478
479
480
481

    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
482
483
    size_t Nrows() const { return nrows; }
    size_t Nchannels() const { return nchan; }
484
485
    uint32_t getIdx(size_t irow, size_t ichan) const
      { return ichan+(irow<<shift); }
Martin Reinecke's avatar
Martin Reinecke committed
486

Martin Reinecke's avatar
Martin Reinecke committed
487
    void effectiveUVW(const mav<const uint32_t,1> &idx, mav<T,2> &res) const
Martin Reinecke's avatar
Martin Reinecke committed
488
489
490
491
492
493
494
495
496
497
498
499
500
      {
      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
501
    template<typename T2> void ms2vis(const mav<const T2,2> &ms,
Martin Reinecke's avatar
Martin Reinecke committed
502
      const mav<const uint32_t,1> &idx, mav<T2,1> &vis, size_t nthreads) const
Martin Reinecke's avatar
Martin Reinecke committed
503
504
505
506
507
508
509
510
      {
      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
511
512
        auto rc = getRowChan(idx(i));
        vis[i] = ms(rc.row, rc.chan);
Martin Reinecke's avatar
Martin Reinecke committed
513
514
515
        }
      }

Martin Reinecke's avatar
Martin Reinecke committed
516
    template<typename T2> void vis2ms(const mav<const T2,1> &vis,
Martin Reinecke's avatar
Martin Reinecke committed
517
      const mav<const uint32_t,1> &idx, mav<T2,2> &ms, size_t nthreads) const
Martin Reinecke's avatar
Martin Reinecke committed
518
519
520
521
522
523
524
525
      {
      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
526
527
        auto rc = getRowChan(idx(i));
        ms(rc.row, rc.chan) += vis(i);
Martin Reinecke's avatar
Martin Reinecke committed
528
529
530
531
532
533
534
535
        }
      }
  };

template<typename T> class GridderConfig
  {
  protected:
    size_t nx_dirty, ny_dirty;
Martin Reinecke's avatar
Martin Reinecke committed
536
    double eps, psx, psy;
Martin Reinecke's avatar
Martin Reinecke committed
537
    size_t supp, nsafe, nu, nv;
Martin Reinecke's avatar
Martin Reinecke committed
538
539
    double beta;
    vector<double> cfu, cfv;
Martin Reinecke's avatar
Martin Reinecke committed
540
    size_t nthreads;
Martin Reinecke's avatar
Martin Reinecke committed
541

Martin Reinecke's avatar
Martin Reinecke committed
542
    complex<T> wscreen(double x, double y, double w, bool adjoint) const
Martin Reinecke's avatar
Martin Reinecke committed
543
544
      {
      constexpr double pi = 3.141592653589793238462643383279502884197;
545
546
547
      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
548
549
550
551
552
553
554
555
      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,
Martin Reinecke's avatar
Martin Reinecke committed
556
      double pixsize_x, double pixsize_y, size_t nthreads_)
Martin Reinecke's avatar
Martin Reinecke committed
557
558
      : nx_dirty(nxdirty), ny_dirty(nydirty), eps(epsilon),
        psx(pixsize_x), psy(pixsize_y),
Martin Reinecke's avatar
Martin Reinecke committed
559
        supp(ES_Kernel::get_supp(epsilon)), nsafe((supp+1)/2),
Martin Reinecke's avatar
Martin Reinecke committed
560
        nu(max(2*nsafe,2*nx_dirty)), nv(max(2*nsafe,2*ny_dirty)),
Martin Reinecke's avatar
Martin Reinecke committed
561
        beta(2.3*supp),
Martin Reinecke's avatar
Martin Reinecke committed
562
        cfu(nx_dirty), cfv(ny_dirty), nthreads(nthreads_)
Martin Reinecke's avatar
Martin Reinecke committed
563
564
565
566
567
568
569
      {
      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");

Martin Reinecke's avatar
Martin Reinecke committed
570
      auto tmp = correction_factors(nu, nx_dirty/2+1, supp, nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
571
572
573
574
      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];
Martin Reinecke's avatar
Martin Reinecke committed
575
      tmp = correction_factors(nv, ny_dirty/2+1, supp, nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
576
577
578
579
580
581
582
583
584
585
586
587
588
589
      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; }
Martin Reinecke's avatar
Martin Reinecke committed
590
    double Beta() const { return beta; }
Martin Reinecke's avatar
Martin Reinecke committed
591
    size_t Nthreads() const { return nthreads; }
Martin Reinecke's avatar
Martin Reinecke committed
592

Martin Reinecke's avatar
Martin Reinecke committed
593
    void apply_taper(const mav<const T,2> &img, mav<T,2> &img2, bool divide) const
Martin Reinecke's avatar
Martin Reinecke committed
594
      {
Martin Reinecke's avatar
Martin Reinecke committed
595
596
      checkShape(img.shape(), {nx_dirty, ny_dirty});
      checkShape(img2.shape(), {nx_dirty, ny_dirty});
Martin Reinecke's avatar
Martin Reinecke committed
597
598
599
      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
600
            img2(i,j) = img(i,j)/(cfu[i]*cfv[j]);
Martin Reinecke's avatar
Martin Reinecke committed
601
602
603
      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
604
            img2(i,j) = img(i,j)*cfu[i]*cfv[j];
Martin Reinecke's avatar
Martin Reinecke committed
605
606
      }

607
608
609
610
611
612
613
614
615
616
617
618
619
620
    void grid2dirty(const const_mav<T,2> &grid, const mav<T,2> &dirty) const
      {
      checkShape(grid.shape(), {nu,nv});
      checkShape(dirty.shape(), {nx_dirty,ny_dirty});
      tmpStorage<T,2> tmpdat({nu,nv});
      auto tmav = tmpdat.getMav();
      hartley2_2D<T>(grid, tmav, nthreads);
      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
621
          dirty(i,j) = tmav(i2,j2)*T(cfu[i]*cfv[j]);
622
623
624
          }
      }

Martin Reinecke's avatar
Martin Reinecke committed
625
    void grid2dirty_c(const mav<const complex<T>,2> &grid, mav<complex<T>,2> &dirty) const
Martin Reinecke's avatar
Martin Reinecke committed
626
      {
Martin Reinecke's avatar
Martin Reinecke committed
627
628
      checkShape(grid.shape(), {nu,nv});
      checkShape(dirty.shape(), {nx_dirty,ny_dirty});
629
630
      tmpStorage<complex<T>,2> tmpdat({nu,nv});
      auto tmp = tmpdat.getMav();
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
631
      constexpr auto sc = ptrdiff_t(sizeof(complex<T>));
Martin Reinecke's avatar
Martin Reinecke committed
632
633
634
      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
635
636
637
638
639
640
641
      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
642
          dirty(i,j) = tmp(i2,j2)*T(cfu[i]*cfv[j]);
Martin Reinecke's avatar
Martin Reinecke committed
643
644
          }
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
645

646
647
648
649
650
651
652
653
654
655
656
657
    void dirty2grid(const const_mav<T,2> &dirty, mav<T,2> &grid) const
      {
      checkShape(dirty.shape(), {nx_dirty, ny_dirty});
      checkShape(grid.shape(), {nu, nv});
      grid.fill(0);
      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
658
          grid(i2,j2) = dirty(i,j)*T(cfu[i]*cfv[j]);
659
          }
Martin Reinecke's avatar
Martin Reinecke committed
660
      hartley2_2D<T>(cmav(grid), grid, nthreads);
661
662
      }

Martin Reinecke's avatar
updates    
Martin Reinecke committed
663
664
    void dirty2grid_c(const const_mav<complex<T>,2> &dirty,
      mav<complex<T>,2> &grid) const
Martin Reinecke's avatar
Martin Reinecke committed
665
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
666
667
      checkShape(dirty.shape(), {nx_dirty, ny_dirty});
      checkShape(grid.shape(), {nu, nv});
668
      grid.fill(0);
Martin Reinecke's avatar
Martin Reinecke committed
669
670
671
672
673
674
675
      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
676
          grid(i2,j2) = dirty(i,j)*T(cfu[i]*cfv[j]);
Martin Reinecke's avatar
Martin Reinecke committed
677
          }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
678
      constexpr auto sc = ptrdiff_t(sizeof(complex<T>));
Martin Reinecke's avatar
updates    
Martin Reinecke committed
679
      pocketfft::stride_t strides{grid.stride(0)*sc,grid.stride(1)*sc};
Martin Reinecke's avatar
Martin Reinecke committed
680
      pocketfft::c2c({nu,nv}, strides, strides, {0,1}, pocketfft::FORWARD,
Martin Reinecke's avatar
updates    
Martin Reinecke committed
681
        grid.data(), grid.data(), T(1), nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
682
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
683

Martin Reinecke's avatar
Martin Reinecke committed
684
    void getpix(T u_in, T v_in, T &u, T &v, int &iu0, int &iv0) const
Martin Reinecke's avatar
Martin Reinecke committed
685
      {
Martin Reinecke's avatar
Martin Reinecke committed
686
      u=fmod1(u_in*psx)*nu,
Martin Reinecke's avatar
Martin Reinecke committed
687
      iu0 = int(u-supp*0.5 + 1 + nu) - nu;
Martin Reinecke's avatar
Martin Reinecke committed
688
      iu0 = min<int>(iu0, (nu+nsafe)-supp);
Martin Reinecke's avatar
Martin Reinecke committed
689
      v=fmod1(v_in*psy)*nv;
Martin Reinecke's avatar
Martin Reinecke committed
690
      iv0 = int(v-supp*0.5 + 1 + nv) - nv;
Martin Reinecke's avatar
Martin Reinecke committed
691
      iv0 = min<int>(iv0, (nv+nsafe)-supp);
Martin Reinecke's avatar
Martin Reinecke committed
692
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
693
694
695

    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
696
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
697
698
      checkShape(dirty.shape(), {nx_dirty, ny_dirty});
      checkShape(dirty2.shape(), {nx_dirty, ny_dirty});
Martin Reinecke's avatar
Martin Reinecke committed
699
700
      double x0 = -0.5*nx_dirty*psx,
             y0 = -0.5*ny_dirty*psy;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
701
#pragma omp parallel for num_threads(nthreads) schedule(static)
Martin Reinecke's avatar
Martin Reinecke committed
702
703
704
705
706
707
708
709
      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
710
          dirty2(i,j) = dirty(i,j)*ws; // lower left
Martin Reinecke's avatar
Martin Reinecke committed
711
712
713
          size_t i2 = nx_dirty-i, j2 = ny_dirty-j;
          if ((i>0)&&(i<i2))
            {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
714
            dirty2(i2,j) = dirty(i2,j)*ws; // lower right
Martin Reinecke's avatar
Martin Reinecke committed
715
            if ((j>0)&&(j<j2))
Martin Reinecke's avatar
updates    
Martin Reinecke committed
716
              dirty2(i2,j2) = dirty(i2,j2)*ws; // upper right
Martin Reinecke's avatar
Martin Reinecke committed
717
718
            }
          if ((j>0)&&(j<j2))
Martin Reinecke's avatar
updates    
Martin Reinecke committed
719
            dirty2(i,j2) = dirty(i,j2)*ws; // upper left
Martin Reinecke's avatar
Martin Reinecke committed
720
721
722
723
724
725
726
          }
        }
      }
  };

constexpr int logsquare=4;

Martin Reinecke's avatar
Martin Reinecke committed
727
template<typename T, typename T2=complex<T>> class Helper
Martin Reinecke's avatar
Martin Reinecke committed
728
729
730
731
732
733
734
735
736
737
738
  {
  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
739
    vector<T2> rbuf, wbuf;
Martin Reinecke's avatar
Martin Reinecke committed
740
741
742
    bool do_w_gridding;
    T w0, xdw;
    size_t nexp;
743
    size_t nvecs;
Martin Reinecke's avatar
Martin Reinecke committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784

    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
785
    T kernel[64] ALIGNED(64);
Martin Reinecke's avatar
Martin Reinecke committed
786

Martin Reinecke's avatar
Martin Reinecke committed
787
788
    Helper(const GridderConfig<T> &gconf_, const T2 *grid_r_, T2 *grid_w_,
      T w0_=-1, T dw_=-1)
Martin Reinecke's avatar
Martin Reinecke committed
789
790
791
792
793
794
      : 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)),
Martin Reinecke's avatar
Martin Reinecke committed
795
796
797
798
799
        do_w_gridding(dw_>0),
        w0(w0_),
        xdw(T(1)/dw_),
        nexp(2*supp + do_w_gridding),
        nvecs(VLEN<T>::val*((nexp+VLEN<T>::val-1)/VLEN<T>::val))
Martin Reinecke's avatar
Martin Reinecke committed
800
801
802
803
      {}
    ~Helper() { if (grid_w) dump(); }

    int lineJump() const { return sv; }
Martin Reinecke's avatar
Martin Reinecke committed
804
    T Wfac() const { return kernel[2*supp]; }
Martin Reinecke's avatar
Martin Reinecke committed
805
    void prep(const UVW<T> &in)
Martin Reinecke's avatar
Martin Reinecke committed
806
807
      {
      T u, v;
Martin Reinecke's avatar
Martin Reinecke committed
808
      gconf.getpix(in.u, in.v, u, v, iu0, iv0);
Martin Reinecke's avatar
Martin Reinecke committed
809
810
811
812
813
      T xsupp=T(2)/supp;
      auto x0 = xsupp*(iu0-u);
      auto y0 = xsupp*(iv0-v);
      for (int i=0; i<supp; ++i)
        {
Martin Reinecke's avatar
Martin Reinecke committed
814
815
        kernel[i  ] = x0+i*xsupp;
        kernel[i+supp] = y0+i*xsupp;
Martin Reinecke's avatar
Martin Reinecke committed
816
        }
Martin Reinecke's avatar
Martin Reinecke committed
817
      if (do_w_gridding)
Martin Reinecke's avatar
Martin Reinecke committed
818
        kernel[2*supp] = min(T(1), xdw*xsupp*abs(w0-in.w));
Martin Reinecke's avatar
Martin Reinecke committed
819
      for (size_t i=nexp; i<nvecs; ++i)
820
821
        kernel[i]=0;
      for (size_t i=0; i<nvecs; ++i)
Martin Reinecke's avatar
Martin Reinecke committed
822
        kernel[i] = exp(beta*(sqrt(T(1)-kernel[i]*kernel[i])-T(1)));
Martin Reinecke's avatar
Martin Reinecke committed
823
824
825
826
827
828
829
830
831
832
833
834
      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;
      }
  };

835
template<class T, class T2, class T3> class VisServ
Martin Reinecke's avatar
updates    
Martin Reinecke committed
836
  {
837
838
839
840
841
842
843
  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
844

845
846
847
  public:
    VisServ(const Baselines<T> &baselines_,
      const const_mav<uint32_t,1> &idx_, T2 vis_, const T3 &wgt_)
Martin Reinecke's avatar
Martin Reinecke committed
848
849
      : baselines(baselines_), idx(idx_), vis(vis_), wgt(wgt_),
        nvis(vis.shape(0)), have_wgt(wgt.size()!=0)
850
851
852
853
854
      {
      checkShape(idx.shape(), {nvis});
      if (have_wgt) checkShape(wgt.shape(), {nvis});
      }
    size_t Nvis() const { return nvis; }
855
    const Baselines<T> &getBaselines() const { return baselines; }
856
857
858
859
860
861
862
863
864
865
    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; }
  };
Martin Reinecke's avatar
Martin Reinecke committed
866
867
868
869
template<class T, class T2, class T3> VisServ<T,T2,T3> makeVisServ
  (const Baselines<T> &baselines,
   const const_mav<uint32_t,1> &idx, T2 vis, const T3 &wgt)
  { return VisServ<T,T2,T3>(baselines, idx, vis, wgt); }
870
871
872
873
874
875
876
877
878
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
879

880
881
882
  public:
    MsServ(const Baselines<T> &baselines_,
    const const_mav<uint32_t,1> &idx_, T2 ms_, const T3 &wgt_)
Martin Reinecke's avatar
Martin Reinecke committed
883
884
      : baselines(baselines_), idx(idx_), ms(ms_), wgt(wgt_),
        nvis(idx.shape(0)), have_wgt(wgt.size()!=0)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
885
      {
Martin Reinecke's avatar
Martin Reinecke committed
886
887
      checkShape(ms.shape(), {baselines.Nrows(), baselines.Nchannels()});
      if (have_wgt) checkShape(wgt.shape(), ms.shape());
Martin Reinecke's avatar
updates    
Martin Reinecke committed
888
      }
Martin Reinecke's avatar
Martin Reinecke committed
889
890
    MsServ(const MsServ &orig, const const_mav<uint32_t,1> &newidx)
      : MsServ(orig.baselines, newidx, orig.ms, orig.wgt) {}
891
    size_t Nvis() const { return nvis; }
892
    const Baselines<T> &getBaselines() const { return baselines; }
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
    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
Martin Reinecke committed
913
914
915
916
template<class T, class T2, class T3> MsServ<T,T2,T3> makeMsServ
  (const Baselines<T> &baselines,
   const const_mav<uint32_t,1> &idx, T2 ms, const T3 &wgt)
  { return MsServ<T,T2,T3>(baselines, idx, ms, wgt); }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
917

918
template<typename T, typename Serv> void x2grid_c
Martin Reinecke's avatar
Martin Reinecke committed
919
920
  (const GridderConfig<T> &gconf, const Serv &srv, mav<complex<T>,2> &grid,
  T w0=-1, T dw=-1)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
921
  {
Martin Reinecke's avatar
Martin Reinecke committed
922
  checkShape(grid.shape(), {gconf.Nu(), gconf.Nv()});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
923
924
  myassert(grid.contiguous(), "grid is not contiguous");
  size_t supp = gconf.Supp();
Martin Reinecke's avatar
Martin Reinecke committed
925
  size_t nthreads = gconf.Nthreads();
Martin Reinecke's avatar
Martin Reinecke committed
926
  bool do_w_gridding = dw>0;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
927
928
929

#pragma omp parallel num_threads(nthreads)
{
Martin Reinecke's avatar
Martin Reinecke committed
930
  Helper<T> hlp(gconf, nullptr, grid.data(), w0, dw);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
931
  int jump = hlp.lineJump();
Martin Reinecke's avatar
Martin Reinecke committed
932
933
  const T * RESTRICT ku = hlp.kernel;
  const T * RESTRICT kv = hlp.kernel+supp;
934
  size_t np = srv.Nvis();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
935
936
937

  // Loop over sampling points
#pragma omp for schedule(guided,100)
938
  for (size_t ipart=0; ipart<np; ++ipart)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
939
    {
940
    UVW<T> coord = srv.getCoord(ipart);
941
    auto flip = coord.FixW();
Martin Reinecke's avatar
Martin Reinecke committed
942
    hlp.prep(coord);
Martin Reinecke's avatar
Martin Reinecke committed
943
    auto * RESTRICT ptr = hlp.p0w;
Martin Reinecke's avatar
Martin Reinecke committed
944
945
    auto v(srv.getVis(ipart));
    if (do_w_gridding) v*=hlp.Wfac();
946
    if (flip) v=conj(v);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
947
948
949
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(v*ku[cu]);
Martin Reinecke's avatar
Martin Reinecke committed
950
951
952
953
954
955
956
957
958
      size_t cv=0;
      for (; cv<supp-3; cv+=4)
        {
        ptr[cv  ] += tmp*kv[cv  ];
        ptr[cv+1] += tmp*kv[cv+1];
        ptr[cv+2] += tmp*kv[cv+2];
        ptr[cv+3] += tmp*kv[cv+3];
        }
      for (; cv<supp; ++cv)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
959
960
961
962
963
964
965
        ptr[cv] += tmp*kv[cv];
      ptr+=jump;
      }
    }
} // end of parallel region
  }

966
template<typename T> void vis2grid_c
Martin Reinecke's avatar
updates    
Martin Reinecke committed
967
  (const Baselines<T> &baselines, const GridderConfig<T> &gconf,
968
  const const_mav<uint32_t,1> &idx, const const_mav<complex<T>,1> &vis,
Martin Reinecke's avatar
Martin Reinecke committed
969
  mav<complex<T>,2> &grid, const const_mav<T,1> &wgt, T w0=-1, T dw=-1)
Martin Reinecke's avatar
Martin Reinecke committed
970
  { x2grid_c(gconf, makeVisServ(baselines, idx, vis, wgt), grid, w0, dw); }
971
972
973
974
975

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)
Martin Reinecke's avatar
Martin Reinecke committed
976
  { x2grid_c(gconf, makeMsServ(baselines, idx, ms, wgt), grid); }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
977

978
template<typename T, typename Serv> void grid2x_c
Martin Reinecke's avatar
Martin Reinecke committed
979
980
  (const GridderConfig<T> &gconf, const const_mav<complex<T>,2> &grid,
  const Serv &srv, T w0=-1, T dw=-1)
981
  {
Martin Reinecke's avatar
Martin Reinecke committed
982
  checkShape(grid.shape(), {gconf.Nu(), gconf.Nv()});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
983
984
  myassert(grid.contiguous(), "grid is not contiguous");
  size_t supp = gconf.Supp();
Martin Reinecke's avatar
Martin Reinecke committed
985
  size_t nthreads = gconf.Nthreads();
Martin Reinecke's avatar
Martin Reinecke committed
986
  bool do_w_gridding = dw>0;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
987
988
989
990

  // Loop over sampling points
#pragma omp parallel num_threads(nthreads)
{
Martin Reinecke's avatar
Martin Reinecke committed
991
  Helper<T> hlp(gconf, grid.data(), nullptr, w0, dw);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
992
  int jump = hlp.lineJump();
Martin Reinecke's avatar
Martin Reinecke committed
993
994
  const T * RESTRICT ku = hlp.kernel;
  const T * RESTRICT kv = hlp.kernel+supp;
995
  size_t np = srv.Nvis();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
996
997

#pragma omp for schedule(guided,100)
998
  for (size_t ipart=0; ipart<np; ++ipart)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
999
    {
1000
    UVW<T> coord = srv.getCoord(ipart);
1001
    auto flip = coord.FixW();
Martin Reinecke's avatar
Martin Reinecke committed
1002
    hlp.prep(coord);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1003
    complex<T> r = 0;
Martin Reinecke's avatar
Martin Reinecke committed
1004
    const auto * RESTRICT ptr = hlp.p0r;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1005
1006
1007
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(0);
Martin Reinecke's avatar
Martin Reinecke committed
1008
1009
1010
1011
1012
1013
1014
      size_t cv=0;
      for (; cv<supp-3; cv+=4)
        tmp += ptr[cv  ]*kv[cv  ]
             + ptr[cv+1]*kv[cv+1]
             + ptr[cv+2]*kv[cv+2]
             + ptr[cv+3]*kv[cv+3];
      for (; cv<supp; ++cv)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1015
1016
1017
1018
        tmp += ptr[cv] * kv[cv];
      r += tmp*ku[cu];
      ptr += jump;
      }
1019
    if (flip) r=conj(r);
Martin Reinecke's avatar
Martin Reinecke committed
1020
1021
    if (do_w_gridding) r*=hlp.Wfac();
    srv.setVis(ipart, r);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1022
1023
1024
    }
}
  }
1025
1026
1027
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,
Martin Reinecke's avatar
Martin Reinecke committed
1028
  mav<complex<T>,1> &vis, const const_mav<T,1> &wgt, T w0=-1, T dw=-1)
Martin Reinecke's avatar
Martin Reinecke committed
1029
  { grid2x_c(gconf, grid, makeVisServ(baselines, idx, vis, wgt), w0, dw); }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1030
1031
1032
1033
1034

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)
Martin Reinecke's avatar
Martin Reinecke committed
1035
  { grid2x_c(gconf, grid, makeMsServ(baselines, idx, ms, wgt)); }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1036

Martin Reinecke's avatar
Martin Reinecke committed
1037
1038
1039
1040
1041
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)
  {
Martin Reinecke's avatar
Martin Reinecke committed
1042
  checkShape(grid.shape(), {gconf.Nu(), gconf.Nv()});
Martin Reinecke's avatar
Martin Reinecke committed
1043
  size_t nvis = idx.shape(0);
Martin Reinecke's avatar
Martin Reinecke committed
1044
  size_t nthreads = gconf.Nthreads();
Martin Reinecke's avatar
Martin Reinecke committed
1045
1046
  bool have_wgt = wgt.size()!=0;
  if (have_wgt) checkShape(wgt.shape(), {nvis});
Martin Reinecke's avatar
Martin Reinecke committed
1047
  checkShape(ogrid.shape(), grid.shape());
Martin Reinecke's avatar
Martin Reinecke committed
1048
  ogrid.fill(0);
Martin Reinecke's avatar
Martin Reinecke committed
1049
1050
1051
1052
1053
1054
1055
  size_t supp = gconf.Supp();

  // Loop over sampling points
#pragma omp parallel num_threads(nthreads)
{
  Helper<T> hlp(gconf, grid.data(), ogrid.data());
  int jump = hlp.lineJump();
Martin Reinecke's avatar
Martin Reinecke committed
1056
1057
  const T * RESTRICT ku = hlp.kernel;
  const T * RESTRICT kv = hlp.kernel+supp;
Martin Reinecke's avatar
Martin Reinecke committed
1058
1059
1060
1061

#pragma omp for schedule(guided,100)
  for (size_t ipart=0; ipart<nvis; ++ipart)
    {
1062
    UVW<T> coord = baselines.effectiveCoord(idx(ipart));
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
1063
    coord.FixW();
Martin Reinecke's avatar
Martin Reinecke committed
1064
    hlp.prep(coord);
Martin Reinecke's avatar
Martin Reinecke committed
1065
    complex<T> r = 0;
Martin Reinecke's avatar
Martin Reinecke committed
1066
    const auto * RESTRICT ptr = hlp.p0r;
Martin Reinecke's avatar
Martin Reinecke committed
1067
1068
1069
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(0);
Martin Reinecke's avatar
Martin Reinecke committed
1070
1071
1072
1073
1074
1075
1076
      size_t cv=0;
      for (;cv<supp-3; cv+=4)
        tmp += ptr[cv  ]*kv[cv  ]
              +ptr[cv+1]*kv[cv+1]
              +ptr[cv+2]*kv[cv+2]
              +ptr[cv+3]*kv[cv+3];
      for (; cv<supp; ++cv)
Martin Reinecke's avatar
Martin Reinecke committed
1077
1078
1079
1080
1081
1082
1083
1084
1085
        tmp += ptr[cv] * kv[cv];
      r += tmp*ku[cu];
      ptr += jump;
      }
    if (have_wgt)
      {
      auto twgt = wgt(ipart);
      r*=twgt*twgt;
      }
Martin Reinecke's avatar
Martin Reinecke committed
1086
    auto * RESTRICT wptr = hlp.p0w;
Martin Reinecke's avatar
Martin Reinecke committed
1087
1088
1089
    for (size_t cu=0; cu<supp; ++cu)
      {
      complex<T> tmp(r*ku[cu]);
Martin Reinecke's avatar
Martin Reinecke committed
1090
1091
1092
1093
1094
1095
1096
1097
1098
      size_t cv=0;
      for (;cv<supp-3; cv+=4)
        {
        wptr[cv  ] += tmp*kv[cv  ];
        wptr[cv+1] += tmp*kv[cv+1];
        wptr[cv+2] += tmp*kv[cv+2];
        wptr[cv+3] += tmp*kv[cv+3];
        }
      for (; cv<supp; ++cv)
Martin Reinecke's avatar
Martin Reinecke committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
        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 nvis = idx.shape(0);
  bool have_wgt = wgt.size()!=0;
  if (have_wgt) checkShape(wgt.shape(), {nvis});
Martin Reinecke's avatar
Martin Reinecke committed
1114
  checkShape(ogrid.shape(), {gconf.Nu(), gconf.Nv()});
Martin Reinecke's avatar
Martin Reinecke committed
1115
1116
1117
  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");
Martin Reinecke's avatar
Martin Reinecke committed
1118
  size_t nthreads = gconf.Nthreads();
Martin Reinecke's avatar
Martin Reinecke committed
1119
  ogrid.fill(0);
Martin Reinecke's avatar
Martin Reinecke committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134