redback.analysis.SpectralTemplateMatcher
- class redback.analysis.SpectralTemplateMatcher(template_library_path: str | Path | None = None, templates: list | None = None)[source]
Bases:
objectMatch spectra to template library (similar to SNID).
Supports Pearson correlation, chi-squared, and the recommended SNID-style rlap cross-correlation metric. Templates can be loaded from SNID .lnw files, CSV/DAT libraries, downloaded from OSC or GitHub, or generated from sncosmo spectral models.
The default template library uses sncosmo models (SALT2 for Type Ia, v19-1998bw for Ic-BL, nugent templates for Ib/c / IIP / IIn, and s11-2004hx for generic Type II), providing realistic spectral shapes at multiple phases for each type.
The default matching method is ‘rlap’, which cross-correlates in log-wavelength space (= velocity space) and is shift-invariant — a small redshift error does not degrade the match quality. A good match has rlap > 5; an excellent match has rlap > 10.
- __init__(template_library_path: str | Path | None = None, templates: list | None = None) None[source]
Initialize the SpectralTemplateMatcher with a template library.
- Parameters:
template_library_path – Path to a directory containing template files (CSV/DAT format). If None and templates is None, uses built-in sncosmo templates (SALT2, 1998bw, Nugent templates, etc.).
templates – List of template dictionaries to use directly. Each template should have keys: ‘wavelength’, ‘flux’, ‘type’, ‘phase’, and optionally ‘name’.
- __call__(**kwargs)
Call self as a function.
Methods
__init__([template_library_path, templates])Initialize the SpectralTemplateMatcher with a template library.
add_template(wavelength, flux, sn_type, phase)Add a single template to the library.
classify_spectrum(spectrum[, ...])Classify a spectrum and return a
ClassificationResult.download_github_templates(repo_url[, ...])Download template files from a GitHub repository.
filter_templates([types, phase_range])Create a new matcher with filtered templates.
from_sesn_templates([cache_dir])Create matcher from METAL/SESNtemple stripped-envelope SN templates.
from_snid_template_directory(directory[, ...])Create a SpectralTemplateMatcher from a directory of SNID template files.
from_super_snid_templates([cache_dir])Create matcher from the Super-SNID template library (Magill et al. 2025).
generate_sncosmo_templates([sources, ...])Generate spectral templates from sncosmo source models.
generate_synthetic_templates([sn_types, ...])Generate spectral templates using sncosmo models (legacy alias for
generate_sncosmo_templates()).Get information about available template sources.
match_spectrum(spectrum[, redshift_range, ...])Find the best-matching template for an observed spectrum.
parse_snid_template_file(file_path)Parse a SNID template file (.lnw format) or two-column ASCII template.
plot_match(spectrum, match_result[, axes])Plot observed spectrum against best-matching template.
save_templates(output_dir[, format])Save current templates to disk for later use.
- add_template(wavelength: ndarray, flux: ndarray, sn_type: str, phase: float, name: str | None = None) None[source]
Add a single template to the library.
- Parameters:
wavelength – Wavelength array in Angstroms
flux – Flux array (will be normalized)
sn_type – Type classification (e.g., ‘Ia’, ‘II’, ‘Ib/c’)
phase – Phase in days from maximum light
name – Optional name for the template
- classify_spectrum(spectrum, redshift_range: tuple = (0, 0.5), n_redshift_points: int = 50, top_n: int = 10, rlap_threshold: float = 3.0) ClassificationResult[source]
Classify a spectrum and return a
ClassificationResult.Type probabilities are computed via softmax over the mean rlap per type across the top_n matches. Using the mean (rather than sum) ensures that types with more templates in the library do not dominate.
- Parameters:
spectrum – Spectrum object with angstroms and flux_density attributes
redshift_range – (z_min, z_max) redshift search range
n_redshift_points – Grid points (only used if method falls back to Pearson when rlap fails)
top_n – Number of top matches to use for probability estimation
rlap_threshold – Matches below this rlap are excluded from the probability estimate. Set to 0 to include all matches.
- Returns:
ClassificationResultinstance
- static download_github_templates(repo_url: str, branch: str = 'master', subdirectory: str = '', cache_dir: str | Path | None = None) Path[source]
Download template files from a GitHub repository.
- Parameters:
repo_url – GitHub repository URL (e.g., ‘https://github.com/metal-sn/SESNtemple’)
branch – Branch name (default: ‘master’)
subdirectory – Subdirectory within repo containing templates
cache_dir – Local directory to cache files. If None, uses ~/.redback/spectral_templates/
- Returns:
Path to downloaded template directory
- filter_templates(types: list | None = None, phase_range: tuple | None = None) SpectralTemplateMatcher[source]
Create a new matcher with filtered templates.
- Parameters:
types – List of SN types to include (e.g., [‘Ia’, ‘Ib’])
phase_range – Tuple of (min_phase, max_phase) in days
- Returns:
New SpectralTemplateMatcher with filtered templates
- classmethod from_sesn_templates(cache_dir: str | Path | None = None) SpectralTemplateMatcher[source]
Create matcher from METAL/SESNtemple stripped-envelope SN templates.
Downloads templates from: https://github.com/metal-sn/SESNtemple
- Parameters:
cache_dir – Local cache directory (default: ~/.redback/spectral_templates/)
- Returns:
SpectralTemplateMatcher instance
- classmethod from_snid_template_directory(directory: str | Path, file_pattern: str = '*.lnw', recursive: bool = False) SpectralTemplateMatcher[source]
Create a SpectralTemplateMatcher from a directory of SNID template files.
- Parameters:
directory – Path to directory containing SNID template files
file_pattern – Glob pattern for template files (default: “*.lnw”)
recursive – If True, search subdirectories recursively (default: False)
- Returns:
SpectralTemplateMatcher instance
- classmethod from_super_snid_templates(cache_dir: str | Path | None = None) SpectralTemplateMatcher[source]
Create matcher from the Super-SNID template library (Magill et al. 2025).
Downloads the repository from https://github.com/dkjmagill/QUB-SNID-Templates, extracts the inner templates.zip, and loads all .lnw template files.
Please cite: Magill et al. 2025 (Zenodo DOI: 10.5281/zenodo.15167198)
- Parameters:
cache_dir – Local cache directory (default: ~/.redback/spectral_templates/)
- Returns:
SpectralTemplateMatcher instance
- classmethod generate_sncosmo_templates(sources: list | None = None, wavelength_range: tuple = (3500, 9000), n_wavelength: int = 1000) list[source]
Generate spectral templates from sncosmo source models.
By default uses SALT2, v19-1998bw (SN 1998bw / Ic-BL), nugent-sn1bc, nugent-sn2p, nugent-sn2n, and s11-2004hx. Each source is sampled at a set of representative phases.
- Parameters:
sources – Optional list of
(source_name, type_label, phases)tuples to override the default set (_SNCOSMO_TEMPLATE_SOURCES).wavelength_range – (min, max) wavelength in Angstroms
n_wavelength – Number of wavelength points
- Returns:
List of template dicts with keys ‘wavelength’, ‘flux’, ‘type’, ‘phase’, ‘name’, ‘source’
- classmethod generate_synthetic_templates(sn_types: list | None = None, wavelength_range: tuple = (3500, 9000), n_wavelength: int = 1000, r_photosphere: float = 1000000000000000.0) list[source]
Generate spectral templates using sncosmo models (legacy alias for
generate_sncosmo_templates()).This method is retained for backward compatibility. New code should call
generate_sncosmo_templates()directly.- Parameters:
sn_types – Ignored (kept for API compatibility).
wavelength_range – (min, max) wavelength in Angstroms
n_wavelength – Number of wavelength points
r_photosphere – Ignored (kept for API compatibility).
- Returns:
List of template dicts
- static get_available_template_sources() dict[source]
Get information about available template sources.
- Returns:
Dictionary with source names and their descriptions/URLs
- match_spectrum(spectrum, redshift_range: tuple = (0, 0.5), n_redshift_points: int = 50, method: str = 'rlap', return_all_matches: bool = False, rlap_threshold: float = 0.0) dict | list | None[source]
Find the best-matching template for an observed spectrum.
- Parameters:
spectrum – Spectrum object with angstroms and flux_density attributes
redshift_range – (z_min, z_max) to restrict the redshift search. For method=’rlap’, the best-fit redshift comes directly from the CCF peak and is clipped to this range. For ‘correlation’ and ‘chi2’, a grid of n_redshift_points values is searched.
n_redshift_points – Grid points for ‘correlation’/’chi2’ methods. Ignored for method=’rlap’.
method –
Matching method: - ‘rlap’ (default): SNID-style cross-correlation in log-wavelength
space. Shift-invariant. Returns rlap quality metric (>5 good, >8 excellent). Recommended for all real use.
’correlation’: Pearson correlation on a redshift grid. Legacy method.
’chi2’: Chi-squared on a redshift grid (requires flux errors for meaningful values).
’both’: Pearson + chi2 with combined normalised score.
return_all_matches – If True, return the full sorted list of match dicts.
rlap_threshold – Minimum rlap to include in results (default 0 = no filter).
- Returns:
Best match dict (or sorted list if return_all_matches=True), or None. Match dict keys: ‘type’, ‘phase’, ‘redshift’, ‘rlap’, ‘correlation’, ‘template_name’, and (if applicable) ‘chi2’, ‘reduced_chi2’, ‘scale_factor’.
- static parse_snid_template_file(file_path: str | Path)[source]
Parse a SNID template file (.lnw format) or two-column ASCII template.
For proper SNID .lnw files (Blondin & Tonry 2007), returns a list of dicts, one per epoch. For simple two-column ASCII files, returns a single dict.
The SNID .lnw format (Blondin & Tonry 2007, Appendix B):
- Line 1 — object header (8 tokens):
nwave nspec type_code type_string redshift age_of_max dm15 name- Next nwave tokens — log10(wavelength) array (may span multiple lines).
wavelength = 10^token (Angstroms). The grid is log-spaced.
- Then nspec epoch blocks, each with:
One header line:
phase_days <ignored>nwave flux tokens (may span multiple lines)
For two-column ASCII files, metadata can be provided via header comments:
# Type: IIn # Phase: -3.5
Comments are parsed case-insensitively. If a comment key is present but has no valid value, the filename is used as fallback.
- Parameters:
file_path – Path to a SNID .lnw template file or two-column ASCII
- Returns:
For .lnw files: list of template dicts, one per epoch. For ASCII files: a single template dict. Each dict has keys: ‘wavelength’, ‘flux’, ‘type’, ‘phase’, ‘name’, ‘source’
- plot_match(spectrum, match_result: dict, axes=None, **kwargs) Axes[source]
Plot observed spectrum against best-matching template.
- Parameters:
spectrum – Observed Spectrum object
match_result – Result dictionary from match_spectrum
axes – Optional matplotlib axes to plot on
kwargs – Additional plotting arguments
- Returns:
Matplotlib axes object