Skip to content

Selections

panel_flowdash.selection

Plot selections as one value, carried by ports of type Selection.

A brush or click on a chart becomes a :class:Selection: predicates on fields of the chart's data, such as category in [A, B] or 10 <= price <= 20, and the node that made it. A filter takes it and keeps the rows matching every predicate; an empty selection keeps every row.

The chart a selection is made on should read the unfiltered data and show its own selection, as Vega-Lite and HoloViews do, so only other views are filtered by it. Feeding the chart from the filter its selection drives is a cycle, which the editor refuses.

:func:from_vega and :func:from_holoviews turn what those libraries report into a Selection, and :func:link_selection gives a component a debounced selection output from a Vega pane or a HoloViews stream.

COALESCE = 10 module-attribute

COALESCE_MAX = 200 module-attribute

DEBOUNCE = 150 module-attribute

EMPTY = Selection() module-attribute

SELECTION_TYPE = register_port_type('Selection') module-attribute

_AGGREGATING_ELEMENTS = ('Bars', 'Histogram') module-attribute

_PART_FREQUENCIES = {'year': 'Y', 'quarter': 'Q', 'month': 'M', 'week': 'W-SAT', 'dayofyear': 'D', 'day': 'D', 'date': 'D', 'hours': 'h', 'minutes': 'min', 'seconds': 's', 'milliseconds': 'ms'} module-attribute

_UNIT_PARTS = ('year', 'quarter', 'month', 'week', 'dayofyear', 'day', 'date', 'hours', 'minutes', 'seconds', 'milliseconds') module-attribute

Predicate dataclass

Rows whose field lies in a range or is one of a set of values.

op is "range", with values the (start, end) bounds, either of which may be None, or "in", with values the values to keep. closed says which bounds of a range are included: "both", or "left" for start <= x < end.

closed = 'both' class-attribute instance-attribute

field instance-attribute

op instance-attribute

values instance-attribute

from_dict(data) classmethod

Return the predicate :meth:to_dict described.

mask(frame)

Return which rows of frame match.

Bounds and values are made comparable with the column: on a datetime column dates become midnights, and naive datetimes, which charts report in UTC, are converted to the column's timezone. A range on an unordered categorical column raises ValueError.

to_dict()

Return the predicate as a dict JSON can hold.

Dates and datetimes are written in ISO format, and types names the kind of each value that was one, e.g. [None, "datetime"].

Selection dataclass

A plot selection: rows matching every predicate, made on the node source.

A selection with no predicates is empty and selects every row.

Some selections cannot be turned into predicates on fields, and filters refuse them: index holds rows named by their position in the chart's data, such as a Vega-Lite point selection without fields, and unsupported says why another kind of selection cannot filter data, such as a lasso or a brush on a repeating time unit.

empty property

Whether the selection keeps every row.

fields property

The fields the predicates are on, in order.

index = None class-attribute instance-attribute

predicates = () class-attribute instance-attribute

source = None class-attribute instance-attribute

unsupported = None class-attribute instance-attribute

check_filterable()

Raise ValueError if the selection cannot be applied to data as predicates on fields.

filter(frame)

Return the rows of frame matching every predicate; an empty selection keeps them all.

from_dict(data) classmethod

Return the selection :meth:to_dict described.

to_dict()

Return the selection as a dict of plain values, e.g. to store it.

SelectionFilter

Bases: Viewer

The rows of a DataFrame that match a selection.

data = param.DataFrame(default=None, allow_None=True, doc='The rows to filter.') class-attribute instance-attribute

selection = param.ClassSelector(class_=Selection, default=None, allow_None=True, doc='The selection rows must match.') class-attribute instance-attribute

filtered()

Return the rows of data matching selection, all of them without one.

Bases: Parameterized

Reports the selection made on a Vega pane or HoloViews stream as value.

Equal selections in a row are reported once. Selections that arrive while one is being reported, for example while the filters it drives run their queries, replace each other, and only the newest is reported next, so at most one is in flight. After a slow report the link waits half as long, up to COALESCE_MAX milliseconds, before the next, so a drag's selections collect rather than each running its own report.

debounce = param.Integer(default=DEBOUNCE, bounds=(0, None), doc="\n Milliseconds a Vega pane waits after the last change of a selection\n before sending it, unless the pane's own debounce was set. Bokeh's\n selection tools report on release already.") class-attribute instance-attribute

source property

The node the selection is made on.

value = param.ClassSelector(class_=Selection, default=EMPTY, doc='The latest selection.') class-attribute instance-attribute

clear()

Report an empty selection.

Follow a HoloViews BoundsXY, BoundsX, BoundsY or Selection1D stream.

Replacing a linked pane or stream clears the selection.

Follow the selections of pane, replacing what was linked before.

The pane's debounce is set to this link's unless it was set before. spec defaults to the pane's object. Replacing a linked pane or stream clears the selection.

push(selection)

Report selection, unless it equals the one reported last.

In a served session it is reported shortly after, together with any that follow it; outside one, at once.

Stop following the pane or stream linked last.

_Channel dataclass

An encoding channel, and whether the view it is in aggregates its rows.

aggregated instance-attribute

spec instance-attribute

_aggregates(view)

_as_datetime(value)

Return a numpy or pandas datetime as a Python one; NaT as None.

_base_unit(unit)

Return unit without its binned and utc prefixes, and whether it is in UTC.

_categorical(frame, dim)

_comparable(value, column)

Return value as a value of column's type where they are temporal.

_dims(element)

_element(element)

Return the element a selection is made on, or why it cannot be told.

A DynamicMap gives the element it shows last. An Overlay gives its only layer, or its first when every layer has the same dimensions; layers that differ are ambiguous and give a reason instead.

_from_epoch_ms(value)

Return Vega's temporal values, epoch milliseconds, as naive datetimes in UTC as Panel sends them.

_interval_predicate(name, values, channel, timezone)

Return the predicate of an interval on one field, or why it cannot be one.

_parse_temporal(value, kind)

_plain(value)

Return a numpy scalar as the Python value JSON can hold.

_range(field, start, end)

_repeating_unit(unit)

Whether unit folds time onto a cycle, e.g. month puts every January together.

_set(ref, name, value)

_short(value)

_snap_bins(start, end, bin_spec)

Return the range of the bins whose midpoint lies within the brush, or None if no bin's does.

Bins are only known here when the spec fixes their step; Vega derives them from maxbins and the data otherwise. Edges lie at anchor, else at the start of an extent that is not made nice, else at multiples of the step.

_snap_time_unit(start_ms, end_ms, unit, timezone)

Return the range of the units Vega highlights, those whose start lies within the brush.

A unit is cut in UTC when it starts with utc and otherwise in the browser's timezone, as Vega does; the bounds are returned as naive datetimes in UTC, as Panel sends naive datetimes. Returns None when the brush covers no unit's start.

_temporal_kind(value)

_time_unit(channel)

_unescape(name)

_unit_parts(unit)

_vega_channels(spec, aggregated=False)

Return the encoding channels by the name a selection reports their field under.

A field with a timeUnit is reported as {timeUnit}_{field}. Layers and concatenated views are searched too.

error_text(exc)

Return an exception's message with its credentials masked, to show a user or an agent.

from_holoviews(stream, element=None, *, key=None, source=None)

Return the selection a HoloViews stream reports.

BoundsXY, BoundsX and BoundsY give ranges on the element's first two dimensions; a box on a categorical axis is unsupported, since its bounds are screen positions rather than values. Selection1D, which Bokeh's box, lasso and tap tools fill, gives the selected rows' values of key: by default the element's first key dimension when it is categorical and its values are unique, such as the categories of Bars, and the rows' positions otherwise, which filters refuse. A Lasso stream's polygon cannot be a filter and is unsupported. For a DynamicMap, the element it shows last is used, and for an Overlay its layer, if the layers agree on their dimensions. On Bars and Histogram the y axis is a measure per group, so a BoundsXY box keeps only its x range and BoundsY is unsupported.

from_vega(value, kind, spec=None, source=None, timezone=None)

Return the selection a Vega pane reports for one selection parameter.

Parameters:

Name Type Description Default
value Any

The value of the parameter on pn.pane.Vega.selection. An interval gives {field: [start, end]} per encoded field on a continuous scale and {field: [v1, v2, ...]} on a discrete one; a point gives a list of {field: value} items, or _vgsid_ row ids when it names no fields. Empty or None means nothing is selected.

required
kind str | None

"interval" or "point", as Vega._selections reports it.

required
spec Any

The Vega-Lite spec, whose encodings give each field's type, time unit and bins.

None
source str | None

The node the selection is made on.

None
timezone str | None

The browser's IANA timezone, in which Vega cuts local time units; UTC when not given.

None
Temporal
required
covers
required
which
required
A
required
whose
required
brushed
required
not
required

Give component a selection output that follows the selections of target.

target is a pn.pane.Vega or a HoloViews stream (with the element it selects on). The selection is written to the parameter output of component, which the component declares, e.g. selection = param.ClassSelector(class_=Selection, default=EMPTY), and lists in provides with type SELECTION_TYPE. Its source is the component's node id. Call it from __init__ or __panel__; the editor unlinks it when the component is removed.

Pass the link returned before when the component replaces its pane, e.g. after its data changed, so the output keeps one link; the new pane starts with nothing selected. Pass source, the node id or a function returning it, when linking outside the component's creation and outside a served session, where the node cannot be looked up.

register(*, page=True, component=False, sidebar=False, title=None, icon=None, description=None, tags=None, extensions=None, default_size=None, min_size=None, max_size=None, framed=None, singleton=False, provides=None, requires=None, placeholder=None, config_schema=None, config=None, config_editor=None, check_config=None, contract=None, config_choices=None, config_completions=None, palette_presets=None, handles_failures=None, aliases=None, port_aliases=None, allow_users=None, allow_groups=None, deny_users=None, deny_groups=None, authorize=None)

Metadata-only decorator for app exports.

Annotates an app object/callable without altering runtime behavior.

The config_schema, config and config_editor arguments declare design-time configuration options that appear in the node editor. Use config_schema (a param.Parameterized subclass, a Pydantic model, or a JSON Schema dict) to define config explicitly, or config to name which of a Viewer's own params are configuration rather than input ports. Pass config_editor to supply a custom editor callable instead of the auto-generated form.

The check_config argument takes a callable, sync or async, that checks a node's config before it is applied: check(config, inputs) gets the node's whole config with the change applied and its input values that are set and not failed ({} before the node is placed). It returns None, a string or an iterable of strings, each non-empty string a problem, or raises ValueError with the problem as its message. A :class:~panel_flowdash.CheckWarning in place of a string is a warning, shown with the config but not refusing it. Any other result or exception, or taking longer than 10 seconds, counts as a failed check. The check runs again when an input of the node is connected or disconnected. A sync check runs in a worker thread and must not change the editor. A config with problems is refused in the inspector and by the agent tools, and reported by validation and previews.

The contract argument takes a :class:~panel_flowdash.ParameterContract: what the dashboard needs of a value bound to a parameter on one of the component's config fields, e.g. the columns its downstream nodes read from a data source. Its expects(context) writes the parameter's expects and its check(context, expects) runs whenever the parameter is rebound, see :mod:panel_flowdash.parameters.

The config_choices argument takes a callable, sync or async, called like check_config as choices(config, inputs), that returns the values each config field may take: {field: choices}, where choices are a list of values, a {label: value} dict or a :class:~panel_flowdash.Choices. The inspector offers them in a dropdown, or as suggestions with Choices(restrict=False), and asks again when the node's inputs or config change. Choices under the name of an input are offered for the value that input takes while it is not connected. A config param may also declare that it names a column of an input, with metadata={"flowdash": {"choices": "columns", "of": "<input>"}}.

The config_completions argument takes a callable, sync or async, called like config_choices, that returns the words the code editor of a code field completes while typing: {field: words}, where words are a list, a {label: word} dict or a :class:~panel_flowdash.Choices whose types are shown beside each word, e.g. the columns of the tables a query reads. Without it a code field completes the column names of the node's tabular inputs.

The palette_presets argument takes a callable, called with the editor's context, that returns further entries the component palette and the command palette offer for the component, each placing it with a config filled in: dicts with a title and a config, and optionally a description, a tooltip, tags and an icon, e.g. one entry per data source the host provides. It is asked again when the editor's context changes, not on every search; an entry without a title or config, or whose config is not JSON-serializable, is skipped, and a failing callable offers none. An entry's optional id identifies it in the command palette; without one, its title and config do. Components found by scanning a project directory offer their presets once imported, which the app does when a dashboard is edited.

The placeholder argument sets the message a dashboard tile shows while a blocking input of the component is unset, in place of the default "Waiting for " text.

The handles_failures argument names the inputs that can receive a failure. With FlowDash(propagate_failures=True) an upstream failure reaches such an input as a param.ReactiveError instead of leaving the input on its last value; the parameter behind it must accept one, so use an untyped param.Parameter.

The aliases argument lists ids the component was registered under before (e.g. ["Old/section_name"]) and port_aliases maps former port or config names to current ones (e.g. {"ticker": "symbol"}), so a saved dashboard that references the old names still loads after a rename.

The framed argument says whether the component's dashboard tile is drawn as a framed card: False for components that are layout chrome themselves, e.g. a divider or a section heading, True for ones that need a frame, and None (the default) to follow the dashboard's "Frame tiles" setting. A tile's own frame option, set in the Layout tab, takes precedence over it.

The extensions argument names the Panel extensions (e.g. ["tabulator"]) the app's output needs. Components are imported lazily, after the page has loaded its JavaScript, so an editor loads every declared extension up front; an undeclared one fails to render in the browser.

The allow_users, allow_groups, deny_users and deny_groups arguments declare page-level authorization rules. Users are matched against either the OAuth login or the system user; groups against the identity's resolved group membership. Deny rules always win; when only allow rules are present the identity must match at least one; with no rules the project's default policy applies. Pass authorize for a custom callable taking the resolved Identity and returning a bool (resolved on import).

The returned decorator exposes the metadata as its record before it is applied, so a factory that builds the class can read the registered title and the rest of the declaration while it builds it::

registration = register(component=True, title=spec["title"])
if not spec.get("columns"):
    raise ValueError(f"{registration.record.title}: declares no columns.")
return registration(type(name, (Viewer,), namespace))

Arguments register refuses, and a component class it refuses, are named by their title when one is given rather than by the Python name.

register_port_type(name, *, aliases=(), subtype_of=(), columns=None, color=None)

Register a port type, its alternative spellings and the types it can feed.

Registering a name again adds to its aliases and supertypes. Aliases and supertypes may be spelled any way that normalizes to a registered type; an unknown supertype is registered on the fly.

Parameters:

Name Type Description Default
name str

Canonical name of the type, e.g. "Customer". Matched case-insensitively.

required
aliases Iterable[str]

Other spellings of the same type, e.g. ["crm.Customer"].

()
subtype_of Iterable[str]

Types an output of this type may connect to, e.g. ["Person"]. Subtyping is transitive.

()
columns Callable | None

For a tabular type that is not a DataFrame, e.g. a lazy query, a callable that lists the columns of a value without fetching rows: columns(value) returns column names, (name, type) pairs or a {name: type} dict. Config fields that offer the columns of an input of this type use it, see :class:~panel_flowdash.Choices. Subtypes inherit it.

None
color str | None

Optional CSS color used for canvas handles of this port type. Subtypes inherit it unless they register their own.

None

Returns:

Type Description
str

The canonical name ports of this type normalize to.

Raises:

Type Description
ValueError

If an alias already names a different type, or the rule would make any a subtype of something.

Unlink every link :func:link_selection made for component.