nifty_gridder.cc 30 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
/*
 *  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_fridder; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

Martin Reinecke's avatar
import  
Martin Reinecke committed
19
20
21
22
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <iostream>
#include <algorithm>
Martin Reinecke's avatar
updates    
Martin Reinecke committed
23
#include "pocketfft_hdronly.h"
Martin Reinecke's avatar
import  
Martin Reinecke committed
24

Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
25
26
#ifdef __GNUC__
#define RESTRICT __restrict__
Martin Reinecke's avatar
Martin Reinecke committed
27
#define NOINLINE __attribute__ ((noinline))
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
28
29
30
31
#else
#define RESTRICT
#endif

Martin Reinecke's avatar
import  
Martin Reinecke committed
32
33
34
35
36
37
using namespace std;

namespace py = pybind11;

namespace {

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
38
39
40
41
//
// basic utilities
//

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
void myassert(bool cond, const char *msg)
  {
  if (cond) return;
  throw runtime_error(msg);
  }

/*! Returns the largest integer \a n that fulfills \a 2^n<=arg. */
template<typename I> inline int ilog2 (I arg)
  {
#ifdef __GNUC__
  if (arg==0) return 0;
  if (sizeof(I)==sizeof(int))
    return 8*sizeof(int)-1-__builtin_clz(arg);
  if (sizeof(I)==sizeof(long))
    return 8*sizeof(long)-1-__builtin_clzl(arg);
  if (sizeof(I)==sizeof(long long))
    return 8*sizeof(long long)-1-__builtin_clzll(arg);
#endif
  int res=0;
  while (arg > 0xFFFF) { res+=16; arg>>=16; }
  if (arg > 0x00FF) { res|=8; arg>>=8; }
  if (arg > 0x000F) { res|=4; arg>>=4; }
  if (arg > 0x0003) { res|=2; arg>>=2; }
  if (arg > 0x0001) { res|=1; }
  return res;
  }

/*! Returns the number of bits needed to represent \a arg different values.
    \a arg must be >=1. */
template<typename I> inline int bits_needed (I arg)
  {
  myassert(arg>=1, "argument must be >=1");
  if (arg==1) return 0;
  return ilog2(arg-1)+1;
  }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
77
78
79
80
81
82
83
84
85
86
87
88

/*! 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;
  }

Martin Reinecke's avatar
Martin Reinecke committed
89
90
91
//
// Utilities for converting between Cartesian coordinates and Peano index
//
Martin Reinecke's avatar
import  
Martin Reinecke committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

static const uint16_t utab[] = {
#define Z(a) 0x##a##0, 0x##a##1, 0x##a##4, 0x##a##5
#define Y(a) Z(a##0), Z(a##1), Z(a##4), Z(a##5)
#define X(a) Y(a##0), Y(a##1), Y(a##4), Y(a##5)
X(0),X(1),X(4),X(5)
#undef X
#undef Y
#undef Z
};

uint32_t coord2morton2D_32 (uint32_t x, uint32_t y)
  {
  typedef uint32_t I;
  return  (I)(utab[x&0xff])     | ((I)(utab[(x>>8)&0xff])<<16)
       | ((I)(utab[y&0xff])<<1) | ((I)(utab[(y>>8)&0xff])<<17);
  }

static const uint8_t m2p2D_1[4][4] = {
{ 4, 1, 11, 2},{0,15, 5, 6},{10,9,3,12},{14,7,13,8}};
static uint8_t m2p2D_3[4][64];
static const uint8_t p2m2D_1[4][4] = {
{ 4, 1, 3, 10},{0,6,7,13},{15,9,8,2},{11,14,12,5}};
static uint8_t p2m2D_3[4][64];
static int peano2d_done=0;

static void init_peano2d (void)
  {
  peano2d_done=1;

  for (int d=0; d<4; ++d)
    for (uint32_t p=0; p<64; ++p)
      {
      unsigned rot = d;
      uint32_t v = p<<26;
      uint32_t res = 0;
      for (int i=0; i<3; ++i)
        {
        unsigned tab=m2p2D_1[rot][v>>30];
        v<<=2;
        res = (res<<2) | (tab&0x3);
        rot = tab>>2;
        }
      m2p2D_3[d][p]=res|(rot<<6);
      }
  for (int d=0; d<4; ++d)
    for (uint32_t p=0; p<64; ++p)
      {
      unsigned rot = d;
      uint32_t v = p<<26;
      uint32_t res = 0;
      for (int i=0; i<3; ++i)
        {
        unsigned tab=p2m2D_1[rot][v>>30];
        v<<=2;
        res = (res<<2) | (tab&0x3);
        rot = tab>>2;
        }
      p2m2D_3[d][p]=res|(rot<<6);
      }
  }

uint32_t morton2peano2D_32(uint32_t v, int bits)
  {
  if (!peano2d_done) init_peano2d();
  unsigned rot = 0;
  uint32_t res = 0;
  v<<=32-(bits<<1);
  int i=0;
  for (; i<bits-2; i+=3)
    {
    unsigned tab=m2p2D_3[rot][v>>26];
    v<<=6;
    res = (res<<6) | (tab&0x3fu);
    rot = tab>>6;
    }
  for (; i<bits; ++i)
    {
    unsigned tab=m2p2D_1[rot][v>>30];
    v<<=2;
    res = (res<<2) | (tab&0x3);
    rot = tab>>2;
    }
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
178
179
180
181
//
// Utilities for indirect sorting (argsort)
//

Martin Reinecke's avatar
import  
Martin Reinecke committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
template<typename It, typename Comp> class IdxComp__
  {
  private:
    It begin;
    Comp comp;
  public:
    IdxComp__ (It begin_, Comp comp_): begin(begin_), comp(comp_) {}
    bool operator() (std::size_t a, std::size_t b) const
      { return comp(*(begin+a),*(begin+b)); }
  };
/*! Performs an indirect sort on the supplied iterator range and returns in
    \a idx a \a vector containing the indices of the smallest, second smallest,
    third smallest, etc. element, according to \a comp. */
template<typename It, typename T2, typename Comp>
  inline void buildIndex (It begin, It end, std::vector<T2> &idx, Comp comp)
  {
  using namespace std;
  T2 num=end-begin;
  idx.resize(num);
  for (T2 i=0; i<num; ++i) idx[i] = i;
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
202
  sort (idx.begin(),idx.end(),IdxComp__<It,Comp>(begin,comp));
Martin Reinecke's avatar
import  
Martin Reinecke committed
203
204
205
206
207
208
209
210
211
212
213
214
215
  }

/*! Performs an indirect sort on the supplied iterator range and returns in
    \a idx a \a vector containing the indices of the smallest, second smallest,
    third smallest, etc. element. */
template<typename It, typename T2> inline void buildIndex (It begin, It end,
  std::vector<T2> &idx)
  {
  using namespace std;
  typedef typename iterator_traits<It>::value_type T;
  buildIndex(begin,end,idx,less<T>());
  }

Martin Reinecke's avatar
Martin Reinecke committed
216
217
218
219
//
// Utilities for Gauss-Legendre quadrature
//

Martin Reinecke's avatar
Martin Reinecke committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
static inline double one_minus_x2 (double x)
  { return (fabs(x)>0.1) ? (1.+x)*(1.-x) : 1.-x*x; }

void legendre_prep(int n, vector<double> &x, vector<double> &w)
  {
  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
{
  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;
      if (++j>=100) throw runtime_error("convergence problem");
      }

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

Martin Reinecke's avatar
Martin Reinecke committed
277
278
279
280
//
// Start of real gridder functionality
//

281
282
283
284
template<typename T>
  using pyarr = py::array_t<T>;
template<typename T>
  using pyarr_c = py::array_t<T, py::array::c_style | py::array::forcecast>;
Martin Reinecke's avatar
import  
Martin Reinecke committed
285

Martin Reinecke's avatar
updates    
Martin Reinecke committed
286
287
288
template<typename T> pyarr_c<T> makearray(const vector<size_t> &shape)
  { return pyarr_c<T>(shape); }

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
289
size_t get_w(double epsilon)
Martin Reinecke's avatar
Martin Reinecke committed
290
291
292
293
294
295
296
297
298
299
300
  {
  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;
  throw runtime_error("requested epsilon too small - minimum is 2e-13");
  }
Martin Reinecke's avatar
Martin Reinecke committed
301

Martin Reinecke's avatar
Martin Reinecke committed
302
303
template<typename T> pyarr_c<T> complex2hartley
  (const pyarr_c<complex<T>> &grid_)
Martin Reinecke's avatar
Martin Reinecke committed
304
305
  {
  myassert(grid_.ndim()==2, "grid array must be 2D");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
306
  size_t nu = size_t(grid_.shape(0)), nv = size_t(grid_.shape(1));
Martin Reinecke's avatar
Martin Reinecke committed
307
308
  auto grid = grid_.data();

Martin Reinecke's avatar
Martin Reinecke committed
309
  auto res = makearray<T>({nu,nv});
Martin Reinecke's avatar
Martin Reinecke committed
310
  auto grid2 = res.mutable_data();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
311
  for (size_t u=0; u<nu; ++u)
Martin Reinecke's avatar
Martin Reinecke committed
312
    {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
313
314
    size_t xu = (u==0) ? 0 : nu-u;
    for (size_t v=0; v<nv; ++v)
Martin Reinecke's avatar
Martin Reinecke committed
315
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
316
317
318
      size_t xv = (v==0) ? 0 : nv-v;
      size_t i1 = u*nv+v;
      size_t i2 = xu*nv+xv;
Martin Reinecke's avatar
Martin Reinecke committed
319
320
      grid2[i1] = T(0.5)*(grid[i1].real()+grid[i1].imag()+
                          grid[i2].real()-grid[i2].imag());
Martin Reinecke's avatar
Martin Reinecke committed
321
322
323
324
325
      }
    }
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
326
327
template<typename T> pyarr_c<complex<T>> hartley2complex
  (const pyarr_c<T> &grid_)
Martin Reinecke's avatar
Martin Reinecke committed
328
329
  {
  myassert(grid_.ndim()==2, "grid array must be 2D");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
330
  size_t nu = size_t(grid_.shape(0)), nv = size_t(grid_.shape(1));
Martin Reinecke's avatar
Martin Reinecke committed
331
332
  auto grid = grid_.data();

Martin Reinecke's avatar
Martin Reinecke committed
333
  auto res=makearray<complex<T>>({nu, nv});
Martin Reinecke's avatar
Martin Reinecke committed
334
  auto grid2 = res.mutable_data();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
335
  for (size_t u=0; u<nu; ++u)
Martin Reinecke's avatar
Martin Reinecke committed
336
    {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
337
338
    size_t xu = (u==0) ? 0 : nu-u;
    for (size_t v=0; v<nv; ++v)
Martin Reinecke's avatar
Martin Reinecke committed
339
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
340
341
342
      size_t xv = (v==0) ? 0 : nv-v;
      size_t i1 = u*nv+v;
      size_t i2 = xu*nv+xv;
Martin Reinecke's avatar
Martin Reinecke committed
343
344
345
      T v1 = T(0.5)*grid[i1];
      T v2 = T(0.5)*grid[i2];
      grid2[i1] = complex<T>(v1+v2, v1-v2);
Martin Reinecke's avatar
Martin Reinecke committed
346
347
348
349
350
351
352
      }
    }
  return res;
  }

/* 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
updates    
Martin Reinecke committed
353
vector<double> correction_factors (size_t n, size_t nval, size_t w)
Martin Reinecke's avatar
Martin Reinecke committed
354
355
356
357
358
359
360
361
362
363
  {
  constexpr double pi = 3.141592653589793238462643383279502884197;
  auto beta = 2.3*w;
  auto p = int(1.5*w+2);
  double alpha = pi*w/n;
  vector<double> x, wgt;
  legendre_prep(2*p,x,wgt);
  auto psi = x;
  for (auto &v:psi)
    v = exp(beta*(sqrt(1-v*v)-1.));
Martin Reinecke's avatar
updates    
Martin Reinecke committed
364
  vector<double> res(nval);
Martin Reinecke's avatar
Martin Reinecke committed
365
366
367
368
369
  for (size_t k=0; k<nval; ++k)
    {
    double tmp=0;
    for (int i=0; i<p; ++i)
      tmp += wgt[i]*psi[i]*cos(alpha*k*x[i]);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
370
    res[k] = 1./(w*tmp);
Martin Reinecke's avatar
Martin Reinecke committed
371
372
373
374
    }
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
375
template<typename T> struct UV
Martin Reinecke's avatar
Martin Reinecke committed
376
  {
Martin Reinecke's avatar
Martin Reinecke committed
377
  T u, v;
Martin Reinecke's avatar
Martin Reinecke committed
378
  UV () {}
Martin Reinecke's avatar
Martin Reinecke committed
379
380
  UV (T u_, T v_) : u(u_), v(v_) {}
  UV operator* (T fct) const
Martin Reinecke's avatar
Martin Reinecke committed
381
382
    { return UV(u*fct, v*fct); }
  };
Martin Reinecke's avatar
Martin Reinecke committed
383
template<typename T> struct UVW
Martin Reinecke's avatar
updates    
Martin Reinecke committed
384
  {
Martin Reinecke's avatar
Martin Reinecke committed
385
  T u, v, w;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
386
  UVW () {}
Martin Reinecke's avatar
Martin Reinecke committed
387
388
  UVW (T u_, T v_, T w_) : u(u_), v(v_), w(w_) {}
  UVW operator* (T fct) const
Martin Reinecke's avatar
updates    
Martin Reinecke committed
389
390
    { return UVW(u*fct, v*fct, w*fct); }
  };
Martin Reinecke's avatar
Martin Reinecke committed
391

Martin Reinecke's avatar
Martin Reinecke committed
392
template<typename T> class Baselines
Martin Reinecke's avatar
Martin Reinecke committed
393
394
  {
  private:
Martin Reinecke's avatar
Martin Reinecke committed
395
396
    vector<UVW<T>> coord;
    vector<T> scaling;
Martin Reinecke's avatar
Martin Reinecke committed
397
    vector<bool> flags;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
398
    size_t nrows, nchan;
Martin Reinecke's avatar
Martin Reinecke committed
399
400
401
    size_t channelbits, channelmask;

  public:
Martin Reinecke's avatar
Martin Reinecke committed
402
403
    Baselines(const pyarr_c<T> &coord_, const pyarr_c<T> &scaling_,
       const pyarr_c<bool> &flags_)
Martin Reinecke's avatar
Martin Reinecke committed
404
405
      {
      myassert(coord_.ndim()==2, "coord array must be 2D");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
406
      myassert(coord_.shape(1)==3, "coord.shape[1] must be 3");
Martin Reinecke's avatar
Martin Reinecke committed
407
      myassert(scaling_.ndim()==1, "scaling array must be 1D");
Martin Reinecke's avatar
Martin Reinecke committed
408
      nrows = coord_.shape(0);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
409
      nchan = scaling_.shape(0);
Martin Reinecke's avatar
Martin Reinecke committed
410
411
412
      myassert(flags_.ndim()==2, "flags array must be 2D");
      myassert(size_t(flags_.shape(0))==nrows, "flags.shape[0] must be nrows");
      myassert(size_t(flags_.shape(1))==nchan, "flags.shape[1] must be chan");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
413
414
      scaling.resize(nchan);
      for (size_t i=0; i<nchan; ++i)
Martin Reinecke's avatar
Martin Reinecke committed
415
416
        scaling[i] = scaling_.data()[i];
      coord.resize(nrows);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
417
      auto cood = coord_.data();
Martin Reinecke's avatar
Martin Reinecke committed
418
      for (size_t i=0; i<coord.size(); ++i)
Martin Reinecke's avatar
Martin Reinecke committed
419
        coord[i] = UVW<T>(cood[3*i], cood[3*i+1], cood[3*i+2]);
Martin Reinecke's avatar
Martin Reinecke committed
420
421
422
423
      flags.resize(nrows*nchan);
      auto pflags=flags_.data();
      for (size_t i=0; i<nrows*nchan; ++i)
        flags[i] = (pflags[i]!=0);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
424
      channelbits = bits_needed(nchan);
Martin Reinecke's avatar
Martin Reinecke committed
425
426
427
428
      channelmask = (size_t(1)<<channelbits)-1;
      auto rowbits = bits_needed(nrows);
      myassert(rowbits+channelbits<=8*sizeof(uint32_t), "Ti too small");
      }
Martin Reinecke's avatar
Martin Reinecke committed
429
430
    vector<uint32_t> getIndices(int chbegin, int chend, T wmin,
      T wmax) const
Martin Reinecke's avatar
Martin Reinecke committed
431
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
432
433
434
      if (chbegin<0) chbegin=0;
      if (chend<0) chend=nchan;
      vector<uint32_t> odata;
Martin Reinecke's avatar
Martin Reinecke committed
435
      for (size_t i=0; i<nrows; ++i)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
436
        for (int j=chbegin; j<chend; ++j)
Martin Reinecke's avatar
Martin Reinecke committed
437
438
439
440
441
442
          if (!flags[i*nchan + j])
            {
            auto w = coord[i].w*scaling[j];
            if ((w>=wmin) && (w<wmax))
              odata.push_back((i<<channelbits)+j);
            }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
443
      return odata;
Martin Reinecke's avatar
Martin Reinecke committed
444
445
      }

Martin Reinecke's avatar
Martin Reinecke committed
446
    UVW<T> effectiveCoord(uint32_t index) const
Martin Reinecke's avatar
Martin Reinecke committed
447
448
      { return coord[index>>channelbits]*scaling[index&channelmask]; }
    size_t Nrows() const { return nrows; }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
449
    size_t Nchannels() const { return nchan; }
Martin Reinecke's avatar
Martin Reinecke committed
450
451
452
453
454
    size_t irow(uint32_t index) const
      { return index>>channelbits; }
    size_t ichannel(uint32_t index) const
      { return index&channelmask; }
    size_t offset(uint32_t index) const
Martin Reinecke's avatar
updates    
Martin Reinecke committed
455
456
      { return (index>>channelbits)*nchan + (index&channelmask); }

Martin Reinecke's avatar
Martin Reinecke committed
457
    template<typename T2> pyarr_c<T2> ms2vis(const pyarr_c<T2> &ms_,
Martin Reinecke's avatar
updates    
Martin Reinecke committed
458
459
460
461
462
463
464
465
466
467
      const pyarr_c<uint32_t> &idx_) const
      {
      myassert(idx_.ndim()==1, "idx array must be 1D");
      myassert(ms_.ndim()==2, "ms array must be 2D");
      myassert(size_t(ms_.shape(0))==nrows, "baselines 1st dim mismatch");
      myassert(size_t(ms_.shape(1))==nchan, "baselines 2nd dim mismatch");
      size_t nvis = size_t(idx_.shape(0));
      auto idx = idx_.data();
      auto ms = ms_.data();

Martin Reinecke's avatar
Martin Reinecke committed
468
      auto res=makearray<T2>({nvis});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
469
470
471
472
473
474
      auto vis = res.mutable_data();
      for (size_t i=0; i<nvis; ++i)
        vis[i] = ms[offset(idx[i])];
      return res;
      }

Martin Reinecke's avatar
Martin Reinecke committed
475
    template<typename T2> pyarr_c<T2> vis2ms(const pyarr_c<T2> &vis_,
Martin Reinecke's avatar
updates    
Martin Reinecke committed
476
477
478
479
480
481
482
483
484
      const pyarr_c<uint32_t> &idx_) const
      {
      myassert(idx_.ndim()==1, "idx array must be 1D");
      myassert(vis_.ndim()==1, "vis array must be 1D");
      size_t nvis = size_t(vis_.shape(0));
      myassert(int(nvis)==idx_.shape(0), "idx/vis size mismatch");
      auto idx = idx_.data();
      auto vis = vis_.data();

Martin Reinecke's avatar
Martin Reinecke committed
485
      auto res = makearray<T2>({nrows, nchan});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
486
487
      auto ms = res.mutable_data();
      for (size_t i=0; i<nrows*nchan; ++i)
Martin Reinecke's avatar
Martin Reinecke committed
488
        ms[i] = T2(0);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
489
490
491
492
493
      for (size_t i=0; i<nvis; ++i)
        ms[offset(idx[i])] = vis[i];
      return res;
      }

Martin Reinecke's avatar
Martin Reinecke committed
494
495
    template<typename T2> pyarr_c<T2> add_vis_to_ms(const pyarr_c<T2> &vis_,
      const pyarr_c<uint32_t> &idx_, pyarr_c<T2> &ms_) const
Martin Reinecke's avatar
updates    
Martin Reinecke committed
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
      {
      myassert(idx_.ndim()==1, "idx array must be 1D");
      myassert(vis_.ndim()==1, "vis array must be 1D");
      myassert(ms_.ndim()==2, "ms array must be 2D");
      myassert(size_t(ms_.shape(0))==nrows, "ms: bad 1st dimension");
      myassert(size_t(ms_.shape(1))==nchan, "ms: bad 2nd dimension");
      size_t nvis = size_t(vis_.shape(0));
      myassert(int(nvis)==idx_.shape(0), "idx/vis size mismatch");
      auto idx = idx_.data();
      auto vis = vis_.data();
      auto ms = ms_.mutable_data();

      for (size_t i=0; i<nvis; ++i)
        ms[offset(idx[i])] += vis[i];
      return ms_;
      }
Martin Reinecke's avatar
Martin Reinecke committed
512
513
  };

Martin Reinecke's avatar
Martin Reinecke committed
514
template<typename T> class GridderConfig
Martin Reinecke's avatar
Martin Reinecke committed
515
516
517
  {
  private:
    size_t nx_dirty, ny_dirty;
Martin Reinecke's avatar
Martin Reinecke committed
518
    T ucorr, vcorr;
Martin Reinecke's avatar
Martin Reinecke committed
519
520
    size_t w, nsafe, nu, nv;
    size_t peano_level;
Martin Reinecke's avatar
Martin Reinecke committed
521
    vector<T> cfu, cfv;
Martin Reinecke's avatar
Martin Reinecke committed
522
523
524
525
526
527
528
529

  public:
    GridderConfig(size_t nxdirty, size_t nydirty, double epsilon,
      double urange, double vrange)
      : nx_dirty(nxdirty), ny_dirty(nydirty),
        ucorr(1./urange), vcorr(1./vrange),
        w(get_w(epsilon)), nsafe((w+1)/2),
        nu(max(2*nsafe,2*nx_dirty)), nv(max(2*nsafe,2*ny_dirty)),
Martin Reinecke's avatar
updates    
Martin Reinecke committed
530
531
        peano_level(bits_needed(max(nu, nv))),
        cfu(nx_dirty), cfv(ny_dirty)
Martin Reinecke's avatar
Martin Reinecke committed
532
533
534
535
536
537
      {
      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(urange>0, "urange must be positive");
      myassert(vrange>0, "vrange must be positive");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
538
539
540
541
542
543
544
545
546
547
548

      auto tmp = correction_factors(nu, nx_dirty/2+1, w);
      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, w);
      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];
Martin Reinecke's avatar
Martin Reinecke committed
549
550
551
552
      }
    size_t Nu() const { return nu; }
    size_t Nv() const { return nv; }
    size_t W() const { return w; }
Martin Reinecke's avatar
Martin Reinecke committed
553
554
    T Ucorr() const { return ucorr; }
    T Vcorr() const { return vcorr; }
Martin Reinecke's avatar
Martin Reinecke committed
555
    size_t coord2peano(const UVW<T> &coord) const
Martin Reinecke's avatar
Martin Reinecke committed
556
      {
Martin Reinecke's avatar
Martin Reinecke committed
557
558
      double u=fmodulo(coord.u*ucorr, T(1))*nu,
             v=fmodulo(coord.v*vcorr, T(1))*nv;
Martin Reinecke's avatar
Martin Reinecke committed
559
560
561
562
      auto iu = min(nu-1, size_t(u));
      auto iv = min(nv-1, size_t(v));
      return morton2peano2D_32(coord2morton2D_32(iu,iv),peano_level);
      }
Martin Reinecke's avatar
Martin Reinecke committed
563
    pyarr_c<T> grid2dirty(const pyarr_c<T> &grid) const
Martin Reinecke's avatar
Martin Reinecke committed
564
      {
Martin Reinecke's avatar
Martin Reinecke committed
565
      auto tmp = makearray<T>({nu, nv});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
566
567
568
569
570
      auto ptmp = tmp.mutable_data();
      pocketfft::r2r_hartley({nu, nv},
        {grid.strides(0), grid.strides(1)},
        {tmp.strides(0), tmp.strides(1)}, {0,1},
        grid.data(),
Martin Reinecke's avatar
Martin Reinecke committed
571
        ptmp, T(1), 0);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
572
573
574
      for(size_t i=1; i<(nu+1)/2; ++i)
        for(size_t j=1; j<(nv+1)/2; ++j)
           {
Martin Reinecke's avatar
Martin Reinecke committed
575
576
577
578
579
580
581
582
           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
updates    
Martin Reinecke committed
583
           }
Martin Reinecke's avatar
Martin Reinecke committed
584
      auto res = makearray<T>({nx_dirty, ny_dirty});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
585
586
587
588
589
590
591
592
593
594
      auto pout = res.mutable_data();
      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;
          pout[ny_dirty*i + j] = ptmp[nv*i2+j2]*cfu[i]*cfv[j];
          }
Martin Reinecke's avatar
Martin Reinecke committed
595
596
      return res;
      }
Martin Reinecke's avatar
Martin Reinecke committed
597
    pyarr_c<T> dirty2grid(const pyarr_c<T> &dirty) const
Martin Reinecke's avatar
updates    
Martin Reinecke committed
598
599
      {
      auto pdirty = dirty.data();
Martin Reinecke's avatar
Martin Reinecke committed
600
      auto tmp = makearray<T>({nu, nv});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
      auto ptmp = tmp.mutable_data();
      for (size_t i=0; i<nu*nv; ++i)
        ptmp[i] = 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;
          ptmp[nv*i2+j2] = pdirty[ny_dirty*i + j]*cfu[i]*cfv[j];
          }
      pocketfft::r2r_hartley({nu, nv},
        {tmp.strides(0), tmp.strides(1)},
        {tmp.strides(0), tmp.strides(1)}, {0,1},
Martin Reinecke's avatar
Martin Reinecke committed
616
        tmp.data(), tmp.mutable_data(), T(1), 0);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
617
618
619
      for(size_t i=1; i<(nu+1)/2; ++i)
        for(size_t j=1; j<(nv+1)/2; ++j)
           {
Martin Reinecke's avatar
Martin Reinecke committed
620
621
622
623
624
625
626
627
           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
updates    
Martin Reinecke committed
628
629
630
           }
      return tmp;
      }
Martin Reinecke's avatar
Martin Reinecke committed
631
632
  };

Martin Reinecke's avatar
Martin Reinecke committed
633
template<typename T> class Helper
Martin Reinecke's avatar
import  
Martin Reinecke committed
634
  {
Martin Reinecke's avatar
Martin Reinecke committed
635
636
  protected:
    int nu, nv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
637
  public:
Martin Reinecke's avatar
Martin Reinecke committed
638
    int w;
Martin Reinecke's avatar
Martin Reinecke committed
639
    T beta;
Martin Reinecke's avatar
Martin Reinecke committed
640
  protected:
Martin Reinecke's avatar
Martin Reinecke committed
641
642
643
    int nsafe, su;
  public:
    int sv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
644

Martin Reinecke's avatar
Martin Reinecke committed
645
    vector<T> kernel;
Martin Reinecke's avatar
Martin Reinecke committed
646
647
648
    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
649
    void NOINLINE update(T u_in, T v_in)
Martin Reinecke's avatar
import  
Martin Reinecke committed
650
      {
Martin Reinecke's avatar
Martin Reinecke committed
651
      auto u = fmodulo(u_in, T(1))*nu;
Martin Reinecke's avatar
Martin Reinecke committed
652
653
      iu0 = int(u-w*0.5 + 1 + nu) - nu;
      if (iu0+w>nu+nsafe) iu0 = nu+nsafe-w;
Martin Reinecke's avatar
Martin Reinecke committed
654
      auto v = fmodulo(v_in, T(1))*nv;
Martin Reinecke's avatar
Martin Reinecke committed
655
656
      iv0 = int(v-w*0.5 + 1 + nv) - nv;
      if (iv0+w>nv+nsafe) iv0 = nv+nsafe-w;
Martin Reinecke's avatar
Martin Reinecke committed
657
      T xw=T(2)/w;
Martin Reinecke's avatar
Martin Reinecke committed
658
      for (int i=0; i<w; ++i)
Martin Reinecke's avatar
import  
Martin Reinecke committed
659
        {
Martin Reinecke's avatar
Martin Reinecke committed
660
661
662
        kernel[i  ] = xw*(iu0+i-u);
        kernel[i+w] = xw*(iv0+i-v);
        }
Martin Reinecke's avatar
Martin Reinecke committed
663
      for (auto &k : kernel)
Martin Reinecke's avatar
Martin Reinecke committed
664
        k = exp(beta*sqrt(T(1)-k*k));
Martin Reinecke's avatar
import  
Martin Reinecke committed
665
666
      }

Martin Reinecke's avatar
Martin Reinecke committed
667
668
    bool need_to_move() const
      { return (iu0<bu0) || (iv0<bv0) || (iu0+w>bu0+su) || (iv0+w>bv0+sv); }
Martin Reinecke's avatar
import  
Martin Reinecke committed
669

Martin Reinecke's avatar
Martin Reinecke committed
670
    void update_position()
Martin Reinecke's avatar
import  
Martin Reinecke committed
671
      {
Martin Reinecke's avatar
Martin Reinecke committed
672
673
      bu0=max(-nsafe, min(nu+nsafe-su, iu0+nsafe-su/2));
      bv0=max(-nsafe, min(nv+nsafe-sv, iv0+nsafe-sv/2));
Martin Reinecke's avatar
import  
Martin Reinecke committed
674
675
      }

Martin Reinecke's avatar
Martin Reinecke committed
676
  protected:
Martin Reinecke's avatar
updates    
Martin Reinecke committed
677
    Helper(int nu_, int nv_, int w_)
Martin Reinecke's avatar
Martin Reinecke committed
678
679
      : nu(nu_), nv(nv_), w(w_), beta(2.3*w), nsafe((w+1)/2),
        su(min(max(2*nsafe,80), nu)), sv(min(max(2*nsafe,80), nv)),
Martin Reinecke's avatar
Martin Reinecke committed
680
681
        kernel(2*w),
        bu0(-1000000), bv0(-1000000)
Martin Reinecke's avatar
import  
Martin Reinecke committed
682
      {
Martin Reinecke's avatar
Martin Reinecke committed
683
      if (min(nu,nv)<2*nsafe) throw runtime_error("grid dimensions too small");
Martin Reinecke's avatar
import  
Martin Reinecke committed
684
685
686
      }
  };

Martin Reinecke's avatar
Martin Reinecke committed
687
template<typename T> class WriteHelper: public Helper<T>
Martin Reinecke's avatar
import  
Martin Reinecke committed
688
  {
Martin Reinecke's avatar
Martin Reinecke committed
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
  protected:
    using Helper<T>::nu;
    using Helper<T>::nv;
  public:
    using Helper<T>::w;
    using Helper<T>::beta;
  protected:
    using Helper<T>::nsafe;
    using Helper<T>::su;
  public:
    using Helper<T>::sv;
    using Helper<T>::kernel;
    using Helper<T>::iu0;
    using Helper<T>::iv0;
    using Helper<T>::bu0;
    using Helper<T>::bv0;
    using Helper<T>::need_to_move;
    using Helper<T>::update_position;
    using Helper<T>::update;

Martin Reinecke's avatar
import  
Martin Reinecke committed
709
  private:
Martin Reinecke's avatar
Martin Reinecke committed
710
711
    vector<complex<T>> data;
    complex<T> *grid;
Martin Reinecke's avatar
import  
Martin Reinecke committed
712
713
714

    void dump()
      {
Martin Reinecke's avatar
Martin Reinecke committed
715
      if (bu0<-nsafe) return; // nothing written into buffer yet
Martin Reinecke's avatar
import  
Martin Reinecke committed
716
717
#pragma omp critical
{
Martin Reinecke's avatar
Martin Reinecke committed
718
719
720
      int idxu = (bu0+nu)%nu;
      int idxv0 = (bv0+nv)%nv;
      for (int iu=0; iu<su; ++iu)
Martin Reinecke's avatar
import  
Martin Reinecke committed
721
722
        {
        int idxv = idxv0;
Martin Reinecke's avatar
Martin Reinecke committed
723
        for (int iv=0; iv<sv; ++iv)
Martin Reinecke's avatar
import  
Martin Reinecke committed
724
          {
Martin Reinecke's avatar
Martin Reinecke committed
725
          grid[idxu*nv + idxv] += data[iu*sv + iv];
Martin Reinecke's avatar
import  
Martin Reinecke committed
726
727
728
729
730
731
732
733
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
}
      }

  public:
Martin Reinecke's avatar
Martin Reinecke committed
734
735
736
    complex<T> *p0;
    WriteHelper(int nu_, int nv_, int w, complex<T> *grid_)
      : Helper<T>(nu_, nv_, w), data(su*sv, T(0)), grid(grid_) {}
Martin Reinecke's avatar
updates    
Martin Reinecke committed
737
    ~WriteHelper() { dump(); }
Martin Reinecke's avatar
import  
Martin Reinecke committed
738

Martin Reinecke's avatar
Martin Reinecke committed
739
    void prep_write(T u_in, T v_in)
Martin Reinecke's avatar
import  
Martin Reinecke committed
740
      {
Martin Reinecke's avatar
Martin Reinecke committed
741
742
      update(u_in, v_in);
      if (need_to_move())
Martin Reinecke's avatar
import  
Martin Reinecke committed
743
744
        {
        dump();
Martin Reinecke's avatar
Martin Reinecke committed
745
        update_position();
Martin Reinecke's avatar
Martin Reinecke committed
746
        fill(data.begin(), data.end(), T(0));
Martin Reinecke's avatar
import  
Martin Reinecke committed
747
        }
Martin Reinecke's avatar
Martin Reinecke committed
748
      p0 = data.data() + sv*(iu0-bu0) + iv0-bv0;
Martin Reinecke's avatar
import  
Martin Reinecke committed
749
750
751
      }
  };

Martin Reinecke's avatar
Martin Reinecke committed
752
template<typename T> class ReadHelper: public Helper<T>
Martin Reinecke's avatar
import  
Martin Reinecke committed
753
  {
Martin Reinecke's avatar
Martin Reinecke committed
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
  protected:
    using Helper<T>::nu;
    using Helper<T>::nv;
  public:
    using Helper<T>::w;
    using Helper<T>::beta;
  protected:
    using Helper<T>::nsafe;
    using Helper<T>::su;
  public:
    using Helper<T>::sv;
    using Helper<T>::kernel;
    using Helper<T>::iu0;
    using Helper<T>::iv0;
    using Helper<T>::bu0;
    using Helper<T>::bv0;
    using Helper<T>::need_to_move;
    using Helper<T>::update_position;
    using Helper<T>::update;

Martin Reinecke's avatar
import  
Martin Reinecke committed
774
  private:
Martin Reinecke's avatar
Martin Reinecke committed
775
776
    vector<complex<T>> data;
    const complex<T> *grid;
Martin Reinecke's avatar
import  
Martin Reinecke committed
777
778
779

    void load()
      {
Martin Reinecke's avatar
Martin Reinecke committed
780
781
782
      int idxu = (bu0+nu)%nu;
      int idxv0 = (bv0+nv)%nv;
      for (int iu=0; iu<su; ++iu)
Martin Reinecke's avatar
import  
Martin Reinecke committed
783
784
        {
        int idxv = idxv0;
Martin Reinecke's avatar
Martin Reinecke committed
785
        for (int iv=0; iv<sv; ++iv)
Martin Reinecke's avatar
import  
Martin Reinecke committed
786
          {
Martin Reinecke's avatar
Martin Reinecke committed
787
          data[iu*sv + iv] = grid[idxu*nv + idxv];
Martin Reinecke's avatar
import  
Martin Reinecke committed
788
789
790
791
792
793
794
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
      }

  public:
Martin Reinecke's avatar
Martin Reinecke committed
795
796
797
    const complex<T> *p0;
    ReadHelper(int nu_, int nv_, int w_, const complex<T> *grid_)
      : Helper<T>(nu_, nv_, w_), data(su*sv,T(0)), grid(grid_), p0(nullptr) {}
Martin Reinecke's avatar
import  
Martin Reinecke committed
798

Martin Reinecke's avatar
Martin Reinecke committed
799
    void prep_read(T u_in, T v_in)
Martin Reinecke's avatar
import  
Martin Reinecke committed
800
      {
Martin Reinecke's avatar
Martin Reinecke committed
801
802
      update(u_in, v_in);
      if (need_to_move())
Martin Reinecke's avatar
import  
Martin Reinecke committed
803
        {
Martin Reinecke's avatar
Martin Reinecke committed
804
        update_position();
Martin Reinecke's avatar
import  
Martin Reinecke committed
805
806
        load();
        }
Martin Reinecke's avatar
Martin Reinecke committed
807
      p0 = data.data() + sv*(iu0-bu0) + iv0-bv0;
Martin Reinecke's avatar
import  
Martin Reinecke committed
808
809
810
      }
  };

Martin Reinecke's avatar
Martin Reinecke committed
811
812
813
template<typename T> pyarr_c<T> vis2grid(const Baselines<T> &baselines,
  const GridderConfig<T> &gconf, const pyarr_c<uint32_t> &idx_,
  const pyarr_c<complex<T>> &vis_)
Martin Reinecke's avatar
import  
Martin Reinecke committed
814
  {
Martin Reinecke's avatar
Martin Reinecke committed
815
  myassert(idx_.ndim()==1, "idx array must be 1D");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
816
817
818
819
  myassert(vis_.ndim()==1, "vis must be 1D");
  auto vis=vis_.data();
  myassert(vis_.shape(0)==idx_.shape(0), "bad vis dimension");
  size_t nvis = size_t(idx_.shape(0));
Martin Reinecke's avatar
Martin Reinecke committed
820
821
822
  auto idx = idx_.data();

  size_t nu=gconf.Nu(), nv=gconf.Nv();
Martin Reinecke's avatar
Martin Reinecke committed
823
  auto res = makearray<complex<T>>({nu, nv});
Martin Reinecke's avatar
import  
Martin Reinecke committed
824
  auto grid = res.mutable_data();
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
825
  for (size_t i=0; i<nu*nv; ++i) grid[i] = 0.;
Martin Reinecke's avatar
Martin Reinecke committed
826
  T ucorr = gconf.Ucorr(), vcorr=gconf.Vcorr();
Martin Reinecke's avatar
import  
Martin Reinecke committed
827
828
829

#pragma omp parallel
{
Martin Reinecke's avatar
Martin Reinecke committed
830
831
832
833
  WriteHelper<T> hlp(nu, nv, gconf.W(), grid);
  T emb = exp(-2*hlp.beta);
  const T * RESTRICT ku = hlp.kernel.data();
  const T * RESTRICT kv = hlp.kernel.data()+hlp.w;
Martin Reinecke's avatar
import  
Martin Reinecke committed
834
835
836

  // Loop over sampling points
#pragma omp for schedule(dynamic,10000)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
837
  for (size_t ipart=0; ipart<nvis; ++ipart)
Martin Reinecke's avatar
import  
Martin Reinecke committed
838
    {
Martin Reinecke's avatar
Martin Reinecke committed
839
    UVW<T> coord = baselines.effectiveCoord(idx[ipart]);
Martin Reinecke's avatar
Martin Reinecke committed
840
    hlp.prep_write(coord.u*ucorr, coord.v*vcorr);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
841
842
    auto * RESTRICT ptr = hlp.p0;
    int w = hlp.w;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
843
    auto v(vis[ipart]*emb);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
844
    for (int cu=0; cu<w; ++cu)
Martin Reinecke's avatar
import  
Martin Reinecke committed
845
      {
Martin Reinecke's avatar
Martin Reinecke committed
846
      complex<T> tmp(v*ku[cu]);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
847
848
849
      for (int cv=0; cv<w; ++cv)
        ptr[cv] += tmp*kv[cv];
      ptr+=hlp.sv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
850
851
852
      }
    }
} // end of parallel region
Martin Reinecke's avatar
Martin Reinecke committed
853
  return complex2hartley(res);
Martin Reinecke's avatar
import  
Martin Reinecke committed
854
  }
Martin Reinecke's avatar
Martin Reinecke committed
855
856
857
858

template<typename T> pyarr_c<complex<T>> grid2vis(const Baselines<T> &baselines,
  const GridderConfig<T> &gconf, const pyarr_c<uint32_t> &idx_,
  const pyarr_c<T> &grid0_)
Martin Reinecke's avatar
Martin Reinecke committed
859
  {
Martin Reinecke's avatar
Martin Reinecke committed
860
861
  size_t nu=gconf.Nu(), nv=gconf.Nv();
  myassert(idx_.ndim()==1, "idx array must be 1D");
Martin Reinecke's avatar
Martin Reinecke committed
862
  auto grid_ = hartley2complex(grid0_);
Martin Reinecke's avatar
import  
Martin Reinecke committed
863
  auto grid = grid_.data();
Martin Reinecke's avatar
Martin Reinecke committed
864
  myassert(grid_.ndim()==2, "data must be 2D");
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
865
866
  myassert(grid_.shape(0)==int(nu), "bad grid dimension");
  myassert(grid_.shape(1)==int(nv), "bad grid dimension");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
867
  size_t nvis = size_t(idx_.shape(0));
Martin Reinecke's avatar
Martin Reinecke committed
868
  auto idx = idx_.data();
Martin Reinecke's avatar
import  
Martin Reinecke committed
869

Martin Reinecke's avatar
Martin Reinecke committed
870
  auto res = makearray<complex<T>>({nvis});
Martin Reinecke's avatar
import  
Martin Reinecke committed
871
  auto vis = res.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
872
  T ucorr = gconf.Ucorr(), vcorr=gconf.Vcorr();
Martin Reinecke's avatar
import  
Martin Reinecke committed
873
874
875
876

  // Loop over sampling points
#pragma omp parallel
{
Martin Reinecke's avatar
Martin Reinecke committed
877
878
879
880
  ReadHelper<T> hlp(nu, nv, gconf.W(), grid);
  T emb = exp(-2*hlp.beta);
  const T * RESTRICT ku = hlp.kernel.data();
  const T * RESTRICT kv = hlp.kernel.data()+hlp.w;
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
881

Martin Reinecke's avatar
import  
Martin Reinecke committed
882
#pragma omp for schedule(dynamic,10000)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
883
  for (size_t ipart=0; ipart<nvis; ++ipart)
Martin Reinecke's avatar
import  
Martin Reinecke committed
884
    {
Martin Reinecke's avatar
Martin Reinecke committed
885
    UVW<T> coord = baselines.effectiveCoord(idx[ipart]);
Martin Reinecke's avatar
Martin Reinecke committed
886
    hlp.prep_read(coord.u*ucorr, coord.v*vcorr);
Martin Reinecke's avatar
Martin Reinecke committed
887
    complex<T> r = 0;
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
888
889
890
    auto * RESTRICT ptr = hlp.p0;
    int w = hlp.w;
    for (int cu=0; cu<w; ++cu)
Martin Reinecke's avatar
import  
Martin Reinecke committed
891
      {
Martin Reinecke's avatar
Martin Reinecke committed
892
      complex<T> tmp(0);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
893
894
895
896
      for (int cv=0; cv<w; ++cv)
        tmp += ptr[cv] * kv[cv];
      r += tmp*ku[cu];
      ptr += hlp.sv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
897
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
898
    vis[ipart] = r*emb;
Martin Reinecke's avatar
import  
Martin Reinecke committed
899
900
901
902
    }
}
  return res;
  }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
903

Martin Reinecke's avatar
Martin Reinecke committed
904
905
template<typename T> pyarr_c<uint32_t> getIndices(const Baselines<T> &baselines,
  const GridderConfig<T> &gconf, int chbegin, int chend, T wmin, T wmax)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
  {
  auto idx = baselines.getIndices(chbegin, chend, wmin, wmax);
  vector<size_t> peano(idx.size());
  for (size_t i=0; i<peano.size(); ++i)
    peano[i] = gconf.coord2peano(baselines.effectiveCoord(idx[i]));
  vector<size_t> newind;
  buildIndex(peano.begin(), peano.end(), newind);
  peano=vector<size_t>(); // deallocate
  auto res = makearray<uint32_t>({idx.size()});
  auto iout = res.mutable_data();
  for (size_t i=0; i<idx.size(); ++i)
    iout[i] = idx[newind[i]];
  return res;
  }

const char *Baselines_DS = R"""(
Class storing UVW coordinates and channel information.

Parameters
==========
Martin Reinecke's avatar
Martin Reinecke committed
926
927
coord: np.array((nrows, 3), dtype=np.float)
    u, v and w coordinates for each row
Martin Reinecke's avatar
updates    
Martin Reinecke committed
928
scaling: np.array((nchannels,), dtype=np.float)
Martin Reinecke's avatar
Martin Reinecke committed
929
    scaling factor for u, v, w for each individual channel
Martin Reinecke's avatar
Martin Reinecke committed
930
931
flags: np.array((nrows, nchannels), dtype=np.bool)
    "True" indicates that the value should not be used
Martin Reinecke's avatar
updates    
Martin Reinecke committed
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
)""";

const char *BL_ms2vis_DS = R"""(
Extracts visibility data from a measurement for the provided indices.

Parameters
==========
ms: np.array((nrows, nchannels), dtype=np.complex)
    the measurement set's visibility data
idx: np.array((nvis,), dtype=np.uint32)
    the indices to be extracted

Returns
=======
np.array((nvis,), dtype=np.complex)
    The visibility data for the index array
)""";

const char *BL_vis2ms_DS = R"""(
Martin Reinecke's avatar
Martin Reinecke committed
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
Produces a new MS with the provided visibilities set.

Parameters
==========
vis: np.array((nvis,), dtype=np.complex)
    The visibility data for the index array
idx: np.array((nvis,), dtype=np.uint32)
    the indices to be inserted

Returns
=======
np.array((nrows, nchannels), dtype=np.complex)
    the measurement set's visibility data (0 where not covered by idx)
)""";

const char *BL_add_vis_to_ms_DS = R"""(
Adds a set of visibilities to an existing MS.

Parameters
==========
vis: np.array((nvis,), dtype=np.complex)
    The visibility data for the index array
idx: np.array((nvis,), dtype=np.uint32)
    the indices to be inserted
ms: np.array((nrows, nchannels), dtype=np.complex)
    a MS

Returns
=======
np.array((nrows, nchannels), dtype=np.complex)
    the updated MS
Martin Reinecke's avatar
updates    
Martin Reinecke committed
982
983
)""";

Martin Reinecke's avatar
import  
Martin Reinecke committed
984
985
986
987
} // unnamed namespace

PYBIND11_MODULE(nifty_gridder, m)
  {
988
989
  using namespace pybind11::literals;

Martin Reinecke's avatar
Martin Reinecke committed
990
  py::class_<Baselines<double>> (m, "Baselines", Baselines_DS)
Martin Reinecke's avatar
Martin Reinecke committed
991
992
    .def(py::init<const pyarr_c<double> &, const pyarr_c<double> &,
      const pyarr_c<bool> &>(), "coord"_a, "scaling"_a, "flags"_a)
Martin Reinecke's avatar
Martin Reinecke committed
993
994
995
996
    .def ("ms2vis",&Baselines<double>::ms2vis<complex<double>>, BL_ms2vis_DS, "ms"_a, "idx"_a)
    .def ("ms2vis_f32",&Baselines<double>::ms2vis<float>, "ms"_a, "idx"_a)
    .def ("vis2ms",&Baselines<double>::vis2ms<complex<double>>, BL_vis2ms_DS, "vis"_a, "idx"_a)
    .def ("add_vis_to_ms",&Baselines<double>::add_vis_to_ms<complex<double>>, BL_add_vis_to_ms_DS,
Martin Reinecke's avatar
Martin Reinecke committed
997
      "vis"_a, "idx"_a, "ms"_a.noconvert());
Martin Reinecke's avatar
Martin Reinecke committed
998
  py::class_<GridderConfig<double>> (m, "GridderConfig")
999
    .def(py::init<size_t, size_t, double, double, double>(),"nxdirty"_a,
Martin Reinecke's avatar
Martin Reinecke committed
1000
      "nydirty"_a, "epsilon"_a, "urange"_a, "vrange"_a)
Martin Reinecke's avatar
Martin Reinecke committed
1001
1002
1003
1004
    .def("Nu", &GridderConfig<double>::Nu)
    .def("Nv", &GridderConfig<double>::Nv)
    .def("grid2dirty", &GridderConfig<double>::grid2dirty, "grid"_a)
    .def("dirty2grid", &GridderConfig<double>::dirty2grid, "dirty"_a);
Martin Reinecke's avatar
Martin Reinecke committed
1005
1006
1007
1008
1009
1010
  m.def("getIndices", getIndices<double>, "baselines"_a, "gconf"_a, "chbegin"_a=-1,
    "chend"_a=-1, "wmin"_a=-1e30, "wmax"_a=1e30);
  m.def("vis2grid",&vis2grid<double>, "baselines"_a, "gconf"_a, "idx"_a, "vis"_a);
  m.def("grid2vis",&grid2vis<double>, "baselines"_a, "gconf"_a, "idx"_a, "grid"_a);

  py::class_<Baselines<float>> (m, "Baselines_f", Baselines_DS)
Martin Reinecke's avatar
Martin Reinecke committed
1011
1012
    .def(py::init<const pyarr_c<float> &, const pyarr_c<float> &,
      const pyarr_c<bool> &>(), "coord"_a, "scaling"_a, "flags"_a)
Martin Reinecke's avatar
Martin Reinecke committed
1013
1014
1015
    .def ("ms2vis",&Baselines<float>::ms2vis<complex<float>>, BL_ms2vis_DS, "ms"_a, "idx"_a)
    .def ("vis2ms",&Baselines<float>::vis2ms<complex<float>>, BL_vis2ms_DS, "vis"_a, "idx"_a)
    .def ("add_vis_to_ms",&Baselines<float>::add_vis_to_ms<complex<float>>, BL_add_vis_to_ms_DS,
Martin Reinecke's avatar
Martin Reinecke committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
      "vis"_a, "idx"_a, "ms"_a.noconvert());
  py::class_<GridderConfig<float>> (m, "GridderConfig_f")
    .def(py::init<size_t, size_t, float, float, float>(),"nxdirty"_a,
      "nydirty"_a, "epsilon"_a, "urange"_a, "vrange"_a)
    .def("Nu", &GridderConfig<float>::Nu)
    .def("Nv", &GridderConfig<float>::Nv)
    .def("grid2dirty", &GridderConfig<float>::grid2dirty, "grid"_a)
    .def("dirty2grid", &GridderConfig<float>::dirty2grid, "dirty"_a);
  m.def("getIndices_f", getIndices<float>, "baselines"_a, "gconf"_a, "chbegin"_a=-1,
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1025
    "chend"_a=-1, "wmin"_a=-1e30, "wmax"_a=1e30);
Martin Reinecke's avatar
Martin Reinecke committed
1026
1027
  m.def("vis2grid_f",&vis2grid<float>, "baselines"_a, "gconf"_a, "idx"_a, "vis"_a);
  m.def("grid2vis_f",&grid2vis<float>, "baselines"_a, "gconf"_a, "idx"_a, "grid"_a);
Martin Reinecke's avatar
import  
Martin Reinecke committed
1028
  }