-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathstats.py
1757 lines (1473 loc) · 59.2 KB
/
stats.py
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools for calculating the properties of sources
defined by an Aperture.
"""
import functools
import inspect
import warnings
from copy import deepcopy
import astropy.units as u
import numpy as np
from astropy.nddata import NDData, StdDevUncertainty
from astropy.stats import (SigmaClip, biweight_location, biweight_midvariance,
mad_std)
from astropy.table import QTable
from astropy.utils import lazyproperty
from astropy.utils.exceptions import AstropyUserWarning
from photutils.aperture import Aperture, SkyAperture, region_to_aperture
from photutils.aperture.core import _aperture_metadata
from photutils.utils._misc import _get_meta
from photutils.utils._moments import _moments, _moments_central
from photutils.utils._quantity_helpers import process_quantities
__all__ = ['ApertureStats']
# default table columns for `to_table()` output
DEFAULT_COLUMNS = ['id', 'xcentroid', 'ycentroid', 'sky_centroid',
'sum', 'sum_err', 'sum_aper_area', 'center_aper_area',
'min', 'max', 'mean', 'median', 'mode', 'std',
'mad_std', 'var', 'biweight_location',
'biweight_midvariance', 'fwhm', 'semimajor_sigma',
'semiminor_sigma', 'orientation', 'eccentricity']
def as_scalar(method):
"""
Return a decorated method where it will always return a scalar value
(instead of a length-1 tuple/list/array) if the class is scalar.
Parameters
----------
method : function
The method to be decorated.
Returns
-------
decorator : function
The decorated method.
"""
@functools.wraps(method)
def _decorator(*args, **kwargs):
result = method(*args, **kwargs)
try:
return (result[0] if args[0].isscalar and len(result) == 1
else result)
except TypeError: # if result has no len
return result
return _decorator
class ApertureStats:
"""
Class to create a catalog of statistics for pixels within an
aperture.
Note that this class returns the statistics of the input
``data`` values within the aperture. It does not convert data
in surface brightness units to flux or counts. Conversion from
surface-brightness units should be performed before using this
function.
Parameters
----------
data : 2D `~numpy.ndarray`, `~astropy.units.Quantity`, \
`~astropy.nddata.NDData`
The 2D array from which to calculate the source properties.
For accurate source properties, ``data`` should be
background-subtracted. Non-finite ``data`` values (NaN and inf)
are automatically masked.
aperture : `~photutils.aperture.Aperture` or supported `~regions.Region`
The aperture or region to apply to the data. The aperture
or region object may contain more than one position. If the
input ``aperture`` is a `~photutils.aperture.SkyAperture` or
`~regions.SkyRegion` object, then a WCS must be input using
the ``wcs`` keyword. Region objects are converted to aperture
objects.
error : 2D `~numpy.ndarray` or `~astropy.units.Quantity`, optional
The total error array corresponding to the input ``data``
array. ``error`` is assumed to include *all* sources of
error, including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have
the same shape as the input ``data``. If ``data`` is a
`~astropy.units.Quantity` array then ``error`` must be a
`~astropy.units.Quantity` array (and vice versa) with identical
units. Non-finite ``error`` values (NaN and +/- inf) are not
automatically masked, unless they are at the same position of
non-finite values in the input ``data`` array. Such pixels can
be masked using the ``mask`` keyword.
mask : 2D `~numpy.ndarray` (bool), optional
A boolean mask with the same shape as ``data`` where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked data are excluded from all calculations. Non-finite
values (NaN and inf) in the input ``data`` are automatically
masked.
wcs : WCS object or `None`, optional
A world coordinate system (WCS) transformation that
supports the `astropy shared interface for WCS
<https://docs.astropy.org/en/stable/wcs/wcsapi.html>`_ (e.g.,
`astropy.wcs.WCS`, `gwcs.wcs.WCS`). ``wcs`` is required if
the input ``aperture`` is a `~photutils.aperture.SkyAperture`
or `~regions.SkyRegion` object. If `None`, then all sky-based
properties will be set to `None`.
sigma_clip : `None` or `astropy.stats.SigmaClip` instance, optional
A `~astropy.stats.SigmaClip` object that defines the sigma
clipping parameters. If `None` then no sigma clipping will
be performed.
sum_method : {'exact', 'center', 'subpixel'}, optional
The method used to determine the overlap of the aperture on
the pixel grid. This method is used only for calculating the
``sum``, ``sum_error``, ``sum_aper_area``, ``data_sumcutout``,
and ``error_sumcutout`` properties. All other properties use the
"center" aperture mask method. Not all options are available for
all aperture types. The following methods are available:
* ``'exact'`` (default):
The exact fractional overlap of the aperture and each pixel is
calculated. The aperture weights will contain values between 0
and 1.
* ``'center'``:
A pixel is considered to be entirely in or out of the aperture
depending on whether its center is in or out of the aperture.
The aperture weights will contain values only of 0 (out) and 1
(in).
* ``'subpixel'``:
A pixel is divided into subpixels (see the ``subpixels``
keyword), each of which are considered to be entirely in or
out of the aperture depending on whether its center is in
or out of the aperture. If ``subpixels=1``, this method is
equivalent to ``'center'``. The aperture weights will contain
values between 0 and 1.
subpixels : int, optional
For the ``'subpixel'`` method, resample pixels by this factor
in each dimension. That is, each pixel is divided into
``subpixels**2`` subpixels. This keyword is ignored unless
``sum_method='subpixel'``.
local_bkg : float, `~numpy.ndarray`, `~astropy.units.Quantity`, or `None`
The per-pixel local background values to subtract from the data
before performing measurements. If input as an array, the order
of ``local_bkg`` values corresponds to the order of the input
``aperture`` positions. ``local_bkg`` must have the same length
as the input ``aperture`` or must be a scalar value, which
will be broadcast to all apertures. If `None`, then no local
background subtraction is performed. If the input ``data`` has
units, then ``local_bkg`` must be a `~astropy.units.Quantity`
with the same units.
Notes
-----
``data`` should be background-subtracted for accurate source
properties. In addition to global background subtraction, local
background subtraction can be performed using the ``local_bkg``
keyword values.
`~regions.Region` objects are converted to `Aperture` objects using
the :func:`region_to_aperture` function.
The returned statistics are measured for the pixels within the
input aperture at its input position. This class does not change
the position of the input aperture. This class returns the centroid
value of the pixels within the input aperture, but the input
aperture is not recentered at the measured centroid position
when making the measurements. If desired, you can create a new
`Aperture` object using the measured centroid and then re-run
`~photutils.aperture.ApertureStats`.
Most source properties are calculated using the "center"
aperture-mask method, which gives aperture weights of 0 or 1. This
avoids the need to compute weighted statistics --- the ``data``
pixel values are directly used.
The input ``sum_method`` and ``subpixels`` keywords are used
to determine the aperture-mask method when calculating the
sum-related properties: ``sum``, ``sum_error``, ``sum_aper_area``,
``data_sumcutout``, and ``error_sumcutout``. The default is
``sum_method='exact'``, which produces exact aperture-weighted
photometry.
.. _SourceExtractor: https://sextractor.readthedocs.io/en/latest/
Examples
--------
>>> from photutils.datasets import make_4gaussians_image
>>> from photutils.aperture import CircularAperture, ApertureStats
>>> data = make_4gaussians_image()
>>> aper = CircularAperture((150, 25), 8)
>>> aperstats = ApertureStats(data, aper)
>>> print(aperstats.xcentroid) # doctest: +FLOAT_CMP
149.99080259251238
>>> print(aperstats.ycentroid) # doctest: +FLOAT_CMP
24.97484633000507
>>> print(aperstats.centroid) # doctest: +FLOAT_CMP
[149.99080259 24.97484633]
>>> print(aperstats.mean, aperstats.median) # doctest: +FLOAT_CMP
47.76300955780609 31.913789514433084
>>> print(aperstats.std) # doctest: +FLOAT_CMP
39.193655383492974
>>> print(aperstats.sum) # doctest: +FLOAT_CMP
9286.709206410273
>>> print(aperstats.sum_aper_area) # doctest: +FLOAT_CMP
201.0619298297468 pix2
>>> # more than one aperture position
>>> aper2 = CircularAperture(((150, 25), (90, 60)), 10)
>>> aperstats2 = ApertureStats(data, aper2)
>>> print(aperstats2.xcentroid) # doctest: +FLOAT_CMP
[149.98470724 89.97893946]
>>> print(aperstats2.sum) # doctest: +FLOAT_CMP
[10177.62548482 36653.97704059]
"""
def __init__(self, data, aperture, *, error=None, mask=None, wcs=None,
sigma_clip=None, sum_method='exact', subpixels=5,
local_bkg=None):
if isinstance(data, NDData):
data, error, mask, wcs = self._unpack_nddata(data, error, mask,
wcs)
inputs = (data, error, local_bkg)
names = ('data', 'error', 'local_bkg')
inputs, unit = process_quantities(inputs, names)
(data, error, local_bkg) = inputs
self._data = self._validate_array(data, 'data', shape=False)
self._data_unit = unit
self._input_aperture = self._validate_aperture(aperture)
aperture_meta = _aperture_metadata(aperture) # use input aperture
if isinstance(aperture, SkyAperture) and wcs is None:
raise ValueError('A wcs is required when using a SkyAperture')
# convert region to aperture if necessary
if not isinstance(aperture, Aperture):
aperture = region_to_aperture(aperture)
self.aperture = aperture
self._error = self._validate_array(error, 'error')
self._mask = self._validate_array(mask, 'mask')
self._wcs = wcs
if sigma_clip is not None and not isinstance(sigma_clip, SigmaClip):
raise TypeError('sigma_clip must be a SigmaClip instance')
self.sigma_clip = sigma_clip
self.sum_method = sum_method
self.subpixels = subpixels
self._local_bkg = np.zeros(self.n_apertures) # no local bkg
if local_bkg is not None:
local_bkg = np.atleast_1d(local_bkg)
if local_bkg.ndim != 1:
raise ValueError('local_bkg must be a 1D array')
n_local_bkg = len(local_bkg)
if n_local_bkg not in (1, self.n_apertures):
raise ValueError('local_bkg must be scalar or have the same '
'length as the input aperture')
local_bkg = np.broadcast_to(local_bkg, self.n_apertures)
if np.any(~np.isfinite(local_bkg)):
raise ValueError('local_bkg must not contain any non-finite '
'(e.g., inf or NaN) values')
self._local_bkg = local_bkg # always an iterable
self._ids = np.arange(self.n_apertures) + 1
self.default_columns = DEFAULT_COLUMNS
self.meta = _get_meta()
self.meta.update(aperture_meta)
@staticmethod
def _unpack_nddata(data, error, mask, wcs):
nddata_attr = {'error': error, 'mask': mask, 'wcs': wcs}
for key, value in nddata_attr.items():
if value is not None:
warnings.warn(f'The {key!r} keyword will be ignored. Its '
'value is obtained from the input NDData '
'object.', AstropyUserWarning)
mask = data.mask
wcs = data.wcs
if isinstance(data.uncertainty, StdDevUncertainty):
if data.uncertainty.unit is None:
error = data.uncertainty.array
else:
error = data.uncertainty.array * data.uncertainty.unit
if data.unit is not None:
data = u.Quantity(data.data, unit=data.unit)
else:
data = data.data
return data, error, mask, wcs
@staticmethod
def _validate_aperture(aperture):
try:
from regions import Region
aper_types = (Aperture, Region)
except ImportError:
aper_types = Aperture
if not isinstance(aperture, aper_types):
raise TypeError('aperture must be an Aperture or Region object')
return aperture
def _validate_array(self, array, name, ndim=2, shape=True):
if name == 'mask' and array is np.ma.nomask:
array = None
if array is not None:
array = np.asanyarray(array)
if array.ndim != ndim:
raise ValueError(f'{name} must be a {ndim}D array.')
if shape and array.shape != self._data.shape:
raise ValueError(f'data and {name} must have the same shape.')
return array
@property
def _lazyproperties(self):
"""
A list of all class lazyproperties (even in superclasses).
"""
def islazyproperty(obj):
return isinstance(obj, lazyproperty)
return [i[0] for i in inspect.getmembers(self.__class__,
predicate=islazyproperty)]
@property
def properties(self):
"""
A sorted list of built-in source properties.
"""
lazyproperties = [name for name in self._lazyproperties if not
name.startswith('_')]
lazyproperties.sort()
return lazyproperties
def __getitem__(self, index):
if self.isscalar:
raise TypeError(f'A scalar {self.__class__.__name__!r} object '
'cannot be indexed')
newcls = object.__new__(self.__class__)
# attributes defined in __init__ that are copied directly to the
# new class
init_attr = ('_data', '_data_unit', '_error', '_mask', '_wcs',
'sigma_clip', 'sum_method', 'subpixels',
'default_columns', 'meta')
for attr in init_attr:
setattr(newcls, attr, getattr(self, attr))
# need to slice _aperture and _ids;
# aperture determines isscalar (needed below)
attrs = ('aperture', '_ids')
for attr in attrs:
setattr(newcls, attr, getattr(self, attr)[index])
# slice evaluated lazyproperty objects
keys = set(self.__dict__.keys()) & set(self._lazyproperties)
keys.add('_local_bkg') # iterable defined in __init__
for key in keys:
value = self.__dict__[key]
# do not insert attributes that are always scalar (e.g.,
# isscalar, n_apertures), i.e., not an array/list for each
# source
if np.isscalar(value):
continue
try:
# keep most _<attrs> as length-1 iterables
if (newcls.isscalar and key.startswith('_')
and key != '_pixel_aperture'):
if isinstance(value, np.ndarray):
val = value[:, np.newaxis][index]
else:
val = [value[index]]
else:
val = value[index]
except TypeError:
# apply fancy indices (e.g., array/list or bool
# mask) to lists
# see https://numpy.org/doc/stable/release/1.20.0-notes.html
# #arraylike-objects-which-do-not-define-len-and-getitem
arr = np.empty(len(value), dtype=object)
arr[:] = list(value)
val = arr[index].tolist()
newcls.__dict__[key] = val
return newcls
def __str__(self):
cls_name = f'<{self.__class__.__module__}.{self.__class__.__name__}>'
with np.printoptions(threshold=25, edgeitems=5):
fmt = [f'Length: {self.n_apertures}']
return f'{cls_name}\n' + '\n'.join(fmt)
def __repr__(self):
return self.__str__()
def __len__(self):
if self.isscalar:
raise TypeError(f'Scalar {self.__class__.__name__!r} object has '
'no len()')
return self.n_apertures
def __iter__(self):
for item in range(len(self)):
yield self.__getitem__(item)
@lazyproperty
def isscalar(self):
"""
Whether the instance is scalar (e.g., a single aperture
position).
"""
return self._pixel_aperture.isscalar
def copy(self):
"""
Return a deep copy of this object.
Returns
-------
result : `ApertureStats`
A deep copy of this object.
"""
return deepcopy(self)
@lazyproperty
def _null_object(self):
"""
Return `None` values.
"""
return np.array([None] * self.n_apertures)
@lazyproperty
def _null_value(self):
"""
Return np.nan values.
"""
values = np.empty(self.n_apertures)
values.fill(np.nan)
return values
@property
@as_scalar
def id(self):
"""
The aperture identification number(s).
"""
return self._ids
@property
def ids(self):
"""
The aperture identification number(s), always as an iterable
`~numpy.ndarray`.
"""
_ids = self._ids
if self.isscalar:
_ids = np.array((_ids,))
return _ids
def get_id(self, id_num):
"""
Return a new `ApertureStats` object for the input ID number
only.
Parameters
----------
id_num : int
The aperture ID number.
Returns
-------
result : `ApertureStats`
A new `ApertureStats` object containing only the source with
the input ID number.
"""
return self.get_ids(id_num)
def get_ids(self, id_nums):
"""
Return a new `ApertureStats` object for the input ID numbers
only.
Parameters
----------
id_nums : list, tuple, or `~numpy.ndarray` of int
The aperture ID number(s).
Returns
-------
result : `ApertureStats`
A new `ApertureStats` object containing only the sources with
the input ID numbers.
"""
for id_num in np.atleast_1d(id_nums):
if id_num not in self.ids:
raise ValueError(f'{id_num} is not a valid source ID number')
sorter = np.argsort(self.id)
indices = sorter[np.searchsorted(self.id, id_nums, sorter=sorter)]
return self[indices]
def to_table(self, columns=None):
"""
Create a `~astropy.table.QTable` of source properties.
Parameters
----------
columns : str, list of str, `None`, optional
Names of columns, in order, to include in the output
`~astropy.table.QTable`. The allowed column names are any of
the `ApertureStats` properties. If ``columns`` is `None`,
then a default list of scalar-valued properties (as defined
by the ``default_columns`` attribute) will be used.
Returns
-------
table : `~astropy.table.QTable`
A table of sources properties with one row per source.
"""
if columns is None:
table_columns = self.default_columns
elif isinstance(columns, str):
table_columns = [columns]
else:
table_columns = columns
tbl = QTable()
tbl.meta.update(self.meta) # keep tbl.meta type
for column in table_columns:
values = getattr(self, column)
# column assignment requires an object with a length
if self.isscalar:
values = (values,)
tbl[column] = values
return tbl
@lazyproperty
def n_apertures(self):
"""
The number of positions in the input aperture.
"""
if self.isscalar:
return 1
return len(self._pixel_aperture)
@lazyproperty
def _pixel_aperture(self):
"""
The input aperture as a PixelAperture.
"""
if isinstance(self.aperture, SkyAperture):
return self.aperture.to_pixel(self._wcs)
return self.aperture
@lazyproperty
def _aperture_masks_center(self):
"""
The aperture masks (`ApertureMask`) generated with the 'center'
method, always as an iterable.
"""
aperture_masks = self._pixel_aperture.to_mask(method='center')
if self.isscalar:
aperture_masks = (aperture_masks,)
return aperture_masks
@lazyproperty
def _aperture_masks(self):
"""
The aperture masks (`ApertureMask`) generated with the
``sum_method`` method, always as an iterable.
"""
aperture_masks = self._pixel_aperture.to_mask(method=self.sum_method,
subpixels=self.subpixels)
if self.isscalar:
aperture_masks = (aperture_masks,)
return aperture_masks
@lazyproperty
def _overlap_slices(self):
"""
The aperture mask overlap slices with the data, always as an
iterable.
The overlap slices are the same for all aperture mask methods.
"""
overlap_slices = []
for apermask in self._aperture_masks_center:
(slc_large, slc_small) = apermask.get_overlap_slices(
self._data.shape)
overlap_slices.append((slc_large, slc_small))
return overlap_slices
@lazyproperty
def _data_cutouts(self):
"""
The local-background-subtracted unmasked data cutouts using the
aperture bounding box, always as a iterable.
"""
cutouts = []
for (slices, local_bkg) in zip(self._overlap_slices,
self._local_bkg, strict=True):
if slices[0] is None:
cutout = None # no aperture overlap with the data
else:
# copy is needed to preserve input data because masks are
# applied to these cutouts later
cutout = (self._data[slices[0]].astype(float, copy=True)
- local_bkg)
cutouts.append(cutout)
return cutouts
def _make_aperture_cutouts(self, aperture_masks):
"""
Make aperture-weighted cutouts for the data and variance, and
cutouts for the total mask and aperture mask weights.
Parameters
----------
aperture_masks : list of `ApertureMask`
A list of `ApertureMask` objects.
Returns
-------
data, variance, mask, weights : list of `~numpy.ndarray`
A list of cutout arrays for the data, variance, mask and weight
arrays for each source (aperture position).
"""
data_cutouts = []
variance_cutouts = []
mask_cutouts = []
weight_cutouts = []
overlaps = []
for (data_cutout, apermask, slices) in zip(self._data_cutouts,
aperture_masks,
self._overlap_slices,
strict=True):
slc_large, slc_small = slices
if slc_large is None: # aperture does not overlap the data
overlap = False
data_cutout = np.array([np.nan])
variance_cutout = np.array([np.nan])
mask_cutout = np.array([False])
weight_cutout = np.array([np.nan])
else:
# create a mask of non-finite ``data`` values combined
# with the input ``mask`` array.
data_mask = ~np.isfinite(data_cutout)
if self._mask is not None:
data_mask |= self._mask[slc_large]
overlap = True
aperweight_cutout = apermask.data[slc_small]
weight_cutout = aperweight_cutout * ~data_mask
# apply the aperture mask; for "exact" and "subpixel"
# this is an expanded boolean mask using the aperture
# mask zero values
mask_cutout = (aperweight_cutout == 0) | data_mask
data_cutout = data_cutout.copy()
if self.sigma_clip is None:
# data_cutout will have zeros where mask_cutout is True
data_cutout *= ~mask_cutout
else:
# to input a mask, SigmaClip needs a MaskedArray
data_cutout_ma = np.ma.masked_array(data_cutout,
mask=mask_cutout)
data_sigclip = self.sigma_clip(data_cutout_ma)
# define a mask of only the sigma-clipped pixels
sigclip_mask = data_sigclip.mask & ~mask_cutout
weight_cutout *= ~sigclip_mask
mask_cutout = data_sigclip.mask
data_cutout = data_sigclip.filled(0.0)
# need to apply the aperture weights
data_cutout *= aperweight_cutout
if self._error is None:
variance_cutout = None
else:
# apply the exact weights and total mask;
# error_cutout will have zeros where mask_cutout is True
variance = self._error[slc_large]**2
variance_cutout = (variance * aperweight_cutout
* ~mask_cutout)
data_cutouts.append(data_cutout)
variance_cutouts.append(variance_cutout)
mask_cutouts.append(mask_cutout)
weight_cutouts.append(weight_cutout)
overlaps.append(overlap)
# use zip (instead of np.transpose) because these may contain
# arrays that have different shapes
return list(zip(data_cutouts, variance_cutouts, mask_cutouts,
weight_cutouts, overlaps, strict=True))
@lazyproperty
def _aperture_cutouts_center(self):
"""
Aperture-weighted cutouts for the data, variance, total mask,
and aperture weights using the "center" aperture mask method.
"""
return self._make_aperture_cutouts(self._aperture_masks_center)
@lazyproperty
def _aperture_cutouts(self):
"""
Aperture-weighted cutouts for the data, variance, total mask,
and aperture weights using the input ``sum_method`` aperture
mask method.
"""
return self._make_aperture_cutouts(self._aperture_masks)
@lazyproperty
def _mask_cutout_center(self):
"""
Boolean mask cutouts representing the total mask.
The total mask is combination of the input ``mask``, non-finite
``data`` values, the cutout aperture mask using the "center"
method, and the sigma-clip mask.
"""
return list(zip(*self._aperture_cutouts_center, strict=True))[2]
@lazyproperty
def _mask_cutout(self):
"""
Boolean mask cutouts representing the total mask.
The total mask is combination of the input ``mask``,
non-finite ``data`` values, the cutout aperture mask using the
``sum_method`` method, and the sigma-clip mask.
"""
return list(zip(*self._aperture_cutouts, strict=True))[2]
def _make_masked_array_center(self, array):
"""
Return a list of cutout masked arrays using the ``_mask_cutout``
mask.
Units are not applied.
"""
return [np.ma.masked_array(arr, mask=mask)
for arr, mask in zip(array, self._mask_cutout_center,
strict=True)]
def _make_masked_array(self, array):
"""
Return a list of cutout masked arrays using the
``_mask_sumcutout`` mask.
Units are not applied.
"""
return [np.ma.masked_array(arr, mask=mask)
for arr, mask in zip(array, self._mask_cutout, strict=True)]
@lazyproperty
@as_scalar
def data_cutout(self):
"""
A 2D aperture-weighted cutout from the data using the aperture
mask with the "center" method as a `~numpy.ma.MaskedArray`.
The cutout does not have units due to current limitations of
masked quantity arrays.
The mask is `True` for pixels from the input ``mask``,
non-finite ``data`` values (NaN and inf), sigma-clipped pixels
within the aperture, and pixels where the aperture mask has zero
weight.
"""
return self._make_masked_array_center(
list(zip(*self._aperture_cutouts_center, strict=True))[0])
@lazyproperty
@as_scalar
def data_sumcutout(self):
"""
A 2D aperture-weighted cutout from the data using the aperture
mask with the input ``sum_method`` method as a
`~numpy.ma.MaskedArray`.
The cutout does not have units due to current limitations of
masked quantity arrays.
The mask is `True` for pixels from the input ``mask``,
non-finite ``data`` values (NaN and inf), sigma-clipped pixels
within the aperture, and pixels where the aperture mask has zero
weight.
"""
return self._make_masked_array(list(zip(*self._aperture_cutouts,
strict=True))[0])
@lazyproperty
def _variance_cutout_center(self):
"""
A 2D aperture-weighted variance cutout using the aperture mask
with the input "center" method as a `~numpy.ma.MaskedArray`.
The cutout does not have units due to current limitations of
masked quantity arrays.
The mask is `True` for pixels from the input ``mask``,
non-finite ``data`` values (NaN and inf), sigma-clipped pixels
within the aperture, and pixels where the aperture mask has zero
weight.
"""
if self._error is None:
return self._null_object
return self._make_masked_array_center(
list(zip(*self._aperture_cutouts_center, strict=True))[1])
@lazyproperty
def _variance_cutout(self):
"""
A 2D aperture-weighted variance cutout using the aperture mask
with the input ``sum_method`` method as a
`~numpy.ma.MaskedArray`.
The cutout does not have units due to current limitations of
masked quantity arrays.
The mask is `True` for pixels from the input ``mask``,
non-finite ``data`` values (NaN and inf), sigma-clipped pixels
within the aperture, and pixels where the aperture mask has zero
weight.
"""
if self._error is None:
return self._null_object
return self._make_masked_array(list(zip(*self._aperture_cutouts,
strict=True))[1])
@lazyproperty
@as_scalar
def error_sumcutout(self):
"""
A 2D aperture-weighted error cutout using the aperture mask with
the input ``sum_method`` method as a `~numpy.ma.MaskedArray`.
The cutout does not have units due to current limitations of
masked quantity arrays.
The mask is `True` for pixels from the input ``mask``,
non-finite ``data`` values (NaN and inf), sigma-clipped pixels
within the aperture, and pixels where the aperture mask has zero
weight.
"""
if self._error is None:
return self._null_object
return [np.sqrt(var) for var in self._variance_cutout]
@lazyproperty
def _weight_cutout_center(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the aperture mask
weights array using the aperture bounding box.
The aperture mask weights are for the "center" method.
The mask is `True` for pixels outside of the aperture mask,
pixels from the input ``mask``, non-finite ``data`` values (NaN
and inf), and sigma-clipped pixels.
"""
return self._make_masked_array_center(
list(zip(*self._aperture_cutouts_center, strict=True))[3])
@lazyproperty
def _weight_cutout(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the aperture mask
weights array using the aperture bounding box.
The aperture mask weights are for the ``sum_method`` method.
The mask is `True` for pixels outside of the aperture mask,
pixels from the input ``mask``, non-finite ``data`` values (NaN
and inf), and sigma-clipped pixels.
"""
return self._make_masked_array(list(zip(*self._aperture_cutouts,
strict=True))[3])
@lazyproperty
def _moment_data_cutout(self):
"""
A list of 2D `~numpy.ndarray` cutouts from the data.
Masked pixels are set to zero in these arrays (zeros do not
contribute to the image moments). The aperture mask weights are
for the "center" method.
These arrays are used to derive moment-based properties.
"""
data = deepcopy(self.data_cutout) # self.data_cutout is a list
if self.isscalar:
data = (data,)
cutouts = []
for arr in data:
if arr.size == 1 and np.isnan(arr[0]): # no aperture overlap
arr_ = np.empty((2, 2))
arr_.fill(np.nan)
else:
arr_ = arr.data
arr_[arr.mask] = 0.0
cutouts.append(arr_)
return cutouts
@lazyproperty
def _all_masked(self):
"""
True if all pixels within the aperture are masked.
"""
return np.array([np.all(mask) for mask in self._mask_cutout_center])
@lazyproperty
def _overlap(self):
"""
True if there is no overlap of the aperture with the data.
"""
return list(zip(*self._aperture_cutouts_center, strict=True))[4]
def _get_values(self, array):
"""
Get a 1D array of unmasked aperture-weighted values from the
input array.
An array with a single NaN is returned for completely-masked
sources.
"""
if self.isscalar:
array = (array,)
return [arr.compressed() if len(arr.compressed()) > 0
else np.array([np.nan]) for arr in array]
@lazyproperty
def _data_values_center(self):
"""
A 1D array of unmasked aperture-weighted data values using the
"center" method.
An array with a single NaN is returned for completely-masked
sources.
"""
return self._get_values(self.data_cutout)
@lazyproperty
@as_scalar
def moments(self):
"""
Spatial moments up to 3rd order of the source.
"""
return np.array([_moments(arr, order=3) for arr in
self._moment_data_cutout])