nifty_gridder.cc 21.5 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 *  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
23
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <iostream>
#include <algorithm>

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

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

namespace py = pybind11;

namespace {

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
Martin Reinecke committed
72
73
74
//
// Utilities for converting between Cartesian coordinates and Peano index
//
Martin Reinecke's avatar
import  
Martin Reinecke committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

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
161
162
163
164
//
// Utilities for indirect sorting (argsort)
//

Martin Reinecke's avatar
import  
Martin Reinecke committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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;
185
186
//  sort (idx.begin(),idx.end(),IdxComp__<It,Comp>(begin,comp));
  stable_sort (idx.begin(),idx.end(),IdxComp__<It,Comp>(begin,comp));
Martin Reinecke's avatar
import  
Martin Reinecke committed
187
188
189
190
191
192
193
194
195
196
197
198
199
  }

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

200
201
202
203
204
205
206
207
208
209
210
211
/*! 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. */
inline double fmodulo (double v1, double v2)
  {
  if (v1>=0)
    return (v1<v2) ? v1 : fmod(v1,v2);
  double tmp=fmod(v1,v2)+v2;
  return (tmp==v2) ? 0. : tmp;
//  return (v1>=0) ? ((v1<v2) ? v1 : fmod(v1,v2)) : (fmod(v1,v2)+v2);
  }

Martin Reinecke's avatar
Martin Reinecke committed
212
213
214
215
//
// Utilities for Gauss-Legendre quadrature
//

Martin Reinecke's avatar
Martin Reinecke committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
273
274
275
276
//
// Start of real gridder functionality
//

277
278
279
280
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>;
using a_u32_c = pyarr_c<uint32_t>;
using a_d_c = pyarr_c<double>;
using a_f_c = pyarr_c<float>;
using a_cd_c = pyarr_c<complex<double>>;
Martin Reinecke's avatar
import  
Martin Reinecke committed
285

286
a_u32_c peanoindex(const a_d_c &uv_, int nu, int nv)
Martin Reinecke's avatar
import  
Martin Reinecke committed
287
288
289
290
291
292
293
294
295
296
297
298
  {
  myassert(uv_.ndim()==2, "uv array must be 2D");
  myassert(uv_.shape(1)==2, "uv.shape[1] must be 2");
  int nvis = uv_.shape(0);
  auto uv = uv_.data();

  int npmax = max(nu, nv);
  int nbits = 0;
  for (int istart = npmax-1; istart!=0; istart>>=1, ++nbits);
  vector<int> ipeano(nvis);
  for (int i=0; i<nvis; ++i)
    {
299
    auto u = fmodulo(uv[2*i], 1.)*nu;
Martin Reinecke's avatar
import  
Martin Reinecke committed
300
    auto iu = min(nu-1, int(u));
301
    auto v = fmodulo(uv[2*i+1], 1.)*nv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
302
303
304
305
306
307
    auto iv = min(nv-1, int(v));
    ipeano[i] = morton2peano2D_32(coord2morton2D_32(iu,iv),nbits);
    }
  vector<int> newind;
  buildIndex(ipeano.begin(), ipeano.end(), newind);
  int odim[] = {nvis};
308
  a_u32_c res(odim);
Martin Reinecke's avatar
import  
Martin Reinecke committed
309
310
311
312
313
314
  auto iout = res.mutable_data();
  for (int i=0; i<nvis; ++i)
    iout[i] = newind[i];
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
315
int get_w(double epsilon)
Martin Reinecke's avatar
Martin Reinecke committed
316
317
318
319
320
321
322
323
324
325
326
  {
  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
327

Martin Reinecke's avatar
import  
Martin Reinecke committed
328
329
class Helper
  {
Martin Reinecke's avatar
Martin Reinecke committed
330
331
  protected:
    int nu, nv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
332
  public:
Martin Reinecke's avatar
Martin Reinecke committed
333
334
    int w;
    double beta;
Martin Reinecke's avatar
Martin Reinecke committed
335
  protected:
Martin Reinecke's avatar
Martin Reinecke committed
336
337
338
    int nsafe, su;
  public:
    int sv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
339

Martin Reinecke's avatar
Martin Reinecke committed
340
341
342
343
    vector<double> kernel;
    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
344
    void NOINLINE update(double u_in, double v_in)
Martin Reinecke's avatar
import  
Martin Reinecke committed
345
      {
346
      auto u = fmodulo(u_in, 1.)*nu;
Martin Reinecke's avatar
Martin Reinecke committed
347
348
      iu0 = int(u-w*0.5 + 1 + nu) - nu;
      if (iu0+w>nu+nsafe) iu0 = nu+nsafe-w;
349
      auto v = fmodulo(v_in, 1.)*nv;
Martin Reinecke's avatar
Martin Reinecke committed
350
351
352
353
      iv0 = int(v-w*0.5 + 1 + nv) - nv;
      if (iv0+w>nv+nsafe) iv0 = nv+nsafe-w;
      double xw=2./w;
      for (int i=0; i<w; ++i)
Martin Reinecke's avatar
import  
Martin Reinecke committed
354
        {
Martin Reinecke's avatar
Martin Reinecke committed
355
356
357
        kernel[i  ] = xw*(iu0+i-u);
        kernel[i+w] = xw*(iv0+i-v);
        }
Martin Reinecke's avatar
Martin Reinecke committed
358
359
      for (auto &k : kernel)
        k = exp(beta*sqrt(1.-k*k));
Martin Reinecke's avatar
import  
Martin Reinecke committed
360
361
      }

Martin Reinecke's avatar
Martin Reinecke committed
362
363
    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
364

Martin Reinecke's avatar
Martin Reinecke committed
365
    void update_position()
Martin Reinecke's avatar
import  
Martin Reinecke committed
366
      {
Martin Reinecke's avatar
Martin Reinecke committed
367
368
      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
369
370
      }

Martin Reinecke's avatar
Martin Reinecke committed
371
372
373
  protected:
    Helper(int nu_, int nv_, double epsilon)
      : nu(nu_), nv(nv_),
Martin Reinecke's avatar
Martin Reinecke committed
374
375
        w(get_w(epsilon)), beta(2.3*w), nsafe((w+1)/2),
        su(min(max(2*w,80), nu)), sv(min(max(2*w,80), nv)),
Martin Reinecke's avatar
Martin Reinecke committed
376
377
        kernel(2*w),
        bu0(-1000000), bv0(-1000000)
Martin Reinecke's avatar
import  
Martin Reinecke committed
378
      {
Martin Reinecke's avatar
Martin Reinecke committed
379
      if (min(nu,nv)<2*nsafe) throw runtime_error("grid dimensions too small");
Martin Reinecke's avatar
import  
Martin Reinecke committed
380
381
382
      }
  };

Martin Reinecke's avatar
Martin Reinecke committed
383
class WriteHelper: public Helper
Martin Reinecke's avatar
import  
Martin Reinecke committed
384
385
386
387
388
389
390
  {
  private:
    vector<complex<double>> data;
    complex<double> *grid;

    void dump()
      {
Martin Reinecke's avatar
Martin Reinecke committed
391
      if (bu0<-nsafe) return; // nothing written into buffer yet
Martin Reinecke's avatar
import  
Martin Reinecke committed
392
393
#pragma omp critical
{
Martin Reinecke's avatar
Martin Reinecke committed
394
395
396
      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
397
398
        {
        int idxv = idxv0;
Martin Reinecke's avatar
Martin Reinecke committed
399
        for (int iv=0; iv<sv; ++iv)
Martin Reinecke's avatar
import  
Martin Reinecke committed
400
          {
Martin Reinecke's avatar
Martin Reinecke committed
401
          grid[idxu*nv + idxv] += data[iu*sv + iv];
Martin Reinecke's avatar
import  
Martin Reinecke committed
402
403
404
405
406
407
408
409
410
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
}
      }

  public:
    complex<double> *p0;
Martin Reinecke's avatar
Martin Reinecke committed
411
412
413
    WriteHelper(int nu_, int nv_, double epsilon, complex<double> *grid_)
      : Helper(nu_, nv_, epsilon), data(su*sv, 0.), grid(grid_) {}
    ~WriteHelper() { dump(); }
Martin Reinecke's avatar
import  
Martin Reinecke committed
414

Martin Reinecke's avatar
Martin Reinecke committed
415
    void prep_write(double u_in, double v_in)
Martin Reinecke's avatar
import  
Martin Reinecke committed
416
      {
Martin Reinecke's avatar
Martin Reinecke committed
417
418
      update(u_in, v_in);
      if (need_to_move())
Martin Reinecke's avatar
import  
Martin Reinecke committed
419
420
        {
        dump();
Martin Reinecke's avatar
Martin Reinecke committed
421
        update_position();
Martin Reinecke's avatar
import  
Martin Reinecke committed
422
423
        fill(data.begin(), data.end(), 0.);
        }
Martin Reinecke's avatar
Martin Reinecke committed
424
      p0 = data.data() + sv*(iu0-bu0) + iv0-bv0;
Martin Reinecke's avatar
import  
Martin Reinecke committed
425
426
427
      }
  };

Martin Reinecke's avatar
Martin Reinecke committed
428
class ReadHelper: public Helper
Martin Reinecke's avatar
import  
Martin Reinecke committed
429
430
431
432
433
434
435
  {
  private:
    vector<complex<double>> data;
    const complex<double> *grid;

    void load()
      {
Martin Reinecke's avatar
Martin Reinecke committed
436
437
438
      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
439
440
        {
        int idxv = idxv0;
Martin Reinecke's avatar
Martin Reinecke committed
441
        for (int iv=0; iv<sv; ++iv)
Martin Reinecke's avatar
import  
Martin Reinecke committed
442
          {
Martin Reinecke's avatar
Martin Reinecke committed
443
          data[iu*sv + iv] = grid[idxu*nv + idxv];
Martin Reinecke's avatar
import  
Martin Reinecke committed
444
445
446
447
448
449
450
451
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
      }

  public:
    const complex<double> *p0;
Martin Reinecke's avatar
Martin Reinecke committed
452
453
    ReadHelper(int nu_, int nv_, double epsilon, const complex<double> *grid_)
      : Helper(nu_, nv_, epsilon), data(su*sv,0.), grid(grid_), p0(nullptr) {}
Martin Reinecke's avatar
import  
Martin Reinecke committed
454

Martin Reinecke's avatar
Martin Reinecke committed
455
    void prep_read(double u_in, double v_in)
Martin Reinecke's avatar
import  
Martin Reinecke committed
456
      {
Martin Reinecke's avatar
Martin Reinecke committed
457
458
      update(u_in, v_in);
      if (need_to_move())
Martin Reinecke's avatar
import  
Martin Reinecke committed
459
        {
Martin Reinecke's avatar
Martin Reinecke committed
460
        update_position();
Martin Reinecke's avatar
import  
Martin Reinecke committed
461
462
        load();
        }
Martin Reinecke's avatar
Martin Reinecke committed
463
      p0 = data.data() + sv*(iu0-bu0) + iv0-bv0;
Martin Reinecke's avatar
import  
Martin Reinecke committed
464
465
466
      }
  };

467
a_d_c complex2hartley (const a_cd_c &grid_)
Martin Reinecke's avatar
Martin Reinecke committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
  {
  myassert(grid_.ndim()==2, "grid array must be 2D");
  int nu = grid_.shape(0), nv = grid_.shape(1);
  auto grid = grid_.data();

  int odim[] = {nu,nv};
  a_d_c res(odim);
  auto grid2 = res.mutable_data();
  for (int u=0; u<nu; ++u)
    {
    int xu = (u==0) ? 0 : nu-u;
    for (int v=0; v<nv; ++v)
      {
      int xv = (v==0) ? 0 : nv-v;
      int i1 = u*nv+v;
      int i2 = xu*nv+xv;
      grid2[i1] = 0.5*(grid[i1].real()+grid[i1].imag()+
                       grid[i2].real()-grid[i2].imag());
      }
    }
  return res;
  }

491
a_d_c to_grid (const a_d_c &uv_, const a_cd_c &vis_,
Martin Reinecke's avatar
Martin Reinecke committed
492
               int nu, int nv, double epsilon)
Martin Reinecke's avatar
import  
Martin Reinecke committed
493
494
495
496
497
498
499
500
501
502
  {
  myassert(uv_.ndim()==2, "uv array must be 2D");
  myassert(uv_.shape(1)==2, "uv.shape[1] must be 2");
  int nvis = uv_.shape(0);
  myassert(vis_.ndim()==1, "vis array must be 1D");
  myassert(vis_.shape(0)==nvis, "array size mismatch");
  auto uv = uv_.data();
  auto vis = vis_.data();

  int odim[] = {nu,nv};
503
  a_cd_c res(odim);
Martin Reinecke's avatar
import  
Martin Reinecke committed
504
505
506
507
508
  auto grid = res.mutable_data();
  for (int i=0; i<nu*nv; ++i) grid[i] = 0.;

#pragma omp parallel
{
Martin Reinecke's avatar
Martin Reinecke committed
509
  WriteHelper hlp(nu, nv, epsilon, grid);
Martin Reinecke's avatar
Martin Reinecke committed
510
  double emb = exp(-2*hlp.beta);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
511
512
  const double * RESTRICT ku = hlp.kernel.data();
  const double * RESTRICT kv = hlp.kernel.data()+hlp.w;
Martin Reinecke's avatar
import  
Martin Reinecke committed
513
514
515
516
517

  // Loop over sampling points
#pragma omp for schedule(dynamic,10000)
  for (int ipart=0; ipart<nvis; ++ipart)
    {
Martin Reinecke's avatar
Martin Reinecke committed
518
    hlp.prep_write(uv[2*ipart], uv[2*ipart+1]);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
519
520
    auto * RESTRICT ptr = hlp.p0;
    int w = hlp.w;
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
521
    auto v(vis[ipart]*emb);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
522
    for (int cu=0; cu<w; ++cu)
Martin Reinecke's avatar
import  
Martin Reinecke committed
523
      {
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
524
      complex<double> tmp(v*ku[cu]);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
525
526
527
      for (int cv=0; cv<w; ++cv)
        ptr[cv] += tmp*kv[cv];
      ptr+=hlp.sv;
Martin Reinecke's avatar
import  
Martin Reinecke committed
528
529
530
      }
    }
} // end of parallel region
Martin Reinecke's avatar
Martin Reinecke committed
531
  return complex2hartley(res);
Martin Reinecke's avatar
import  
Martin Reinecke committed
532
533
  }

534
a_cd_c hartley2complex (const a_d_c &grid_)
Martin Reinecke's avatar
Martin Reinecke committed
535
536
537
538
539
540
  {
  myassert(grid_.ndim()==2, "grid array must be 2D");
  int nu = grid_.shape(0), nv = grid_.shape(1);
  auto grid = grid_.data();

  int odim[] = {nu,nv};
541
  a_cd_c res(odim);
Martin Reinecke's avatar
Martin Reinecke committed
542
543
544
545
546
547
548
549
550
  auto grid2 = res.mutable_data();
  for (int u=0; u<nu; ++u)
    {
    int xu = (u==0) ? 0 : nu-u;
    for (int v=0; v<nv; ++v)
      {
      int xv = (v==0) ? 0 : nv-v;
      int i1 = u*nv+v;
      int i2 = xu*nv+xv;
Martin Reinecke's avatar
Martin Reinecke committed
551
552
553
      double v1 = 0.5*grid[i1];
      double v2 = 0.5*grid[i2];
      grid2[i1] = complex<double>(v1+v2, v1-v2);
Martin Reinecke's avatar
Martin Reinecke committed
554
555
556
557
558
      }
    }
  return res;
  }

559
a_cd_c from_grid (const a_d_c &uv_, const a_d_c &grid0_, double epsilon)
Martin Reinecke's avatar
import  
Martin Reinecke committed
560
561
562
  {
  myassert(uv_.ndim()==2, "uv array must be 2D");
  myassert(uv_.shape(1)==2, "uv.shape[1] must be 2");
Martin Reinecke's avatar
Martin Reinecke committed
563
564
  myassert(grid0_.ndim()==2, "grid array must be 2D");
  auto grid_ = hartley2complex(grid0_);
Martin Reinecke's avatar
import  
Martin Reinecke committed
565
566
567
568
  int nvis = uv_.shape(0);
  auto uv = uv_.data();
  auto grid = grid_.data();

Martin Reinecke's avatar
Martin Reinecke committed
569
570
  int nu=grid_.shape(0),
      nv=grid_.shape(1);
Martin Reinecke's avatar
import  
Martin Reinecke committed
571
572

  int odim[] = {nvis};
573
  a_cd_c res(odim);
Martin Reinecke's avatar
import  
Martin Reinecke committed
574
575
576
577
578
  auto vis = res.mutable_data();

  // Loop over sampling points
#pragma omp parallel
{
Martin Reinecke's avatar
Martin Reinecke committed
579
  ReadHelper hlp(nu, nv, epsilon, grid);
Martin Reinecke's avatar
Martin Reinecke committed
580
  double emb = exp(-2*hlp.beta);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
581
582
  const double * RESTRICT ku = hlp.kernel.data();
  const double * RESTRICT kv = hlp.kernel.data()+hlp.w;
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
583

Martin Reinecke's avatar
import  
Martin Reinecke committed
584
585
586
#pragma omp for schedule(dynamic,10000)
  for (int ipart=0; ipart<nvis; ++ipart)
    {
Martin Reinecke's avatar
Martin Reinecke committed
587
    hlp.prep_read(uv[2*ipart], uv[2*ipart+1]);
Martin Reinecke's avatar
import  
Martin Reinecke committed
588
    complex<double> r = 0.;
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
589
590
591
    auto * RESTRICT ptr = hlp.p0;
    int w = hlp.w;
    for (int cu=0; cu<w; ++cu)
Martin Reinecke's avatar
import  
Martin Reinecke committed
592
      {
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
593
      complex<double> tmp(0.);
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
594
595
596
597
      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
598
      }
Martin Reinecke's avatar
Martin Reinecke committed
599
    vis[ipart] = r*emb;
Martin Reinecke's avatar
import  
Martin Reinecke committed
600
601
602
603
604
    }
}
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
605
606
/* 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
607
608
a_d_c correction_factors (size_t n, size_t nval, double epsilon)
  {
Martin Reinecke's avatar
Martin Reinecke committed
609
  constexpr double pi = 3.141592653589793238462643383279502884197;
Martin Reinecke's avatar
Martin Reinecke committed
610
  auto w = get_w(epsilon);
Martin Reinecke's avatar
Martin Reinecke committed
611
612
613
614
615
616
617
618
  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
tweaks    
Martin Reinecke committed
619
  int odim[] = {int(nval)};
Martin Reinecke's avatar
Martin Reinecke committed
620
621
622
623
624
625
626
627
628
629
630
631
  a_d_c res(odim);
  auto val = res.mutable_data();
  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]);
    val[k] = 1./(w*tmp);
    }
  return res;
  }

632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
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
class GridderConfig
  {
  private:
    size_t nx_dirty, ny_dirty;
    double epsilon, ucorr, vcorr;
    size_t nx_grid, ny_grid;
    size_t peano_level;

  public:
    GridderConfig(size_t nxdirty, size_t nydirty, double epsilon_,
      double urange, double vrange)
      : nx_dirty(nxdirty), ny_dirty(nydirty), epsilon(epsilon_),
        ucorr(1./urange), vcorr(1./vrange),
        nx_grid(2*nx_dirty), ny_grid(2*ny_dirty),
        peano_level(bits_needed(max(nx_grid, ny_grid)))
      {
      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");
      }
    template<typename Tcoord> void coord2cell(const Tcoord &coord,
      size_t &iu, size_t &iv, double &fu, double &fv) const
      {
      }
    template<typename Tcoord> size_t coord2peano(const Tcoord &coord) const
      {
      double u=fmodulo(coord.u*ucorr, 1.)*nx_grid,
             v=fmodulo(coord.v*vcorr, 1.)*ny_grid;
      auto iu = min(nx_grid-1, size_t(u));
      auto iv = min(ny_grid-1, size_t(v));
      return morton2peano2D_32(coord2morton2D_32(iu,iv),peano_level);
      }
    template<typename Ti, typename Tbase> pyarr_c<Ti> reorder_indices
      (const pyarr_c<Ti> &idx, const Tbase &baselines) const
      {
      myassert(idx.ndim()==1, "need 1D index array");
      vector<size_t> peano(idx.shape(0));
      auto pidx = idx.data();
      for (size_t i=0; i<peano.size(); ++i)
        peano[i] = coord2peano(baselines.EffectiveCoord(pidx[i]));
      vector<size_t> newind;
      buildIndex(peano.begin(), peano.end(), newind);
      peano=vector<size_t>(); // deallocate
      int odim[] = {idx.shape(0)};
      pyarr_c<Ti> res(odim);
      auto iout = res.mutable_data();
      for (int i=0; i<idx.shape(0); ++i)
        iout[i] = pidx[newind[i]];
      return res;
      }
  };

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

template<typename Ti, typename Tcoord, typename Ts> class Baselines
  {
  static_assert(is_integral<Ti>::value, "Ti must be an integral type");
  static_assert(is_unsigned<Ti>::value, "Ti must be an unsigned type");

  private:
    vector<Tcoord> coord;
    vector<Ts> scaling;
    size_t nrows;
    size_t channelbits, channelmask;

  public:
    Baselines(const vector<Tcoord> &coord_, const vector<Ts> &scaling_)
      : coord(coord_), scaling(scaling_), nrows(coord.size()/scaling.size())
      {
      myassert(nrows*scaling.size()==coord.size(), "bad array dimensions");
      channelbits = bits_needed(scaling.size());
      channelmask = (size_t(1)<<channelbits)-1;
      auto rowbits = bits_needed(nrows);
      myassert(rowbits+channelbits<=8*sizeof(Ti), "Ti too small");
      }
    Baselines(const pyarr_c<typename Tcoord::dtype> &coord_,
      const pyarr_c<Ts> &scaling_)
      {
      myassert(coord_.ndim()==2, "coord array must be 2D");
      myassert(coord_.shape(1)==2, "coord.shape[1] must be 2");
      myassert(scaling_.ndim()==1, "scaling array must be 1D");
      nrows = coord_.shape(0)/scaling_.shape(0);
      myassert(nrows*size_t(scaling_.shape(0))==size_t(coord_.shape(0)),
        "bad array dimensions");
      scaling.resize(scaling_.shape(0));
      for (size_t i=0; i<scaling.size(); ++i)
        scaling[i] = scaling_.data()[i];
      coord.resize(nrows);
      for (size_t i=0; i<coord.size(); ++i)
        coord[i] = UV<double>(coord_.data()[2*i], coord_.data()[2*i+1]);
      channelbits = bits_needed(scaling.size());
      channelmask = (size_t(1)<<channelbits)-1;
      auto rowbits = bits_needed(nrows);
      myassert(rowbits+channelbits<=8*sizeof(Ti), "Ti too small");
      }

    pyarr_c<Ti> getIndices() const
      {
      int odim[] = {int(nrows*scaling.size())};
      pyarr_c<Ti> res(odim);
      auto odata = res.mutable_data();
      for (size_t i=0; i<nrows; ++i)
        for (size_t j=0; j<scaling.size(); ++j)
          odata[j+scaling.size()*i] = (i<<channelbits)+j;
      return res;
      }

    Tcoord EffectiveCoord(Ti index) const
      { return coord[index>>channelbits]*scaling[index&channelmask]; }
  };

using Baselines_i32_uv_d = Baselines<uint32_t, UV<double>, double>;

template<typename Tbase> void blah(const Tbase &baselines)
  {
  auto x=baselines.getIndices();
  auto data = x.data();
  auto res = baselines.EffectiveCoord(data[0]);
  cout << res.u << " " << res.v << " " << endl;
  }

Martin Reinecke's avatar
import  
Martin Reinecke committed
772
773
774
775
} // unnamed namespace

PYBIND11_MODULE(nifty_gridder, m)
  {
776
  using namespace pybind11::literals;
Martin Reinecke's avatar
import  
Martin Reinecke committed
777
  m.def("peanoindex",&peanoindex);
Martin Reinecke's avatar
Martin Reinecke committed
778
  m.def("get_w",&get_w);
Martin Reinecke's avatar
import  
Martin Reinecke committed
779
780
  m.def("to_grid",&to_grid);
  m.def("from_grid",&from_grid);
Martin Reinecke's avatar
Martin Reinecke committed
781
  m.def("correction_factors",&correction_factors);
782
783
784
785
786
787
788
789
790
791

  py::class_<Baselines_i32_uv_d> (m, "Baselines_i32_uv_d")
    .def(py::init<a_d_c, a_d_c>(), "coord"_a, "scaling"_a)
    .def("getIndices", &Baselines_i32_uv_d::getIndices);
  py::class_<GridderConfig> (m, "GridderConfig")
    .def(py::init<size_t, size_t, double, double, double>(),"nxdirty"_a,
       "nydirty"_a, "epsilon"_a, "urange"_a, "vrange"_a)
    .def("reorder_indices", &GridderConfig::reorder_indices<uint32_t, Baselines_i32_uv_d>,
       "idx"_a, "baselines"_a);
  m.def ("blah",&blah<Baselines_i32_uv_d>);
Martin Reinecke's avatar
import  
Martin Reinecke committed
792
  }