Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ JSON reduction configuration consumed by
`usansred <https://github.com/neutrons/usansred/>`_. It reuses the ONCat login
and run-browsing widgets from
`pyoncatng <https://github.com/neutrons/pyoncatng/>`_ to sign in, browse a USANS
experiment's runs, and (soon) assign runs to roles and export a setup file.
experiment's runs, and assign runs to roles; exporting the setup file is
planned.

.. toctree::
:maxdepth: 2
Expand Down
40 changes: 36 additions & 4 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,43 @@ pyoncatng's `OncatLogin` and `IPTSTable`:
selection. Clearing the selection disables both buttons again.
5. Click **Fetch Runs** to capture the highlighted runs. The button stays
disabled until the table has a selection, and the captured runs are ordered
by increasing run number regardless of the order they were selected in.
by decreasing run number, as the table lists them, regardless of the order
they were selected in.
Loading another IPTS clears the selection and disables the button again;
the runs fetched before it are kept. Each click replaces the previous
capture, so the widget holds exactly the runs highlighted at the last click.
The role table below adds each capture to the runs it already holds; see
the next section.

Assigning runs to roles (sample / background / empty cell / empty beam) and
exporting the `usansred` JSON configuration are planned for subsequent
iterations.
## The RoleCastTable widget

Below the `RunsSelector`, the landing page mounts a `RoleCastTable`, where each
fetched run is assigned the role it plays in the reduction: sample, background
or empty cell. The table lists each run's ID, Name (its title), Role, Thickness
and Transmission, by decreasing run number. Thickness and Transmission are
empty for now.

1. Click **Fetch Runs** in the `RunsSelector` to add the highlighted runs to the
role table. Each fetch adds runs; runs already in the table stay, with their
role. A new run starts as a sample, unless runs with the same Name are
already in the table, in which case it takes their role.
2. Select runs in the role table: click selects one run, Ctrl/Cmd+click toggles
a run, and Shift+click selects a range.
3. Click **Set as Background**, **Set as Empty Cell** or **Set as Sample** to
assign that role. The runs of one measurement share a Name, so a button
assigns the role to every run with the same Name as a selected run. Runs
with the same Name therefore always have the same role. Names are compared
exactly, including case and spaces.
4. Click **Remove Runs** to take the selected runs out of the table. Only the
selected runs are removed; other runs with the same Name stay, with their
role.

The four buttons are enabled only while the role table has a selection. After
each click the selection is cleared, and a status line below the buttons
reports how many runs were assigned or removed.

Each row is colored by its role: white for sample, light pink for background
and light blue for empty cell.

Exporting the `usansred` JSON configuration is planned for a subsequent
iteration.
2 changes: 1 addition & 1 deletion pixi.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
name = "usansemble"
description = "NiceGUI web app to assemble usansred JSON reduction configurations"
dynamic = ["version"]
requires-python = ">=3.10"
requires-python = ">=3.11"
license = { text = "GPL-3.0" }
keywords = ["neutrons", "usans", "usansred", "oncat", "nicegui"]
readme = "README.md"
Expand Down Expand Up @@ -83,7 +83,7 @@ platforms = ["linux-64", "osx-arm64"] # add additional platforms as needed

[tool.pixi.dependencies]
# Conda package dependencies
python = ">=3.10"
python = ">=3.11"
pyoncatng = "*"
nicegui = "*"
argcomplete = "*"
Expand All @@ -101,7 +101,7 @@ msgpack-python = ">=1.2.1" # GHSA-6v7p-g79w-8964
[tool.pixi.pypi-dependencies]
# PyPI dependencies, including this package to allow local editable installs
usansemble = { path = ".", editable = true }
jaraco-context = ">=6.1.0" # CVE-2026-23949
jaraco-context = ">=6.1.0" # CVE-2026-23949

# Pixi Build configuration - https://pixi.sh/latest/reference/pixi_manifest/#pixi-build

Expand All @@ -110,14 +110,14 @@ hatchling = "*"
versioningit = "*"

[tool.pixi.package.run-dependencies]
python = ">=3.10"
python = ">=3.11"
pyoncatng = "*"
nicegui = "*"
argcomplete = "*"

[tool.pixi.package]
name = "usansemble"
version = "0.0.0" # placeholder, overwritten by sync-version
version = "0.0.0" # placeholder, overwritten by sync-version

[tool.pixi.package.build]
backend = { name = "pixi-build-python", version = "*" }
Expand Down
27 changes: 19 additions & 8 deletions src/usansemble/app.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
"""The usansemble single-page app.

For now the page mounts a :class:`~usansemble.widgets.runs_selector.RunsSelector`
so a user can sign in to ONCat and browse a USANS experiment's runs. This is the
first step of the intended assemble-config wizard (sign in / pick runs -> assign
roles -> export usansred JSON); the later steps land as their widgets are built.
The page mounts a :class:`~usansemble.widgets.runs_selector.RunsSelector`, so a
user can sign in to ONCat and pick a USANS experiment's runs, above a
:class:`~usansemble.widgets.role_cast_table.RoleCastTable` that receives the
fetched runs for role assignment. These are the first two steps of the intended
assemble-config wizard (sign in / pick runs -> assign roles -> export usansred
JSON); the export step lands once its widget is built.
"""

from nicegui import ui

from usansemble.widgets.role_cast_table import RoleCastTable
from usansemble.widgets.runs_selector import RunsSelector


@ui.page("/")
def index() -> None:
"""The landing page: a titled RunsSelector."""
"""The landing page: a titled RunsSelector feeding a RoleCastTable."""
with ui.column().classes("q-pa-md").style("width: 100%; max-width: 1000px"):
ui.label("usansemble").classes("text-h5")
ui.markdown(
"Sign in to ONCat, then enter an IPTS number (e.g. **24703**) and click "
"**Load** to fetch its USANS runs. Use the table's selection gestures "
"to choose runs, then click **Fetch Runs** to capture them; assigning "
"them to roles and exporting a `usansred` configuration will come next."
"to choose runs, then click **Fetch Runs** to add them to the role "
"table below. A new run starts as a sample, or with the role of the "
"runs already there with the same name: select runs in the role table "
"and click **Set as Background** or **Set as Empty Cell** to reassign "
"them, or **Set as Sample** to reassign them back. Each of these "
"buttons reassigns every run with the same name as a selected run. "
"**Remove Runs** removes only the selected runs. "
"Exporting a `usansred` configuration will come next."
)
RunsSelector(facility="SNS", instrument="USANS")
selector = RunsSelector(facility="SNS", instrument="USANS")
role_table = RoleCastTable()
selector.on_runs_fetched(role_table.add_runs)
32 changes: 32 additions & 0 deletions src/usansemble/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Enumerations shared across usansemble.

:class:`MeasurementType` mirrors ``usansred.enums.MeasurementType`` member for
member and value for value, so a role assigned here serializes to exactly the
string ``usansred`` expects in its reduction configuration.

``usansred`` is not a dependency yet: it pins Python to ``>=3.12,<3.13`` and
pulls ``mantidworkbench`` into what is otherwise a lightweight web app. Once it
is adopted, this mirror is replaced by ``from usansred.enums import
MeasurementType``; ``tests/test_enums.py`` guards the mirror until then.

Display text lives in :data:`ROLE_LABELS` rather than on the enum, so the enum
itself stays identical to ``usansred``'s.
"""

from enum import StrEnum


class MeasurementType(StrEnum):
"""The role a run plays in a USANS reduction."""

SAMPLE = "sample"
BACKGROUND = "background"
EMPTY_CELL = "empty_cell"


# Text shown in the UI for each role.
ROLE_LABELS: dict[MeasurementType, str] = {
MeasurementType.SAMPLE: "sample",
MeasurementType.BACKGROUND: "background",
MeasurementType.EMPTY_CELL: "empty cell",
}
167 changes: 167 additions & 0 deletions src/usansemble/role_cast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"""The role assignment model behind the role table.

A :class:`RoleCast` holds one :class:`RunAssignment` per fetched run, recording
the role that run plays in the reduction (sample, background or empty cell).
It is pure data with no NiceGUI calls, so it is unit-testable without a UI
context, in the same spirit as pyoncatng's ``RunTable.build_options``.

Validation is limited to run-number lookup: ``usansred.ReductionConfig`` will
own validation once ``usansred`` becomes a dependency, so nothing here
anticipates it.
"""

import copy
from collections.abc import Iterable, Sequence
from dataclasses import dataclass

from pyoncatng.widgets.iptstable import KEY_COLUMN as ID_COLUMN
from pyoncatng.widgets.iptstable import Row

from usansemble.enums import ROLE_LABELS, MeasurementType

# The column of a ``RunsSelector`` row that seeds a run's name. It must match
# ``runs_selector.TITLE_COLUMN``; it is repeated here so the model does not
# import the login widget, and a test checks that the two agree.
TITLE_COLUMN = "Title"

# Keys of the rows emitted by :meth:`RoleCast.as_rows`. ``ROLE_VALUE_KEY`` has
# no matching grid column: it carries the raw enum value for the row-coloring
# rules, which then do not depend on the display label.
NAME_COLUMN = "Name"
ROLE_COLUMN = "Role"
THICKNESS_COLUMN = "Thickness"
TRANSMISSION_COLUMN = "Transmission"
ROLE_VALUE_KEY = "_role"


@dataclass
class RunAssignment:
"""The role of one run, with the per-run values a reduction needs."""

run_number: int
name: str
role: MeasurementType = MeasurementType.SAMPLE
thickness: float | None = None
transmission: float | None = None


def _row_name(row: Row) -> str:
"""The validated measurement name carried by a fetched run row."""
title = row[TITLE_COLUMN]
if title is None:
raise ValueError(f"run {row[ID_COLUMN]!r} has no {TITLE_COLUMN}")
name = str(title)
if not name.strip():
raise ValueError(f"run {row[ID_COLUMN]!r} has no {TITLE_COLUMN}")
return name


class RoleCast:
"""The role assignments of the fetched runs, keyed by run number.

Assignments are ordered by decreasing run number, the order in which the
``IPTSTable`` of ``RunsSelector`` lists the runs, whatever order
:meth:`add_runs` receives them in. Runs are added by :meth:`add_runs` and
leave only through :meth:`remove`.

Runs sharing a name belong to one USANS measurement, so they always share a
role: :meth:`assign` sets the role of whole name groups, and a newly fetched
run takes the role of the runs with its name already in the cast. Names are compared exactly, as the
title double-click of ``RunsSelector`` compares titles.
"""

def __init__(self) -> None:
self._assignments: dict[int, RunAssignment] = {}

@property
def assignments(self) -> list[RunAssignment]:
"""Deep copies of the assignments, by decreasing run number."""
return copy.deepcopy(list(self._assignments.values()))

def add_runs(self, rows: Sequence[Row]) -> list[int]:
"""Add the runs in ``rows`` that are not in the cast yet.

A run already present keeps its assignment unchanged, and no run is
dropped. A new run is named after its ``Title`` and takes the role of
the runs with the same name already in the cast, or starts as a sample
if there are none. ``int`` makes a run number reported as a string
match the same run reported as an integer, and keeps the ordering
numeric.

Returns
-------
list of int
The run numbers added, by decreasing run number.
"""
# Runs sharing a name share a role, so any run of a group gives it.
group_roles = {assignment.name: assignment.role for assignment in self._assignments.values()}
assignments = dict(self._assignments)
added: list[int] = []
for row in rows:
run_number = int(row[ID_COLUMN])
if run_number in assignments:
continue
name = _row_name(row)
role = group_roles.get(name, MeasurementType.SAMPLE)
assignments[run_number] = RunAssignment(run_number=run_number, name=name, role=role)
added.append(run_number)
self._assignments = dict(sorted(assignments.items(), reverse=True))
return sorted(added, reverse=True)

def remove(self, run_numbers: Iterable[int]) -> list[int]:
"""Remove the runs in ``run_numbers``, and only those.

Other runs sharing a name with a removed run stay, with their role.

Returns
-------
list of int
The run numbers removed, by decreasing run number.

Raises
------
KeyError
If a run number is not present. Every run number is looked up
before any run is removed, so a failed call removes nothing.
"""
targets = {self._assignments[int(run_number)].run_number for run_number in run_numbers}
self._assignments = {n: a for n, a in self._assignments.items() if n not in targets}
return sorted(targets, reverse=True)

def assign(self, run_numbers: Iterable[int], role: MeasurementType) -> list[int]:
"""Give ``role`` to every run sharing a name with a run in ``run_numbers``.

Selecting any one run of a measurement therefore assigns the role to the
whole measurement.

Returns
-------
list of int
The run numbers whose role was set, by decreasing run number.

Raises
------
KeyError
If a run number is not present. Every run number is looked up
before any role changes, so a failed call leaves all roles as they
were.
"""
names = {self._assignments[int(run_number)].name for run_number in run_numbers}
targets = [assignment for assignment in self._assignments.values() if assignment.name in names]
for assignment in targets:
assignment.role = role
return [assignment.run_number for assignment in targets]

def as_rows(self) -> list[Row]:
"""Project the assignments into grid rows, by decreasing run number."""
return [
{
ID_COLUMN: assignment.run_number,
NAME_COLUMN: assignment.name,
ROLE_COLUMN: ROLE_LABELS[assignment.role],
THICKNESS_COLUMN: assignment.thickness,
TRANSMISSION_COLUMN: assignment.transmission,
ROLE_VALUE_KEY: assignment.role.value,
}
for assignment in self._assignments.values()
]
Loading
Loading