ipyaladin

A real-sky atlas that pans, zooms, and clicks its way into your Shiny app’s reactive graph.

Aladin Lite streams HiPS sky survey imagery – DSS, 2MASS, allWISE, Gaia, PanSTARRS, and dozens more – tiled and reprojected on demand, so panning and zooming across the whole sky feels like a slippy map. @render_ipyaladin makes it a reactive Shiny output: clicking a catalog source, box-selecting a region, panning, or zooming comes back to Python as a value you read like any other reactive input.

hero

The Orion Nebula (M42), the whole app in four lines. Try the app.

Installation

pip install 'shinywidgets[ipyaladin]'

This installs ipyaladin, which pulls in astropy (every coordinate ipyaladin hands back is an astropy SkyCoord, Angle, or Table). The viewer needs network access at render time – its JavaScript and sky imagery both stream from CDS – so it won’t render anything useful fully offline. The footprints and MOCs example also uses mocpy to build a region to display, a separate, optional dependency not part of the ipyaladin extra.

Quick start

from ipyaladin import Aladin
from shiny.express import ui
from shinywidgets import render_ipyaladin

ui.page_opts(title="ipyaladin quick start", fillable=True)

with ui.card(full_screen=True):
    ui.card_header("Orion Nebula (M42)")

    @render_ipyaladin
    def sky():
        return Aladin(target=(83.82, -5.39), fov=1.2)

That’s the whole app: a card, a target, a field of view. The viewer fills the card, and dragging to pan or scrolling to zoom already works.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Reacting to interaction

ipyaladin exposes four accessors that report what the user did to the sky: clicked_object(), selected(), target(), and fov(). Call one from any reactive context, the same way you’d call input.my_slider(), and that context re-runs whenever the user does it again.

Click a catalog source

from astropy.table import Table
from ipyaladin import Aladin
from shiny.express import render, ui
from shinywidgets import render_ipyaladin

PLEIADES = Table(
    {
        "name": ["Alcyone", "Atlas", "Electra", "Maia", "Merope", "Taygeta", "Pleione"],
        "ra": [56.871, 56.978, 56.216, 56.579, 56.752, 56.447, 56.751],
        "dec": [24.105, 24.054, 24.113, 24.367, 23.948, 24.467, 24.137],
        "vmag": [2.87, 3.62, 3.70, 3.87, 4.17, 4.30, 5.09],
    }
)

ui.page_opts(title="clicked_object(): click a source for detail", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_ipyaladin
        def sky():
            # Centered on Alcyone, the cluster's brightest star
            aladin = Aladin(target=(56.871, 24.105), fov=1.2)
            aladin.add_table(PLEIADES, shape="circle", source_size=16, color="#ffd166")
            return aladin

    with ui.card():
        ui.card_header("Clicked star")

        @render.code
        def detail():
            clicked = sky.clicked_object()
            if clicked is None:
                return "Click a star to see its catalog row."
            return "\n".join(f"{k}: {v}" for k, v in clicked["data"].items())

clicked_object()["data"] is the clicked source’s full catalog row – every column from the Table passed to add_table(), not just ra/dec. add_table() takes any astropy Table or QTable with recognizable coordinate columns (it auto-detects ra/dec-like names, or you name them explicitly with ra_field/dec_field) and draws every row as a marker; the whole row travels with the marker.

What’s in view

import numpy as np
import pandas as pd
from ipyaladin import Aladin
from shiny.express import render, ui
from shinywidgets import render_ipyaladin

MESSIER = pd.DataFrame(
    {
        "name": ["M31", "M42", "M45", "M1", "M13", "M51", "M57", "M81", "M27", "M33"],
        "ra": [10.685, 83.822, 56.75, 83.633, 250.423, 202.47, 283.396, 148.888, 299.902, 23.462],
        "dec": [41.269, -5.391, 24.12, 22.014, 36.46, 47.195, 33.029, 69.065, 22.721, 30.66],
        "type": [
            "Galaxy", "Nebula", "Open cluster", "Supernova remnant", "Globular cluster",
            "Galaxy", "Planetary nebula", "Galaxy", "Planetary nebula", "Galaxy",
        ],
    }
)

ui.page_opts(title="target()/fov(): what's in view", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_ipyaladin
        def sky():
            return Aladin(target=(60, 20), fov=90)

    with ui.card():
        ui.card_header("Messier objects in the current view")

        @render.data_frame
        def in_view():
            center, radius = sky.target(), sky.fov().deg / 2
            dist = np.hypot(
                (MESSIER["ra"] - center.ra.deg) * np.cos(np.radians(center.dec.deg)),
                MESSIER["dec"] - center.dec.deg,
            )
            return MESSIER[dist <= radius].reset_index(drop=True)

target() and fov() turn “where is the user looking and how zoomed in are they” into two ordinary values, so a @render.data_frame (or any computation) built on them stays in sync with every pan and zoom – the same pattern works for a VizieR cone search or any lookup keyed on sky position.

Updating in place

Two ways to change an already-rendered viewer, and when each is right:

  • Re-render (return a new Aladin from the render function): simplest, but the viewer tears down and rebuilds – camera position, zoom, color map, and any overlays are all reset to whatever the new constructor call specifies. Fine when the change really is a new viewer (a different base catalog, a fresh session).
  • Update in place (sky.widget.<trait> = ... in a @reactive.effect): the existing viewer keeps its camera, zoom, and overlays; only what you explicitly set changes. This is almost always what you want for navigation, survey switches, and re-coloring.

Switch surveys and color maps

from ipyaladin import Aladin
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import reactive_read, render_ipyaladin

# A few HiPS surveys hosted by CDS (https://aladin.cds.unistra.fr/hips/)
SURVEYS = {
    "https://alaskybis.unistra.fr/DSS/DSSColor": "DSS color (optical)",
    "https://alaskybis.unistra.fr/2MASS/Color": "2MASS color (infrared)",
    "https://alaskybis.unistra.fr/AllWISE/Color": "allWISE color (mid-IR)",
}
CMAPS = ["native", "viridis", "cubehelix", "grayscale"]

ui.page_opts(title="Switch surveys and color maps", fillable=True)
ui.input_select("survey", "Survey", SURVEYS)
ui.input_select("cmap", "Color map", CMAPS)

with ui.card(full_screen=True):

    @render_ipyaladin
    def sky():
        return Aladin(target=(83.822, -5.391), fov=2, survey=list(SURVEYS)[0])  # M42

    # `survey` is a plain synced trait, so it updates as soon as it's set
    @reactive.effect
    def _():
        w = sky.widget
        if w:
            w.survey = input.survey()

    # set_color_map() sends a one-off message rather than syncing a trait,
    # so it's lost if sent before the browser has loaded -- gate on _is_loaded
    @reactive.effect
    def _():
        w = sky.widget
        if w and reactive_read(w, "_is_loaded") and input.cmap() != "native":
            w.set_color_map(input.cmap())

    @render.text
    def label():
        return f"{SURVEYS[input.survey()]}, {input.cmap()} color map"

One HiPS URL swaps the base imagery entirely (optical, infrared, radio – whatever HiPS survey you point it at), and set_color_map() re-palettes it, both without touching the camera. Assigning survey works the moment the widget exists, but set_color_map() is silently dropped if called before the browser has finished loading, so it needs the _is_loaded gate (see Beyond the accessors).

Re-render vs. update in place

examples/10_update_in_place_vs_rerender.py makes the difference concrete: zoom the sky to a custom field of view, then compare the two buttons.

from ipyaladin import Aladin
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_ipyaladin

ui.page_opts(title="Update in place vs. re-render", fillable=True)
ui.input_action_button("rerender", "Re-render (new Aladin())")
ui.input_action_button("in_place", "Update in place (.widget.target = ...)")
ui.p(
    "Zoom the sky to some custom field of view first, then try each button: "
    "in-place keeps it, re-render resets it to the constructor's fov=1.",
    class_="text-muted",
)

with ui.card(full_screen=True):

    @render_ipyaladin
    @reactive.event(input.rerender, ignore_none=False)
    def sky():
        return Aladin(target=(83.822, -5.391), fov=1)  # M42

    @reactive.effect
    @reactive.event(input.in_place)
    def _():
        sky.widget.target = "10.685 41.269"  # M31

    @render.text
    def fov():
        return f"field of view: {sky.fov().deg:.3f} deg"

Zoomed to a custom field of view, then after “Update in place” (target changed to M31, field of view unchanged):

And after “Re-render” instead (field of view reset to the constructor’s fov=1):

View reset by the re-render

Don’t read a reactive input in the render function for a value an effect also updates in place: Aladin(survey=input.survey(), ...) plus a w.survey = input.survey() effect rebuilds the whole viewer on every survey change instead of re-skinning it. Keep the constructor’s inputs static (or read them under reactive.isolate()) and let effects own the updates, as every example in this guide does.

Some methods – add_table(), add_moc(), add_graphic_overlay_from_stcs() – and plain property assignments (.widget.fov = ...) are safe to call from the render function even before the browser has finished loading. set_color_map() and selection() are not: gate both on reactive_read(w, "_is_loaded"), as shown throughout this guide.

Linking widgets

Lasso stars on the sky

examples/11_jscatter_stars_on_sky.py pairs ipyaladin with jupyter-scatter: lasso a region of a color-magnitude diagram, and the selected stars’ real sky positions light up on the viewer, in place.

import numpy as np
import pandas as pd
from astropy.table import Table
from ipyaladin import Aladin
from jscatter import Scatter
from shiny import reactive
from shiny.express import ui
from shinywidgets import render_ipyaladin, render_jscatter

# A plausible color-magnitude diagram for ~400 field stars around the
# Pleiades (synthetic: real surveys of this field have far more stars than
# fit cleanly in a short demo, but the main-sequence shape is realistic)
rng = np.random.default_rng(0)
n = 400
bp_rp = rng.uniform(-0.3, 2.5, n)
abs_g = -(4.5 * bp_rp + rng.normal(0, 0.6, n) + 1.0)
stars = pd.DataFrame(
    {
        "ra": 56.75 + rng.normal(0, 0.6, n),
        "dec": 24.12 + rng.normal(0, 0.5, n),
        "bp_rp": bp_rp,
        "abs_g": abs_g,
    }
)

ui.page_opts(title="Select stars in a plot, mark them on the sky", fillable=True)

with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("Color-magnitude diagram (lasso to select)")

        @render_jscatter
        def hr():
            return Scatter(data=stars, x="bp_rp", y="abs_g").lasso(initiator=True)

    with ui.card(full_screen=True):
        ui.card_header("Selected stars on the sky")

        @render_ipyaladin
        def sky():
            return Aladin(target=(56.75, 24.12), fov=2)


@reactive.effect
def _mark_selection():
    w = sky.widget
    idx = hr.selected()
    if w is None:
        return
    with reactive.isolate():
        try:
            w.remove_overlay("selected")
        except ValueError:
            pass
        if len(idx):
            w.add_table(
                Table.from_pandas(stars.iloc[idx]),
                name="selected",
                color="#ef476f",
                shape="circle",
                source_size=12,
            )

Before lassoing, and after (the lassoed points’ real RA/Dec positions are marked on the sky):

remove_overlay() clears the previous selection’s markers before drawing the new ones, so re-lassoing replaces the overlay instead of stacking another one on top. jupyter-scatter’s selected() returns row positions into the same stars frame add_table() draws from, so stars.iloc[idx] lines the two up directly; see the jscatter guide for that accessor.

Accessor reference

Accessor Returns Before any interaction Across a re-render Default rate policy
clicked_object() dict (ra, dec, data) or None None re-seeded to None (a freshly built viewer has no click yet) none
selected() list[astropy.table.Table] (one per catalog) [] re-seeded to [] none
target() astropy SkyCoord (or (Longitude, Latitude) for planetary surveys) seeded from the constructor’s target re-seeded from the new viewer’s target none
fov() astropy Angle seeded from the constructor’s fov re-seeded from the new viewer’s fov none

All four attach the moment the viewer renders and are seeded from its state immediately, so an interaction made before the first read is reflected in that read, not lost. All four also re-seed from the new viewer on every re-render rather than carrying the previous viewer’s value forward: a fresh Aladin has no click recorded yet, so clicked_object() goes back to None and selected() to []; target()/fov() pick up whatever the new constructor call passed, discarding any pan or zoom the user did before the re-render. This is why clicked_object() needs req(sky.clicked_object()) to wait for a click, while target()/fov() never need req(). None of the four declares a default rate limit.

clicked_object()

Prefer clicked_object() (or selected()/target()/fov()) over ipyaladin’s older set_listener() API for anything multi-user: set_listener() shares one callback registry across every Aladin instance in the process, so in a multi-session Shiny app, one session’s click can fire another session’s callback.

selected()

import pandas as pd
from astropy.table import Table
from ipyaladin import Aladin
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import reactive_read, render_ipyaladin

PLEIADES = Table(
    {
        "name": ["Alcyone", "Atlas", "Electra", "Maia", "Merope", "Taygeta", "Pleione"],
        "ra": [56.871, 56.978, 56.216, 56.579, 56.752, 56.447, 56.751],
        "dec": [24.105, 24.054, 24.113, 24.367, 23.948, 24.467, 24.137],
        "vmag": [2.87, 3.62, 3.70, 3.87, 4.17, 4.30, 5.09],
    }
)

ui.page_opts(title="selected(): box-select sources", fillable=True)
ui.input_action_button("arm", "Arm rectangle selection")

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_ipyaladin
        def sky():
            aladin = Aladin(target=(56.871, 24.105), fov=1.2)
            aladin.add_table(PLEIADES, shape="circle", source_size=16, color="#ffd166")
            return aladin

        @reactive.effect
        def _():
            w = sky.widget
            if input.arm() > 0 and w and reactive_read(w, "_is_loaded"):
                w.selection("rectangle")

    with ui.card():
        ui.card_header("Stars inside the selection")

        @render.data_frame
        def table():
            tables = sky.selected()
            if not tables:
                return pd.DataFrame({"name": [], "vmag": []})
            return tables[0].to_pandas()[["name", "vmag"]]

Stars inside a box selection

Box selection is opt-in: .widget.selection("rectangle") (or "circle") arms it for the next drag, after which the viewer goes back to its normal pan behavior. selected() returns one Table per catalog that has an add_table()-drawn overlay and sources inside the selection; with a single catalog (as above) that’s tables[0].

target() and fov()

Shown together in What’s in view. They’re the only two of the four accessors that re-seed from the new viewer’s constructor arguments, rather than resetting to empty, on a re-render – a camera position and field of view are never “nothing”.

Beyond the accessors: reactive_read()

One widget-level trait is worth reading directly: _is_loaded, which flips to True once the viewer has finished loading in the browser. Gate any effect that calls set_color_map() or selection() on it, as this guide does throughout. Don’t gate on _ready instead: current ipyaladin never sets it.

Tuning accessors

Reading on demand

target()/fov() are seeded the moment the viewer renders and stay live from then on, so they’re safe to read from a button handler that runs long after any pan or zoom. This button appends the current pointing to a running list of saved views each time it’s pressed.

examples/13_save_view.pyexcerpt · 30 of 34 lines
from ipyaladin import Aladin
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_ipyaladin

ui.page_opts(title="Save the current view", fillable=True)
ui.input_action_button("save", "Save this view")

views = reactive.Value([])

with ui.card(full_screen=True):

    @render_ipyaladin
    def sky():
        return Aladin(target=(83.822, -5.391), fov=1.2)  # Orion Nebula (M42)


@reactive.effect
@reactive.event(input.save)
def _():
    t, f = sky.target(), sky.fov()
    bookmark = f"ra={t.ra.deg:.2f} dec={t.dec.deg:.2f}  fov={f.deg:.2f} deg"
    views.set([*views(), bookmark])


@render.ui
def saved():
    if not views():
        return ui.p("No saved views yet.")
    return ui.tags.ul(*[ui.tags.li(v) for v in views()])

save view

Rate limiting

None of ipyaladin’s four accessors declare a default rate policy, but target() and fov() are the ones where that matters: a drag or a scroll-zoom reports an update for every intermediate mouse position, not one at the end. Pass rate_policy="debounce" (and optionally rate_delay=) to @render_ipyaladin(...) to coalesce a burst of pans/zooms into the trailing one:

from ipyaladin import Aladin
from shiny import reactive
from shiny.express import render, ui
from shinywidgets import render_ipyaladin

ui.page_opts(title="Rate-limited target()/fov()", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_ipyaladin(rate_policy="debounce", rate_delay=0.3)
        def sky():
            return Aladin(target=(83.63, 22.01), fov=5)

    with ui.card():
        ui.card_header("Pans/zooms seen by Python (debounced to 1 per 300 ms)")
        count = reactive.value(0)

        @reactive.effect
        def _count():
            sky.target()
            sky.fov()
            with reactive.isolate():
                count.set(count() + 1)

        @render.text
        def n():
            return f"updates received: {count()}"

Coalesced pan/zoom count

Debounce publishes once the stream goes quiet for rate_delay; it doesn’t guarantee exactly one publish per gesture, since a long or jittery drag can have quiet gaps longer than the delay in the middle of it. If you need that guarantee, track the drag’s end yourself – a sufficiently long rate_delay relative to your users’ typical pause-between-moves gets close in practice.

Large data

The sky imagery itself is “only send what’s visible” by construction – see Large data & performance’s three approaches: HiPS tiles are fetched from CDS only for the part of the sky currently in view, the same idea as a web map’s tile pyramid. add_table() catalogs are a different story: every row travels to the browser in one message when you call it, same as a table-heavy renderer like mols2grid – for large catalogs, that message can approach Shiny’s websocket limit (shiny run --ws-max-size raises it).

Layout and sizing

from ipyaladin import Aladin
from shiny.express import ui
from shinywidgets import render_ipyaladin

ui.page_opts(title="Fill vs. fixed height", fillable=True)

with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("Fills the card")

        @render_ipyaladin
        def fills():
            return Aladin(target=(83.822, -5.391), fov=2)  # M42

    with ui.card():
        ui.card_header("Fixed height (Aladin(height=250))")

        @render_ipyaladin
        def fixed():
            return Aladin(target=(83.822, -5.391), fov=2, height=250)

fill vs. fixed height

A viewer fills its card or output unless the Aladin has an explicit height (as above) or the output itself is given one (output_widget("sky", height="400px")). full_screen=True cards, sidebars, and layout_columns() all just work, including full_screen’s expand/collapse.

Gotchas

  • The constructor accepts Aladin(target=(83.63, 22.01)), but the equivalent in-place assignment w.target = (83.63, 22.01) raises AttributeError: 'float' object has no attribute 'deg'. Use a "ra dec" string (w.target = "83.63 22.01") or a SkyCoord instead.
  • _ready is never set by current ipyaladin. Gate in-place effects on reactive_read(w, "_is_loaded") instead.
  • Aladin(target="M31") blocks the render function on a network call to CDS’s Sesame service, and raises if CDS is slow or unreachable. Prefer coordinates, and reserve name strings for a user-driven search box.
  • The viewer needs live network access: its JavaScript and sky imagery stream from CDS at render time. If CDS is slow or unreachable, the viewer’s UI and overlays still render, but the imagery stays at “loading…”.

Learn more