This file is indexed.

/usr/lib/python3/dist-packages/ginga/trcalc.py is in python3-ginga 2.6.1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
547
548
549
550
551
#
# trcalc.py -- transformation calculations for image data
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import math
import numpy
import time

interpolation_methods = ['basic']
def use(pkgname):
    global have_opencv, cv2, cv2_resize
    global have_opencl, trcalc_cl

    if pkgname == 'opencv':
        import cv2
        have_opencv = True
        cv2_resize = {
            'nearest': cv2.INTER_NEAREST,
            'linear' : cv2.INTER_LINEAR,
            'area'   : cv2.INTER_AREA,
            'bicubic': cv2.INTER_CUBIC,
            'lanczos': cv2.INTER_LANCZOS4,
            }
        if not 'nearest' in interpolation_methods:
            interpolation_methods.extend(cv2_resize.keys())
            interpolation_methods.sort()

    elif pkgname == 'opencl':
        try:
            from ginga.opencl import CL
            have_opencl = True

            trcalc_cl = CL.CL('trcalc.cl')
        except Exception as e:
            raise ImportError(e)

have_opencv = False
try:
    # optional opencv package speeds up certain operations, especially
    # rotation
    # TEMP: opencv broken on older anaconda mac (importing causes segv)
    # --> temporarily disable, can enable using use() function above
    #use('opencv')
    pass

except ImportError:
    pass

have_opencl = False
trcalc_cl = None
try:
    # optional opencl package speeds up certain operations, especially
    # rotation
    # TEMP: pyopencl prompts users if it can't determine which device
    #       to use for acceleration.
    # --> temporarily disable, can enable using use() function above
    #use('opencl')
    pass

except ImportError:
    pass

have_numexpr = False
try:
    # optional numexpr package speeds up certain combined numpy array
    # operations, especially rotation
    import numexpr as ne
    have_numexpr = True

except ImportError:
    pass

# For testing
#have_numexpr = False
#have_opencv = False
#have_opencl = False

def get_center(data_np):
    ht, wd = data_np.shape[:2]

    ctr_x = wd // 2
    ctr_y = ht // 2
    return (ctr_x, ctr_y)


def rotate_pt(x_arr, y_arr, theta_deg, xoff=0, yoff=0):
    """
    Rotate an array of points (x_arr, y_arr) by theta_deg offsetted
    from a center point by (xoff, yoff).
    """
    # TODO: use opencv acceleration if available
    a_arr = x_arr - xoff
    b_arr = y_arr - yoff
    cos_t = numpy.cos(numpy.radians(theta_deg))
    sin_t = numpy.sin(numpy.radians(theta_deg))
    ap = (a_arr * cos_t) - (b_arr * sin_t)
    bp = (a_arr * sin_t) + (b_arr * cos_t)
    return (ap + xoff, bp + yoff)

rotate_arr = rotate_pt

def rotate_coord(coord, theta_deg, offsets):
    arr = numpy.asarray(coord)
    # TODO: handle dimensional rotation N>2
    x_arr, y_arr = rotate_pt(arr.T[0], arr.T[1], theta_deg,
                             xoff=offsets[0], yoff=offsets[1])
    arr = numpy.column_stack((x_arr, y_arr))
    return arr

def rotate_clip(data_np, theta_deg, rotctr_x=None, rotctr_y=None,
                out=None, use_opencl=True, logger=None):
    """
    Rotate numpy array `data_np` by `theta_deg` around rotation center
    (rotctr_x, rotctr_y).  If the rotation center is omitted it defaults
    to the center of the array.

    No adjustment is done to the data array beforehand, so the result will
    be clipped according to the size of the array (the output array will be
    the same size as the input array).
    """

    # If there is no rotation, then we are done
    if math.fmod(theta_deg, 360.0) == 0.0:
        return data_np

    ht, wd = data_np.shape[:2]

    if rotctr_x is None:
        rotctr_x = wd // 2
    if rotctr_y is None:
        rotctr_y = ht // 2

    if have_opencv:
        if logger is not None:
            logger.debug("rotating with OpenCv")
        # opencv is fastest
        M = cv2.getRotationMatrix2D((rotctr_y, rotctr_x), theta_deg, 1)
        if out is not None:
            out[:, :, ...] = cv2.warpAffine(data_np, M, (wd, ht))
            newdata = out

        else:
            newdata = cv2.warpAffine(data_np, M, (wd, ht))
            new_ht, new_wd = newdata.shape[:2]

            assert (wd == new_wd) and (ht == new_ht), \
                   Exception("rotated cutout is %dx%d original=%dx%d" % (
                new_wd, new_ht, wd, ht))

    elif have_opencl and use_opencl:
        if logger is not None:
            logger.debug("rotating with OpenCL")
        # opencl is very close, sometimes better, sometimes worse
        if (data_np.dtype == numpy.uint8) and (len(data_np.shape) == 3):
            # special case for 3D RGB images
            newdata = trcalc_cl.rotate_clip_uint32(data_np, theta_deg,
                                                   rotctr_x, rotctr_y,
                                                   out=out)
        else:
            newdata = trcalc_cl.rotate_clip(data_np, theta_deg,
                                            rotctr_x, rotctr_y,
                                            out=out)

    else:
        if logger is not None:
            logger.debug("rotating with numpy")
        yi, xi = numpy.mgrid[0:ht, 0:wd]
        xi -= rotctr_x
        yi -= rotctr_y
        cos_t = numpy.cos(numpy.radians(theta_deg))
        sin_t = numpy.sin(numpy.radians(theta_deg))

        if have_numexpr:
            ap = ne.evaluate("(xi * cos_t) - (yi * sin_t) + rotctr_x")
            bp = ne.evaluate("(xi * sin_t) + (yi * cos_t) + rotctr_y")
        else:
            ap = (xi * cos_t) - (yi * sin_t) + rotctr_x
            bp = (xi * sin_t) + (yi * cos_t) + rotctr_y

        #ap = numpy.rint(ap).astype('int').clip(0, wd-1)
        #bp = numpy.rint(bp).astype('int').clip(0, ht-1)
        # Optomizations to reuse existing intermediate arrays
        numpy.rint(ap, out=ap)
        ap = ap.astype('int')
        ap.clip(0, wd-1, out=ap)
        numpy.rint(bp, out=bp)
        bp = bp.astype('int')
        bp.clip(0, ht-1, out=bp)

        if out is not None:
            out[:, :, ...] = data_np[bp, ap]
            newdata = out
        else:
            newdata = data_np[bp, ap]
            new_ht, new_wd = newdata.shape[:2]

            assert (wd == new_wd) and (ht == new_ht), \
                   Exception("rotated cutout is %dx%d original=%dx%d" % (
                new_wd, new_ht, wd, ht))

    return newdata


def rotate(data_np, theta_deg, rotctr_x=None, rotctr_y=None, pad=20,
           use_opencl=True, logger=None):

    # If there is no rotation, then we are done
    if math.fmod(theta_deg, 360.0) == 0.0:
        return data_np

    ht, wd = data_np.shape[:2]

    ocx, ocy = wd // 2, ht // 2

    # Make a square with room to rotate
    side = int(math.sqrt(wd**2 + ht**2) + pad)
    new_wd = new_ht = side
    dims = (new_ht, new_wd) + data_np.shape[2:]
    # Find center of new data array
    ncx, ncy = new_wd // 2, new_ht // 2

    if have_opencl and use_opencl:
        if logger is not None:
            logger.debug("rotating with OpenCL")
        # find offsets of old image in new image
        dx, dy = ncx - ocx, ncy - ocy

        newdata = trcalc_cl.rotate(data_np, theta_deg,
                                   rotctr_x=rotctr_x, rotctr_y=rotctr_y,
                                   clip_val=0, out=None,
                                   out_wd=new_wd, out_ht=new_ht,
                                   out_dx=dx, out_dy=dy)
    else:
        # Overlay the old image on the new (blank) image
        ldx, rdx = min(ocx, ncx), min(wd - ocx, ncx)
        bdy, tdy = min(ocy, ncy), min(ht - ocy, ncy)

        # TODO: fill with a different value?
        newdata = numpy.zeros(dims, dtype=data_np.dtype)
        newdata[ncy-bdy:ncy+tdy, ncx-ldx:ncx+rdx] = \
                                 data_np[ocy-bdy:ocy+tdy, ocx-ldx:ocx+rdx]

        # Now rotate with clip as usual
        newdata = rotate_clip(newdata, theta_deg,
                              rotctr_x=rotctr_x, rotctr_y=rotctr_y,
                              out=newdata)
    return newdata


def get_scaled_cutout_wdht_view(shp, x1, y1, x2, y2, new_wd, new_ht):
    """
    Like get_scaled_cutout_wdht, but returns the view/slice to extract
    from an image instead of the extraction itself.
    """
    # calculate dimensions of NON-scaled cutout
    old_wd = x2 - x1 + 1
    old_ht = y2 - y1 + 1
    max_x, max_y = shp[1] - 1, shp[0] - 1

    if (new_wd != old_wd) or (new_ht != old_ht):
        # Make indexes and scale them
        # Is there a more efficient way to do this?
        yi = numpy.mgrid[0:new_ht].reshape(-1, 1)
        xi = numpy.mgrid[0:new_wd].reshape(1, -1)
        iscale_x = float(old_wd) / float(new_wd)
        iscale_y = float(old_ht) / float(new_ht)

        xi = (x1 + xi * iscale_x).clip(0, max_x).astype('int')
        yi = (y1 + yi * iscale_y).clip(0, max_y).astype('int')
        wd, ht = xi.shape[1], yi.shape[0]

        # bounds check against shape (to protect future data access)
        xi_max, yi_max = xi[0, -1], yi[-1, 0]
        assert xi_max <= max_x, ValueError("X index (%d) exceeds shape bounds (%d)" % (xi_max, max_x))
        assert yi_max <= max_y, ValueError("Y index (%d) exceeds shape bounds (%d)" % (yi_max, max_y))

        view = numpy.s_[yi, xi]

    else:
        # simple stepped view will do, because new view is same as old
        view = numpy.s_[y1:y2+1, x1:x2+1]
        wd, ht = old_wd, old_ht

    # Calculate actual scale used (vs. desired)
    old_wd, old_ht = max(old_wd, 1), max(old_ht, 1)
    scale_x = float(wd) / old_wd
    scale_y = float(ht) / old_ht

    # return view + actual scale factors used
    return (view, (scale_x, scale_y))


def get_scaled_cutout_wdht(data_np, x1, y1, x2, y2, new_wd, new_ht,
                           interpolation='basic', logger=None):

    rdim = data_np.shape[2:]
    open_cl_ok = (len(rdim) == 0 or (len(rdim) == 1 and rdim[0] == 4))

    if have_opencv:
        if logger is not None:
            logger.debug("resizing with OpenCv")
        # opencv is fastest and supports many methods
        if interpolation == 'basic':
            interpolation = 'nearest'
        method = cv2_resize[interpolation]
        newdata = cv2.resize(data_np[y1:y2+1, x1:x2+1], (new_wd, new_ht),
                             interpolation=method)

        old_wd, old_ht = max(x2 - x1 + 1, 1), max(y2 - y1 + 1, 1)
        ht, wd = newdata.shape[:2]
        scale_x, scale_y = float(wd) / old_wd, float(ht) / old_ht

    elif (have_opencl and interpolation in ('basic', 'nearest')
          and open_cl_ok):
        # opencl is almost as fast or sometimes faster, but currently
        # we only support nearest neighbor
        if logger is not None:
            logger.debug("resizing with OpenCL")
        old_wd, old_ht = max(x2 - x1 + 1, 1), max(y2 - y1 + 1, 1)
        scale_x, scale_y = float(new_wd) / old_wd, float(new_ht) / old_ht

        newdata, (scale_x, scale_y) = trcalc_cl.get_scaled_cutout_basic(data_np,
                                                                        x1, y1, x2, y2,
                                                                        scale_x, scale_y)

    elif interpolation not in ('basic', 'nearest'):
        raise ValueError("Interpolation method not supported: '%s'" % (
            interpolation))

    else:
        if logger is not None:
            logger.debug('resizing by slicing')
        view, (scale_x, scale_y) = get_scaled_cutout_wdht_view(data_np.shape,
                                                               x1, y1, x2, y2,
                                                               new_wd, new_ht)
        newdata = data_np[view]

    return newdata, (scale_x, scale_y)


def get_scaled_cutout_basic_view(shp, x1, y1, x2, y2, scale_x, scale_y):
    """
    Like get_scaled_cutout_basic, but returns the view/slice to extract
    from an image, instead of the extraction itself
    """

    # calculate dimensions of NON-scaled cutout
    old_wd = x2 - x1 + 1
    old_ht = y2 - y1 + 1
    # calculate dimensions of scaled cutout
    new_wd = int(round(scale_x * old_wd))
    new_ht = int(round(scale_y * old_ht))

    return get_scaled_cutout_wdht_view(shp, x1, y1, x2, y2, new_wd, new_ht)


def get_scaled_cutout_basic(data_np, x1, y1, x2, y2, scale_x, scale_y,
                            interpolation='basic', logger=None):

    rdim = data_np.shape[2:]
    open_cl_ok = (len(rdim) == 0 or (len(rdim) == 1 and rdim[0] == 4))

    if have_opencv:
        if logger is not None:
            logger.debug("resizing with OpenCv")
        # opencv is fastest
        if interpolation == 'basic':
            interpolation = 'nearest'
        method = cv2_resize[interpolation]
        newdata = cv2.resize(data_np[y1:y2+1, x1:x2+1], None,
                             fx=scale_x, fy=scale_y,
                             interpolation=method)
        old_wd, old_ht = max(x2 - x1 + 1, 1), max(y2 - y1 + 1, 1)
        ht, wd = newdata.shape[:2]
        scale_x, scale_y = float(wd) / old_wd, float(ht) / old_ht

    elif (have_opencl and interpolation in ('basic', 'nearest')
          and open_cl_ok):
        if logger is not None:
            logger.debug("resizing with OpenCL")
        newdata, (scale_x, scale_y) = trcalc_cl.get_scaled_cutout_basic(data_np,
                                                                        x1, y1, x2, y2,
                                                                        scale_x, scale_y)

    elif interpolation not in ('basic', 'nearest'):
        raise ValueError("Interpolation method not supported: '%s'" % (
            interpolation))

    else:
        if logger is not None:
            logger.debug('resizing by slicing')
        view, (scale_x, scale_y) = get_scaled_cutout_basic_view(data_np.shape,
                                                                x1, y1, x2, y2,
                                                                scale_x, scale_y)
        newdata = data_np[view]

    return newdata, (scale_x, scale_y)


def transform(data_np, flip_x=False, flip_y=False, swap_xy=False):

    # Do transforms as necessary
    if flip_y:
        data_np = numpy.flipud(data_np)
    if flip_x:
        data_np = numpy.fliplr(data_np)
    if swap_xy:
        data_np = data_np.swapaxes(0, 1)

    return data_np


def calc_image_merge_clip(x1, y1, x2, y2,
                          dst_x, dst_y, a1, b1, a2, b2):
    """
    (x1, y1) and (x2, y2) define the extent of the (non-scaled) data
    shown.  The image, defined by region (a1, b1), (a2, b2) is to be
    placed at (dst_x, dst_y) in the image (destination may be outside
    of the actual data array).

    Refines the tuple (a1, b1, a2, b2) defining the clipped rectangle
    needed to be cut from the source array and scaled.
    """
    src_wd, src_ht = a2 - a1, b2 - b1

    # Trim off parts of srcarr that would be "hidden"
    # to the left and above the dstarr edge.
    ex = y1 - dst_y
    if ex > 0:
        src_ht -= ex
        dst_y += ex
        #b2 -= ex
        b1 += ex

    ex = x1 - dst_x
    if ex > 0:
        src_wd -= ex
        dst_x += ex
        a1 += ex

    # Trim off parts of srcarr that would be "hidden"
    # to the right and below the dstarr edge.
    ex = dst_y + src_ht - y2
    if ex > 0:
        src_ht -= ex
        #b1 += ex
        b2 -= ex

    ex = dst_x + src_wd - x2
    if ex > 0:
        src_wd -= ex
        a2 -= ex

    return (dst_x, dst_y, a1, b1, a2, b2)


def overlay_image(dstarr, dst_x, dst_y, srcarr, dst_order='RGBA',
                  src_order='RGBA',
                  alpha=1.0, copy=False, fill=True, flipy=False):

    dst_ht, dst_wd, dst_dp = dstarr.shape
    src_ht, src_wd, src_dp = srcarr.shape
    dst_x, dst_y = int(round(dst_x)), int(round(dst_y))

    if flipy:
        srcarr = numpy.flipud(srcarr)

    # Trim off parts of srcarr that would be "hidden"
    # to the left and above the dstarr edge.
    if dst_y < 0:
        dy = abs(dst_y)
        srcarr = srcarr[dy:, :, :]
        src_ht -= dy
        dst_y = 0

    if dst_x < 0:
        dx = abs(dst_x)
        srcarr = srcarr[:, dx:, :]
        src_wd -= dx
        dst_x = 0

    if src_wd <= 0 or src_ht <=0:
        return dstarr

    # Trim off parts of srcarr that would be "hidden"
    # to the right and below the dstarr edge.
    ex = dst_y + src_ht - dst_ht
    if ex > 0:
        srcarr = srcarr[:dst_ht, :, :]
        src_ht -= ex

    ex = dst_x + src_wd - dst_wd
    if ex > 0:
        srcarr = srcarr[:, :dst_wd, :]
        src_wd -= ex

    if copy:
        dstarr = numpy.copy(dstarr, order='C')

    da_idx = -1
    slc = slice(0, 3)
    if 'A' in dst_order:
        da_idx = dst_order.index('A')

        # Currently we assume that alpha channel is in position 0 or 3 in dstarr
        if da_idx == 0:
            slc = slice(1, 4)
        elif da_idx != 3:
            raise ValueError("Alpha channel not in expected position (0 or 4) in dstarr")

    # fill alpha channel in destination in the area we will be dropping
    # the image
    if fill and (da_idx >= 0):
        dstarr[dst_y:dst_y+src_ht, dst_x:dst_x+src_wd, da_idx] = 255

    if src_dp > 3:
        sa_idx = src_order.index('A')
        # if overlay source contains an alpha channel, extract it
        # and use it, otherwise use scalar keyword parameter
        alpha = srcarr[0:src_ht, 0:src_wd, sa_idx] / 255.0
        alpha = numpy.dstack((alpha, alpha, alpha))

    # reorder srcarr if necessary to match dstarr for alpha merge
    get_order = dst_order
    if ('A' in dst_order) and not ('A' in src_order):
        get_order = dst_order.replace('A', '')
    if get_order != src_order:
        srcarr = reorder_image(get_order, srcarr, src_order)

    # calculate alpha blending
    #   Co = CaAa + CbAb(1 - Aa)
    a_arr = (alpha * srcarr[0:src_ht, 0:src_wd, slc]).astype(numpy.uint8)
    b_arr = ((1.0 - alpha) * dstarr[dst_y:dst_y+src_ht,
                                    dst_x:dst_x+src_wd,
                                    slc]).astype(numpy.uint8)

    # Place our srcarr into this dstarr at dst offsets
    #dstarr[dst_y:dst_y+src_ht, dst_x:dst_x+src_wd, slc] += addarr[0:src_ht, 0:src_wd, slc]
    dstarr[dst_y:dst_y+src_ht, dst_x:dst_x+src_wd, slc] = \
             a_arr[0:src_ht, 0:src_wd, slc] + b_arr[0:src_ht, 0:src_wd, slc]

    return dstarr

def reorder_image(dst_order, src_arr, src_order):
    indexes = [ src_order.index(c) for c in dst_order ]
    return numpy.dstack([ src_arr[..., idx] for idx in indexes ])


#END