scikit-planetary 0.0.1__tar.gz → 0.0.2__tar.gz

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.
Files changed (33) hide show
  1. scikit_planetary-0.0.2/LICENSE +21 -0
  2. scikit_planetary-0.0.2/PKG-INFO +20 -0
  3. scikit_planetary-0.0.2/README.md +169 -0
  4. scikit_planetary-0.0.2/pyproject.toml +37 -0
  5. scikit_planetary-0.0.2/src/scikit_planetary/__init__.py +26 -0
  6. scikit_planetary-0.0.2/src/scikit_planetary/hapke.py +54 -0
  7. scikit_planetary-0.0.2/src/scikit_planetary/noise.py +120 -0
  8. scikit_planetary-0.0.2/src/scikit_planetary/photometry.py +81 -0
  9. scikit_planetary-0.0.2/src/scikit_planetary/porosity.py +80 -0
  10. scikit_planetary-0.0.2/src/scikit_planetary/regularizations.py +25 -0
  11. scikit_planetary-0.0.2/src/scikit_planetary/spectra.py +96 -0
  12. scikit_planetary-0.0.2/src/scikit_planetary/thermal.py +53 -0
  13. scikit_planetary-0.0.2/src/scikit_planetary/unmixing.py +136 -0
  14. scikit_planetary-0.0.2/src/scikit_planetary.egg-info/PKG-INFO +20 -0
  15. scikit_planetary-0.0.2/src/scikit_planetary.egg-info/SOURCES.txt +25 -0
  16. scikit_planetary-0.0.2/src/scikit_planetary.egg-info/requires.txt +5 -0
  17. scikit_planetary-0.0.2/src/scikit_planetary.egg-info/top_level.txt +1 -0
  18. scikit_planetary-0.0.2/tests/test_hapke.py +78 -0
  19. scikit_planetary-0.0.2/tests/test_noise.py +131 -0
  20. scikit_planetary-0.0.2/tests/test_photometry.py +69 -0
  21. scikit_planetary-0.0.2/tests/test_porosity.py +92 -0
  22. scikit_planetary-0.0.2/tests/test_regularizations.py +62 -0
  23. scikit_planetary-0.0.2/tests/test_spectra.py +137 -0
  24. scikit_planetary-0.0.2/tests/test_thermal.py +94 -0
  25. scikit_planetary-0.0.2/tests/test_unmixing.py +172 -0
  26. scikit_planetary-0.0.1/PKG-INFO +0 -16
  27. scikit_planetary-0.0.1/README.md +0 -4
  28. scikit_planetary-0.0.1/pyproject.toml +0 -21
  29. scikit_planetary-0.0.1/scikit_planetary.egg-info/PKG-INFO +0 -16
  30. scikit_planetary-0.0.1/scikit_planetary.egg-info/SOURCES.txt +0 -6
  31. scikit_planetary-0.0.1/scikit_planetary.egg-info/top_level.txt +0 -1
  32. {scikit_planetary-0.0.1 → scikit_planetary-0.0.2}/setup.cfg +0 -0
  33. {scikit_planetary-0.0.1 → scikit_planetary-0.0.2/src}/scikit_planetary.egg-info/dependency_links.txt +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aidang116
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: scikit-planetary
3
+ Version: 0.0.2
4
+ Summary: Planetary science toolkit
5
+ Author: Aidan Gray
6
+ License: MIT
7
+ Project-URL: Repository, https://github.com/aidang116/scikit_planetary
8
+ Keywords: planetary-science,astronomy,spectroscopy,inversion,albedo
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
14
+ Requires-Python: >=3.8
15
+ License-File: LICENSE
16
+ Requires-Dist: numpy>=1.24.0
17
+ Requires-Dist: scipy>=1.10.0
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=7.0; extra == "test"
20
+ Dynamic: license-file
@@ -0,0 +1,169 @@
1
+ # scikit-planetary
2
+
3
+ **Radiative transfer, photometric modeling, spectral unmixing, and physical property inversion tools for planetary surface spectroscopy.**
4
+
5
+ `scikit-planetary` provides lightweight, NumPy- and SciPy-based utilities for analyzing visible and near-infrared (VNIR) reflectance spectra of airless planetary bodies (such as asteroids, the Moon, and meteorites). It covers the full workflow from reflectance-to-single-scattering-albedo conversion and phase-reddening correction to thermal tail weighting, diagnostic silicate band extraction, space-weathering-aware spectral unmixing, and bulk grain density / macroporosity inversion.
6
+
7
+ ---
8
+
9
+ ## Features & Modules
10
+
11
+ | Module | Functions | Description |
12
+ | :--- | :--- | :--- |
13
+ | `scikit_planetary.hapke` | `reflectance_to_ssa`<br>`ssa_to_reflectance` | Exact forward and inverse conversions between directional-hemispherical reflectance (R) and single-scattering albedo (w) using Hapke's isotropic two-stream approximation. |
14
+ | `scikit_planetary.unmixing` | `fcls_unmix_weathered_ssa`<br>`forward_weathered_ssa` | Fully Constrained Least Squares (FCLS) linear mixing of endmember SSA spectra combined with an exponential space-weathering continuum \(\exp(-S(\lambda - 0.55))\), pseudo-Huber outlier robustness, and forward spectrum evaluation. |
15
+ | `scikit_planetary.porosity` | `calculate_grain_density`<br>`calculate_macroporosity` | Effective modal mineral grain density calculation from volume fractions and endmember densities, plus bulk macroporosity \(P = 1 - \rho_{\text{bulk}} / \rho_{\text{grain}}\) with physical validity checks. |
16
+ | `scikit_planetary.spectra` | `sample_smoothed_band`<br>`compute_band_parameters` | Local median spectral sampling and automated calculation of 1 µm and 2 µm silicate absorption band depths and approximate Band Area Ratio (BAR). |
17
+ | `scikit_planetary.thermal` | `calculate_thermal_emission_weights` | NEATM-based subsolar equilibrium temperature estimation (\(T_{\text{ss}}\)) and per-channel down-weighting beyond 1.8 µm to suppress thermal emission tails on warm bodies (\(T_{\text{ss}} > 280\text{ K}\)). |
18
+ | `scikit_planetary.photometry` | `calculate_phase_reddening_coefficient`<br>`correct_phase_reddening` | Albedo-dependent logistic model for estimating spectral phase-reddening slope coefficients and removing exponential phase-reddening slopes from normalized spectra. |
19
+ | `scikit_planetary.regularizations` | `calculate_l1_sparsity_penalty` | Albedo-dependent exponential decay weighting for L1 sparsity regularization in low-SNR vs. high-SNR regimes. |
20
+ | `scikit_planetary.noise` | `calculate_channel_noise`<br>`estimate_ar1_autocorrelation`<br>`generate_ar1_noise` | Rolling-window per-channel spectral noise estimation, lag-1 residual autocorrelation estimation, and stationary AR(1) correlated spectral noise synthesis for Monte Carlo error propagation. |
21
+
22
+ ---
23
+
24
+ ## Installation
25
+
26
+ Clone the repository and install in editable mode from the root directory:
27
+
28
+ ```bash
29
+ git clone https://github.com
30
+ cd scikit_planetary
31
+ pip install -e .
32
+ ```
33
+
34
+ To include test dependencies (`pytest`):
35
+
36
+ ```bash
37
+ pip install -e ".[test]"
38
+ ```
39
+
40
+ ### Requirements
41
+ * Python >= 3.10
42
+ * `numpy`
43
+ * `scipy`
44
+
45
+ ---
46
+
47
+ ## Quickstart
48
+
49
+ ### 1. Convert Reflectance to Single-Scattering Albedo (Hapke)
50
+
51
+ ```python
52
+ import numpy as np
53
+ from scikit_planetary.hapke import reflectance_to_ssa, ssa_to_reflectance
54
+
55
+ reflectance = np.array([0.05, 0.15, 0.35])
56
+ ssa = reflectance_to_ssa(reflectance)
57
+ recovered = ssa_to_reflectance(ssa)
58
+ ```
59
+
60
+ ### 2. Compute 1 µm & 2 µm Silicate Band Parameters & Phase Correction
61
+
62
+ ```python
63
+ import numpy as np
64
+ from scikit_planetary.photometry import correct_phase_reddening
65
+ from scikit_planetary.spectra import compute_band_parameters
66
+
67
+ wv = np.linspace(0.5, 2.5, 201)
68
+ spectrum = np.ones_like(wv)
69
+ spectrum -= 0.20 * np.exp(-((wv - 1.05) / 0.15) ** 2) # 1 µm band
70
+ spectrum -= 0.10 * np.exp(-((wv - 2.00) / 0.20) ** 2) # 2 µm band
71
+
72
+ # Remove phase reddening for an observation taken at 25 deg phase angle
73
+ spectrum_corr = correct_phase_reddening(wv, spectrum, phase_angle=25.0, albedo=0.20)
74
+
75
+ depth_1, depth_2, bar_approx = compute_band_parameters(wv, spectrum_corr)
76
+ print(f"Band I Depth: {depth_1:.3f}, Band II Depth: {depth_2:.3f}, BAR: {bar_approx:.2f}")
77
+ ```
78
+
79
+ ### 3. Space-Weathered FCLS Unmixing, Grain Density & Macroporosity
80
+
81
+ ```python
82
+ import numpy as np
83
+ from scikit_planetary.hapke import reflectance_to_ssa
84
+ from scikit_planetary.noise import calculate_channel_noise
85
+ from scikit_planetary.porosity import calculate_grain_density, calculate_macroporosity
86
+ from scikit_planetary.thermal import calculate_thermal_emission_weights
87
+ from scikit_planetary.unmixing import fcls_unmix_weathered_ssa, forward_weathered_ssa
88
+
89
+ wv = np.linspace(0.45, 2.45, 100)
90
+
91
+ # Synthetic endmember reflectance library (n_channels, n_endmembers)
92
+ E_ref = np.column_stack([
93
+ 0.35 - 0.12 * np.exp(-((wv - 1.05) / 0.18) ** 2), # Olivine-like
94
+ 0.45 - 0.10 * np.exp(-((wv - 0.95) / 0.12) ** 2) - 0.08 * np.exp(-((wv - 1.95) / 0.22) ** 2), # Pyroxene-like
95
+ np.full_like(wv, 0.06), # Dark opaque
96
+ ])
97
+ E_ssa = reflectance_to_ssa(E_ref)
98
+ endmember_densities = np.array([3.32, 3.55, 2.20]) # g/cm^3
99
+
100
+ # Observed target spectrum (e.g., Near-Earth Asteroid at 1.05 AU)
101
+ y_ssa = forward_weathered_ssa(E_ssa, np.array([0.55, 0.30, 0.15]), wv, slope_S=0.22)
102
+
103
+ # Estimate channel noise & thermal emission weights
104
+ sigma = calculate_channel_noise(y_ssa[:, None])[:, 0]
105
+ w_thermal = calculate_thermal_emission_weights(helio_dist=1.05, albedo=0.14, wv_vals=wv)
106
+ weights = w_thermal / (sigma ** 2)
107
+
108
+ # Unmix abundances and space-weathering slope
109
+ abundances, slope_S, obj_val = fcls_unmix_weathered_ssa(
110
+ E_ssa=E_ssa,
111
+ y_ssa=y_ssa,
112
+ wv_vals=wv,
113
+ weights=weights,
114
+ )
115
+
116
+ # Invert mineral grain density and asteroid macroporosity
117
+ rho_grain = calculate_grain_density(abundances, endmember_densities)
118
+ porosity = calculate_macroporosity(rho_bulk=1.95, rho_grain=rho_grain)
119
+
120
+ print("Endmember abundances:", np.round(abundances, 3))
121
+ print(f"Space-weathering slope S: {slope_S:.3f}")
122
+ print(f"Grain density: {rho_grain:.2f} g/cm^3 | Macroporosity: {porosity * 100:.1f}%")
123
+ ```
124
+
125
+ ---
126
+
127
+ ## Running Tests
128
+
129
+ Run the full `pytest` suite from the repository root:
130
+
131
+ ```bash
132
+ pytest -v
133
+ ```
134
+
135
+ ---
136
+
137
+ ## Project Structure
138
+
139
+ ```text
140
+ scikit_planetary/
141
+ ├── src/
142
+ │ └── scikit_planetary/
143
+ │ ├── __init__.py
144
+ │ ├── hapke.py
145
+ │ ├── noise.py
146
+ │ ├── photometry.py
147
+ │ ├── porosity.py
148
+ │ ├── regularizations.py
149
+ │ ├── spectra.py
150
+ │ ├── thermal.py
151
+ │ └── unmixing.py
152
+ ├── tests/
153
+ │ ├── test_hapke.py
154
+ │ ├── test_noise.py
155
+ │ ├── test_photometry.py
156
+ │ ├── test_porosity.py
157
+ │ ├── test_regularizations.py
158
+ │ ├── test_spectra.py
159
+ │ ├── test_thermal.py
160
+ │ └── test_unmixing.py
161
+ ├── pyproject.toml
162
+ └── README.md
163
+ ```
164
+
165
+ ---
166
+
167
+ ## License
168
+
169
+ MIT License. See `LICENSE` for details.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scikit-planetary"
7
+ version = "0.0.2"
8
+ description = "Planetary science toolkit"
9
+ requires-python = ">=3.8"
10
+ license = { text = "MIT" }
11
+ authors = [
12
+ { name = "Aidan Gray" }
13
+ ]
14
+ keywords = ["planetary-science", "astronomy", "spectroscopy", "inversion", "albedo"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Science/Research",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Scientific/Engineering :: Astronomy",
21
+ ]
22
+ dependencies = [
23
+ "numpy>=1.24.0",
24
+ "scipy>=1.10.0",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ test = [
29
+ "pytest>=7.0",
30
+ ]
31
+
32
+ [tool.pytest.ini_options]
33
+ testpaths = ["tests"]
34
+ addopts = "-v --import-mode=importlib"
35
+
36
+ [project.urls]
37
+ Repository = "https://github.com/aidang116/scikit_planetary"
@@ -0,0 +1,26 @@
1
+ from .regularizations import calculate_l1_sparsity_penalty
2
+ from .noise import calculate_channel_noise, generate_ar1_noise, estimate_ar1_autocorrelation
3
+ from .hapke import reflectance_to_ssa, ssa_to_reflectance
4
+ from .photometry import calculate_phase_reddening_coefficient, correct_phase_reddening
5
+ from .thermal import calculate_thermal_emission_weights
6
+ from .spectra import compute_band_parameters, sample_smoothed_band
7
+ from .unmixing import fcls_unmix_weathered_ssa, forward_weathered_ssa
8
+ from .porosity import calculate_grain_density, calculate_macroporosity
9
+
10
+ __all__ = [
11
+ "calculate_l1_sparsity_penalty",
12
+ "calculate_channel_noise",
13
+ "reflectance_to_ssa",
14
+ "ssa_to_reflectance",
15
+ "calculate_phase_reddening_coefficient",
16
+ "calculate_thermal_emission_weights",
17
+ "sample_smoothed_band",
18
+ "compute_band_parameters",
19
+ "fcls_unmix_weathered_ssa",
20
+ "calculate_grain_density",
21
+ "calculate_macroporosity",
22
+ "estimate_ar1_autocorrelation",
23
+ "generate_ar1_noise",
24
+ "correct_phase_reddening",
25
+ "forward_weathered_ssa"
26
+ ]
@@ -0,0 +1,54 @@
1
+ """Hapke radiative transfer conversions between reflectance and single-scattering albedo."""
2
+
3
+ import numpy as np
4
+ from numpy.typing import ArrayLike, NDArray
5
+
6
+
7
+ def reflectance_to_ssa(R):
8
+ """Convert directional-hemispherical reflectance to single-scattering albedo (SSA).
9
+
10
+ Uses Hapke's isotropic two-stream approximation (assuming unit backscattering
11
+ and standard viewing geometry) to invert reflectance into single-scattering
12
+ albedo ``w``.
13
+
14
+ Parameters
15
+ ----------
16
+ R : float or array_like
17
+ Reflectance factor(s), clipped to ``[0.0, 0.9999]`` for numerical stability.
18
+
19
+ Returns
20
+ -------
21
+ float or ndarray
22
+ Single-scattering albedo ``w`` in ``[0.0, 1.0)``.
23
+
24
+ See Also
25
+ --------
26
+ ssa_to_reflectance : Inverse conversion from single-scattering albedo to reflectance.
27
+ """
28
+ R_clipped = np.clip(R, 0.0, 0.9999)
29
+ gamma = (1.0 - R_clipped) / (1.0 + 2.0 * R_clipped)
30
+ return 1.0 - gamma**2
31
+
32
+ def ssa_to_reflectance(w):
33
+ """Convert single-scattering albedo (SSA) to directional-hemispherical reflectance.
34
+
35
+ Uses Hapke's isotropic two-stream approximation to compute reflectance from
36
+ single-scattering albedo ``w``.
37
+
38
+ Parameters
39
+ ----------
40
+ w : float or array_like
41
+ Single-scattering albedo(s), clipped to ``[0.0, 0.9999]``.
42
+
43
+ Returns
44
+ -------
45
+ float or ndarray
46
+ Reflectance factor(s) in ``[0.0, 1.0)``.
47
+
48
+ See Also
49
+ --------
50
+ reflectance_to_ssa : Inverse conversion from reflectance to single-scattering albedo.
51
+ """
52
+ w_clipped = np.clip(w, 0.0, 0.9999)
53
+ gamma = np.sqrt(np.maximum(0.0, 1.0 - w_clipped))
54
+ return (1.0 - gamma) / (1.0 + 2.0 * gamma)
@@ -0,0 +1,120 @@
1
+ """Noise estimation utilities for planetary reflectance and SSA spectra."""
2
+
3
+ import numpy as np
4
+ from numpy.lib.stride_tricks import sliding_window_view
5
+ from numpy.typing import ArrayLike, NDArray
6
+
7
+ def calculate_channel_noise(ssa_matrix, window_size=5):
8
+ """Estimate per-channel spectral noise using a rolling standard deviation.
9
+
10
+ Pads each spectrum along the wavelength axis using edge values and computes
11
+ a moving-window standard deviation across adjacent spectral channels,
12
+ enforcing a minimum noise floor to prevent division-by-zero or overfitting
13
+ in flat spectral regions.
14
+
15
+ Parameters
16
+ ----------
17
+ ssa_matrix : array_like of shape (n_channels, n_spectra)
18
+ 2D array of single-scattering albedo (SSA) or reflectance spectra,
19
+ where rows correspond to spectral channels and columns to individual
20
+ spectra.
21
+ window_size : int, default=5
22
+ Number of adjacent spectral channels included in the moving window.
23
+
24
+ Returns
25
+ -------
26
+ ndarray of shape (n_channels, n_spectra)
27
+ Estimated per-channel noise matrix matching the input shape.
28
+ """
29
+ noise = np.zeros_like(ssa_matrix)
30
+ pad = window_size // 2
31
+ for i in range(ssa_matrix.shape[1]):
32
+ spec = ssa_matrix[:, i]
33
+ padded = np.pad(spec, (pad, pad), mode='edge')
34
+ moving_std = np.array([np.std(padded[j:j + window_size]) for j in range(len(spec))])
35
+ noise[:, i] = np.maximum(moving_std, 0.002)
36
+ return noise
37
+
38
+ def estimate_ar1_autocorrelation(
39
+ residuals: ArrayLike,
40
+ default_phi: float = 0.65,
41
+ clip_bounds: tuple[float, float] = (-0.8, 0.8),
42
+ ) -> float:
43
+ """Estimate lag-1 autocorrelation coefficient from spectral fit residuals.
44
+
45
+ Parameters
46
+ ----------
47
+ residuals : array_like of shape (n_channels,)
48
+ 1D array of spectral model residuals ordered by wavelength.
49
+ default_phi : float, default=0.65
50
+ Fallback autocorrelation coefficient returned when fewer than 3 channels
51
+ are provided or correlation is undefined (e.g., constant zero residuals).
52
+ clip_bounds : tuple of (float, float), default=(-0.8, 0.8)
53
+ Lower and upper bounds applied to the estimated lag-1 correlation to
54
+ preserve numerical stability in stationary AR(1) synthesis.
55
+
56
+ Returns
57
+ -------
58
+ float
59
+ Estimated lag-1 autocorrelation coefficient ``phi`` clipped to ``clip_bounds``.
60
+ """
61
+ res = np.asarray(residuals, dtype=float)
62
+ if res.ndim != 1:
63
+ raise ValueError("residuals must be a 1D array.")
64
+ if res.size <= 2:
65
+ return float(default_phi)
66
+
67
+ with np.errstate(divide="ignore", invalid="ignore"):
68
+ phi = np.corrcoef(res[:-1], res[1:])[0, 1]
69
+
70
+ if np.isnan(phi):
71
+ return float(default_phi)
72
+ return float(np.clip(phi, clip_bounds[0], clip_bounds[1]))
73
+
74
+
75
+ def generate_ar1_noise(
76
+ n_channels: int,
77
+ sigma: float,
78
+ phi: float = 0.65,
79
+ rng: np.random.Generator | None = None,
80
+ ) -> NDArray[np.floating]:
81
+ """Generate stationary AR(1) correlated Gaussian noise across spectral channels.
82
+
83
+ Synthesizes channel-correlated noise using
84
+ ``x[t] = phi * x[t - 1] + sqrt(1 - phi**2) * eps[t]`` where ``eps ~ N(0, sigma)``,
85
+ preserving marginal variance ``sigma**2`` across all channels.
86
+
87
+ Parameters
88
+ ----------
89
+ n_channels : int
90
+ Number of spectral channels to generate.
91
+ sigma : float
92
+ Marginal standard deviation of the noise process (non-negative).
93
+ phi : float, default=0.65
94
+ Lag-1 autocorrelation coefficient strictly inside ``(-1.0, 1.0)``.
95
+ rng : numpy.random.Generator, optional
96
+ Random number generator instance for reproducibility. Defaults to
97
+ ``np.random.default_rng()``.
98
+
99
+ Returns
100
+ -------
101
+ ndarray of shape (n_channels,)
102
+ Simulated AR(1) spectral noise vector.
103
+ """
104
+ if n_channels <= 0:
105
+ raise ValueError("n_channels must be a positive integer.")
106
+ if sigma < 0.0:
107
+ raise ValueError("sigma must be non-negative.")
108
+ if not (-1.0 < phi < 1.0):
109
+ raise ValueError("phi must be strictly between -1.0 and 1.0 for stationarity.")
110
+
111
+ generator = np.random.default_rng() if rng is None else rng
112
+ white_noise = generator.normal(0.0, sigma, size=n_channels)
113
+ ar_noise = np.zeros(n_channels, dtype=float)
114
+ ar_noise[0] = white_noise[0]
115
+
116
+ innovation_scale = np.sqrt(1.0 - phi**2)
117
+ for t in range(1, n_channels):
118
+ ar_noise[t] = phi * ar_noise[t - 1] + innovation_scale * white_noise[t]
119
+
120
+ return ar_noise
@@ -0,0 +1,81 @@
1
+ """Photometric and phase-angle correction models for planetary surfaces."""
2
+
3
+ import numpy as np
4
+ from numpy.typing import ArrayLike, NDArray
5
+
6
+
7
+ def calculate_phase_reddening_coefficient(
8
+ albedo: float | ArrayLike,
9
+ ) -> float | NDArray[np.floating]:
10
+ """Estimate the spectral phase-reddening slope coefficient from surface albedo.
11
+
12
+ Clamps input surface albedo to ``[0.02, 0.60]`` and evaluates a logistic
13
+ sigmoid curve transitioning from low phase-reddening coefficients on dark,
14
+ primitive surfaces (~0.00012 / deg) to higher coefficients on brighter,
15
+ silicate-rich surfaces (~0.00060 / deg), centered around an albedo of 0.09.
16
+
17
+ Parameters
18
+ ----------
19
+ albedo : float or array_like
20
+ Surface geometric or normal albedo (dimensionless).
21
+
22
+ Returns
23
+ -------
24
+ float or ndarray
25
+ Phase-reddening coefficient(s) bounded in ``[0.00012, 0.00060]``
26
+ (typically in units of spectral slope change per degree of phase angle).
27
+ """
28
+ a_clamped = np.clip(albedo, 0.02, 0.60)
29
+ return 0.00012 + (0.00048 / (1.0 + np.exp(-18.0 * (a_clamped - 0.09))))
30
+
31
+ def correct_phase_reddening(
32
+ wv_vals: ArrayLike,
33
+ y_norm: ArrayLike,
34
+ phase_angle: float,
35
+ albedo: float,
36
+ ref_angle: float = 5.0,
37
+ ref_wv: float = 0.55,
38
+ ) -> NDArray[np.floating]:
39
+ """Remove exponential spectral phase-reddening from a normalized reflectance spectrum.
40
+
41
+ For observations taken at solar phase angles exceeding ``ref_angle``, estimates
42
+ the albedo-dependent phase-reddening slope coefficient ``k_phase`` and applies
43
+ the exponential continuum correction
44
+ ``y_corr = y_norm * exp(-k_phase * (phase_angle - ref_angle) * (wv - ref_wv))``.
45
+ Observations at or below ``ref_angle`` (or with non-finite phase angle) are
46
+ returned unchanged.
47
+
48
+ Parameters
49
+ ----------
50
+ wv_vals : array_like of shape (n_channels,)
51
+ Wavelength grid in micrometers (µm).
52
+ y_norm : array_like of shape (n_channels,)
53
+ Normalized reflectance spectrum matching ``wv_vals``.
54
+ phase_angle : float
55
+ Solar phase angle at the time of observation in degrees.
56
+ albedo : float
57
+ Surface geometric or normal albedo (dimensionless).
58
+ ref_angle : float, default=5.0
59
+ Reference phase angle threshold in degrees below which no correction is applied.
60
+ ref_wv : float, default=0.55
61
+ Reference normalization wavelength in micrometers (µm) where the correction
62
+ factor equals 1.0.
63
+
64
+ Returns
65
+ -------
66
+ ndarray of shape (n_channels,)
67
+ Phase-corrected reflectance spectrum.
68
+ """
69
+ wv = np.asarray(wv_vals, dtype=float)
70
+ y = np.asarray(y_norm, dtype=float)
71
+
72
+ if wv.shape != y.shape:
73
+ raise ValueError("wv_vals and y_norm must have the same shape.")
74
+
75
+ if np.isfinite(phase_angle) and phase_angle > ref_angle:
76
+ k_phase = float(calculate_phase_reddening_coefficient(albedo))
77
+ phase_slope_corr = k_phase * (phase_angle - ref_angle)
78
+ phase_continuum = np.exp(-phase_slope_corr * (wv - ref_wv))
79
+ return y * phase_continuum
80
+
81
+ return y.copy()
@@ -0,0 +1,80 @@
1
+ """Physical property and bulk grain density utilities for planetary materials."""
2
+
3
+ import numpy as np
4
+ from numpy.typing import ArrayLike, NDArray
5
+
6
+
7
+ def calculate_grain_density(
8
+ volume_fractions: ArrayLike,
9
+ endmember_densities: ArrayLike,
10
+ ) -> float:
11
+ """Compute effective mineral grain density from volume fractions and endmember densities.
12
+
13
+ Converts modal volume fractions ``f_i`` and endmember mineral densities
14
+ ``rho_i`` into normalized mass fractions ``w_i`` and evaluates the
15
+ harmonic-mean bulk grain density ``1.0 / sum(w_i / rho_i)`` (mathematically
16
+ equivalent to the volume-weighted average ``sum(f_i * rho_i)`` when
17
+ ``sum(f_i) == 1``).
18
+
19
+ Parameters
20
+ ----------
21
+ volume_fractions : array_like of shape (n_endmembers,)
22
+ Modal volume or areal abundance fractions ``f_i`` (non-negative,
23
+ typically summing to 1.0).
24
+ endmember_densities : array_like of shape (n_endmembers,)
25
+ Endmember mineral grain densities in g/cm^3 (strictly positive).
26
+
27
+ Returns
28
+ -------
29
+ float
30
+ Effective bulk grain density in g/cm^3, or ``np.nan`` if inputs are
31
+ invalid or total mass is non-positive.
32
+ """
33
+ f = np.asarray(volume_fractions, dtype=float)
34
+ rho = np.asarray(endmember_densities, dtype=float)
35
+
36
+ if f.ndim != 1 or rho.ndim != 1 or f.shape != rho.shape or f.size == 0:
37
+ raise ValueError("volume_fractions and endmember_densities must be non-empty 1D arrays of equal length.")
38
+ if np.any(~np.isfinite(f)) or np.any(~np.isfinite(rho)):
39
+ return float(np.nan)
40
+ if np.any(f < 0.0) or np.any(rho <= 0.0):
41
+ raise ValueError("volume_fractions must be non-negative and endmember_densities must be strictly positive.")
42
+
43
+ mass_weights_unnorm = f * rho
44
+ total_mass = np.sum(mass_weights_unnorm)
45
+ if total_mass <= 0.0:
46
+ return float(np.nan)
47
+
48
+ w = mass_weights_unnorm / total_mass
49
+ return float(1.0 / np.sum(w / rho))
50
+
51
+ def calculate_macroporosity(
52
+ rho_bulk: float | ArrayLike,
53
+ rho_grain: float | ArrayLike,
54
+ ) -> float | NDArray[np.floating]:
55
+ """Compute macroporosity from bulk density and grain density.
56
+
57
+ Evaluates ``P = 1.0 - (rho_bulk / rho_grain)``. Returns ``np.nan`` where
58
+ inputs are non-finite, non-positive, or unphysical (``rho_bulk > rho_grain``).
59
+
60
+ Parameters
61
+ ----------
62
+ rho_bulk : float or array_like
63
+ Observed bulk density in g/cm^3.
64
+ rho_grain : float or array_like
65
+ Mineral grain density in g/cm^3.
66
+
67
+ Returns
68
+ -------
69
+ float or ndarray
70
+ Macroporosity in ``[0.0, 1.0)``, or ``np.nan`` where unconstrained or invalid.
71
+ """
72
+ is_scalar = np.ndim(rho_bulk) == 0 and np.ndim(rho_grain) == 0
73
+ rb = np.asarray(rho_bulk, dtype=float)
74
+ rg = np.asarray(rho_grain, dtype=float)
75
+
76
+ valid = np.isfinite(rb) & np.isfinite(rg) & (rb > 0.0) & (rg > 0.0) & (rb <= rg)
77
+ with np.errstate(divide="ignore", invalid="ignore"):
78
+ porosity = np.where(valid, 1.0 - (rb / rg), np.nan)
79
+
80
+ return float(porosity) if is_scalar else porosity
@@ -0,0 +1,25 @@
1
+ """Regularization and penalty functions for planetary spectrophotometric inversion."""
2
+
3
+ import numpy as np
4
+ from numpy.typing import ArrayLike, NDArray
5
+
6
+ def calculate_l1_sparsity_penalty(albedo):
7
+ """Compute an albedo-dependent L1 sparsity penalty weight.
8
+
9
+ Clamps input surface albedo to the physical range [0.02, 0.50] and applies
10
+ an exponential decay curve that assigns stronger regularization to dark,
11
+ low-albedo surfaces (where signal-to-noise is typically lower) and weaker
12
+ regularization to brighter surfaces.
13
+
14
+ Parameters
15
+ ----------
16
+ albedo : float or array_like
17
+ Surface geometric or Bond albedo (dimensionless, typically 0.0 to 1.0).
18
+
19
+ Returns
20
+ -------
21
+ float or ndarray
22
+ L1 regularization weight(s) bounded roughly between 5.0e-5 and 1.63e-4.
23
+ """
24
+ a_clamped = np.clip(albedo, 0.02, 0.50)
25
+ return 5e-5 + 1e-4 * np.exp(-12.0 * (a_clamped - 0.03))