astrocook.core.system_list module#
- astrocook.core.system_list.get_all_w_rest(series_name: str) List[float][source]#
Returns a list of rest wavelengths in Angstroms for a given series name. Handles single lines, standard multiplets, and custom comma-separated lists.
- astrocook.core.system_list.FWHM_BLEND_FACTOR = 1.0#
Blend threshold in units of the instrumental FWHM (findings register F14): two lines are grouped when their centres are closer than
FWHM_BLEND_FACTORtimes the FWHM, i.e. when their instrumental profiles overlap above half maximum (Guido’s choice, October 2026). The thresholds4 band 30 km/s are kept as floors (they were the whole rule before F14, and the only one when the resolution is unknown).
- astrocook.core.system_list.instrumental_fwhm(spec: Spectrum | None)[source]#
Instrumental FWHM (km/s) of a spectrum as a function of the observed wavelength in Angstrom, from its
resolcolumn (#526).Returns
Noneif there is no spectrum or it has no resolution; the returned function gives NaN outside the range of the spectrum.
- astrocook.core.system_list.are_overlapping(c1: ComponentData, c2: ComponentData, constraints_map: dict, fwhm_at=None) bool[source]#
Checks if two components should be grouped together for fitting.
fwhm_at(frominstrumental_fwhm()) gives the instrumental FWHM at a wavelength: two lines are blended when their centres are closer thanmax(4 b, 30 km/s, FWHM_BLEND_FACTOR * FWHM)(F14), with the larger FWHM of the two lines. Without it (or where the resolution is unknown) the threshold ismax(4 b, 30 km/s).
- class astrocook.core.system_list.SystemList(data: SystemListData)[source]#
Bases:
objectAPI layer for managing component lists, constraints, and fitting.
This class wraps the immutable
SystemListDataand provides methods to add, update, delete, and group components. It also initializes the constraint model used by the fitting engine.- Parameters:
data (SystemListData) – The core data container holding the list of components and constraint maps.
- __init__(data: SystemListData)[source]#
- constraint_model: VoigtModelConstraint#
- property components: List[ComponentData]#
List of all component data objects.
- property t: Table#
Returns an Astropy Table representation of the system list. Useful for quick inspection or V1 compatibility.
- property z: List[float]#
List of redshifts for all components.
- property series: List[str]#
List of series names for all components.
- property id: List[int]#
List of integer IDs for all components.
- property v1_models_t: Any#
- property constraint_status: Dict[str, ndarray]#
Dictionary reflecting the free/fixed status of parameters.
- property parsed_constraints: Dict[Tuple[str, str], ParameterConstraint]#
- property v2_constraints_for_save: Dict[str, Dict[str, Any]]#
- fitting_context(active_uuids: List[str] | None = None, group_depth: int = 2, spec: Spectrum | None = None)[source]#
Context manager for safe fitting.
Temporarily sets the active fitting mask on the constraint model and guarantees cleanup (resetting the mask) even if errors occur.
- Parameters:
active_uuids (list of str, optional) – List of UUIDs to set as active.
group_depth (int, optional) – Grouping depth for finding connected components. Defaults to
2.spec (Spectrum, optional) – The spectrum to be fitted: its resolution sets the blend threshold of the grouping (see
get_connected_group()).
- add_components_from_regions(spec: Spectrum, region_id_col: str, series_map: Dict[int, str], z_map: Dict[int, float]) SystemList[source]#
Populate the list with initial components based on identified regions.
- Parameters:
spec (Spectrum) – The spectrum containing the region definitions.
region_id_col (str) – Name of the column containing region IDs (e.g.,
'abs_ids').series_map (dict) – Mapping
{region_id: series_name}.z_map (dict) – Mapping
{region_id: redshift}.
- Returns:
A new instance populated with the identified components.
- Return type:
- add_component(series: str, z: float, logN: float = 13.5, b: float = 10.0, btur: float = 0.0) SystemList[source]#
Return a new SystemList with properties of a specific component updated.
- Parameters:
uuid (str) – The UUID of the component to update.
**changes (dict) – Keyword arguments for the fields to change (e.g.
z=2.5,logN=14.0).
- Returns:
A new instance with the updated component.
- Return type:
- get_component_by_uuid(uuid: str) ComponentData | None[source]#
Retrieve a component object by its UUID.
- Parameters:
uuid (str) – The unique identifier of the component.
- Returns:
The component object, or None if not found.
- Return type:
ComponentData or None
- update_component(uuid: str, **changes) SystemList[source]#
Return a new SystemList with properties of a specific component updated.
- Parameters:
uuid (str) – The UUID of the component to update.
**changes (dict) – Keyword arguments for the fields to change (e.g.
z=2.5,logN=14.0).
- Returns:
A new instance with the updated component.
- Return type:
- update_components(uuids: List[str], **changes) SystemList[source]#
Batch update parameters for multiple components in a single pass.
This method is significantly faster than calling
update_component()repeatedly because it creates a new immutable state only once after applying all changes.- Parameters:
uuids (list of str) – A list of component UUIDs to update.
**changes (dict) – Keyword arguments specifying the fields to update (e.g.,
z=2.5). Changes are applied identically to all specified components.
- Returns:
A new instance with the components updated.
- Return type:
- update_constraint(uuid: str, param: str, is_free: bool | None = None, expression: str | None = None, target_uuid: str | None = None) SystemList[source]#
Update the constraint for a specific component parameter.
- Parameters:
uuid (str) – The component UUID.
param (str) – The parameter name (e.g.,
'z','logN').is_free (bool, optional) – If True, parameter varies freely. If False, it is fixed or linked.
expression (str, optional) – Mathematical string for linking (e.g.
"p['target_uuid'].z").target_uuid (str, optional) – UUID of the component this parameter is linked to.
- Returns:
A new instance with the updated constraints.
- Return type:
- delete_component(uuid: str | None = None, uuids: list | None = None) SystemList[source]#
Remove component(s) and clean up constraints linking to them.
- Parameters:
- Returns:
A new instance with components removed and constraints cleaned.
- Return type:
- get_connected_group(seed_uuids: Collection[str], max_depth: int = 2, spec: Spectrum | None = None) Set[str][source]#
Find a set of components that must be fitted together.
This method traverses relationships to find all “fluid neighbors” of the seed components (via links, spectral overlap, or kinematic proximity).
- Parameters:
seed_uuids (list of str) – The UUIDs of the components initially selected for fitting.
max_depth (int, optional) – How many degrees of separation to traverse. Defaults to
2.spec (Spectrum, optional) – The spectrum the components are fitted to. Lines closer than its instrumental FWHM are blended (findings register F14, see
are_overlapping()); without it, onlymax(4 b, 30 km/s).
- Returns:
The full set of UUIDs in the connected group.
- Return type:
set of str
- fit_groups(seed_uuids, max_depth: int, spec: Spectrum | None = None, max_size: int | None = None) List[List[str]][source]#
The groups of components that are fitted together, as Refit All fits them (moved here from
refit_allin phase 6-ter, PR 3, so that the MCP server shows the same groups).The seeds are taken by increasing redshift (then series): the group of a seed is
get_connected_group()(it can take in components that are not seeds), and its members are not seeds again. A group larger thanmax_sizeis split in chunks ofmax_sizecomponents, by redshift.- Parameters:
seed_uuids (iterable of str) – The components to group (e.g. those in the region of the fit).
max_depth (int) – Depth of the friends-of-friends expansion (
get_connected_group()).spec (Spectrum, optional) – The spectrum the components are fitted to (its resolution sets which lines are blended).
max_size (int, optional) – The largest group fitted at once; None: no limit.
- Returns:
The groups, each sorted by redshift (then series), in the order of their seeds. A component pulled in by two seeds is in both groups, as in
refit_all.- Return type:
list of list of str
- merge(other: SystemList, copy_uuids: bool = False) SystemList[source]#
Merge components from another system list into this one.
- Parameters:
other (SystemList) – The source list to copy from.
copy_uuids (bool, optional) – If True, keeps original UUIDs (risky if merging into self). If False, regenerates UUIDs to avoid conflicts. Defaults to
False.
- Returns:
A new merged system list.
- Return type:
- optimize_hierarchy(spec: Spectrum, uuid_seed: str, max_components: int = 5, threshold_sigma: float = 2.5, aic_penalty: float = 0.0, z_window_kms: float = 100.0, min_dv: float = 10.0, group_depth: int = 2, patience: int = 2, trace: dict | None = None, max_nfev: int = 1000) SystemList[source]#
Iteratively adds components to a system to minimize residuals using the Akaike Information Criterion (AIC).
This method performs the following steps:
Baseline Fit: Fits the seed component (and its connected group) to establish a baseline AIC.
Residual Scan: Calculates the residuals (Flux - Model) over the specified velocity window.
Candidate Detection: Identifies the strongest un-modeled absorption feature (negative residual).
Trial: If the feature exceeds
threshold_sigma, adds a new component at that position.Evaluation: Fits the new configuration. If AIC improves (decreases) by
aic_penalty, the new component is kept.Termination: Repeats until
max_componentsis reached orpatienceis exhausted.
- Parameters:
spec (Spectrum) – The spectrum data used for fitting and residual calculation.
uuid_seed (str) – UUID of the seed component. This defines the series (e.g. CIV) and the center of the velocity search window.
max_components (int, optional) – Maximum number of candidates tried, each counting also when rejected or too close to a component (default: 5).
threshold_sigma (float, optional) – Significance level (in standard deviations) of the residual dip required to trigger a new component trial (default: 2.5).
aic_penalty (float, optional) – Minimum AIC improvement required to accept a new component (default: 0.0). Higher values favor simpler models (Occam’s razor).
z_window_kms (float, optional) – Half-width (km/s) of the window around the first line of the seed component, where the residuals are searched and the AIC is computed; also passed to the fits, where it bounds how far the redshifts can move (default: 100.0).
min_dv (float, optional) – Minimum velocity separation (km/s) required between a candidate and existing components. Lower this to de-blend close doublets (default: 10.0).
group_depth (int, optional) – Depth for finding connected neighbors during the fit (default: 2).
patience (int, optional) – Number of consecutive trials allowed without AIC improvement before stopping (default: 2).
max_nfev (int, optional) – Maximum number of evaluations of the model in each fit (default: 1000). A fit that does not converge within it counts as failed (AIC infinite): its candidate is rejected (F149).
trace (dict, optional) – Filled with what the search did (F118, trial 3 of the MCP server):
start_aic,tried(one dict per candidate:z,residual_sigma,outcome, andaic_before/aic_afterwhen it was fitted) andstopped(the reason).
- Returns:
A new system list containing the optimized components.
- Return type:
- remove_in_region(obs_min: Quantity, obs_max: Quantity) SystemList[source]#
Remove components whose center falls within the observed wavelength range.
- Parameters:
obs_min (Quantity) – The wavelength bounds.
obs_max (Quantity) – The wavelength bounds.
- Returns:
A new instance with components removed.
- Return type:
- filter_by_criteria(condition_func) SystemList[source]#
Remove components whose center falls within the observed wavelength range.
- Parameters:
obs_min (Quantity) – The wavelength bounds.
obs_max (Quantity) – The wavelength bounds.
- Returns:
A new instance with components removed.
- Return type:
- filter_by_range(xmin_nm: float, xmax_nm: float) SystemList[source]#
Return a new SystemList containing only components within the range.
- Parameters:
xmin_nm (float) – Wavelength range in nanometers.
xmax_nm (float) – Wavelength range in nanometers.
- Returns:
A new instance with filtered components.
- Return type: