ShareModule¶
ShareModule is a wrapper around JAX/Equinox models that enables parameter sharing and provides utilities for model inspection and manipulation.
Building Models¶
Use build_model() to turn your Equinox model into a spectracles model (a
ShareModule). It accepts either a model instance, or the model class followed
by its constructor arguments; the two are equivalent:
import spectracles as sp
model = sp.build_model(MyModel(shared_component=inner, ...))
model = sp.build_model(MyModel, shared_component=inner, ...) # the same
build_model is also where sharing is detected: a component or parameter used
in several places becomes one shared component or parameter. Don't construct a
ShareModule directly.
Inspecting the Model¶
Parameter Paths¶
# Get all unique parameter paths (excludes shared duplicates and Known)
paths = model.get_parameter_paths()
# Include shared parameters
paths = model.get_parameter_paths(show_shared=True)
# Include Known parameters
paths = model.get_parameter_paths(show_knowns=True)
Parameter Summary¶
Shows path, shape, bounds, free/fixed status, and sharing info for each parameter.
Sharing Summary¶
# Component-level: which modules are the same object
model.get_sharing_summary(level="component")
# Returns: {'line_1.v': ['line_2.v']}
# Parameter-level: which parameter values are shared
model.get_sharing_summary(level="parameter")
# Returns: {'line_1.v.coefficients': ['line_2.v.coefficients']}
Model Tree¶
# Print the model structure
model.print_model_tree()
# Include sharing relationships
model.print_model_tree(show_sharing=True)
Model Graph¶
# Plot the model as a directed graph
model.plot_model_graph()
# Component-level view (shared modules point to same node)
model.plot_model_graph(sharing_level="component")
# Parameter-level view (shows all paths)
model.plot_model_graph(sharing_level="parameter")
Modifying Parameters¶
Setting Values¶
# Set a single parameter
model = model.set("line_1.A.coefficients", new_value)
# Set multiple parameters
model = model.set(["path.to.param1", "path.to.param2"], [value1, value2])
Fixing/Freeing Parameters¶
# Fix parameters (won't be optimized)
model = model.set_fixed_status(["path.to.param"], [True])
# Free parameters
model = model.set_fixed_status(["path.to.param"], [False])
# Fix all parameters
model = model.fix_all()
# Free all parameters
model = model.free_all()
Evaluating Parts of a Model¶
Calling the whole model always works, with or without sharing:
Calling a part of it needs care when that part contains sharing. A shared
parameter is stored once, at its parent location; its other locations hold a
Shared reference to it. That is what makes it one parameter: it is updated in
one place (by set, an optimiser or the latent space) and every location sees
the same value. But a submodule that holds such a reference can't be called on
its own, because the reference is not a value:
model = build_model(TwoLines, line_1=Line(v=shared_gp), line_2=Line(v=shared_gp))
model.line_1(data) # fine: line_1 holds the shared GP itself
model.line_2(data) # RuntimeError: line_2 holds a reference to line_1.v
for_evaluation() returns a copy with every reference replaced by its value, so
any part can be called or inspected:
evaluable = model.for_evaluation()
flux_2 = evaluable.line_2(data)
velocity = evaluable.line_2.v(grid)
The copy no longer tracks sharing, so use it for evaluation only (predictions,
plots, checks), not for optimisation or to build a LatentSpace. Keep working
with the original model for those. (get_locked_model() is the old name of
for_evaluation() and is deprecated.)
Priors¶
from spectracles.priors import Laplace, LogNormal
model = model.with_priors(
{
"**.kernel.length_scale": LogNormal(0.5, 0.2),
"offset.spaxel_values": Laplace(0.02),
"line.σ_lsf.spaxel_values": "fixed",
}
)
model.get_priors() # {path: prior} for every parameter that has one
See Priors and inference for the full workflow.
Validation¶
API Reference¶
spectracles.ShareModule
¶
Bases: Module
get_parameter_paths(show_shared=False, show_knowns=False)
¶
Get all parameter paths that can be used with the set() method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_shared
|
bool
|
If False (default), only returns paths to unique/parent parameters. If True, also includes paths to shared (duplicate) parameters. |
False
|
show_knowns
|
bool
|
If False (default), excludes Known parameters from the results. Known parameters are fixed constants that cannot be optimized. |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of parameter path strings (e.g., ['line.A.coefficients', |
list[str]
|
'line.v.coefficients']). |
Examples:
get_parameter_summary(show_shared=True, show_knowns=False)
¶
Print a summary table of all parameters with their status.
Shows path, shape, bounds, free/fixed status, and sharing info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_shared
|
bool
|
If True (default), include parameters that are shared from other parameters. If False, only show unique/parent parameters. |
True
|
show_knowns
|
bool
|
If False (default), exclude Known parameters from the summary. If True, include them with status 'known'. |
False
|
Examples:
>>> model.get_parameter_summary()
Parameter Summary
──────────────────────────────────────────────────────────────────
Path Shape Bounds Status Shared from
──────────────────────────────────────────────────────────────────
line_1.A.coefficients (10,) (-∞, ∞) free -
line_1.v.coefficients (10,) (-∞, ∞) fixed -
line_2.v.coefficients (10,) (-∞, ∞) fixed line_1.v.coefficients
──────────────────────────────────────────────────────────────────
3 parameters (2 unique, 1 shared) · 1 free, 2 fixed
get_sharing_summary(level='component')
¶
Get a summary of what is shared in the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str
|
What level of sharing to report: - 'component': Shows which modules are the same object. (e.g., 'line_1.v' -> ['line_2.v']) - 'parameter': Shows which leaf parameter arrays are shared. More comprehensive, catches sharing done via tree_at. (e.g., 'line_1.v' -> ['line_2.v']) |
'component'
|
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
A dictionary mapping parent paths to lists of paths that share |
dict[str, list[str]]
|
with them. Only items that are actually shared are included. |
Examples:
print_model_tree(show_sharing=False)
¶
Print the model tree in an easy to parse format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_sharing
|
bool
|
If True, also print summaries of sharing relationships after the tree. Shows both shared modules (entire modules that are the same object) and shared parameters. Default is False for backwards compatibility. |
False
|
Example with show_sharing=True: └── model (LineRatioModel) ├── line_1 (EmissionLine) │ └── v (GPField) └── line_2 (LinkedEmissionLine) └── v (GPField)
Shared modules (parameters within are also shared):
line_1.v:
← line_2.v
Shared parameters:
line_1.v.coefficients:
← line_2.v.coefficients
plot_model_graph(ax=None, show=True, label_func=None, nx_draw_kwds=DEFAULT_NX_KWDS, sharing_level='component')
¶
Plot the model as a graph using networkx and matplotlib. The graph is directed towards parameters and accounts for the sharing structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Matplotlib axes to plot on. If None, creates a new figure. |
None
|
show
|
bool
|
If True, calls plt.show() after plotting. |
True
|
label_func
|
Callable[[DiGraph], dict[int, str]] | None
|
Custom function to generate node labels. |
None
|
nx_draw_kwds
|
dict
|
Keyword arguments for networkx drawing functions. |
DEFAULT_NX_KWDS
|
sharing_level
|
str
|
How to display sharing - 'component' (default) shows module-level sharing, 'parameter' shows leaf-level sharing. |
'component'
|
set(params, values=None, allow_set_knowns=False)
¶
Return a new model with updated parameter values. Can only be used to update values of Parameters or ConstrainedParameters. The model must not be locked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
list[str] | dict[str, Array]
|
List of parameter paths to update, or a dict from path to
new value (e.g. the output of |
required |
values
|
list[Array] | None
|
List of new values for each parameter, when |
None
|
allow_set_knowns
|
bool
|
If False (default), raises an error when trying to set Known parameters. Set to True to allow modifying Known values (use with caution). |
False
|
Returns:
| Type | Description |
|---|---|
Self
|
A new ShareModule with updated parameter values. |
set_fixed_status(params, fix)
¶
Return a new model with parameters updated to be fixed or not based on provided paths and list of bools. Can only be used to update fixed statuses of Parameters or ConstrainedParameters. The model must not be locked.
Known parameters cannot be unfixed - they are always fixed by definition.
with_priors(spec)
¶
Return a new model with priors set (or parameters fixed) by path or glob.
Patterns use the same glob syntax as build_schedule ('*' matches one
path component, '**' any number). Values are a spectracles.priors.Prior
or the string "fixed". Patterns are matched against all non-Known
parameter paths, including shared ones: a shared parameter is one
parameter, so a pattern on any of its paths sets that one parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any]
|
Mapping from path pattern to a Prior or "fixed". |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new ShareModule; the original is unchanged. Parameter values and |
Self
|
free/fixed status are kept (except where "fixed" is given). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a pattern matches nothing, if two patterns ask for different things on the same parameter, or if a prior is given for a ConstrainedParameter. |
TypeError
|
If a value is neither a Prior nor "fixed". |
Examples:
get_priors()
¶
Get the priors of all (unique, non-Known) parameters that have one.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary mapping parameter paths to their Prior, in tree order. |
dict[str, Any]
|
Shared parameters appear once, under their parent path. |
fix_all()
¶
Return a new model with all parameters set to fixed.
This is useful for freezing all parameters, e.g., when you want to use the model for inference only without any further optimization.
Returns:
| Type | Description |
|---|---|
Self
|
A new ShareModule with all parameters fixed. |
Examples:
free_all()
¶
Return a new model with all parameters set to free (not fixed).
This is useful for unfreezing all parameters for optimization.
Returns:
| Type | Description |
|---|---|
Self
|
A new ShareModule with all parameters free. |
Examples:
validate_sharing(raise_on_error=True)
¶
Validate the sharing structure of the model.
Checks that: 1. All Shared objects reference valid parent parameters 2. Parent parameters exist and have the expected shape 3. No orphaned Shared objects exist 4. All locations of a shared parameter have the same fixed status and prior
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raise_on_error
|
bool
|
If True (default), raises ValueError on validation failure. If False, returns validation results without raising. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing validation results: |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
Examples:
copy()
¶
Create a proper copy of the ShareModule with correct sharing structure preserved and duplicated array data. It's like deepcopy but preserves the sharing structure.
for_evaluation()
¶
A copy of the model for evaluating any part of it.
In a model with sharing, each shared value is stored once, at its parent
location; its other locations hold Shared references to it. That is
what keeps a shared parameter one parameter, but it means a submodule
containing such a reference can't be called on its own. In the copy
returned here every reference is replaced by its value, so any
submodule can be called, e.g. model.for_evaluation().line_2.v(data).
The copy no longer tracks sharing, so it is for evaluation only: it
can't be optimised or used to build a LatentSpace. The model itself is
unchanged; calling it (model(data)) never needs this.
debug_repr()
¶
Return the full equinox-style repr for debugging.
spectracles.build_model(cls, *args, **kwargs)
¶
Build a model from its class and arguments, or from an instance.
build_model(MyModel, a=..., b=...) and build_model(MyModel(a=..., b=...))
are equivalent. Sharing between parts of the model is detected here.