nifty_gridder.cc 50.3 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 *  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
Martin Reinecke's avatar
Martin Reinecke committed
15
 *  along with nifty_gridder; if not, write to the Free Software
Martin Reinecke's avatar
Martin Reinecke committed
16
17
18
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

Martin Reinecke's avatar
Martin Reinecke committed
19
20
21
/* Copyright (C) 2019 Max-Planck-Society
   Author: Martin Reinecke */

Martin Reinecke's avatar
import  
Martin Reinecke committed
22
23
24
25
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <iostream>
#include <algorithm>
26
27
#include <cstdlib>
#include <cmath>
Martin Reinecke's avatar
Martin Reinecke committed
28

Martin Reinecke's avatar
updates    
Martin Reinecke committed
29
#include "pocketfft_hdronly.h"
Martin Reinecke's avatar
import  
Martin Reinecke committed
30
31
32
33
34
35
36

using namespace std;

namespace py = pybind11;

namespace {

Martin Reinecke's avatar
Martin Reinecke committed
37
38
auto None = py::none();

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

43
44
45
46
47
48
void myassert(bool cond, const char *msg)
  {
  if (cond) return;
  throw runtime_error(msg);
  }

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
49
50
51
52
53
54
55
56
57
58
59
/*! 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;
  }

60
61
62
63
64
65
66
67
68
69
70
71
static size_t nthreads = 1;

constexpr auto set_nthreads_DS = R"""(
Specifies the number of threads to be used by the module

Parameters
==========
nthreads: int
    the number of threads to be used. Must be >=1.
)""";
void set_nthreads(size_t nthreads_)
  {
72
  myassert(nthreads_>=1, "nthreads must be >= 1");
73
74
75
76
77
78
79
80
81
82
83
  nthreads = nthreads_;
  }

constexpr auto get_nthreads_DS = R"""(
Returns the number of threads used by the module

Returns
=======
int : the number of threads used by the module
)""";
size_t get_nthreads()
Martin Reinecke's avatar
Martin Reinecke committed
84
  { return nthreads; }
85

Martin Reinecke's avatar
Martin Reinecke committed
86
87
88
89
//
// Utilities for Gauss-Legendre quadrature
//

Martin Reinecke's avatar
Martin Reinecke committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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.);

104
#pragma omp parallel num_threads(nthreads)
Martin Reinecke's avatar
Martin Reinecke committed
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
{
  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;
138
      myassert(++j<100, "convergence problem");
Martin Reinecke's avatar
Martin Reinecke committed
139
140
141
142
143
144
145
146
      }

    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
147
148
149
150
//
// Start of real gridder functionality
//

151
152
template<typename T>
  using pyarr = py::array_t<T>;
153
// The "_c" suffix here stands for "C memory order, contiguous"
154
155
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
156

Martin Reinecke's avatar
merge    
Martin Reinecke committed
157
template<typename T> pyarr_c<T> makeArray(const vector<size_t> &shape)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
158
159
  { return pyarr_c<T>(shape); }

160
size_t get_supp(double epsilon)
Martin Reinecke's avatar
Martin Reinecke committed
161
162
163
164
165
166
167
168
169
170
171
  {
  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
172

Martin Reinecke's avatar
merge    
Martin Reinecke committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
void checkArray(const py::array &arr, const char *aname,
  const vector<size_t> &shape)
  {
  if (size_t(arr.ndim())!=shape.size())
    {
    cerr << "Array '" << aname << "' has " << arr.ndim() << " dimensions; "
            "expected " << shape.size() << endl;
    throw runtime_error("bad dimensionality");
    }
  for (size_t i=0; i<shape.size(); ++i)
    if ((shape[i]!=0) && (size_t(arr.shape(i))!=shape[i]))
      {
      cerr << "Dimension " << i << " of array '" << aname << "' has size "
           << arr.shape(i) << "; expected " << shape[i] << endl;
      throw runtime_error("bad array size");
      }
  }

Martin Reinecke's avatar
Martin Reinecke committed
191
template<typename T> pyarr<T> provideArray(const py::object &in,
Martin Reinecke's avatar
merge    
Martin Reinecke committed
192
193
  const vector<size_t> &shape)
  {
194
  if (in.is_none())
Martin Reinecke's avatar
merge    
Martin Reinecke committed
195
196
197
198
199
200
201
202
    {
    auto tmp_ = makeArray<T>(shape);
    size_t sz = size_t(tmp_.size());
    auto tmp = tmp_.mutable_data();
    for (size_t i=0; i<sz; ++i)
      tmp[i] = T(0);
    return tmp_;
    }
203
  auto tmp_ = in.cast<pyarr<T>>();
Martin Reinecke's avatar
merge    
Martin Reinecke committed
204
205
206
207
  checkArray(tmp_, "temporary", shape);
  return tmp_;
  }

Martin Reinecke's avatar
Martin Reinecke committed
208
209
210
211
212
213
214
215
216
217
template<typename T> pyarr<T> providePotentialArray(const py::object &in,
  const vector<size_t> &shape)
  {
  if (in.is_none())
    return makeArray<T>(vector<size_t>(shape.size(), 0));
  auto tmp_ = in.cast<pyarr<T>>();
  checkArray(tmp_, "temporary", shape);
  return tmp_;
  }

Martin Reinecke's avatar
Martin Reinecke committed
218
template<typename T> pyarr_c<T> provideCArray(py::object &in,
Martin Reinecke's avatar
merge    
Martin Reinecke committed
219
220
  const vector<size_t> &shape)
  {
221
  if (in.is_none())
Martin Reinecke's avatar
merge    
Martin Reinecke committed
222
223
224
225
226
227
228
229
230
231
232
233
234
    {
    auto tmp_ = makeArray<T>(shape);
    size_t sz = size_t(tmp_.size());
    auto tmp = tmp_.mutable_data();
    for (size_t i=0; i<sz; ++i)
      tmp[i] = T(0);
    return tmp_;
    }
  auto tmp_ = in.cast<pyarr_c<T>>();
  checkArray(tmp_, "temporary", shape);
  return tmp_;
  }

Martin Reinecke's avatar
Martin Reinecke committed
235
template<typename T> pyarr_c<T> complex2hartley
236
  (const pyarr_c<complex<T>> &grid_, py::object &grid_in)
Martin Reinecke's avatar
Martin Reinecke committed
237
  {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
238
  checkArray(grid_, "grid", {0,0});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
239
  size_t nu = size_t(grid_.shape(0)), nv = size_t(grid_.shape(1));
Martin Reinecke's avatar
Martin Reinecke committed
240
241
  auto grid = grid_.data();

242
  auto res = provideCArray<T>(grid_in, {nu, nv});
Martin Reinecke's avatar
Martin Reinecke committed
243
  auto grid2 = res.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
244
245
  {
  py::gil_scoped_release release;
246
#pragma omp parallel for num_threads(nthreads)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
247
  for (size_t u=0; u<nu; ++u)
Martin Reinecke's avatar
Martin Reinecke committed
248
    {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
249
250
    size_t xu = (u==0) ? 0 : nu-u;
    for (size_t v=0; v<nv; ++v)
Martin Reinecke's avatar
Martin Reinecke committed
251
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
252
253
254
      size_t xv = (v==0) ? 0 : nv-v;
      size_t i1 = u*nv+v;
      size_t i2 = xu*nv+xv;
255
256
      grid2[i1] += T(0.5)*(grid[i1].real()+grid[i1].imag()+
                           grid[i2].real()-grid[i2].imag());
Martin Reinecke's avatar
Martin Reinecke committed
257
258
      }
    }
Martin Reinecke's avatar
Martin Reinecke committed
259
  }
Martin Reinecke's avatar
Martin Reinecke committed
260
261
262
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
263
264
template<typename T> pyarr_c<complex<T>> hartley2complex
  (const pyarr_c<T> &grid_)
Martin Reinecke's avatar
Martin Reinecke committed
265
  {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
266
  checkArray(grid_, "grid", {0, 0});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
267
  size_t nu = size_t(grid_.shape(0)), nv = size_t(grid_.shape(1));
Martin Reinecke's avatar
Martin Reinecke committed
268
269
  auto grid = grid_.data();

Martin Reinecke's avatar
merge    
Martin Reinecke committed
270
  auto res=makeArray<complex<T>>({nu, nv});
Martin Reinecke's avatar
Martin Reinecke committed
271
  auto grid2 = res.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
272
273
  {
  py::gil_scoped_release release;
274
#pragma omp parallel for num_threads(nthreads)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
275
  for (size_t u=0; u<nu; ++u)
Martin Reinecke's avatar
Martin Reinecke committed
276
    {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
277
278
    size_t xu = (u==0) ? 0 : nu-u;
    for (size_t v=0; v<nv; ++v)
Martin Reinecke's avatar
Martin Reinecke committed
279
      {
Martin Reinecke's avatar
updates    
Martin Reinecke committed
280
281
282
      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
283
284
285
      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
286
287
      }
    }
Martin Reinecke's avatar
Martin Reinecke committed
288
  }
Martin Reinecke's avatar
Martin Reinecke committed
289
290
291
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
292
293
294
template<typename T> void hartley2_2D(const pyarr_c<T> &in, pyarr_c<T> &out)
  {
  size_t nu=in.shape(0), nv=in.shape(1);
Martin Reinecke's avatar
Martin Reinecke committed
295
296
297
  pocketfft::stride_t s_i{in.strides(0), in.strides(1)},
                      s_o{out.strides(0), out.strides(1)};
  auto d_i = in.data();
Martin Reinecke's avatar
Martin Reinecke committed
298
  auto ptmp = out.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
299
300
  {
  py::gil_scoped_release release;
301
302
303
  pocketfft::r2r_separable_hartley({nu, nv}, s_i, s_o, {0,1}, d_i, ptmp, T(1),
    nthreads);
#pragma omp parallel for num_threads(nthreads)
Martin Reinecke's avatar
Martin Reinecke committed
304
305
306
307
308
309
310
311
312
313
314
315
316
  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
317
  }
Martin Reinecke's avatar
Martin Reinecke committed
318

319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
template<typename T> class EC_Kernel
  {
  protected:
    size_t supp;
    T beta, emb_;

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

template<typename T> class EC_Kernel_with_correction: public EC_Kernel<T>
  {
  protected:
    static constexpr T pi = T(3.141592653589793238462643383279502884197L);
    int p;
    vector<T> x, wgt, psi;
    using EC_Kernel<T>::supp;

  public:
    using EC_Kernel<T>::operator();
    EC_Kernel_with_correction(size_t supp_)
      : EC_Kernel<T>(supp_), p(int(1.5*supp_+2))
      {
      legendre_prep(2*p,x,wgt);
      psi=x;
      for (auto &v:psi)
        v=operator()(v);
      }
    T corfac(T v) const
      {
      T tmp=0;
      for (int i=0; i<p; ++i)
        tmp += wgt[i]*psi[i]*cos(pi*supp*v*x[i]);
      return T(1)/(supp*tmp);
      }
  };
Martin Reinecke's avatar
Martin Reinecke committed
359
360
/* Compute correction factors for the ES gridding kernel
   This implementation follows eqs. (3.8) to (3.10) of Barnett et al. 2018 */
361
vector<double> correction_factors (size_t n, size_t nval, size_t supp)
Martin Reinecke's avatar
Martin Reinecke committed
362
  {
363
  EC_Kernel_with_correction<double> kernel(supp);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
364
  vector<double> res(nval);
365
  double xn = 1./n;
366
#pragma omp parallel for schedule(static) num_threads(nthreads)
Martin Reinecke's avatar
Martin Reinecke committed
367
  for (size_t k=0; k<nval; ++k)
368
    res[k] = kernel.corfac(k*xn);
Martin Reinecke's avatar
Martin Reinecke committed
369
370
371
  return res;
  }

Martin Reinecke's avatar
Martin Reinecke committed
372
template<typename T> struct UVW
Martin Reinecke's avatar
updates    
Martin Reinecke committed
373
  {
Martin Reinecke's avatar
Martin Reinecke committed
374
  T u, v, w;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
375
  UVW () {}
Martin Reinecke's avatar
Martin Reinecke committed
376
377
  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
378
379
    { return UVW(u*fct, v*fct, w*fct); }
  };
Martin Reinecke's avatar
Martin Reinecke committed
380

381
382
383
384
385
386
387
388
389
390
constexpr auto Baselines_DS = R"""(
Class storing UVW coordinates and channel information.

Parameters
==========
coord: np.array((nrows, 3), dtype=np.float)
    u, v and w coordinates for each row
freq: np.array((nchannels,), dtype=np.float)
    frequency for each individual channel (in Hz)
)""";
Martin Reinecke's avatar
Martin Reinecke committed
391
template<typename T> class Baselines
Martin Reinecke's avatar
Martin Reinecke committed
392
393
  {
  private:
Martin Reinecke's avatar
Martin Reinecke committed
394
    vector<UVW<T>> coord;
395
    vector<T> f_over_c;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
396
    size_t nrows, nchan;
Martin Reinecke's avatar
Martin Reinecke committed
397
398

  public:
399
    Baselines(const pyarr<T> &coord_, const pyarr<T> &freq_)
Martin Reinecke's avatar
Martin Reinecke committed
400
      {
401
      constexpr double speedOfLight = 299792458.;
Martin Reinecke's avatar
merge    
Martin Reinecke committed
402
      checkArray(coord_, "coord", {0, 3});
403
      checkArray(freq_, "freq", {0});
Martin Reinecke's avatar
Martin Reinecke committed
404
      nrows = coord_.shape(0);
405
      nchan = freq_.shape(0);
Martin Reinecke's avatar
Martin Reinecke committed
406
      myassert(nrows*nchan<(size_t(1)<<32), "too many entries in MS");
407
408
      auto freq = freq_.template unchecked<1>();
      auto cood = coord_.template unchecked<2>();
Martin Reinecke's avatar
Martin Reinecke committed
409
410
      {
      py::gil_scoped_release release;
411
      f_over_c.resize(nchan);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
412
      for (size_t i=0; i<nchan; ++i)
413
        f_over_c[i] = freq(i)/speedOfLight;
Martin Reinecke's avatar
Martin Reinecke committed
414
415
      coord.resize(nrows);
      for (size_t i=0; i<coord.size(); ++i)
416
        coord[i] = UVW<T>(cood(i,0), cood(i,1), cood(i,2));
Martin Reinecke's avatar
Martin Reinecke committed
417
      }
Martin Reinecke's avatar
Martin Reinecke committed
418
419
      }

Martin Reinecke's avatar
Martin Reinecke committed
420
    UVW<T> effectiveCoord(uint32_t index) const
421
422
423
      {
      size_t irow = index/nchan;
      size_t ichan = index-nchan*irow;
424
      return coord[irow]*f_over_c[ichan];
425
426
      }
    UVW<T> effectiveCoord(size_t irow, size_t ichan) const
427
      { return coord[irow]*f_over_c[ichan]; }
Martin Reinecke's avatar
Martin Reinecke committed
428
    size_t Nrows() const { return nrows; }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
429
430
    size_t Nchannels() const { return nchan; }

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
    static constexpr auto 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
    )""";
446

Philipp Arras's avatar
Philipp Arras committed
447
    pyarr_c<T> effectiveuvw(const pyarr_c<uint32_t> &idx_) const
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
    {
      checkArray(idx_, "idx", {0});
      size_t nvis = size_t(idx_.shape(0));
      auto idx = idx_.template unchecked<1>();
      auto res_=makeArray<T>({nvis, 3});
      auto res = res_.template mutable_unchecked<2>();
      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;
        }
      return res_;
    }

464
    template<typename T2> pyarr_c<T2> ms2vis(const pyarr<T2> &ms_,
Martin Reinecke's avatar
updates    
Martin Reinecke committed
465
466
      const pyarr_c<uint32_t> &idx_) const
      {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
467
468
      checkArray(idx_, "idx", {0});
      checkArray(ms_, "ms", {nrows, nchan});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
469
      size_t nvis = size_t(idx_.shape(0));
470
471
      auto idx = idx_.template unchecked<1>();
      auto ms = ms_.template unchecked<2>();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
472

Martin Reinecke's avatar
merge    
Martin Reinecke committed
473
      auto res=makeArray<T2>({nvis});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
474
      auto vis = res.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
475
476
      {
      py::gil_scoped_release release;
477
#pragma omp parallel for num_threads(nthreads)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
478
      for (size_t i=0; i<nvis; ++i)
479
480
481
482
483
484
        {
        auto t = idx(i);
        auto row = t/nchan;
        auto chan = t-row*nchan;
        vis[i] = ms(row, chan);
        }
Martin Reinecke's avatar
Martin Reinecke committed
485
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
486
487
488
      return res;
      }

489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
    static constexpr auto vis2ms_DS = R"""(
    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
    ms_in: np.array((nrows, nchannels), dtype=np.complex), optional
        input measurement set to which the visibilities are added.

    Returns
    =======
    np.array((nrows, nchannels), dtype=np.complex)
        the measurement set's visibility data (0 where not covered by idx)
    )""";
506
507
    template<typename T2> pyarr_c<T2> vis2ms(const pyarr<T2> &vis_,
      const pyarr<uint32_t> &idx_, py::object &ms_in) const
Martin Reinecke's avatar
updates    
Martin Reinecke committed
508
      {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
509
      checkArray(vis_, "vis", {0});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
510
      size_t nvis = size_t(vis_.shape(0));
Martin Reinecke's avatar
merge    
Martin Reinecke committed
511
      checkArray(idx_, "idx", {nvis});
512
513
      auto idx = idx_.template unchecked<1>();
      auto vis = vis_.template unchecked<1>();
Martin Reinecke's avatar
updates    
Martin Reinecke committed
514

Martin Reinecke's avatar
merge    
Martin Reinecke committed
515
      auto res = provideArray<T2>(ms_in, {nrows, nchan});
516
      auto ms = res.template mutable_unchecked<2>();
Martin Reinecke's avatar
Martin Reinecke committed
517
518
      {
      py::gil_scoped_release release;
519
#pragma omp parallel for num_threads(nthreads)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
520
      for (size_t i=0; i<nvis; ++i)
521
522
523
524
        {
        auto t = idx(i);
        auto row = t/nchan;
        auto chan = t-row*nchan;
Martin Reinecke's avatar
Martin Reinecke committed
525
        ms(row, chan) += vis(i);
526
        }
Martin Reinecke's avatar
Martin Reinecke committed
527
      }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
528
529
      return res;
      }
Martin Reinecke's avatar
Martin Reinecke committed
530
531
  };

Martin Reinecke's avatar
Martin Reinecke committed
532
533
constexpr int logsquare=4;

534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
constexpr auto grid2dirty_DS = R"""(
Converts from UV grid to dirty image (FFT, cropping, correction)

Parameters
==========
grid: np.array((nu, nv), dtype=np.float64)
    gridded UV data

Returns
=======
nd.array((nxdirty, nydirty), dtype=np.float64)
    the dirty image
)""";

constexpr auto dirty2grid_DS = R"""(
Converts from a dirty image to a UV grid (correction, padding, FFT)

Parameters
==========
dirty: nd.array((nxdirty, nydirty), dtype=np.float64)
    the dirty image

Returns
=======
np.array((nu, nv), dtype=np.float64)
    gridded UV data
)""";

Martin Reinecke's avatar
Martin Reinecke committed
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
constexpr auto apply_taper_DS = R"""(
Applies the taper (or its inverse) to an image

Parameters
==========
img: nd.array((nxdirty, nydirty), dtype=np.float64)
    the image
divide: bool
    if True, the routine dividex by the taper, otherwise it multiplies by it

Returns
=======
np.array((nxdirty, nydirty), dtype=np.float64)
    the image with the taper applied
)""";

Martin Reinecke's avatar
Martin Reinecke committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
constexpr auto apply_wscreen_DS = R"""(
Applies the w screen to an image

Parameters
==========
dirty: nd.array((nxdirty, nydirty), dtype=np.complex128)
    the image
w : float
    the w value to use
adjoint: bool
    if True, apply the complex conjugate of the w screen

Returns
=======
np.array((nxdirty, nydirty), dtype=np.complex128)
    the image with the w screen applied
)""";

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
constexpr auto GridderConfig_DS = R"""(
Class storing information related to the gridding/degridding process.

Parameters
==========
nxdirty: int
    x resolution of the dirty image; must be even
nydirty: int
    y resolution of the dirty image; must be even
epsilon: float
    required accuracy for the gridding/degridding step
    Must be >= 2e-13.
pixsize_x: float
    Pixel size in x direction (radians)
pixsize_y: float
    Pixel size in y direction (radians)
)""";
Martin Reinecke's avatar
Martin Reinecke committed
613
template<typename T> class GridderConfig
Martin Reinecke's avatar
Martin Reinecke committed
614
615
616
  {
  private:
    size_t nx_dirty, ny_dirty;
Martin Reinecke's avatar
Martin Reinecke committed
617
    double eps, psx, psy;
618
    size_t supp, nsafe, nu, nv;
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
619
    T beta;
Martin Reinecke's avatar
Martin Reinecke committed
620
    vector<T> cfu, cfv;
Martin Reinecke's avatar
Martin Reinecke committed
621

Martin Reinecke's avatar
Martin Reinecke committed
622
623
624
    complex<T> wscreen(double x, double y, double w, bool adjoint) const
      {
      constexpr double pi = 3.141592653589793238462643383279502884197;
625
#if 1
626
627
628
      double eps = sqrt(x+y);
      double s = sin(eps);
      double nm1 = -s*s/(1.+cos(eps));
629
630
631
#else
      double nm1 = (-x-y)/(sqrt(1.-x-y)+1);
#endif
632
633
      double n = nm1+1., xn = 1./n;
      double phase = 2*pi*w*nm1;
Martin Reinecke's avatar
Martin Reinecke committed
634
635
636
637
      if (adjoint) phase *= -1;
      return complex<T>(cos(phase)*xn, sin(phase)*xn);
      }

Martin Reinecke's avatar
Martin Reinecke committed
638
639
  public:
    GridderConfig(size_t nxdirty, size_t nydirty, double epsilon,
Martin Reinecke's avatar
Martin Reinecke committed
640
      double pixsize_x, double pixsize_y)
Martin Reinecke's avatar
Martin Reinecke committed
641
642
      : nx_dirty(nxdirty), ny_dirty(nydirty), eps(epsilon),
        psx(pixsize_x), psy(pixsize_y),
643
        supp(get_supp(epsilon)), nsafe((supp+1)/2),
Martin Reinecke's avatar
Martin Reinecke committed
644
        nu(max(2*nsafe,2*nx_dirty)), nv(max(2*nsafe,2*ny_dirty)),
645
        beta(2.3*supp),
Martin Reinecke's avatar
updates    
Martin Reinecke committed
646
        cfu(nx_dirty), cfv(ny_dirty)
Martin Reinecke's avatar
Martin Reinecke committed
647
      {
Martin Reinecke's avatar
Martin Reinecke committed
648
649
      {
      py::gil_scoped_release release;
Martin Reinecke's avatar
Martin Reinecke committed
650
651
652
      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");
Martin Reinecke's avatar
Martin Reinecke committed
653
654
      myassert(pixsize_x>0, "pixsize_x must be positive");
      myassert(pixsize_y>0, "pixsize_y must be positive");
Martin Reinecke's avatar
updates    
Martin Reinecke committed
655

656
      auto tmp = correction_factors(nu, nx_dirty/2+1, supp);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
657
658
659
660
      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];
661
      tmp = correction_factors(nv, ny_dirty/2+1, supp);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
662
663
664
665
      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
666
      }
Martin Reinecke's avatar
Martin Reinecke committed
667
      }
Martin Reinecke's avatar
Martin Reinecke committed
668
669
670
671
672
    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; }
Martin Reinecke's avatar
Martin Reinecke committed
673
674
    size_t Nu() const { return nu; }
    size_t Nv() const { return nv; }
675
    size_t Supp() const { return supp; }
676
    size_t Nsafe() const { return nsafe; }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
677
    T Beta() const { return beta; }
678

Martin Reinecke's avatar
Martin Reinecke committed
679
    pyarr_c<T> grid2dirty(const pyarr_c<T> &grid) const
Martin Reinecke's avatar
Martin Reinecke committed
680
      {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
681
682
      checkArray(grid, "grid", {nu, nv});
      auto tmp = makeArray<T>({nu, nv});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
683
      auto ptmp = tmp.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
684
      hartley2_2D<T>(grid, tmp);
Martin Reinecke's avatar
merge    
Martin Reinecke committed
685
      auto res = makeArray<T>({nx_dirty, ny_dirty});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
686
      auto pout = res.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
687
688
      {
      py::gil_scoped_release release;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
689
690
691
692
693
694
695
696
697
      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
698
      }
Martin Reinecke's avatar
Martin Reinecke committed
699
700
      return res;
      }
Martin Reinecke's avatar
Martin Reinecke committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
    pyarr_c<T> apply_taper(const pyarr_c<T> &img, bool divide) const
      {
      checkArray(img, "img", {nx_dirty, ny_dirty});
      auto pin = img.data();
      auto res = makeArray<T>({nx_dirty, ny_dirty});
      auto pout = res.mutable_data();
      {
      py::gil_scoped_release release;
      if (divide)
        for (size_t i=0; i<nx_dirty; ++i)
          for (size_t j=0; j<ny_dirty; ++j)
            pout[ny_dirty*i + j] = pin[ny_dirty*i + j]/(cfu[i]*cfv[j]);
      else
        for (size_t i=0; i<nx_dirty; ++i)
          for (size_t j=0; j<ny_dirty; ++j)
            pout[ny_dirty*i + j] = pin[ny_dirty*i + j]*cfu[i]*cfv[j];
      }
      return res;
      }
720
721
    pyarr_c<complex<T>> grid2dirty_c(const pyarr_c<complex<T>> &grid) const
      {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
722
723
      checkArray(grid, "grid", {nu, nv});
      auto tmp = makeArray<complex<T>>({nu, nv});
724
725
726
      auto ptmp = tmp.mutable_data();
      pocketfft::c2c({nu,nv},{grid.strides(0),grid.strides(1)},
        {tmp.strides(0), tmp.strides(1)}, {0,1}, pocketfft::BACKWARD,
727
        grid.data(), tmp.mutable_data(), T(1), nthreads);
Martin Reinecke's avatar
merge    
Martin Reinecke committed
728
      auto res = makeArray<complex<T>>({nx_dirty, ny_dirty});
729
      auto pout = res.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
730
731
      {
      py::gil_scoped_release release;
732
733
734
735
736
737
738
739
740
      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
741
      }
742
743
      return res;
      }
744

Martin Reinecke's avatar
Martin Reinecke committed
745
    pyarr_c<T> dirty2grid(const pyarr_c<T> &dirty) const
Martin Reinecke's avatar
updates    
Martin Reinecke committed
746
      {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
747
      checkArray(dirty, "dirty", {nx_dirty, ny_dirty});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
748
      auto pdirty = dirty.data();
Martin Reinecke's avatar
merge    
Martin Reinecke committed
749
      auto tmp = makeArray<T>({nu, nv});
Martin Reinecke's avatar
updates    
Martin Reinecke committed
750
      auto ptmp = tmp.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
751
752
      {
      py::gil_scoped_release release;
Martin Reinecke's avatar
updates    
Martin Reinecke committed
753
754
755
756
757
758
759
760
761
762
763
      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];
          }
Martin Reinecke's avatar
Martin Reinecke committed
764
      }
Martin Reinecke's avatar
Martin Reinecke committed
765
      hartley2_2D<T>(tmp, tmp);
Martin Reinecke's avatar
updates    
Martin Reinecke committed
766
767
      return tmp;
      }
768
769
    pyarr_c<complex<T>> dirty2grid_c(const pyarr_c<complex<T>> &dirty) const
      {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
770
      checkArray(dirty, "dirty", {nx_dirty, ny_dirty});
771
      auto pdirty = dirty.data();
Martin Reinecke's avatar
merge    
Martin Reinecke committed
772
      auto tmp = makeArray<complex<T>>({nu, nv});
773
      auto ptmp = tmp.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
774
775
776
      pocketfft::stride_t strides{tmp.strides(0),tmp.strides(1)};
      {
      py::gil_scoped_release release;
777
778
779
780
781
782
783
784
785
786
787
      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];
          }
Martin Reinecke's avatar
Martin Reinecke committed
788
      pocketfft::c2c({nu,nv}, strides, strides, {0,1}, pocketfft::FORWARD,
789
        ptmp, ptmp, T(1), nthreads);
Martin Reinecke's avatar
Martin Reinecke committed
790
      }
791
792
      return tmp;
      }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
793
794
    inline void getpix(T u_in, T v_in, T &u, T &v, int &iu0, int &iv0) const
      {
Martin Reinecke's avatar
Martin Reinecke committed
795
      u=fmodulo(u_in*psx, T(1))*nu,
796
797
      iu0 = int(u-supp*0.5 + 1 + nu) - nu;
      if (iu0+supp>nu+nsafe) iu0 = nu+nsafe-supp;
Martin Reinecke's avatar
Martin Reinecke committed
798
      v=fmodulo(v_in*psy, T(1))*nv;
799
800
      iv0 = int(v-supp*0.5 + 1 + nv) - nv;
      if (iv0+supp>nv+nsafe) iv0 = nv+nsafe-supp;
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
801
      }
Martin Reinecke's avatar
test1    
Martin Reinecke committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
    pyarr_c<complex<T>> apply_wscreen(const pyarr_c<complex<T>> &dirty_, double w, bool adjoint) const
      {
      checkArray(dirty_, "dirty", {nx_dirty, ny_dirty});
      auto dirty = dirty_.data();
      auto res_ = makeArray<complex<T>>({nx_dirty, ny_dirty});
      auto res = res_.mutable_data();
      double x0 = -0.5*nx_dirty*psx,
             y0 = -0.5*ny_dirty*psy;
      {
      py::gil_scoped_release release;
#pragma omp parallel num_threads(nthreads)
{
#pragma omp for schedule(static)
      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
Martin Reinecke committed
823
824
          res[ny_dirty*i+j] = dirty[ny_dirty*i+j]*ws; // lower left
          size_t i2 = nx_dirty-i, j2 = ny_dirty-j;
Martin Reinecke's avatar
Martin Reinecke committed
825
826
          if ((i>0)&&(i<i2))
            {
Martin Reinecke's avatar
Martin Reinecke committed
827
            res[ny_dirty*i2+j] = dirty[ny_dirty*i2+j]*ws; // lower right
Martin Reinecke's avatar
Martin Reinecke committed
828
            if ((j>0)&&(j<j2))
Martin Reinecke's avatar
Martin Reinecke committed
829
              res[ny_dirty*i2+j2] = dirty[ny_dirty*i2+j2]*ws; // upper right
Martin Reinecke's avatar
Martin Reinecke committed
830
831
            }
          if ((j>0)&&(j<j2))
Martin Reinecke's avatar
Martin Reinecke committed
832
            res[ny_dirty*i+j2] = dirty[ny_dirty*i+j2]*ws; // upper left
Martin Reinecke's avatar
test1    
Martin Reinecke committed
833
834
          }
        }
835
836
837
838
}
      }
      return res_;
      }
Martin Reinecke's avatar
Martin Reinecke committed
839
840
  };

841
template<typename T, typename T2=complex<T>> class Helper
Martin Reinecke's avatar
import  
Martin Reinecke committed
842
  {
Martin Reinecke's avatar
Martin Reinecke committed
843
  private:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
844
    const GridderConfig<T> &gconf;
845
    int nu, nv, nsafe, supp;
Martin Reinecke's avatar
Martin Reinecke committed
846
    T beta;
847
848
    const T2 *grid_r;
    T2 *grid_w;
849
    int su, sv;
Martin Reinecke's avatar
Martin Reinecke committed
850
851
852
    int iu0, iv0; // start index of the current visibility
    int bu0, bv0; // start index of the current buffer

853
    vector<T2> rbuf, wbuf;
Martin Reinecke's avatar
import  
Martin Reinecke committed
854

Martin Reinecke's avatar
Martin Reinecke committed
855
    void dump() const
Martin Reinecke's avatar
import  
Martin Reinecke committed
856
      {
Martin Reinecke's avatar
Martin Reinecke committed
857
      if (bu0<-nsafe) return; // nothing written into buffer yet
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
858

Martin Reinecke's avatar
merge    
Martin Reinecke committed
859
#pragma omp critical (gridder_writing_to_grid)
Martin Reinecke's avatar
import  
Martin Reinecke committed
860
{
Martin Reinecke's avatar
Martin Reinecke committed
861
862
863
      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
864
865
        {
        int idxv = idxv0;
Martin Reinecke's avatar
Martin Reinecke committed
866
        for (int iv=0; iv<sv; ++iv)
Martin Reinecke's avatar
import  
Martin Reinecke committed
867
          {
868
          grid_w[idxu*nv + idxv] += wbuf[iu*sv + iv];
Martin Reinecke's avatar
import  
Martin Reinecke committed
869
870
871
872
873
874
875
876
877
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
}
      }

    void load()
      {
Martin Reinecke's avatar
Martin Reinecke committed
878
879
880
      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
881
882
        {
        int idxv = idxv0;
Martin Reinecke's avatar
Martin Reinecke committed
883
        for (int iv=0; iv<sv; ++iv)
Martin Reinecke's avatar
import  
Martin Reinecke committed
884
          {
885
          rbuf[iu*sv + iv] = grid_r[idxu*nv + idxv];
Martin Reinecke's avatar
import  
Martin Reinecke committed
886
887
888
889
890
891
892
          if (++idxv>=nv) idxv=0;
          }
        if (++idxu>=nu) idxu=0;
        }
      }

  public:
893
894
    const T2 *p0r;
    T2 *p0w;
Martin Reinecke's avatar
Martin Reinecke committed
895
    vector<T> kernel;
Martin Reinecke's avatar
import  
Martin Reinecke committed
896

897
    Helper(const GridderConfig<T> &gconf_, const T2 *grid_r_, T2 *grid_w_)
898
      : gconf(gconf_), nu(gconf.Nu()), nv(gconf.Nv()), nsafe(gconf.Nsafe()),
899
900
        supp(gconf.Supp()), beta(gconf.Beta()), grid_r(grid_r_),
        grid_w(grid_w_), su(2*nsafe+(1<<logsquare)), sv(2*nsafe+(1<<logsquare)),
901
902
903
        bu0(-1000000), bv0(-1000000),
        rbuf(su*sv*(grid_r!=nullptr),T(0)),
        wbuf(su*sv*(grid_w!=nullptr),T(0)),
904
        kernel(2*supp)
Martin Reinecke's avatar
Martin Reinecke committed
905
      {}
906
907
908
    ~Helper() { if (grid_w) dump(); }

    int lineJump() const { return sv; }
Martin Reinecke's avatar
Martin Reinecke committed
909
910

    void prep(T u_in, T v_in)
Martin Reinecke's avatar
import  
Martin Reinecke committed
911
      {
Martin Reinecke's avatar
Martin Reinecke committed
912
913
      T u, v;
      gconf.getpix(u_in, v_in, u, v, iu0, iv0);
914
915
916
917
      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
918
        {
919
        auto x = x0+i*xsupp;
Martin Reinecke's avatar
Martin Reinecke committed
920
        kernel[i  ] = beta*sqrt(T(1)-x*x);
921
922
        auto y = y0+i*xsupp;
        kernel[i+supp] = beta*sqrt(T(1)-y*y);
Martin Reinecke's avatar
Martin Reinecke committed
923
924
925
926
        }
      for (auto &k : kernel)
        k = exp(k);

927
      if ((iu0<bu0) || (iv0<bv0) || (iu0+supp>bu0+su) || (iv0+supp>bv0+sv))
Martin Reinecke's avatar
import  
Martin Reinecke committed
928
        {
929
        if (grid_w) { dump(); fill(wbuf.begin(), wbuf.end(), T(0)); }
Martin Reinecke's avatar
Martin Reinecke committed
930
931
        bu0=((((iu0+nsafe)>>logsquare)<<logsquare))-nsafe;
        bv0=((((iv0+nsafe)>>logsquare)<<logsquare))-nsafe;
932
        if (grid_r) load();
Martin Reinecke's avatar
import  
Martin Reinecke committed
933
        }
934
935
      p0r = grid_r ? rbuf.data() + sv*(iu0-bu0) + iv0-bv0 : nullptr;
      p0w = grid_w ? wbuf.data() + sv*(iu0-bu0) + iv0-bv0 : nullptr;
Martin Reinecke's avatar
import  
Martin Reinecke committed
936
937
938
      }
  };

939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
constexpr auto vis2grid_c_DS = R"""(
Grids visibilities onto a UV grid

Parameters
==========
baselines: Baselines
    the Baselines object
gconf: GridderConf
    the GridderConf object to be used
    (used to optimize the ordering of the indices)
idx: np.array((nvis,), dtype=np.uint32)
    the indices for the entries to be gridded
vis: np.array((nvis,), dtype=np.complex)
    The visibility data for the index array
grid_in: np.array((nu,nv), dtype=np.complex128), optional
    If present, the result is added to this array.
Martin Reinecke's avatar
Martin Reinecke committed
955
956
wgt: np.array((nvis,), dtype=np.float64), optional
    If present, visibilities are multiplied by the corresponding entries.
957
958
959
960
961
962

Returns
=======
np.array((nu,nv), dtype=np.complex128):
    the gridded visibilities
)""";
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
963
964
template<typename T> pyarr_c<complex<T>> vis2grid_c(
  const Baselines<T> &baselines, const GridderConfig<T> &gconf,
Martin Reinecke's avatar
Martin Reinecke committed
965
  const pyarr<uint32_t> &idx_, const pyarr<complex<T>> &vis_,
Martin Reinecke's avatar
Martin Reinecke committed
966
  py::object &grid_in, const py::object &wgt_)
967
  {
Martin Reinecke's avatar
merge    
Martin Reinecke committed
968
969
970
  checkArray(vis_, "vis", {0});
  size_t nvis = size_t(vis_.shape(0));
  checkArray(idx_, "idx", {nvis});
971
972
  auto vis=vis_.template unchecked<1>();
  auto idx = idx_.template unchecked<1>();
Martin Reinecke's avatar
Martin Reinecke committed
973
974
975
  pyarr<T> wgt2 = providePotentialArray<T>(wgt_, {nvis});
  bool have_wgt = wgt2.size()>0;
  auto wgt = wgt2.template unchecked<1>();
976

977
  size_t nu=gconf.Nu(), nv=gconf.Nv();
Martin Reinecke's avatar
Martin Reinecke committed
978
  auto res = provideCArray<complex<T>>(grid_in, {nu, nv});
979
  auto grid = res.mutable_data();
Martin Reinecke's avatar
Martin Reinecke committed
980
981
  {
  py::gil_scoped_release release;
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
982
  T beta = gconf.Beta();
983
  size_t supp = gconf.Supp();
984

985
#pragma omp parallel num_threads(nthreads)
986
{
987
  Helper<T> hlp(gconf, nullptr, grid);
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
988
  T emb = exp(-2*beta);
989
  int jump = hlp.lineJump();
Martin Reinecke's avatar
Martin Reinecke committed
990
  const T * ku = hlp.kernel.data();
991
  const T * kv = hlp.kernel.data()+supp;
992
993
994
995
996

  // Loop over sampling points
#pragma omp for schedule(guided,100)
  for (size_t ipart=0; ipart<nvis; ++ipart)
    {
997
    UVW<T> coord = baselines.effectiveCoord(idx(ipart));
Martin Reinecke's avatar
Martin Reinecke committed
998
    hlp.prep(coord.u, coord.v);
Martin Reinecke's avatar
Martin Reinecke committed
999
    auto * ptr = hlp.p0w;
1000
    auto v(vis(ipart)*emb);
Martin Reinecke's avatar
Martin Reinecke committed
1001
1002
    if (have_wgt)
      v*=wgt(ipart);
1003
    for (size_t cu=0; cu<supp; ++cu)
1004
1005
      {
      complex<T> tmp(v*ku[cu]);
1006
      for (size_t cv=0; cv<supp; ++cv)
1007
        ptr[cv] += tmp*kv[cv];
1008
      ptr+=jump;
1009
1010
1011
      }
    }
} // end of parallel region
Martin Reinecke's avatar
Martin Reinecke committed
1012
  }
1013
1014
1015
  return res;
  }

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
constexpr auto vis2grid_DS = R"""(
Grids visibilities onto a UV grid

Parameters
==========
baselines: Baselines
    the Baselines object
gconf: GridderConf
    the GridderConf object to be used
    (used to optimize the ordering of the indices)
idx: np.array((nvis,), dtype=np.uint32)
    the indices for the entries to be gridded
vis: np.array((nvis,), dtype=np.complex)
    The visibility data for the index array
Martin Reinecke's avatar
Martin Reinecke committed
1030
1031
grid_in: np.array((nu,nv), dtype=np.float64), optional
    If present, the result is added to this array.
Martin Reinecke's avatar
Martin Reinecke committed
1032
1033
wgt: np.array((nvis,), dtype=np.float64), optional
    If present, visibilities are multiplied by the corresponding entries.
1034
1035
1036
1037
1038
1039

Returns
=======
np.array((nu,nv), dtype=np.float64):
    the gridded visibilities (made real by making use of Hermitian symmetry)
)""";
Martin Reinecke's avatar
Martin Reinecke committed
1040
template<typename T> pyarr_c<T> vis2grid(const Baselines<T> &baselines,
1041
  const GridderConfig<T> &gconf, const pyarr<uint32_t> &idx_,
Martin Reinecke's avatar
Martin Reinecke committed
1042
1043
  const pyarr<complex<T>> &vis_, py::object &grid_in, const py::object &wgt_)
  { return complex2hartley(vis2grid_c(baselines, gconf, idx_, vis_, None, wgt_), grid_in); }
Martin Reinecke's avatar
updates    
Martin Reinecke committed
1044

1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
constexpr auto ms2grid_c_DS = R"""(
Grids measurement set data onto a UV grid

Parameters
==========
baselines: Baselines
    the Baselines object
gconf: GridderConf
    the GridderConf object to be used
    (used to optimize the ordering of the indices)
idx: np.array((nvis,), dtype=np.uint32)
    the indices for the entries to be gridded
ms: np.array((nrows, nchannels), dtype=np.complex128)
    the measurement set.
grid_in: np.array((nu,nv), dtype=np.complex128), optional
    If present, the result is added to this array.
Martin Reinecke's avatar
Martin Reinecke committed
1061
1062
wgt: np.array((nrows, nchannels), dtype=np.float64), optional
    If present, visibilities are multiplied by the corresponding entries.
1063
1064
1065
1066
1067
1068

Returns
=======
np.array((nu,nv), dtype=np.complex128):
    the gridded visibilities
)""";
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
1069
1070
template<typename T> pyarr_c<complex<T>> ms2grid_c(
  const Baselines<T> &baselines, const GridderConfig<T> &gconf,
Martin Reinecke's avatar
Martin Reinecke committed
1071
  const pyarr<uint32_t> &idx_, const pyarr<complex<T>> &ms_,
Martin Reinecke's avatar
Martin Reinecke committed
1072
  py::object &grid_in, const py::object &wgt_)
Martin Reinecke's avatar
merge    
Martin Reinecke committed
1073
1074
1075
1076
1077
1078
  {
  auto nrows = baselines.Nrows();
  auto nchan = baselines.Nchannels();
  checkArray(ms_, "ms", {nrows, nchan});
  checkArray(idx_, "idx", {0});
  size_t nvis = size_t(idx_.shape(0));
1079
1080
  auto ms = ms_.template unchecked<2>();
  auto idx = idx_.template unchecked<1>();
Martin Reinecke's avatar
Martin Reinecke committed
1081
1082
1083
  auto wgt2 = providePotentialArray<T>(wgt_, {nrows, nchan});
  bool have_wgt = wgt2.size()>0;
  auto wgt = wgt2.template unchecked<2>();
Simon Perkins's avatar
Simon Perkins committed
1084

Martin Reinecke's avatar
merge    
Martin Reinecke committed
1085
  size_t nu=gconf.Nu(), nv=gconf.Nv();
Martin Reinecke's avatar
Martin Reinecke committed
1086
  auto res = provideCArray<complex<T>>(grid_in, {nu, nv});
Martin Reinecke's avatar
merge    
Martin Reinecke committed
1087
  auto grid = res.mutable_data();