epimetheus-psf 0.8.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,87 @@
1
+ import shutil
2
+ import subprocess
3
+ import warnings
4
+
5
+ def check_sextractor():
6
+ """
7
+ Check if SExtractor is installed and accessible.
8
+ Returns the name and path to the executable or None.
9
+ """
10
+ # SExtractor can be called as 'sex', 'sextractor', or 'source-extractor'
11
+ possible_names = ['sex', 'sextractor', 'source-extractor']
12
+
13
+ for name in possible_names:
14
+ path = shutil.which(name)
15
+ if path is not None:
16
+ return name, path
17
+
18
+ return None, None
19
+
20
+
21
+ def get_sextractor_version(executable):
22
+ """Get the version of SExtractor."""
23
+ try:
24
+ result = subprocess.run(
25
+ [executable, '--version'],
26
+ capture_output=True,
27
+ text=True
28
+ )
29
+ return result.stdout.strip() or result.stderr.strip()
30
+ except Exception:
31
+ return "unknown"
32
+
33
+
34
+ def require_sextractor():
35
+ """
36
+ Check for SExtractor and raise an error with installation instructions if not found.
37
+ """
38
+ sex_name , sex_path = check_sextractor()
39
+
40
+ if sex_path is None:
41
+ install_instructions = """
42
+ ╔══════════════════════════════════════════════════════════════════════════════╗
43
+ ║ SExtractor is required but not found! ║
44
+ ╠══════════════════════════════════════════════════════════════════════════════╣
45
+ ║ Please install SExtractor using one of the following methods: ║
46
+ ║ ║
47
+ ║ Ubuntu/Debian: ║
48
+ ║ sudo apt-get install sextractor ║
49
+ ║ ║
50
+ ║ macOS (Homebrew): ║
51
+ ║ brew install sextractor ║
52
+ ║ ║
53
+ ║ Conda (any platform): ║
54
+ ║ conda install -c conda-forge astromatic-source-extractor ║
55
+ ║ ║
56
+ ║ From source: ║
57
+ ║ https://github.com/astromatic/sextractor ║
58
+ ╚══════════════════════════════════════════════════════════════════════════════╝
59
+ """
60
+
61
+ warnings.warn(
62
+ install_instructions,
63
+ UserWarning
64
+ )
65
+
66
+ return sex_name, sex_path
67
+
68
+
69
+ def check_all_dependencies(verbose=True):
70
+ """
71
+ Check all external (non-Python) dependencies.
72
+ """
73
+ status = {}
74
+
75
+ # Check SExtractor
76
+ sex_name , sex_path = require_sextractor()
77
+ if sex_path:
78
+ version = get_sextractor_version(sex_path)
79
+ status['sextractor'] = {'installed': True, 'name':sex_name, 'path': sex_path, 'version': version}
80
+ if verbose:
81
+ print(f"SExtractor found: {sex_path} ({version})")
82
+ else:
83
+ status['sextractor'] = {'installed': False, 'path': None, 'version': None}
84
+ if verbose:
85
+ print("SExtractor not found")
86
+
87
+ return status
epimetheus/common.py ADDED
@@ -0,0 +1,284 @@
1
+ # epi/core.py
2
+ import numpy as np
3
+ from astropy import units as u
4
+
5
+ class ZeropointCalculator:
6
+ """Calculate AB magnitude zeropoint for astronomical images."""
7
+
8
+ # AB mag reference: 3631 Jy
9
+ AB_REFERENCE_JY = 3631.0
10
+
11
+ def __init__(self, header, bunit=None, pixel_scale=None, wavelength=None):
12
+ """
13
+ Parameters
14
+ ----------
15
+ header : fits.Header
16
+ FITS header
17
+ bunit : str, u.Unit, or None
18
+ Unit specification (header keyword or unit)
19
+ pixel_scale : float or Quantity, optional
20
+ Pixel scale in arcsec/pixel. Required for /sr units.
21
+ wavelength : float or Quantity, optional
22
+ Effective wavelength. Required for erg/s/cm²/Å type units.
23
+ If float, assumed to be in Angstrom.
24
+ """
25
+ self.header = header
26
+ self.unit = self._parse_unit(bunit)
27
+ self.pixel_scale = self._parse_pixel_scale(pixel_scale)
28
+ self.wavelength = self._parse_wavelength(wavelength)
29
+
30
+ # Determine unit type
31
+ self.unit_type = self._classify_unit()
32
+
33
+ def _parse_unit(self, bunit):
34
+ """Parse unit from header keyword or direct unit."""
35
+ if bunit is None:
36
+ bunit = "BUNIT"
37
+
38
+ if isinstance(bunit, str):
39
+ unit_str = self.header.get(bunit)
40
+ if unit_str is None:
41
+ raise KeyError(f"Header keyword '{bunit}' not found")
42
+ return u.Unit(unit_str)
43
+
44
+ elif isinstance(bunit, u.UnitBase):
45
+ return bunit
46
+
47
+ raise TypeError(f"bunit must be str or Unit, got {type(bunit).__name__}")
48
+
49
+ def _parse_pixel_scale(self, pixel_scale):
50
+ """Parse pixel scale."""
51
+ if pixel_scale is None:
52
+ # Try header
53
+ for key in ["CD1_1","PIXSCALE", "CDELT1"]:
54
+ if key in self.header:
55
+ val = np.abs(self.header[key])
56
+ if key == "CDELT1":
57
+ return (val * u.deg).to(u.arcsec)
58
+ elif key == "CD1_1":
59
+ val = np.sqrt((self.header["CD1_1"])**2 + (self.header["CD2_1"])**2)
60
+ return (val * u.deg).to(u.arcsec)
61
+ return val * u.arcsec
62
+ return None
63
+
64
+ if isinstance(pixel_scale, u.Quantity):
65
+ return pixel_scale.to(u.arcsec)
66
+ return pixel_scale * u.arcsec
67
+
68
+ def _parse_wavelength(self, wavelength):
69
+ """Parse wavelength."""
70
+ if wavelength is None:
71
+ # Try common header keywords
72
+ for key in ["PHOTPLAM", "WAVELENG", "LAMBDA_C", "CENWAVE"]:
73
+ if key in self.header:
74
+ return self.header[key] * u.AA
75
+ return None
76
+
77
+ if isinstance(wavelength, u.Quantity):
78
+ return wavelength.to(u.AA)
79
+ return wavelength * u.AA
80
+
81
+ def _classify_unit(self):
82
+ """Classify the unit type."""
83
+ # Check for frequency-based flux density (Jy, erg/s/cm²/Hz)
84
+ try:
85
+ self.unit.to(u.Jy)
86
+ return "f_nu"
87
+ except u.UnitConversionError:
88
+ pass
89
+
90
+ # Check for frequency-based surface brightness (/sr)
91
+ try:
92
+ (self.unit * u.sr).to(u.Jy)
93
+ return "f_nu_per_sr"
94
+ except u.UnitConversionError:
95
+ pass
96
+
97
+ # Check for wavelength-based flux density (erg/s/cm²/Å)
98
+ try:
99
+ self.unit.to(u.erg / u.s / u.cm**2 / u.AA)
100
+ return "f_lambda"
101
+ except u.UnitConversionError:
102
+ pass
103
+
104
+ # Check for wavelength-based surface brightness
105
+ try:
106
+ (self.unit * u.sr).to(u.erg / u.s / u.cm**2 / u.AA)
107
+ return "f_lambda_per_sr"
108
+ except u.UnitConversionError:
109
+ pass
110
+
111
+ raise ValueError(f"Cannot classify unit: {self.unit}")
112
+
113
+ @property
114
+ def pixel_solid_angle(self):
115
+ """Pixel solid angle in steradians."""
116
+ if self.pixel_scale is None:
117
+ raise ValueError(
118
+ "pixel_scale required for surface brightness units. "
119
+ "Provide pixel_scale or add PIXSCALE/CDELT1 to header."
120
+ )
121
+ return (self.pixel_scale.to(u.rad).value ** 2) * u.sr
122
+
123
+ def _f_lambda_to_f_nu(self, f_lambda):
124
+ """
125
+ Convert f_λ to f_ν.
126
+
127
+ f_ν = f_λ * λ² / c
128
+ """
129
+ if self.wavelength is None:
130
+ raise ValueError(
131
+ "wavelength required for f_λ units (erg/s/cm²/Å). "
132
+ "Provide wavelength parameter or add PHOTPLAM/WAVELENG to header."
133
+ )
134
+
135
+ # f_nu = f_lambda * lambda^2 / c
136
+ c = 2.998e18 * u.AA / u.s # speed of light in Å/s
137
+ f_nu = f_lambda * (self.wavelength**2) / c
138
+
139
+ return f_nu.to(u.erg / u.s / u.cm**2 / u.Hz)
140
+
141
+ def _to_jy(self, value=1.0):
142
+ """Convert a pixel value to Jy."""
143
+
144
+ if self.unit_type == "f_nu":
145
+ # Direct conversion to Jy
146
+ return (value * self.unit).to(u.Jy)
147
+
148
+ elif self.unit_type == "f_nu_per_sr":
149
+ # Multiply by pixel solid angle
150
+ flux = value * self.unit * self.pixel_solid_angle
151
+ return flux.to(u.Jy)
152
+
153
+ elif self.unit_type == "f_lambda":
154
+ # Convert f_λ to f_ν, then to Jy
155
+ f_lambda = value * self.unit
156
+ f_nu = self._f_lambda_to_f_nu(f_lambda)
157
+ return f_nu.to(u.Jy)
158
+
159
+ elif self.unit_type == "f_lambda_per_sr":
160
+ # Multiply by solid angle, then convert f_λ to f_ν
161
+ f_lambda = value * self.unit * self.pixel_solid_angle
162
+ f_nu = self._f_lambda_to_f_nu(f_lambda)
163
+ return f_nu.to(u.Jy)
164
+
165
+ @property
166
+ def zeropoint(self):
167
+ """
168
+ Calculate AB magnitude zeropoint.
169
+
170
+ Zeropoint = magnitude when pixel value = 1
171
+ """
172
+ flux_jy = self._to_jy(value=1.0).value
173
+
174
+ # m_AB = -2.5 * log10(f_Jy / 3631)
175
+ zp = -2.5 * np.log10(flux_jy / self.AB_REFERENCE_JY)
176
+
177
+ return zp
178
+
179
+ def __repr__(self):
180
+ info = [
181
+ f"ZeropointCalculator(",
182
+ f" unit = {self.unit}",
183
+ f" type = {self.unit_type}",
184
+ ]
185
+ if self.pixel_scale is not None:
186
+ info.append(f" pixel_scale = {self.pixel_scale:.4f}")
187
+ if self.wavelength is not None:
188
+ info.append(f" wavelength = {self.wavelength:.1f}")
189
+ info.append(f" zeropoint = {self.zeropoint:.4f} ABmag")
190
+ info.append(")")
191
+ return "\n".join(info)
192
+
193
+
194
+
195
+
196
+ def block_reduce(image, block_size=2, func=np.sum, cval=0, func_kwargs=None):
197
+ """Downsample an image by applying a function to local blocks.
198
+
199
+ NumPy-only reimplementation of ``skimage.measure.block_reduce``.
200
+ Useful for sum, max, min, mean or median pooling, as well as custom
201
+ reductions such as weighted or harmonic combinations.
202
+
203
+ Parameters
204
+ ----------
205
+ image : (M[, ...]) ndarray
206
+ N-dimensional input image.
207
+ block_size : int or array_like of int, optional
208
+ Down-sampling factor along each axis. A scalar is applied to every
209
+ axis. Default is 2.
210
+ func : callable, optional
211
+ Function used to reduce each block to a single value. It must accept
212
+ an ``axis`` keyword argument and reduce over a tuple of axes
213
+ (e.g. ``np.sum``, ``np.min``, ``np.max``, ``np.mean``, ``np.median``).
214
+ Default is ``np.sum``.
215
+ cval : float, optional
216
+ Constant value used to pad the end of each axis when the image shape
217
+ is not an exact multiple of the block size. Default is 0.
218
+ func_kwargs : dict, optional
219
+ Extra keyword arguments forwarded to ``func``, e.g.
220
+ ``{'dtype': np.float32}`` for ``np.mean``.
221
+
222
+ Returns
223
+ -------
224
+ ndarray
225
+ Down-sampled image with the same number of dimensions as the input.
226
+ Each axis has length ``ceil(shape[i] / block_size[i])``.
227
+
228
+ Raises
229
+ ------
230
+ ValueError
231
+ If ``block_size`` has a length different from ``image.ndim`` or
232
+ contains values smaller than 1.
233
+
234
+ Notes
235
+ -----
236
+ ``func`` receives an array of shape ``(n0, b0, n1, b1, ...)`` where
237
+ ``b_i`` are the block sizes, and is asked to reduce over the block axes
238
+ (1, 3, 5, ...). This differs from skimage, which puts the block axes last.
239
+ For standard NumPy reductions the result is identical.
240
+
241
+ Examples
242
+ --------
243
+ >>> image = np.arange(16).reshape(4, 4)
244
+ >>> block_reduce(image, 2, np.sum)
245
+ array([[10, 18],
246
+ [42, 50]])
247
+ >>> block_reduce(np.ones((5, 5)), 2, np.sum) # padded with zeros
248
+ array([[4., 4., 2.],
249
+ [4., 4., 2.],
250
+ [2., 2., 1.]])
251
+ """
252
+ image = np.asarray(image)
253
+
254
+ # Normalize block_size to a tuple with one entry per axis
255
+ if np.isscalar(block_size):
256
+ block_size = (int(block_size),) * image.ndim
257
+ else:
258
+ block_size = tuple(int(b) for b in block_size)
259
+ if len(block_size) != image.ndim:
260
+ raise ValueError(
261
+ "`block_size` must be a scalar or have the same length "
262
+ "as `image.shape`"
263
+ )
264
+
265
+ if any(b < 1 for b in block_size):
266
+ raise ValueError("Down-sampling factors must be >= 1.")
267
+
268
+ if func_kwargs is None:
269
+ func_kwargs = {}
270
+
271
+ # Padding needed at the end of each axis to make it divisible by the block
272
+ pad_width = [(0, (-s) % b) for s, b in zip(image.shape, block_size)]
273
+ if any(after for _, after in pad_width):
274
+ image = np.pad(image, pad_width, mode="constant", constant_values=cval)
275
+
276
+ # Split each axis into (number of blocks, block size):
277
+ # (N0, N1, ...) -> (n0, b0, n1, b1, ...)
278
+ new_shape = []
279
+ for s, b in zip(image.shape, block_size):
280
+ new_shape.extend((s // b, b))
281
+ blocked = image.reshape(new_shape)
282
+
283
+ # Reduce over the block axes, which sit at odd positions (1, 3, 5, ...)
284
+ return func(blocked, axis=tuple(range(1, blocked.ndim, 2)), **func_kwargs)
epimetheus/config.py ADDED
@@ -0,0 +1,2 @@
1
+
2
+ CACHE_DIR = "./epi"