Skip to content

Latest commit

 

History

History
225 lines (173 loc) · 9.07 KB

python.md

File metadata and controls

225 lines (173 loc) · 9.07 KB

Python bindings

Status: Python public interface for NSB 0.3.0. Audience: Python users, integrators, and binding maintainers. Scope: Installation, canonical upstream types, evaluation/planning, units, errors, and local development.

NSB exposes a deliberately small Python API for NSB evaluation and planning. The Rust crate in crates/nsb remains the scientific implementation and the authoritative public model contract.

The Python distribution is named nsb-py; the import remains:

import nsb

Python 3.10 or newer is supported.

Installation

python -m pip install nsb-py

The distribution declares siderust>=0.6.0,<0.7 and tempoch>=0.5.0,<0.6 as runtime dependencies, so pip installs the matching canonical upstream packages. NSB's Rust crate and Python distribution share the same NSB release version; upstream Siderust and Tempoch use their own versions. See Siderust compatibility.

Ownership boundary

NSB owns the Python API for model configuration, component selection, NSB evaluation, result/component metadata, threshold planning, and reusable planning contexts.

Generic scientific primitives belong upstream:

  • Siderust owns observers, coordinate systems, directions, and astronomy semantics.
  • qtty owns physical quantities and units.
  • tempoch / tempoch-py own time-scale, interval, and Python datetime conversion semantics.

Python observers and directions are the canonical siderust.Observer and siderust.direction.ICRS / siderust.direction.Horizontal classes from siderust-py 0.6 (bridge protocol 2). PointQuery and ThresholdQuery accept either direction type via the same target argument. NSB consumes siderust_py::interop::{icrs,horizontal}_{from,to}_python. At the Rust boundary, ICRS directions transform through Siderust's frame-bias rotation to NSB's EquatorialMeanJ2000 target; horizontal targets resolve per evaluation instant. Getters reconstruct the matching canonical Python object and preserve the originally requested frame.

Migration from NSB 0.2.0: replace siderust.Direction with ICRS from siderust.direction and install the supported Siderust 0.6.x runtime.

Siderust owns coordinate validity for its classes. NSB additionally rejects out-of-range horizontal altitudes that escape Siderust canonicalization.

Package layout

This is a pure-Rust maturin project with import name nsb. Maturin supplies its minimal generated package initializer, and the root-level nsb.pyi ships beside the extension for static typing. There is no maintained pass-through facade or duplicated re-export list.

Point evaluation

from datetime import datetime, timezone

import nsb
import siderust
from siderust.direction import ICRS, Horizontal

# CTAO South WGS84 coordinates from the bundled observatory catalog.
ctao_south = siderust.Observer(
    lon_deg=-70.31634444444444,
    lat_deg=-24.683427777777776,
    height_m=2184.6,
)
# Sagittarius A* in ICRS coordinates.
sgr_a_star = ICRS(
    ra_deg=266.41683,
    dec_deg=-29.00781,
)

config = (
    nsb.NsbModelConfig.generic_clear_sky()
    .with_site_profile(nsb.SiteProfile.CTA_SOUTH)
)
evaluator = nsb.NsbEvaluator(config)

query = nsb.PointQuery(
    ctao_south,
    datetime(2026, 9, 27, 22, 0, tzinfo=timezone.utc),
    sgr_a_star,
)
result = evaluator.evaluate(query)

print(result.integrated_photons_cm2_ns_sr)
for component in result.components:
    print(component.name, component.integrated_photons_cm2_ns_sr)

For a fixed horizontal pointing, use the same observer and time:

horizontal = Horizontal(alt_deg=60.0, az_deg=130.0)
horizontal_query = nsb.PointQuery(ctao_south, query.time, horizontal)
horizontal_result = evaluator.evaluate(horizontal_query)

The pointing stays fixed in Alt/Az; its equatorial direction and Starlight contribution change with time. ThresholdQuery accepts the same horizontal target. Adaptive discovery is not a mathematical certificate; certified search rejects unsupported dynamic Starlight certificates.

SiteProfile is a Python application-layer selector enum (GENERIC_CLEAR_SKY, CTA_NORTH, CTA_SOUTH). Each variant constructs a typed Rust SiteProfile<P> with a binding-local SiteProfileTag marker before NsbModelConfig::with_site_profile erases the type. CTAO North/South are convenience presets only; the generic Rust public API exports SiteProfileTag, SiteProfile<P>, and GenericClearSky — not CTAO markers. Inspect the selected Python profile via the config.site_profile property and config.site_profile.as_str(). The Rust-only NsbModelConfig::site_profile_name() metadata getter is not separately exposed by the Python binding.

ComponentMask exposes named component flags and bitwise composition. Raw bit construction is not part of the public Python API.

Planning

Planning windows use ordinary timezone-aware Python datetimes at the boundary:

max_nsb_photons_cm2_ns_sr = 0.25

query = nsb.ThresholdQuery(
    ctao_south,
    sgr_a_star,
    datetime(2026, 9, 27, 20, 0, tzinfo=timezone.utc),
    datetime(2026, 9, 28, 4, 0, tzinfo=timezone.utc),
    max_nsb_photons_cm2_ns_sr,
    components=nsb.ComponentMask.ZODIACAL | nsb.ComponentMask.AIRGLOW,
)

context = evaluator.prepare_site_window_context(query)
result = evaluator.periods_below_threshold_with_context(context, query)

for start, end in result.periods:
    print(start, end)

Returned periods are (start, end) tuples of timezone-aware UTC datetime.datetime values. NSB does not expose a bespoke Python UtcPeriod type.

Normal planning methods use step-free adaptive discovery in NSB 0.3.0. Explicit adaptive method names are aliases for the same search. Inclusive bands use the shared two-threshold engine:

result = evaluator.periods_below_threshold_adaptive_with_context(context, query)
band = evaluator.periods_in_band_adaptive_with_context(context, query, 0.10)

The band condition is inclusive: 0.10 <= NSB <= query.threshold. Both levels share the same physical fits, exact probes and crossing brackets. Returned boundaries contract inward and are checked at Python microsecond precision. Numerical ambiguity or resource exhaustion raises an error without a partial schedule. Adaptive discovery is empirical under documented model-resolution assumptions; it does not certify every unvisited instant. The strict certified methods continue to require sound interval enclosures.

Time boundary

Input datetimes must be timezone-aware. tempoch-py validates Python datetime objects, normalizes explicit non-UTC offsets, and performs the canonical conversion to tempoch::Time<UTC>. NSB only translates conversion failures to its documented nsb.OutOfRangeError with argument context. Returned instants and period endpoints are created through the same upstream bridge as aware UTC datetime.datetime values.

Units

Python scalar arguments and properties carry units in their names because Rust qtty quantities do not cross the Python boundary directly. Common suffixes are _deg, _m, _s, _nm, _photons_cm2_ns_sr, _mag_per_arcsec2, and _s10.

Errors and concurrency

Rust NsbError categories map to subclasses of nsb.NsbError. Generic boundary validation uses OutOfRangeError; NSB does not define a separate Siderust/tempoch exception taxonomy.

Evaluator construction, point evaluation, and planning operations detach from the Python interpreter while Rust-only work runs. The binding does not reimplement scientific calculations in Python.

Development

python -m venv .venv
. .venv/bin/activate
python -m pip install -U pip "maturin>=1.9,<2" pytest
python -m pip install "siderust>=0.6.0,<0.7" "tempoch>=0.5.0,<0.6"
maturin develop --locked
python -m pytest python/tests

To validate an installed wheel:

maturin build --release --locked --out dist
python -m pip install --force-reinstall --only-binary=:all: dist/nsb_py-*.whl
python -m pytest python/tests

The NSB binding uses PyO3's CPython stable ABI with a Python 3.10 floor (abi3-py310). Python support and the siderust-py / tempoch-py Rust bridge dependencies remain feature-gated, so normal Rust builds do not enable PyO3.

The installed wheel tests resolve released Siderust 0.6 and Tempoch 0.5 wheels from PyPI. The Rust extension links siderust-py 0.6 / tempoch-py 0.5 against Siderust 0.15.1 and Tempoch 0.11.1. CLI, Rust and Python band searches use the same joint algorithm; periods_in_band_adaptive(query, minimum) accepts minimum <= NSB <= query.threshold, with both crossing brackets contracted inward. The context variant shares preparation. The certified band variant requires a sound enclosure of the whole band and fails for unsupported models. Ordinary Python timestamps remain timezone-aware datetime values, with inward projection checked at microsecond precision.

The supported Siderust Python runtime and Rust bridge begin at 0.6.0 (bridge protocol 2 with explicit direction.ICRS / direction.Horizontal). NSB validates installed-wheel interop in CI. For scientific use, record the installed NSB, Siderust and Tempoch versions and review the validation and applicability guide.