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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
72
73
74
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// Licensed under a 3-clause BSD style license - see LICENSE.rst

/*----------------------------- WARNING! -----------------------------
 * The C functions below are NOT designed to be called externally to
 * the Python function astropy/astropy/convolution/convolve.py.
 * They do NOT include any of the required correct usage checking.
 *
 *------------------------------- NOTES ------------------------------
 *
 * The simplest implementation of convolution does not deal with any boundary
 * treatment, and pixels within half a kernel width of the edge of the image are
 * set to zero. In cases where a boundary mode is set, we pad the input array in
 * the Python code. In the 1D case, this means that the input array to the C
 * code has a size nx + nkx where nx is the original array size and nkx is the
 * size of the kernel. If we also padded the results array, then we could use
 * the exact same C code for the convolution, provided that the results array
 * was 'unpadded' in the Python code after the C code.
 *
 * However, to avoid needlessly padding the results array, we instead adjust the
 * index when accessing the results array - for example in the 1D case we shift
 * the index in the results array compared to the input array by half the kernel
 * size. This is done via the 'result_index' variable, and this behavior is
 * triggered by the 'embed_result_within_padded_region' setting.
 *
 */


#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stddef.h>

#include "convolve.h"

// Distutils on Windows automatically exports ``PyInit__convolve``,
// create dummy to prevent linker complaining about missing symbol.
#if defined(_MSC_VER)
void PyInit__convolve(void)
{
    return;
}
#endif

#ifdef _OPENMP
#include <omp.h>
#endif


void convolveNd_c(DTYPE * const result,
        const DTYPE * const f,
        const unsigned n_dim,
        const size_t * const image_shape,
        const DTYPE * const g,
        const size_t * const kernel_shape,
        const bool nan_interpolate,
        const bool embed_result_within_padded_region,
        const unsigned n_threads)
{
#ifdef NDEBUG
    if (!result || !f || !g || !image_shape || !kernel_shape)
        return;
#else
    assert(result);
    assert(f);
    assert(g);
    assert(image_shape);
    assert(kernel_shape);
#endif

    if (n_dim == 1)
        convolve1d_c(result, f,
                image_shape[0],
                g, kernel_shape[0],
                nan_interpolate,
                embed_result_within_padded_region,
                n_threads);
    else if (n_dim == 2)
        convolve2d_c(result, f,
                image_shape[0], image_shape[1],
                g, kernel_shape[0], kernel_shape[1],
                nan_interpolate,
                embed_result_within_padded_region,
                n_threads);
    else if (n_dim == 3)
        convolve3d_c(result, f,
                        image_shape[0], image_shape[1], image_shape[2],
                        g, kernel_shape[0], kernel_shape[1], kernel_shape[2],
                        nan_interpolate,
                        embed_result_within_padded_region,
                        n_threads);
    else
        assert(0); // Unimplemented: n_dim > 3
}

/*-------------------------PERFORMANCE NOTES--------------------------------
 * The function wrappers below are designed to take advantage of the following:
 * The preprocessor will inline convolve<N>d(), effectively
 * expanding the two logical branches, replacing nan_interpolate
 * for their literal equivalents. The corresponding conditionals
 * within these functions will then be optimized away, this
 * being the goal - removing the unnecessary conditionals from
 * the loops without duplicating code.
 *--------------------------------------------------------------------------
 */

void convolve1d_c(DTYPE * const result,
        const DTYPE * const f, const size_t nx,
        const DTYPE * const g, const size_t nkx,
        const bool nan_interpolate,
        const bool embed_result_within_padded_region,
        const unsigned n_threads)
{
#ifdef NDEBUG
    if (!result || !f || !g)
        return;
#else
    assert(result);
    assert(f);
    assert(g);
#endif

    if (nan_interpolate) {
      if (embed_result_within_padded_region)
        convolve1d(result, f, nx, g, nkx, true, true, n_threads);
      else
        convolve1d(result, f, nx, g, nkx, true, false, n_threads);
    } else {
      if (embed_result_within_padded_region)
        convolve1d(result, f, nx, g, nkx, false, true, n_threads);
      else
        convolve1d(result, f, nx, g, nkx, false, false, n_threads);
    }
}

void convolve2d_c(DTYPE * const result,
        const DTYPE * const f, const size_t nx, const size_t ny,
        const DTYPE * const g, const size_t nkx, const size_t nky,
        const bool nan_interpolate,
        const bool embed_result_within_padded_region,
        const unsigned n_threads)
{
#ifdef NDEBUG
    if (!result || !f || !g)
        return;
#else
    assert(result);
    assert(f);
    assert(g);
#endif

    if (nan_interpolate) {
      if (embed_result_within_padded_region)
        convolve2d(result, f, nx, ny, g, nkx, nky, true, true, n_threads);
      else
        convolve2d(result, f, nx, ny, g, nkx, nky, true, false, n_threads);
    } else {
      if (embed_result_within_padded_region)
        convolve2d(result, f, nx, ny, g, nkx, nky, false, true, n_threads);
      else
        convolve2d(result, f, nx, ny, g, nkx, nky, false, false, n_threads);
    }
}

void convolve3d_c(DTYPE * const result,
        const DTYPE * const f, const size_t nx, const size_t ny, const size_t nz,
        const DTYPE * const g, const size_t nkx, const size_t nky, const size_t nkz,
        const bool nan_interpolate,
        const bool embed_result_within_padded_region,
        const unsigned n_threads)
{
#ifdef NDEBUG
    if (!result || !f || !g)
        return;
#else
    assert(result);
    assert(f);
    assert(g);
#endif

    if (nan_interpolate) {
      if (embed_result_within_padded_region)
        convolve3d(result, f, nx, ny, nz, g, nkx, nky, nkz, true, true, n_threads);
      else
        convolve3d(result, f, nx, ny, nz, g, nkx, nky, nkz, true, false, n_threads);
    } else {
      if (embed_result_within_padded_region)
        convolve3d(result, f, nx, ny, nz, g, nkx, nky, nkz, false, true, n_threads);
      else
        convolve3d(result, f, nx, ny, nz, g, nkx, nky, nkz, false, false, n_threads);
    }
}

// 1D
FORCE_INLINE void convolve1d(DTYPE * const result,
        const DTYPE * const f, const size_t _nx,
        const DTYPE * const g, const size_t _nkx,
        const bool _nan_interpolate,
        const bool _embed_result_within_padded_region,
        const unsigned n_threads)
{
#ifdef NDEBUG
    if (!result || !f || !g)
        return;
#else
    assert(result);
    assert(f);
    assert(g);
#endif

    const size_t _wkx = _nkx / 2;

#ifdef NDEBUG
    if (!(_nx > 2*_wkx))
        return;
#else
    assert(_nx > 2*_wkx);
#endif

#ifdef _OPENMP
    omp_set_num_threads(n_threads); // Set number of threads to use
#pragma omp parallel
    { // Code within this block is threaded
#endif

    // Copy these to thread locals to allow compiler to optimize (hoist/loads licm)
    // when threaded. Without these, compile time constant conditionals may
    // not be optimized away.
    const size_t nx = _nx;
    const size_t nkx = _nkx;
    const size_t nkx_minus_1 = nkx - 1;
    const bool nan_interpolate = _nan_interpolate;
    const bool embed_result_within_padded_region = _embed_result_within_padded_region;

    // Thread locals
    const size_t wkx = _wkx;
    const omp_iter_var nx_minus_wkx = nx - wkx;
    size_t i_minus_wkx;
    size_t result_index;

    DTYPE top, bot=0., ker, val;

    {omp_iter_var i;
#ifdef _OPENMP
#pragma omp for schedule(dynamic)
#endif
    for (i = wkx; i < nx_minus_wkx; ++i)
    {
        i_minus_wkx = i - wkx;

        top = 0.;
        if (nan_interpolate) // compile time constant
            bot = 0.;
        {omp_iter_var ii;
        for (ii = 0; ii < nkx; ++ii)
        {
            val = f[i_minus_wkx + ii];
            ker = g[nkx_minus_1 - ii];
            if (nan_interpolate) // compile time constant
            {
                if (!isnan(val))
                {
                    top += val * ker;
                    bot += ker;
                }
            }
            else
                top += val * ker;
        }}

        if (embed_result_within_padded_region) { // compile time constant
            result_index = i;
        } else {
            result_index = i_minus_wkx;
        }

        if (nan_interpolate) // compile time constant
        {
            if (bot == 0) // This should prob be np.isclose(kernel_sum, 0, atol=normalization_zero_tol)
                result[result_index]  = f[i];
            else
                result[result_index]  = top / bot;
        }
        else
            result[result_index] = top;
    }}
#ifdef _OPENMP
    }//end parallel scope
#endif
}

// 2D
FORCE_INLINE void convolve2d(DTYPE * const result,
        const DTYPE * const f, const size_t _nx, const size_t _ny,
        const DTYPE * const g, const size_t _nkx, const size_t _nky,
        const bool _nan_interpolate,
        const bool _embed_result_within_padded_region,
        const unsigned n_threads)
{
#ifdef NDEBUG
    if (!result || !f || !g)
        return;
#else
    assert(result);
    assert(f);
    assert(g);
#endif

    const size_t _wkx = _nkx / 2;
    const size_t _wky = _nky / 2;
#ifdef NDEBUG
    if (!(_nx > 2*_wkx) || !(_ny > 2*_wky))
        return;
#else
    assert(_nx > 2*_wkx);
    assert(_ny > 2*_wky);
#endif

#ifdef _OPENMP
    omp_set_num_threads(n_threads); // Set number of threads to use
#pragma omp parallel
    { // Code within this block is threaded
#endif

    // Copy these to thread locals to allow compiler to optimize (hoist/loads licm)
    // when threaded. Without these, compile time constant conditionals may
    // not be optimized away.
    const size_t nx = _nx, ny = _ny;
    const size_t nkx = _nkx, nky = _nky;
    const size_t nkx_minus_1 = nkx - 1, nky_minus_1 = nky - 1;
    const bool nan_interpolate = _nan_interpolate;
    const bool embed_result_within_padded_region = _embed_result_within_padded_region;

    // Thread locals
    const size_t wkx = _wkx;
    const size_t wky = _wky;
    const omp_iter_var nx_minus_wkx = nx - wkx;
    const omp_iter_var ny_minus_wky = ny - wky;
    const size_t ny_minus_2wky = ny - 2 * wky;
    size_t i_minus_wkx, j_minus_wky;
    size_t result_cursor;
    size_t f_cursor, g_cursor;
    size_t result_index;

    DTYPE top, bot=0., ker, val;

    {omp_iter_var i;
#ifdef _OPENMP
#pragma omp for schedule(dynamic)
#endif
    for (i = wkx; i < nx_minus_wkx; ++i)
    {
        i_minus_wkx = i - wkx;
        result_cursor = i*ny;

        {omp_iter_var j;
        for (j = wky; j < ny_minus_wky; ++j)
        {
            j_minus_wky = j - wky;

            top = 0.;
            if (nan_interpolate) // compile time constant
                bot = 0.;
            {omp_iter_var ii;
            for (ii = 0; ii < nkx; ++ii)
            {
                f_cursor = (i_minus_wkx + ii)*ny + j_minus_wky;
                g_cursor = (nkx_minus_1 - ii)*nky + nky_minus_1;

                {omp_iter_var jj;
                for (jj = 0; jj < nky; ++jj)
                {
                    val = f[f_cursor + jj];
                    ker = g[g_cursor - jj];
                    if (nan_interpolate) // compile time constant
                    {
                        if (!isnan(val))
                        {
                            top += val * ker;
                            bot += ker;
                        }
                    }
                    else
                        top += val * ker;
                }}
            }}

            if (embed_result_within_padded_region) { // compile time constant
                result_index = result_cursor + j;
            } else {
                result_index = i_minus_wkx * ny_minus_2wky + j_minus_wky;
            }

            if (nan_interpolate) // compile time constant
            {
                if (bot == 0) // This should prob be np.isclose(kernel_sum, 0, atol=normalization_zero_tol)
                    result[result_index]  = f[result_cursor + j] ;
                else
                    result[result_index]  = top / bot;
            }
            else
                result[result_index] = top;
        }}
    }}
#ifdef _OPENMP
    }//end parallel scope
#endif
}

// 3D
FORCE_INLINE void convolve3d(DTYPE * const result,
        const DTYPE * const f, const size_t _nx, const size_t _ny, const size_t _nz,
        const DTYPE * const g, const size_t _nkx, const size_t _nky, const size_t _nkz,
        const bool _nan_interpolate,
        const bool _embed_result_within_padded_region,
        const unsigned n_threads)
{
#ifdef NDEBUG
    if (!result || !f || !g)
        return;
#else
    assert(result);
    assert(f);
    assert(g);
#endif

    const size_t _wkx = _nkx / 2;
    const size_t _wky = _nky / 2;
    const size_t _wkz = _nkz / 2;
#ifdef NDEBUG
    if (!(_nx > 2*_wkx) || !(_ny > 2*_wky) || !(_nz > 2*_wkz))
        return;
#else
    assert(_nx > 2*_wkx);
    assert(_ny > 2*_wky);
    assert(_nz > 2*_wkz);
#endif

#ifdef _OPENMP
    omp_set_num_threads(n_threads); // Set number of threads to use
#pragma omp parallel
    { // Code within this block is threaded
#endif

    // Copy these to thread locals to allow compiler to optimize (hoist/loads licm)
    // when threaded. Without these, compile time constant conditionals may
    // not be optimized away.
    const size_t nx = _nx, ny = _ny, nz = _nz;
    const size_t nkx = _nkx, nky = _nky, nkz = _nkz;
    const size_t nkx_minus_1 = nkx - 1, nky_minus_1 = nky - 1, nkz_minus_1 = nkz - 1;
    const bool nan_interpolate = _nan_interpolate;
    const bool embed_result_within_padded_region = _embed_result_within_padded_region;

    // Thread locals
    const size_t wkx = _wkx;
    const size_t wky = _wky;
    const size_t wkz = _wkz;
    const size_t nx_minus_wkx = nx - wkx;
    const omp_iter_var ny_minus_wky = ny - wky;
    const omp_iter_var nz_minus_wkz = nz - wkz;
    const size_t ny_minus_2wky = ny - 2 * wky;
    const size_t nz_minus_2wkz = nz - 2 * wkz;
    size_t i_minus_wkx, j_minus_wky, k_minus_wkz;
    size_t f_ii_cursor, g_ii_cursor;
    size_t f_cursor, g_cursor;
    size_t array_cursor, array_i_cursor;
    size_t result_index;

    DTYPE top, bot=0., ker, val;

    {omp_iter_var i;
#ifdef _OPENMP
#pragma omp for schedule(dynamic)
#endif
    for (i = wkx; i < nx_minus_wkx; ++i)
    {
        i_minus_wkx = i - wkx;
        array_i_cursor = i*ny;

        {omp_iter_var j;
        for (j = wky; j < ny_minus_wky; ++j)
        {
            j_minus_wky = j - wky;
            array_cursor = (array_i_cursor + j)*nz;

            {omp_iter_var k;
            for (k = wkz; k < nz_minus_wkz; ++k)
            {
                k_minus_wkz = k - wkz;

                top = 0.;
                if (nan_interpolate) // compile time constant
                    bot = 0.;
                {omp_iter_var ii;
                for (ii = 0; ii < nkx; ++ii)
                {
                    f_ii_cursor = ((i_minus_wkx + ii)*ny + j_minus_wky)*nz + k_minus_wkz;
                    g_ii_cursor = ((nkx_minus_1 - ii)*nky + nky_minus_1)*nkz + nkz_minus_1;

                    {omp_iter_var jj;
                    for (jj = 0; jj < nky; ++jj)
                    {
                        f_cursor = f_ii_cursor + jj*nz;
                        g_cursor = g_ii_cursor - jj*nkz;
                        {omp_iter_var kk;
                        for (kk = 0; kk < nkz; ++kk)
                        {
                            val = f[f_cursor + kk];
                            ker = g[g_cursor - kk];
                            if (nan_interpolate) // compile time constant
                            {
                                if (!isnan(val))
                                {
                                    top += val * ker;
                                    bot += ker;
                                }
                            }
                            else
                                top += val * ker;
                        }}
                    }}
                }}

                if (embed_result_within_padded_region) { // compile time constant
                    result_index = array_cursor + k;
                } else {
                    result_index = (i_minus_wkx*ny_minus_2wky + j_minus_wky)*nz_minus_2wkz + k_minus_wkz;
                }

                if (nan_interpolate) // compile time constant
                {
                    if (bot == 0) // This should prob be np.isclose(kernel_sum, 0, atol=normalization_zero_tol)
                        result[result_index]  = f[array_cursor+ k] ;
                    else
                        result[result_index]  = top / bot;
                }
                else
                    result[result_index] = top;
            }}
        }}
    }}
#ifdef _OPENMP
    }//end parallel scope
#endif
}