RSAbs 2.0.0__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.
- RSAbs/__init__.py +63 -0
- RSAbs/absorptions.py +26 -0
- RSAbs/absorptions_depth.py +23 -0
- RSAbs/compat.py +79 -0
- RSAbs/core.py +464 -0
- RSAbs/data/usgs_minerals_lut_cr.csv.gz +0 -0
- RSAbs/data/usgs_minerals_lut_raw.csv.gz +0 -0
- RSAbs/features.py +354 -0
- RSAbs/library.py +793 -0
- RSAbs/preprocessing.py +412 -0
- RSAbs/seek_absorptions.py +17 -0
- RSAbs/seek_absorptions_depth.py +60 -0
- RSAbs/viewer.py +270 -0
- RSAbs/visualization.py +232 -0
- rsabs-2.0.0.dist-info/METADATA +310 -0
- rsabs-2.0.0.dist-info/RECORD +20 -0
- rsabs-2.0.0.dist-info/WHEEL +5 -0
- rsabs-2.0.0.dist-info/entry_points.txt +2 -0
- rsabs-2.0.0.dist-info/licenses/LICENSE.txt +17 -0
- rsabs-2.0.0.dist-info/top_level.txt +1 -0
RSAbs/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""RSAbs: Reflectance Spectroscopy Absorption Detection & Mineral Identification."""
|
|
2
|
+
|
|
3
|
+
from .compat import (
|
|
4
|
+
absorptions,
|
|
5
|
+
absorptions_depth,
|
|
6
|
+
seek_absorptions,
|
|
7
|
+
seek_absorptions_depth,
|
|
8
|
+
)
|
|
9
|
+
from .core import RSAbs, SpectralAnalyzer
|
|
10
|
+
from .features import (
|
|
11
|
+
extract_features,
|
|
12
|
+
extract_spectrum_features,
|
|
13
|
+
filter_features,
|
|
14
|
+
)
|
|
15
|
+
from .library import (
|
|
16
|
+
ENVIRONMENT_PRESETS,
|
|
17
|
+
build_library_from_spectra,
|
|
18
|
+
identify_minerals,
|
|
19
|
+
list_environments,
|
|
20
|
+
list_usgs_minerals,
|
|
21
|
+
load_usgs_library,
|
|
22
|
+
)
|
|
23
|
+
from .preprocessing import (
|
|
24
|
+
DEFAULT_BAD_BANDS,
|
|
25
|
+
SENSOR_PRESETS,
|
|
26
|
+
continuum_removal,
|
|
27
|
+
mask_bands,
|
|
28
|
+
resample_spectra,
|
|
29
|
+
smooth_spectra,
|
|
30
|
+
splice_correction,
|
|
31
|
+
)
|
|
32
|
+
from .viewer import RSAbsViewer, launch_viewer
|
|
33
|
+
from .visualization import plot_spectra
|
|
34
|
+
|
|
35
|
+
__version__ = "2.0.0"
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"RSAbs",
|
|
39
|
+
"SpectralAnalyzer",
|
|
40
|
+
"continuum_removal",
|
|
41
|
+
"splice_correction",
|
|
42
|
+
"smooth_spectra",
|
|
43
|
+
"mask_bands",
|
|
44
|
+
"resample_spectra",
|
|
45
|
+
"SENSOR_PRESETS",
|
|
46
|
+
"DEFAULT_BAD_BANDS",
|
|
47
|
+
"extract_spectrum_features",
|
|
48
|
+
"extract_features",
|
|
49
|
+
"filter_features",
|
|
50
|
+
"ENVIRONMENT_PRESETS",
|
|
51
|
+
"list_environments",
|
|
52
|
+
"list_usgs_minerals",
|
|
53
|
+
"load_usgs_library",
|
|
54
|
+
"build_library_from_spectra",
|
|
55
|
+
"identify_minerals",
|
|
56
|
+
"plot_spectra",
|
|
57
|
+
"launch_viewer",
|
|
58
|
+
"RSAbsViewer",
|
|
59
|
+
"absorptions",
|
|
60
|
+
"absorptions_depth",
|
|
61
|
+
"seek_absorptions",
|
|
62
|
+
"seek_absorptions_depth",
|
|
63
|
+
]
|
RSAbs/absorptions.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from scipy.signal import find_peaks
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
import itertools
|
|
5
|
+
|
|
6
|
+
def absorptions(spectra_df, wavelength_df, integrity='ASD_CR'):
|
|
7
|
+
if isinstance(spectra_df, pd.DataFrame)==False: #Check whether spectra_df argument is satisfactory
|
|
8
|
+
print('Error: spectra_df argument not identified as pd.DataFrame')
|
|
9
|
+
if isinstance(wavelength_df, pd.DataFrame)==False: #Check whether spectra_df argument is satisfactory
|
|
10
|
+
print('Error: spectra_df argument not identified as pd.DataFrame')
|
|
11
|
+
def abs_features(spectra_df, wavelength_df):
|
|
12
|
+
spectra_array = spectra_df.values.flatten()
|
|
13
|
+
wavelength_array = wavelength_df.values.flatten()
|
|
14
|
+
if integrity=='ASD_CR':
|
|
15
|
+
absorps, _ = find_peaks(-spectra_array, width = 6, distance = 25, prominence = 0.001) #For using continuum removed spectra
|
|
16
|
+
elif integrity=='ASD_Normal':
|
|
17
|
+
absorps, _ = find_peaks(-spectra_array, width = 5, distance = 15, prominence = 0.001) #For using non-continuum removed spectra
|
|
18
|
+
elif integrity=='HyMap_CR':
|
|
19
|
+
absorps, _ = find_peaks(-spectra_array, width = 3, distance = 5, prominence = 0.001) #For using continuum removed HYMAP spectra
|
|
20
|
+
else:
|
|
21
|
+
print('Enter integrity argument based on avaiable options:"ASD_CR" for ASD continuum removed spectra, "ASD_Normal" for ASD non-continuum removed spectra, or "HyMap_CR" for HyMap continuum removed spectra. Default is "ASD_CR".')
|
|
22
|
+
|
|
23
|
+
absorp_locs = wavelength_array[absorps]
|
|
24
|
+
return pd.Series(absorp_locs) #For normal spectra
|
|
25
|
+
|
|
26
|
+
return pd.DataFrame(spectra_df.apply(abs_features, wavelength_df=wavelength_df, axis=0)) #apply is used because the abs_features function only works for one column at a time, so apply iterates the function through the columns and a new df is created. Returns a dataframe of all absorptions for each spectra/column in spectra_df
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from scipy.signal import find_peaks
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
import itertools
|
|
5
|
+
|
|
6
|
+
def absorptions_depth(spectra_df, integrity='ASD_CR'): #returns dataframe with the depth of each feature, where the depth is from the top of the convex hull (1.00) minus the value of the absorption minima
|
|
7
|
+
if isinstance(spectra_df, pd.DataFrame)==False: #Check whether spectra_df argument is satisfactory
|
|
8
|
+
print('Error: spectra_df argument not identified as pd.DataFrame')
|
|
9
|
+
def depth_props(spectra_df):
|
|
10
|
+
spectra_array = spectra_df.values.flatten()
|
|
11
|
+
if integrity=='ASD_CR':
|
|
12
|
+
absorps, props = find_peaks(-spectra_array, width = 6, distance = 25, prominence = 0.001) #For using continuum removed spectra
|
|
13
|
+
elif integrity=='ASD_Normal':
|
|
14
|
+
absorps, props = find_peaks(-spectra_array, width = 5, distance = 15, prominence = 0.001) #For using non-continuum removed spectra
|
|
15
|
+
elif integrity=='HyMap_CR':
|
|
16
|
+
absorps, props = find_peaks(-spectra_array, width = 3, distance = 5, prominence = 0.001) #For using continuum removed HYMAP spectra
|
|
17
|
+
else:
|
|
18
|
+
print('Enter integrity argument based on avaiable options:"ASD_CR" for ASD continuum removed spectra, "ASD_Normal" for ASD non-continuum removed spectra, or "HyMap_CR" for HyMap continuum removed spectra. Default is "ASD_CR".')
|
|
19
|
+
|
|
20
|
+
depths = props["prominences"]
|
|
21
|
+
return pd.Series(depths) #For normal spectra
|
|
22
|
+
|
|
23
|
+
return pd.DataFrame(spectra_df.apply(depth_props, axis=0))
|
RSAbs/compat.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Backward-compatible functional wrappers for RSAbs v0.8.1 API."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from .features import extract_features, filter_features
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _legacy_params(integrity):
|
|
10
|
+
if integrity == "ASD_CR":
|
|
11
|
+
return dict(continuum_removed=True, min_distance_nm=25.0, min_width_nm=6.0, min_prominence=0.001, min_depth=0.001)
|
|
12
|
+
if integrity == "ASD_Normal":
|
|
13
|
+
return dict(continuum_removed=False, min_distance_nm=15.0, min_width_nm=5.0, min_prominence=0.001, min_depth=0.001)
|
|
14
|
+
if integrity == "HyMap_CR":
|
|
15
|
+
return dict(continuum_removed=True, min_distance_nm=5.0, min_width_nm=3.0, min_prominence=0.001, min_depth=0.001)
|
|
16
|
+
raise ValueError(
|
|
17
|
+
'Enter integrity argument based on available options: "ASD_CR", "ASD_Normal", or "HyMap_CR".'
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _tidy_to_wide(tidy_df, columns, value_col):
|
|
22
|
+
wide = {}
|
|
23
|
+
for col in columns:
|
|
24
|
+
vals = tidy_df.loc[tidy_df["sample"] == col, value_col].to_numpy()
|
|
25
|
+
wide[col] = pd.Series(vals)
|
|
26
|
+
return pd.DataFrame(wide)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def absorptions(spectra_df, wavelength_df, integrity="ASD_CR"):
|
|
30
|
+
"""Legacy wrapper returning a wide DataFrame of absorption wavelengths."""
|
|
31
|
+
params = _legacy_params(integrity)
|
|
32
|
+
wvl = wavelength_df.to_numpy(dtype=float).flatten()
|
|
33
|
+
tidy = extract_features(spectra_df, wvl, refine_wavelength=False, **params)
|
|
34
|
+
return _tidy_to_wide(tidy, spectra_df.columns, "wavelength")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def absorptions_depth(spectra_df, integrity="ASD_CR"):
|
|
38
|
+
"""Legacy wrapper returning a wide DataFrame of absorption depths."""
|
|
39
|
+
params = _legacy_params(integrity)
|
|
40
|
+
wvl = np.arange(len(spectra_df), dtype=float)
|
|
41
|
+
tidy = extract_features(spectra_df, wvl, refine_wavelength=False, **params)
|
|
42
|
+
return _tidy_to_wide(tidy, spectra_df.columns, "depth")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def seek_absorptions(
|
|
46
|
+
absorptions_df,
|
|
47
|
+
start_wavelength=350,
|
|
48
|
+
end_wavelength=2500,
|
|
49
|
+
wavelength_unit="nanometer",
|
|
50
|
+
):
|
|
51
|
+
"""Legacy wrapper filtering wide absorptions DataFrame by wavelength range."""
|
|
52
|
+
if wavelength_unit not in {"nanometer", "micrometer"}:
|
|
53
|
+
raise ValueError('wavelength_unit must be "nanometer" or "micrometer".')
|
|
54
|
+
mask = (absorptions_df >= start_wavelength) & (absorptions_df <= end_wavelength)
|
|
55
|
+
cols = absorptions_df.columns[mask.any(axis=0)]
|
|
56
|
+
if len(cols) == 0:
|
|
57
|
+
return pd.DataFrame()
|
|
58
|
+
return absorptions_df[cols].where(mask[cols]).apply(lambda s: pd.Series(s.dropna().to_numpy()))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def seek_absorptions_depth(
|
|
62
|
+
spectra_df,
|
|
63
|
+
wavelength_df,
|
|
64
|
+
integrity="ASD_CR",
|
|
65
|
+
start_wavelength=350,
|
|
66
|
+
end_wavelength=2500,
|
|
67
|
+
wavelength_unit="nanometer",
|
|
68
|
+
):
|
|
69
|
+
"""Legacy wrapper returning absorption depths within a wavelength range."""
|
|
70
|
+
if wavelength_unit not in {"nanometer", "micrometer"}:
|
|
71
|
+
raise ValueError('wavelength_unit must be "nanometer" or "micrometer".')
|
|
72
|
+
params = _legacy_params(integrity)
|
|
73
|
+
wvl = wavelength_df.to_numpy(dtype=float).flatten()
|
|
74
|
+
tidy = extract_features(spectra_df, wvl, refine_wavelength=False, **params)
|
|
75
|
+
filtered = filter_features(tidy, min_wavelength=start_wavelength, max_wavelength=end_wavelength)
|
|
76
|
+
cols = [c for c in spectra_df.columns if c in set(filtered["sample"])]
|
|
77
|
+
if not cols:
|
|
78
|
+
return pd.DataFrame()
|
|
79
|
+
return _tidy_to_wide(filtered, cols, "depth")
|
RSAbs/core.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
"""Class-based primary interface for RSAbs spectral analysis."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import warnings
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from .features import extract_features, filter_features
|
|
9
|
+
from .preprocessing import (
|
|
10
|
+
continuum_removal,
|
|
11
|
+
mask_bands,
|
|
12
|
+
resample_spectra,
|
|
13
|
+
smooth_spectra,
|
|
14
|
+
splice_correction,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _normalize_unit(unit):
|
|
19
|
+
u = str(unit).strip().lower()
|
|
20
|
+
if u in {"nm", "nanometer", "nanometers"}:
|
|
21
|
+
return "nm"
|
|
22
|
+
if u in {"um", "micrometer", "micrometers", "micron", "microns"}:
|
|
23
|
+
return "um"
|
|
24
|
+
raise ValueError(
|
|
25
|
+
f"Unsupported wavelength_unit '{unit}'. Use 'nanometer' ('nm') or 'micrometer' ('um')."
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SpectralAnalyzer:
|
|
30
|
+
"""Object-oriented workflow for VSWIR reflectance preprocessing, feature extraction, and mineral ID.
|
|
31
|
+
|
|
32
|
+
Encapsulates spectral data alongside wavelength metadata (in nanometers) and
|
|
33
|
+
continuum-removal state so preprocessing, absorption parameterization,
|
|
34
|
+
visualization, and like-to-like USGS mineral matching stay consistent.
|
|
35
|
+
|
|
36
|
+
References:
|
|
37
|
+
Clark, R. N., & Roush, T. L. (1984). Reflectance spectroscopy:
|
|
38
|
+
Quantitative analysis techniques for remote sensing applications.
|
|
39
|
+
*Journal of Geophysical Research*, 89(B7), 6329-6340.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
spectra: Input spectral data as a ``pd.DataFrame``, 1D/2D ``np.ndarray``,
|
|
43
|
+
or path to a CSV file. If a DataFrame contains a wavelength column
|
|
44
|
+
(e.g., ``'Wavelength'``, ``'wavelength'``, ``'wvl'``) and
|
|
45
|
+
``wavelengths`` is None, it is extracted automatically.
|
|
46
|
+
wavelengths: 1D array-like, DataFrame, or Series of wavelength values.
|
|
47
|
+
wavelength_unit: Unit of input wavelengths (``'nanometer'``/``'nm'`` or
|
|
48
|
+
``'micrometer'``/``'um'``). Converted internally to nanometers.
|
|
49
|
+
continuum_removed: Whether input spectra are already continuum-removed.
|
|
50
|
+
orient: Whether individual spectra are stored as ``'columns'`` (default)
|
|
51
|
+
or ``'rows'``.
|
|
52
|
+
bad_value: Optional sentinel value (e.g., ``-1.23e34``) to replace with ``NaN``.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
spectra,
|
|
58
|
+
wavelengths=None,
|
|
59
|
+
wavelength_unit="nanometer",
|
|
60
|
+
continuum_removed=False,
|
|
61
|
+
orient="columns",
|
|
62
|
+
bad_value=None,
|
|
63
|
+
):
|
|
64
|
+
if isinstance(spectra, (str, Path)):
|
|
65
|
+
df = pd.read_csv(spectra, low_memory=False)
|
|
66
|
+
elif isinstance(spectra, pd.DataFrame):
|
|
67
|
+
df = spectra.copy()
|
|
68
|
+
elif isinstance(spectra, np.ndarray):
|
|
69
|
+
arr = np.asarray(spectra, dtype=float)
|
|
70
|
+
if arr.ndim == 1:
|
|
71
|
+
arr = arr[:, None]
|
|
72
|
+
df = pd.DataFrame(arr, columns=[f"Spectrum_{i+1}" for i in range(arr.shape[1])])
|
|
73
|
+
else:
|
|
74
|
+
raise TypeError("spectra must be a DataFrame, ndarray, or file path.")
|
|
75
|
+
|
|
76
|
+
if orient == "rows":
|
|
77
|
+
df = df.T
|
|
78
|
+
elif orient != "columns":
|
|
79
|
+
raise ValueError("orient must be 'columns' or 'rows'.")
|
|
80
|
+
|
|
81
|
+
# Auto-detect wavelength column if wavelengths not explicitly supplied
|
|
82
|
+
if wavelengths is None:
|
|
83
|
+
wvl_col = None
|
|
84
|
+
for col in df.columns:
|
|
85
|
+
if str(col).strip().lower() in {"wavelength", "wavelengths", "wvl", "lambda", "band"}:
|
|
86
|
+
wvl_col = col
|
|
87
|
+
break
|
|
88
|
+
if wvl_col is not None:
|
|
89
|
+
wvl = df[wvl_col].to_numpy(dtype=float)
|
|
90
|
+
df = df.drop(columns=[wvl_col])
|
|
91
|
+
else:
|
|
92
|
+
try:
|
|
93
|
+
wvl = df.index.to_numpy(dtype=float)
|
|
94
|
+
except (ValueError, TypeError) as exc:
|
|
95
|
+
raise ValueError(
|
|
96
|
+
"wavelengths not provided and could not be inferred from a column or numeric index."
|
|
97
|
+
) from exc
|
|
98
|
+
else:
|
|
99
|
+
if isinstance(wavelengths, (pd.DataFrame, pd.Series)):
|
|
100
|
+
wvl = wavelengths.to_numpy(dtype=float).flatten()
|
|
101
|
+
else:
|
|
102
|
+
wvl = np.asarray(wavelengths, dtype=float).flatten()
|
|
103
|
+
|
|
104
|
+
if len(wvl) != len(df):
|
|
105
|
+
raise ValueError(
|
|
106
|
+
f"Length of wavelengths ({len(wvl)}) does not match number of bands ({len(df)})."
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
unit = _normalize_unit(wavelength_unit)
|
|
110
|
+
if unit == "um":
|
|
111
|
+
wvl = wvl * 1000.0
|
|
112
|
+
|
|
113
|
+
# Ensure numeric float DataFrame and handle sentinel bad values
|
|
114
|
+
df = df.apply(pd.to_numeric, errors="coerce")
|
|
115
|
+
if bad_value is not None:
|
|
116
|
+
df = df.where(~np.isclose(df.to_numpy(dtype=float), float(bad_value), rtol=1e-5), np.nan)
|
|
117
|
+
|
|
118
|
+
# Sort ascending by wavelength
|
|
119
|
+
order = np.argsort(wvl)
|
|
120
|
+
self.wavelengths = wvl[order]
|
|
121
|
+
self.spectra = df.iloc[order].reset_index(drop=True)
|
|
122
|
+
self.continuum_removed = bool(continuum_removed)
|
|
123
|
+
self.continuum = None
|
|
124
|
+
self.features_ = None
|
|
125
|
+
|
|
126
|
+
if not self.continuum_removed and not self.spectra.empty:
|
|
127
|
+
col_max = self.spectra.max(axis=0, skipna=True)
|
|
128
|
+
col_min = self.spectra.min(axis=0, skipna=True)
|
|
129
|
+
if ((col_max >= 0.995) & (col_max <= 1.005)).mean() >= 0.5 and (col_min >= 0.0).all():
|
|
130
|
+
warnings.warn(
|
|
131
|
+
"Input spectra appear to be continuum-removed (column maxima ~= 1.0), "
|
|
132
|
+
"but continuum_removed=False. Pass continuum_removed=True so "
|
|
133
|
+
"identify_minerals() uses the continuum-removed USGS lookup table.",
|
|
134
|
+
UserWarning,
|
|
135
|
+
stacklevel=2,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def _clone(self, spectra, wavelengths=None, continuum_removed=None, continuum=None):
|
|
139
|
+
obj = SpectralAnalyzer.__new__(SpectralAnalyzer)
|
|
140
|
+
obj.wavelengths = self.wavelengths.copy() if wavelengths is None else np.asarray(wavelengths, dtype=float)
|
|
141
|
+
obj.spectra = spectra.copy()
|
|
142
|
+
obj.continuum_removed = self.continuum_removed if continuum_removed is None else bool(continuum_removed)
|
|
143
|
+
obj.continuum = continuum
|
|
144
|
+
obj.features_ = None
|
|
145
|
+
return obj
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def sample_names(self):
|
|
149
|
+
"""List of sample/spectrum column names."""
|
|
150
|
+
return list(self.spectra.columns)
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def n_samples(self):
|
|
154
|
+
"""Number of spectra."""
|
|
155
|
+
return self.spectra.shape[1]
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def n_bands(self):
|
|
159
|
+
"""Number of spectral bands."""
|
|
160
|
+
return self.spectra.shape[0]
|
|
161
|
+
|
|
162
|
+
def splice_correct(self, splice_wavelengths=(1000.0, 1800.0), method="offset", fit_bands=5):
|
|
163
|
+
"""Return a new SpectralAnalyzer with ASD detector splice jumps corrected."""
|
|
164
|
+
corr = splice_correction(
|
|
165
|
+
self.spectra,
|
|
166
|
+
self.wavelengths,
|
|
167
|
+
splice_wavelengths=splice_wavelengths,
|
|
168
|
+
method=method,
|
|
169
|
+
fit_bands=fit_bands,
|
|
170
|
+
)
|
|
171
|
+
return self._clone(corr)
|
|
172
|
+
|
|
173
|
+
def smooth(self, method="savgol", window_length=11, polyorder=2, sigma=2.0):
|
|
174
|
+
"""Return a new SpectralAnalyzer with smoothed spectra."""
|
|
175
|
+
sm = smooth_spectra(
|
|
176
|
+
self.spectra,
|
|
177
|
+
method=method,
|
|
178
|
+
window_length=window_length,
|
|
179
|
+
polyorder=polyorder,
|
|
180
|
+
sigma=sigma,
|
|
181
|
+
)
|
|
182
|
+
return self._clone(sm)
|
|
183
|
+
|
|
184
|
+
def mask_bands(self, bad_ranges=None, interpolate=False):
|
|
185
|
+
"""Return a new SpectralAnalyzer with bad/water-vapor bands masked or interpolated."""
|
|
186
|
+
masked = mask_bands(
|
|
187
|
+
self.spectra,
|
|
188
|
+
self.wavelengths,
|
|
189
|
+
bad_ranges=bad_ranges,
|
|
190
|
+
interpolate=interpolate,
|
|
191
|
+
)
|
|
192
|
+
return self._clone(masked)
|
|
193
|
+
|
|
194
|
+
def continuum_remove(self, method="convex_hull", window=None):
|
|
195
|
+
"""Return a new SpectralAnalyzer with continuum-removed spectra."""
|
|
196
|
+
cr_df, cont_df = continuum_removal(
|
|
197
|
+
self.spectra,
|
|
198
|
+
self.wavelengths,
|
|
199
|
+
method=method,
|
|
200
|
+
window=window,
|
|
201
|
+
)
|
|
202
|
+
if window is not None:
|
|
203
|
+
mask = (self.wavelengths >= window[0]) & (self.wavelengths <= window[1])
|
|
204
|
+
wvl_out = self.wavelengths[mask]
|
|
205
|
+
else:
|
|
206
|
+
wvl_out = self.wavelengths
|
|
207
|
+
return self._clone(cr_df, wavelengths=wvl_out, continuum_removed=True, continuum=cont_df)
|
|
208
|
+
|
|
209
|
+
def resample(self, target="landsat8", target_wavelengths=None, target_fwhm=None):
|
|
210
|
+
"""Return a new SpectralAnalyzer resampled to a target sensor or wavelength grid."""
|
|
211
|
+
res_df, wvl_out = resample_spectra(
|
|
212
|
+
self.spectra,
|
|
213
|
+
self.wavelengths,
|
|
214
|
+
target=target,
|
|
215
|
+
target_wavelengths=target_wavelengths,
|
|
216
|
+
target_fwhm=target_fwhm,
|
|
217
|
+
)
|
|
218
|
+
return self._clone(res_df, wavelengths=wvl_out, continuum_removed=self.continuum_removed)
|
|
219
|
+
|
|
220
|
+
def extract_features(
|
|
221
|
+
self,
|
|
222
|
+
min_depth=0.005,
|
|
223
|
+
min_prominence=0.002,
|
|
224
|
+
min_distance_nm=15.0,
|
|
225
|
+
min_width_nm=4.0,
|
|
226
|
+
refine_wavelength=True,
|
|
227
|
+
force=False,
|
|
228
|
+
):
|
|
229
|
+
"""Detect and parameterize all absorption features across all samples."""
|
|
230
|
+
if self.features_ is None or force:
|
|
231
|
+
self.features_ = extract_features(
|
|
232
|
+
self.spectra,
|
|
233
|
+
self.wavelengths,
|
|
234
|
+
continuum_removed=self.continuum_removed,
|
|
235
|
+
min_depth=min_depth,
|
|
236
|
+
min_prominence=min_prominence,
|
|
237
|
+
min_distance_nm=min_distance_nm,
|
|
238
|
+
min_width_nm=min_width_nm,
|
|
239
|
+
refine_wavelength=refine_wavelength,
|
|
240
|
+
)
|
|
241
|
+
return self.features_.copy()
|
|
242
|
+
|
|
243
|
+
def filter_features(
|
|
244
|
+
self,
|
|
245
|
+
min_wavelength=None,
|
|
246
|
+
max_wavelength=None,
|
|
247
|
+
wavelength_ranges=None,
|
|
248
|
+
min_depth=None,
|
|
249
|
+
max_depth=None,
|
|
250
|
+
min_prominence=None,
|
|
251
|
+
min_fwhm=None,
|
|
252
|
+
max_fwhm=None,
|
|
253
|
+
min_area=None,
|
|
254
|
+
samples=None,
|
|
255
|
+
):
|
|
256
|
+
"""Filter extracted absorption features by wavelength, depth, FWHM, area, or sample."""
|
|
257
|
+
feats = self.extract_features()
|
|
258
|
+
return filter_features(
|
|
259
|
+
feats,
|
|
260
|
+
min_wavelength=min_wavelength,
|
|
261
|
+
max_wavelength=max_wavelength,
|
|
262
|
+
wavelength_ranges=wavelength_ranges,
|
|
263
|
+
min_depth=min_depth,
|
|
264
|
+
max_depth=max_depth,
|
|
265
|
+
min_prominence=min_prominence,
|
|
266
|
+
min_fwhm=min_fwhm,
|
|
267
|
+
max_fwhm=max_fwhm,
|
|
268
|
+
min_area=min_area,
|
|
269
|
+
samples=samples,
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
def summary(self):
|
|
273
|
+
"""Return a per-sample summary DataFrame of detected absorption features."""
|
|
274
|
+
feats = self.extract_features()
|
|
275
|
+
if feats.empty:
|
|
276
|
+
return pd.DataFrame(
|
|
277
|
+
columns=["sample", "n_features", "deepest_wavelength", "max_depth", "mean_fwhm"]
|
|
278
|
+
)
|
|
279
|
+
rows = []
|
|
280
|
+
for sample in self.sample_names:
|
|
281
|
+
sub = feats[feats["sample"] == sample]
|
|
282
|
+
if sub.empty:
|
|
283
|
+
rows.append(
|
|
284
|
+
{
|
|
285
|
+
"sample": sample,
|
|
286
|
+
"n_features": 0,
|
|
287
|
+
"deepest_wavelength": np.nan,
|
|
288
|
+
"max_depth": np.nan,
|
|
289
|
+
"mean_fwhm": np.nan,
|
|
290
|
+
}
|
|
291
|
+
)
|
|
292
|
+
else:
|
|
293
|
+
idx_max = sub["depth"].idxmax()
|
|
294
|
+
rows.append(
|
|
295
|
+
{
|
|
296
|
+
"sample": sample,
|
|
297
|
+
"n_features": int(len(sub)),
|
|
298
|
+
"deepest_wavelength": float(sub.loc[idx_max, "wavelength"]),
|
|
299
|
+
"max_depth": float(sub.loc[idx_max, "depth"]),
|
|
300
|
+
"mean_fwhm": float(sub["fwhm"].mean()),
|
|
301
|
+
}
|
|
302
|
+
)
|
|
303
|
+
return pd.DataFrame(rows)
|
|
304
|
+
|
|
305
|
+
def identify_minerals(
|
|
306
|
+
self,
|
|
307
|
+
top_n=5,
|
|
308
|
+
mode="mixture",
|
|
309
|
+
sigma_vnir=20.0,
|
|
310
|
+
sigma_swir=8.0,
|
|
311
|
+
min_score=0.25,
|
|
312
|
+
min_residual_score=0.12,
|
|
313
|
+
min_feature_depth=0.005,
|
|
314
|
+
min_ref_coverage=0.5,
|
|
315
|
+
require_top_diagnostic=True,
|
|
316
|
+
wavelength_range=(380.0, 2480.0),
|
|
317
|
+
suppress_subsets=True,
|
|
318
|
+
discriminate_groups=True,
|
|
319
|
+
environment=None,
|
|
320
|
+
include_minerals=None,
|
|
321
|
+
exclude_minerals=None,
|
|
322
|
+
library=None,
|
|
323
|
+
):
|
|
324
|
+
"""Match detected absorption features against the USGS mineral lookup table.
|
|
325
|
+
|
|
326
|
+
Automatically selects either the continuum-removed or non-continuum-removed
|
|
327
|
+
embedded USGS ``splib07a`` lookup table to match ``self.continuum_removed``
|
|
328
|
+
(like-to-like comparison).
|
|
329
|
+
|
|
330
|
+
References:
|
|
331
|
+
Clark, R. N., et al. (2003). Imaging spectroscopy: Earth and planetary
|
|
332
|
+
remote sensing with the USGS Tetracorder and expert systems. *JGR*, 108.
|
|
333
|
+
|
|
334
|
+
Kokaly, R. F., et al. (2017). *USGS Spectral Library Version 7*
|
|
335
|
+
(Data Series 1035). U.S. Geological Survey.
|
|
336
|
+
|
|
337
|
+
Args:
|
|
338
|
+
top_n: Maximum number of top-scoring mineral candidates per sample.
|
|
339
|
+
mode: Matching mode (``'mixture'`` for IDF-weighted reference recall
|
|
340
|
+
with region-aware Gaussian distance; ``'pure'`` to also weight
|
|
341
|
+
observed precision, FWHM/asymmetry, and depth-ratio consistency).
|
|
342
|
+
sigma_vnir: Gaussian distance scale (nm) for VNIR bands (<1100 nm).
|
|
343
|
+
sigma_swir: Gaussian distance scale (nm) for SWIR bands (>=1100 nm).
|
|
344
|
+
min_score: Minimum composite match score (0-1) required to report.
|
|
345
|
+
min_residual_score: Minimum unexplained residual score (0-1) for
|
|
346
|
+
secondary minerals when ``suppress_subsets=True``.
|
|
347
|
+
min_feature_depth: Minimum depth of observed features considered.
|
|
348
|
+
min_ref_coverage: Minimum fraction (0-1) of reference features
|
|
349
|
+
that must be matched (suite-completeness check).
|
|
350
|
+
require_top_diagnostic: If True, requires the #1 diagnostic band
|
|
351
|
+
(and >=2 of top 3 for >=3-band minerals) to be present.
|
|
352
|
+
wavelength_range: Optional ``(min_nm, max_nm)`` window for matching.
|
|
353
|
+
suppress_subsets: If True, uses iterative residual scoring to
|
|
354
|
+
suppress secondary candidates riding on already-explained bands.
|
|
355
|
+
environment: Optional Utah geological environment preset
|
|
356
|
+
(``'all'``, ``'evaporite_playa'``, ``'lacustrine_carbonate'``,
|
|
357
|
+
``'clastic_redbed'``, ``'hydrothermal_alteration'``, or
|
|
358
|
+
``'marine_carbonate'``). See ``RSAbs.list_environments()``.
|
|
359
|
+
include_minerals: Optional whitelist of mineral names.
|
|
360
|
+
exclude_minerals: Optional blacklist of mineral names.
|
|
361
|
+
library: Optional custom mineral feature lookup table. If None,
|
|
362
|
+
uses the embedded USGS ``splib07a`` Minerals lookup table.
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
pd.DataFrame: Ranked mineral identification results per sample.
|
|
366
|
+
"""
|
|
367
|
+
from .library import identify_minerals
|
|
368
|
+
|
|
369
|
+
feats = self.extract_features()
|
|
370
|
+
return identify_minerals(
|
|
371
|
+
feats,
|
|
372
|
+
library=library,
|
|
373
|
+
continuum_removed=self.continuum_removed,
|
|
374
|
+
mode=mode,
|
|
375
|
+
top_n=top_n,
|
|
376
|
+
sigma_vnir=sigma_vnir,
|
|
377
|
+
sigma_swir=sigma_swir,
|
|
378
|
+
min_score=min_score,
|
|
379
|
+
min_residual_score=min_residual_score,
|
|
380
|
+
min_feature_depth=min_feature_depth,
|
|
381
|
+
min_ref_coverage=min_ref_coverage,
|
|
382
|
+
require_top_diagnostic=require_top_diagnostic,
|
|
383
|
+
wavelength_range=wavelength_range,
|
|
384
|
+
suppress_subsets=suppress_subsets,
|
|
385
|
+
discriminate_groups=discriminate_groups,
|
|
386
|
+
environment=environment,
|
|
387
|
+
include_minerals=include_minerals,
|
|
388
|
+
exclude_minerals=exclude_minerals,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
def plot(
|
|
392
|
+
self,
|
|
393
|
+
samples=None,
|
|
394
|
+
annotation_mode="none",
|
|
395
|
+
top_n_minerals=1,
|
|
396
|
+
xlim=None,
|
|
397
|
+
ylim=None,
|
|
398
|
+
x_major_tick=200.0,
|
|
399
|
+
x_minor_tick=50.0,
|
|
400
|
+
y_major_tick=0.2,
|
|
401
|
+
y_minor_tick=0.05,
|
|
402
|
+
grid=True,
|
|
403
|
+
stack_offset=0.0,
|
|
404
|
+
reference_lines=None,
|
|
405
|
+
title=None,
|
|
406
|
+
figsize=(11, 5.5),
|
|
407
|
+
ax=None,
|
|
408
|
+
save_path=None,
|
|
409
|
+
dpi=300,
|
|
410
|
+
show_legend=True,
|
|
411
|
+
):
|
|
412
|
+
"""Plot spectra with optional feature minima or grouped mineral lines.
|
|
413
|
+
|
|
414
|
+
Parameters
|
|
415
|
+
----------
|
|
416
|
+
annotation_mode : {'none', 'features', 'minerals'}, default 'none'
|
|
417
|
+
``'features'`` draws vertical lines at detected absorption minima.
|
|
418
|
+
``'minerals'`` draws one deduplicated line per mineral diagnostic
|
|
419
|
+
feature across all plotted samples.
|
|
420
|
+
"""
|
|
421
|
+
from .visualization import plot_spectra
|
|
422
|
+
|
|
423
|
+
feats = None
|
|
424
|
+
mins = None
|
|
425
|
+
mode = str(annotation_mode).lower()
|
|
426
|
+
if mode in {"features", "minerals"}:
|
|
427
|
+
feats = self.extract_features()
|
|
428
|
+
if mode == "minerals":
|
|
429
|
+
mins = self.identify_minerals(top_n=top_n_minerals)
|
|
430
|
+
|
|
431
|
+
return plot_spectra(
|
|
432
|
+
self.spectra,
|
|
433
|
+
self.wavelengths,
|
|
434
|
+
samples=samples,
|
|
435
|
+
features_df=feats,
|
|
436
|
+
minerals_df=mins,
|
|
437
|
+
annotation_mode=mode,
|
|
438
|
+
continuum_removed=self.continuum_removed,
|
|
439
|
+
xlim=xlim,
|
|
440
|
+
ylim=ylim,
|
|
441
|
+
x_major_tick=x_major_tick,
|
|
442
|
+
x_minor_tick=x_minor_tick,
|
|
443
|
+
y_major_tick=y_major_tick,
|
|
444
|
+
y_minor_tick=y_minor_tick,
|
|
445
|
+
grid=grid,
|
|
446
|
+
stack_offset=stack_offset,
|
|
447
|
+
reference_lines=reference_lines,
|
|
448
|
+
title=title,
|
|
449
|
+
figsize=figsize,
|
|
450
|
+
ax=ax,
|
|
451
|
+
save_path=save_path,
|
|
452
|
+
dpi=dpi,
|
|
453
|
+
show_legend=show_legend,
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
def launch_viewer(self):
|
|
457
|
+
"""Launch the interactive desktop viewer window for this dataset."""
|
|
458
|
+
from .viewer import launch_viewer
|
|
459
|
+
|
|
460
|
+
launch_viewer(self)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
# Convenient alias
|
|
464
|
+
RSAbs = SpectralAnalyzer
|
|
Binary file
|
|
Binary file
|