sheap.Assistants.parser_mapper module
Mappers & Parsers
Utility functions to (a) map parameter names to indices, (b) scale/unscale amplitudes, and (c) parse and enforce inter‑parameter constraints (“ties”) both during optimization and when reconstructing full parameter vectors.
Public API
mapping_params():Resolve indices in
params_dictthat match name patterns.
scale_amp()/descale_amp():Apply / undo multiplicative flux scaling on amplitude-like params.
parse_dependency()/parse_dependencies():Parse dependency strings into structured constraints.
project_params_clasic()/project_params():Clip to bounds and enforce parsed dependencies (JAX‑JIT friendly).
make_get_param_coord_value():Build a helper that retrieves (index, value, name) for a param key.
apply_arithmetic_ties()/apply_tied_and_fixed_params():Compose free→full parameter vectors using arithmetic ties.
build_tied():Convert human‑readable ties to dependency strings with indices.
flatten_tied_map():Resolve chained ties so all targets depend on free sources directly.
Constraint String Grammar
Each dependency is written as a single string and later parsed to a tuple. Supported forms (indices refer to positions in the flat parameter vector):
- Arithmetic:
"target source *k"→param[target] = param[source] * k"target source /k"→ divide;"target source +k"/-k→ additive ties.- Inequality (strict, enforced with small ε):
"target source <"→param[target] < param[source]"target source >"→param[target] > param[source]- Range (literals):
"target in [lo,hi]"→ clip target to the closed interval.- Range (between params):
"target lower_idx upper_idx"→ clip target between two indices.
Examples
- Tie two line centers with an offset of +1.2 Å:
"15 12 +1.2"
- Force a width to be less than another width:
"7 6 <"
- Keep a continuum slope within [-5, 5]:
"3 in [-5, 5]"
- Constrain a parameter between two others:
"9 2 5"
Notes
All helpers are JAX‑compatible where marked with
@jit; inputs should be JAX arrays whenever you need tracing/compilation.Arithmetic ties combine naturally for reconstruction of full parameter vectors (see
apply_tied_and_fixed_params()).
- apply_arithmetic_ties(samples, ties)[source]
Apply arithmetic constraints to parameter vector.
- Parameters:
samples (jnp.ndarray) – Parameter values.
ties (tuple) – Arithmetic tie specification.
- Returns:
Updated value for the tied parameter.
- Return type:
jnp.ndarray
- apply_tied_and_fixed_params(free_params, template_params, dependencies)[source]
Insert tied parameters into the full parameter vector using a template.
- Parameters:
free_params (jnp.ndarray) – Vector of free (optimized) parameters.
template_params (jnp.ndarray) – Template full-length parameter vector.
dependencies (list of tuple) – Structured arithmetic ties.
- Returns:
Full parameter vector including tied values.
- Return type:
jnp.ndarray
- build_tied(tied_params, get_param_coord_value)[source]
Convert human‑readable ties (using semantic keys) into dependency strings that reference indices in the flattened parameter vector.
- Parameters:
tied_params (list[list[str]]) – Each item is either
[target_key, source_key](auto “*1” or center offset) or[target_key, source_key, op_str]whereop_stris one of'*k','/k','+k','-k'(knumeric).get_param_coord_value (Callable) – Function returned by
make_get_param_coord_value()to translate semantic keys into (index, value, name).
- Returns:
Dependency strings like
"target_idx source_idx *k"ready forparse_dependencies().- Return type:
list[str]
- descale_amp(params_dict, params, scale)[source]
Reverse amplitude scaling on both amplitude and log-amplitude parameters.
- Parameters:
params_dict (dict) – Dictionary mapping parameter names to indices.
params (jnp.ndarray) – Parameter array of shape (N, D).
scale (jnp.ndarray) – Scale values of shape (N,).
- Returns:
Descaled parameter array.
- Return type:
jnp.ndarray
- flatten_tied_map(tied_map)[source]
Resolve chained ties so that every target ultimately depends on a free (non‑tied) source.
- Parameters:
tied_map (dict[int, tuple[int, str, float]]) –
target_idx -> (source_idx, op, operand)- Returns:
target_idx -> (free_source_idx, op', operand')with combined ops.- Return type:
dict[int, tuple[int, str, float]]
- make_get_param_coord_value(params_dict, initial_params)[source]
Generate a function to retrieve the index and value of a parameter by key components.
- Parameters:
params_dict (dict) – Mapping from parameter key to index.
initial_params (jnp.ndarray) – Array of parameter values.
- Returns:
Function to extract (index, value, param_name).
- Return type:
callable
- mapping_params(params_dict, params, verbose=False)[source]
Identify indices in the parameter dictionary that match given name patterns.
- Parameters:
params_dict (dict | np.ndarray) – Maps full parameter keys (e.g.,
'amplitude_Hbeta_1_broad') to indices. If an array is passed, indices are inferred from enumeration of its elements.params (str | list[str] | list[list[str]]) – One or more substring patterns. Each pattern can be a list of substrings that must all appear in the key (logical AND). Examples:
"amplitude",["amplitude", "Hbeta"], or[["amplitude"], ["center","OIII"]].verbose (bool, optional) – If
True, print matching keys.
- Returns:
1‑D array of unique matching indices (sorted).
- Return type:
jnp.ndarray
- parse_dependencies(dependencies)[source]
Parse multiple dependency strings into a tuple of structured constraints.
See the module docstring “Constraint String Grammar” for supported forms.
- Parameters:
dependencies (list[str]) – Dependency strings, e.g.,
["7 6 <", "3 in [0.1, 10.0]"].- Returns:
Parsed constraints (each an
("arithmetic"|... , ...)tuple).- Return type:
tuple
- parse_dependency(dep_str)[source]
Parse a single dependency string into structured format.
Supported formats
Arithmetic: “target source *2”
Inequality: “target source <”
Range: “target in [lower,upper]”
- param dep_str:
A dependency string.
- type dep_str:
str
- returns:
Parsed representation of the dependency.
- rtype:
tuple
- Parameters:
dep_str (str)
- project_params(params, constraints, parsed_dependencies=None)
Project parameters to satisfy individual bounds and inter-parameter constraints.
- Parameters:
params (jnp.ndarray) – Flat parameter vector.
constraints (jnp.ndarray) – Array of shape (N, 2) with lower and upper bounds.
parsed_dependencies (list of tuple, optional) – Output of parse_dependencies.
- Returns:
Projected parameter vector.
- Return type:
jnp.ndarray
- project_params_clasic(params, constraints)
Project flat parameters to satisfy individual min/max constraints.
- Parameters:
params (jnp.ndarray) – Parameter vector.
constraints (jnp.ndarray) – Constraint array of shape (N, 2) with lower and upper bounds.
- Returns:
Projected parameters within bounds.
- Return type:
jnp.ndarray
- scale_amp(params_dict, params, scale)[source]
Scale amplitude and log-amplitude parameters by a multiplicative factor. Works with both NumPy and JAX arrays.
- Parameters:
params_dict (dict) – Dictionary mapping parameter names to indices.
params (jnp.ndarray or np.ndarray) – Parameter array of shape (N, D).
scale (jnp.ndarray or np.ndarray) – Scale values of shape (N,).
- Returns:
Scaled parameter array.
- Return type:
jnp.ndarray or np.ndarray
- get_sample_params(posterior, main_key, region, line_name, param)[source]
Extract a parameter for a given emission line within a region from a posterior dictionary, for all objects. main_key = “basic_params”/extra,etc region = “narrow” #TODO require more detail
posterior = sheapspectral.result.posterior[“montecarlo”][“posterior_result”]
import numpy as np :returns: Array with shape (N_obj, N_samples, N_match) :rtype: np.ndarray
- get_multiple_sample_params(posterior, region, main_key, line_name, param)[source]
TODO add description
- summarize_spectral_lines(lines, *, gaussian_token='gaussian', print_lines=True, center_fmt='{:.3f}')[source]
Summarize a list of SpectralLine-like objects. #sheapspectral.result.sheapmodel.lines It counts:
how many entries per region (broad/narrow/wind/continuum/etc.)
how many entries are Gaussian-ish (subprofile/profile contains ‘gaussian’)
for kinematic entries (e.g., broad1), prints a mapping of region_lines <-> center
continuum components are explicitly named continuum1, continuum2, …
- Parameters:
lines (Iterable[Any]) – Iterable of SpectralLine-like objects. Must have attributes similar to: region, line_name, profile, subprofile, center, region_lines.
gaussian_token (str) – Token used to detect gaussian profiles (‘gaussian’ by default).
print_lines (bool) – If True, prints a human-readable summary.
center_fmt (str) – Format string for numeric centers.
- Returns:
summary – Dictionary with counts and parsed line mappings.
- Return type:
dict