Context API#
Context packages backend operations, default dtype, and runtime validation
policy. Spaces and operators store a normalized context and use it for array
construction and checks.
Use check_level="none", "cheap", "standard", or "strict".
The exported spacecore.CheckLevel literal is available for annotations.
Context#
Select backend operations, representation dtype, and validation policy. |
- class spacecore.backend.Context(ops, dtype=None, enable_checks=None, *, check_level=None)[source]#
Bases:
objectSelect backend operations, representation dtype, and validation policy.
A context collects the backend operations object, default dtype, and runtime validation policy used by spaces, linear operators, and context-bound values. It is intentionally small: it does not own arrays, but it defines how new arrays are created and how existing arrays are checked or converted for a backend family.
- Parameters:
ops (BackendOps) – Backend operations implementation. This must be an instance of
spacecore.backend.BackendOps, such asspacecore.backend.NumpyOpsorspacecore.backend.JaxOps.dtype (dtype-like or None, optional) – Default array representation dtype used by
asarray()andassparse(). The value is normalized throughops.sanitize_dtypeduring initialization. It does not independently define a mathematical scalar field; spaces expose that contract throughspacecore.space.Space.field.enable_checks (bool or None, optional) – Deprecated compatibility alias.
Truemaps to"standard"andFalsemaps to"none". Passing both policy arguments is an error.check_level ({"none", "cheap", "standard", "strict"}, optional) – Runtime validation policy. The default is
"standard".
- ops#
Normalized backend operations instance.
- Type:
- dtype#
Backend-native dtype used by array constructors.
- Type:
dtype-like
Notes
Contextis frozen and slot-based. Methods that convert values return new backend arrays or sparse objects; they do not mutate the context itself.Equality compares backend family, dtype, and
check_level.Examples
Create a NumPy context and convert a Python list to a backend array.
>>> import numpy as np >>> import spacecore as sc >>> ctx = sc.Context(sc.NumpyOps(), dtype=np.float64) >>> x = ctx.asarray([1.0, 2.0]) >>> x.dtype == np.dtype("float64") True
- check_level: Literal['none', 'cheap', 'standard', 'strict']#
- __init__(ops, dtype=None, enable_checks=None, *, check_level=None)[source]#
Validate and normalize the context after dataclass initialization.
- Raises:
TypeError – If
opsis not aBackendOpsinstance.- Parameters:
ops (BackendOps)
dtype (Any | None)
enable_checks (bool | None)
check_level (Literal['none', 'cheap', 'standard', 'strict'] | None)
- Return type:
None
- assert_dense(x)[source]#
Return
xafter verifying that it is a dense array for this backend.- Parameters:
x (Any) – Object to validate.
- Returns:
The original object, typed as a dense array.
- Return type:
DenseArray
- Raises:
TypeError – If
xis not recognized as a dense array byself.ops.
- assert_sparse(x)[source]#
Return
xafter verifying that it is a sparse array for this backend.- Parameters:
x (Any) – Object to validate.
- Returns:
The original object, typed as a sparse array.
- Return type:
SparseArray
- Raises:
TypeError – If the backend does not allow sparse arrays or if
xis not recognized as a sparse array byself.ops.
- asarray(x)[source]#
Convert
xto a dense backend array using this context’s dtype.- Parameters:
x (Any) – Array-like object accepted by the backend implementation.
- Returns:
Backend-native dense array with dtype
self.dtype.- Return type:
DenseArray
- Raises:
TypeError – If conversion to
self.dtypewould discard a complex representation. Extract the real part explicitly before conversion when that loss is intentional.
- assparse(x)[source]#
Convert
xto a sparse backend object using this context’s dtype.- Parameters:
x (Any) – Array-like or sparse object accepted by the backend implementation.
- Returns:
Backend-native sparse object with dtype
self.dtype.- Return type:
SparseArray
- Raises:
TypeError – If the backend implementation does not support sparse conversion, or conversion to
self.dtypewould discard a complex representation.
- convert(x)[source]#
Convert an existing backend array to this context.
Dense inputs are converted with
asarray(); sparse inputs are converted withassparse().- Parameters:
x (Any) – Dense or sparse backend array recognized by
self.ops.- Returns:
Converted dense or sparse backend object.
- Return type:
ArrayLike
- Raises:
NotImplementedError – If
xis neither dense nor sparse according to this backend.
Context helpers#
Return the current process-wide default SpaceCore context. |
|
Set the process-wide default SpaceCore context. |
|
Normalize a context specification through the process-wide state. |
|
Normalize backend operations through the process-wide state. |
|
Resolve the context assigned to a newly created object. |
|
Register a backend operations implementation. |
get_contextandset_contextmanage the global default context.normalize_contextturns backend names, families, concrete contexts, orNoneinto a context.resolve_context_prioritychooses a common context for constructors.register_opsadds a custom backend implementation.
- spacecore.get_context()[source]#
Return the current process-wide default SpaceCore context.
- Returns:
Active process-wide default context.
- Return type:
- spacecore.set_context(ctx=None, dtype=None, enable_checks=None, *, check_level=None)[source]#
Set the process-wide default SpaceCore context.
- Parameters:
ctx (Context, BackendFamily, str, or None, optional) – Context or backend specification.
dtype (Any, optional) – Default dtype override.
enable_checks (bool or None, optional) – Deprecated Boolean validation override.
check_level (CheckLevel or None, optional) – Validation policy override for backend-name contexts.
- Return type:
None
- spacecore.normalize_context(ctx=None, dtype=None, enable_checks=None, *, check_level=None)[source]#
Normalize a context specification through the process-wide state.
- Parameters:
ctx (Context, BackendFamily, str, or None, optional) – Context or backend specification.
dtype (Any, optional) – Default dtype override.
enable_checks (bool or None, optional) – Deprecated Boolean validation override.
check_level (CheckLevel or None, optional) – Validation policy override for backend-name contexts.
- Returns:
Normalized context.
- Return type:
- spacecore.normalize_ops(ops)[source]#
Normalize backend operations through the process-wide state.
- Parameters:
ops (str, BackendFamily, BackendOps, type of BackendOps, or Context) – Backend operations specification.
- Returns:
Normalized backend operations singleton.
- Return type:
- spacecore.resolve_context_priority(priority_ctx=None, *other_ctx)[source]#
Resolve the context assigned to a newly created object.
- spacecore.register_ops(ops)[source]#
Register a backend operations implementation.
- Parameters:
ops (type of BackendOps) – Backend operations class to register.
- Returns:
Registered backend operations class.
- Return type:
type of BackendOps