Skip to content

torchsky.viz

Experimental surface

These APIs are under active development. Names, defaults, and result objects may change between minor releases; pin a version if you depend on them in production.

torchsky.viz — astronomy visualization: browser server and slide figures.

Guides: viz, cli


This reference is generated from the package source. Names are grouped by the module that defines them; import every name from the public namespace torchsky.viz unless the group text says otherwise.

Top-level namespace

torchsky.viz — astronomy visualization: browser server and slide figures.

Two surfaces live here:

  • the browser server, which computes server-side and ships PNG tiles, JSON geometries and chart data to the bundled Aladin Lite viewer;
  • matplotlib figures for talks and papers — full-sky maps in allsky and cube quick-looks in plots — themed in theme.

Usage::

# CLI
torchsky viz --root /path/to/data --port 8822

# Python
import torchsky.viz as viz
viz.serve(root="/path/to/data", port=8822)
viz.plot_healpix_sky(values, nside=256, save="sky.png")

serve

serve(
    root: str | Path = ".",
    port: int = 8822,
    host: str = "127.0.0.1",
    open_browser: bool = True,
    cache_mb: int = 512,
    log_level: str = "warning",
    *,
    max_registered_surveys: int = 64,
    max_validation_pairs: int = 32,
    max_image_pixels: int | None = None,
    expose_root_in_health: bool = False,
    cors_allow_origins: list[str] | None = None,
    cors_allow_credentials: bool = False,
) -> None

Start the torchsky viz server (blocking).

Parameters:

Name Type Description Default
root str | Path

Directory to browse. Defaults to current directory.

'.'
port int

HTTP port. Default 8822.

8822
host str

Bind address. Default 127.0.0.1 (localhost only).

'127.0.0.1'
open_browser bool

Open the browser automatically.

True
cache_mb int

Tile cache size in MiB.

512
log_level str

uvicorn log level.

'warning'
max_registered_surveys int

Cap HiPS registrations (FIFO eviction).

64
max_validation_pairs int

Cap validation pairs (FIFO eviction).

32
max_image_pixels int | None

Max H*W per image for HiPS/validation (default 512M).

None
expose_root_in_health bool

Put absolute root path in /api/health JSON.

False
cors_allow_origins list[str] | None

Explicit CORS origins; None allows no CORS origins.

None
cors_allow_credentials bool

Enable credentialed CORS (disallowed with * origins).

False

serve_background

serve_background(
    root: str | Path = ".",
    port: int = 8822,
    host: str = "127.0.0.1",
    cache_mb: int = 512,
    **kwargs: object,
) -> Thread

Start the server in a daemon thread (non-blocking, for notebooks).

Returns the thread so callers can check liveness.

show_url

show_url(port: int = 8822, host: str = '127.0.0.1') -> str

Return (and print) the correct URL, auto-detecting Jupyter environment.

Allsky

torchsky.viz — astronomy visualization: browser server and slide figures.

Two surfaces live here:

  • the browser server, which computes server-side and ships PNG tiles, JSON geometries and chart data to the bundled Aladin Lite viewer;
  • matplotlib figures for talks and papers — full-sky maps in allsky and cube quick-looks in plots — themed in theme.

Usage::

# CLI
torchsky viz --root /path/to/data --port 8822

# Python
import torchsky.viz as viz
viz.serve(root="/path/to/data", port=8822)
viz.plot_healpix_sky(values, nside=256, save="sky.png")

SkyGrid dataclass

SkyGrid(
    lon_edges: Tensor,
    lat_edges: Tensor,
    data: Tensor,
    counts: Tensor,
    statistic: str = "mean",
    sampling: str = "binned",
)

A regular longitude/latitude grid of values covering the whole sphere.

lon_edges span [-180, 180] degrees and lat_edges span [-90, 90]; data is (len(lat_edges) - 1, len(lon_edges) - 1) with NaN in cells that received no samples.

counts instance-attribute

counts: Tensor

data instance-attribute

data: Tensor

lat_edges instance-attribute

lat_edges: Tensor

lon_edges instance-attribute

lon_edges: Tensor

n_samples property

n_samples: int

Number of samples that landed on the grid.

resolution property

resolution: tuple[int, int]

(width, height) of the grid in cells.

sampling class-attribute instance-attribute

sampling: str = 'binned'

statistic class-attribute instance-attribute

statistic: str = 'mean'

healpix_sky_grid

healpix_sky_grid(
    values: Tensor,
    *,
    nside: int | None = None,
    nest: bool = False,
    pixels: Tensor | None = None,
    resolution: tuple[int, int] | None = None,
    statistic: Statistic = "mean",
    resample: bool | None = None,
) -> SkyGrid

Turn a dense or sparse HEALPix map into a full-sky grid.

Pass pixels alongside values for a sparse map; otherwise values must hold one sample per pixel of nside.

A dense map is nearest-pixel resampled: each grid cell shows the pixel containing its centre, so the figure has no empty cells and the cost depends on the grid rather than on the map size. Pass resample=False to box-average instead (statistic selects mean or sum), which anti-aliases a map much finer than the grid. Sparse maps are always binned: there is no value to resample at unobserved pixels, so their holes are real.

resolution=None picks a grid about one pixel wide at the input nside.

plot_healpix_sky

plot_healpix_sky(
    values: Tensor | None = None,
    *,
    nside: int | None = None,
    nest: bool = False,
    pixels: Tensor | None = None,
    resolution: tuple[int, int] | None = None,
    statistic: Statistic = "mean",
    **plot_kwargs: Any,
) -> Any

Plot a dense or sparse HEALPix map as a full-sky figure.

values=None draws only the graticule and any overlays, which is the usual way to show a survey footprint on a blank sky. All remaining keyword arguments go to :func:plot_sky_grid.

plot_sky_grid

plot_sky_grid(
    sky: SkyGrid | None = None,
    *,
    projection: SkyProjection = "mollweide",
    ra_increases_left: bool = True,
    cmap: str = "viridis",
    stretch: Stretch = "asinh",
    vmin: float | None = None,
    vmax: float | None = None,
    percentile: tuple[float, float] = (1.0, 99.0),
    unit: str | None = None,
    cbar_label: str | None = None,
    colorbar_extend: bool | None = None,
    title: str | None = None,
    subtitle: str | None = None,
    theme: str = "dark",
    grid: bool = True,
    colorbar: bool = True,
    footnote: bool = True,
    figsize: tuple[float, float] | None = None,
    dpi: int = 200,
    ax: Any = None,
    save: str | Path | None = None,
    moc: Any | None = None,
    moc_label: str | None = "footprint",
    points: tuple[Tensor, Tensor] | None = None,
    point_label: str | None = None,
    point_color: str | None = None,
    point_size: float = 18.0,
) -> Any

Draw a full-sky grid on an all-sky projection.

Parameters:

Name Type Description Default
sky SkyGrid | None

grid from :func:healpix_sky_grid/:func:sky_grid, or None to draw only the graticule and overlays.

None
projection SkyProjection

mollweide, aitoff, hammer (full-sky 2:1) or polar (north-pole disc, colatitude as radius).

'mollweide'
ra_increases_left bool

flip longitude so RA grows to the left (default); for polar it sets the clockwise/counter-clockwise direction.

True
cmap str

any matplotlib colormap name, or a bundled tile palette name.

'viridis'
stretch Stretch

asinh (default, keeps faint structure visible across a high dynamic range), linear or log normalization.

'asinh'
vmin float | None

lower display limit; percentile decides when omitted.

None
vmax float | None

upper display limit; percentile decides when omitted.

None
unit str | None

colorbar unit; short units of the plotted quantity.

None
cbar_label str | None

overrides the colorbar caption entirely.

None
colorbar_extend bool | None

force colorbar arrow ends; None derives them from whether the display range actually clips the data.

None
theme str

dark or paper.

'dark'
grid bool

draw the graticule (also controls the RA/Dec tick labels).

True
colorbar bool

draw a horizontal colorbar under the map.

True
footnote bool

print projection, grid size and sampling under the figure.

True
figsize tuple[float, float] | None

figure size in inches; defaults to 13x7, or 8.2x8.2 for polar.

None
moc Any | None

optional :class:torchsky.sphere.moc.MOC outline overlay.

None
points tuple[Tensor, Tensor] | None

optional (lon, lat) catalog overlay.

None
save str | Path | None

path to write a PNG/PDF/SVG; the figure is themed for saving.

None

Returns:

Type Description
Any

The matplotlib axes.

sky_grid

sky_grid(
    lon: Tensor,
    lat: Tensor,
    values: Tensor,
    *,
    resolution: tuple[int, int] = (1440, 720),
    statistic: Statistic = "mean",
) -> SkyGrid

Bin point samples (lon, lat, values) onto a full-sky grid.

Longitude is in degrees and may be given in any range (it wraps); latitude must be in [-90, 90]. Non-finite samples are dropped rather than poisoning their cell.

Plots

torchsky.viz — astronomy visualization: browser server and slide figures.

Two surfaces live here:

  • the browser server, which computes server-side and ships PNG tiles, JSON geometries and chart data to the bundled Aladin Lite viewer;
  • matplotlib figures for talks and papers — full-sky maps in allsky and cube quick-looks in plots — themed in theme.

Usage::

# CLI
torchsky viz --root /path/to/data --port 8822

# Python
import torchsky.viz as viz
viz.serve(root="/path/to/data", port=8822)
viz.plot_healpix_sky(values, nside=256, save="sky.png")

plot_pixel_spectrum

plot_pixel_spectrum(
    cube: Tensor,
    spectral_axis: SpectralAxis,
    y: int,
    x: int,
    *,
    spectral_axis_index: int = 0,
    ax: Any = None,
    theme: str = "dark",
    title: str | None = None,
    subtitle: str | None = None,
    label: str | None = None,
    legend: bool = True,
    grid: bool = True,
    save: str | Path | None = None,
    dpi: int = 200,
    **kwargs: Any,
) -> Any

Plot the 1D spectrum at one pixel of a data cube.

Parameters:

Name Type Description Default
cube Tensor

3D data cube tensor.

required
spectral_axis SpectralAxis

SpectralAxis for the spectral dimension.

required
y int

Row coordinate of the spectrum in pixel space.

required
x int

Column coordinate of the spectrum in pixel space.

required
spectral_axis_index int

Dimension index of the spectral axis (0, 1 or 2).

0
ax Any

Optional matplotlib axes; a themed figure is created when omitted.

None
theme str

dark (default) or paper.

'dark'
title str | None

Figure headline.

None
subtitle str | None

Quieter second line under the headline.

None
label str | None

Legend label for the spectrum; defaults to the pixel position.

None
legend bool

Toggle the legend.

True
grid bool

Toggle the graticule.

True
save str | Path | None

Path to write the figure.

None
dpi int

Output resolution used when creating/saving the figure.

200
kwargs Any

Forwarded to plot.

{}

Returns:

Type Description
Any

The matplotlib axes.

plot_pseudo_rgb

plot_pseudo_rgb(
    cube: Tensor,
    spectral_axis: SpectralAxis,
    *,
    spectral_axis_index: int = 0,
    stretch: str = "asinh",
    ax: Any = None,
    theme: str = "dark",
    title: str | None = None,
    subtitle: str | None = None,
    percentile: tuple[float, float] = (0.5, 99.5),
    show_band_key: bool = True,
    save: str | Path | None = None,
    dpi: int = 200,
    **kwargs: Any,
) -> Any

Render a pseudo-RGB composite from a spectral cube.

The spectral axis is split into three equal-count bands (blue, green, red) so every channel carries the same amount of data. By default all three channels share one display range, which keeps colour ratios meaningful; percentile clips the bright tail.

Parameters:

Name Type Description Default
cube Tensor

3D data cube tensor.

required
spectral_axis SpectralAxis

SpectralAxis for the spectral dimension.

required
spectral_axis_index int

Dimension index of the spectral axis (0, 1 or 2).

0
stretch str

asinh (default), linear, log or sqrt.

'asinh'
ax Any

Optional matplotlib axes; when omitted a themed figure is created.

None
theme str

dark (default) or paper.

'dark'
title str | None

Figure headline.

None
subtitle str | None

Quieter second line under the headline.

None
percentile tuple[float, float]

Display limits in percentiles of the finite data.

(0.5, 99.5)
show_band_key bool

Print the wavelength range of each channel.

True
save str | Path | None

Path to write the figure; returns the axes either way.

None
dpi int

Output resolution used when creating/saving the figure.

200
kwargs Any

Forwarded to imshow.

{}

Returns:

Type Description
Any

The matplotlib axes.