Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
2a92639
feat: add plate_row and plate_col fields to PositionBase
ieivanov Mar 24, 2026
fa4f009
feat: add plate_row and plate_col fields to PositionBase
ieivanov Mar 24, 2026
e1fdddc
feat: add configurable name_pattern to grid plans
ieivanov Mar 25, 2026
436d880
style(pre-commit.ci): auto fixes [...]
pre-commit-ci[bot] Mar 25, 2026
3ad1742
feat: auto-generate position name from plate_row/plate_col
ieivanov Mar 25, 2026
e29b780
style(pre-commit.ci): auto fixes [...]
pre-commit-ci[bot] Mar 25, 2026
c44ebc9
docs: update docstrings for plate_row, plate_col, and name_pattern
ieivanov Mar 25, 2026
4161d7d
feat: enforce name matches plate_row/plate_col
ieivanov Mar 25, 2026
b8dde70
feat: allow plate_row and plate_col to be int or str
ieivanov Mar 25, 2026
3e2de02
test: add tests for plate_row/plate_col, name_pattern, and composite …
ieivanov Mar 25, 2026
0d8a19a
style(pre-commit.ci): auto fixes [...]
pre-commit-ci[bot] Mar 25, 2026
439849c
feat: relax name validation for string plate_row/plate_col
ieivanov Mar 25, 2026
013dfda
style(pre-commit.ci): auto fixes [...]
pre-commit-ci[bot] Mar 25, 2026
5cbb6f1
fix: resolve mypy type narrowing for plate_row/plate_col
ieivanov Mar 25, 2026
710ee3c
style(pre-commit.ci): auto fixes [...]
pre-commit-ci[bot] Mar 25, 2026
4b15a8a
Merge branch 'add-plate-row-col' of https://github.com/ieivanov/useq-…
ieivanov Mar 26, 2026
3fe9125
Apply suggestion from @tlambert03
tlambert03 Mar 30, 2026
61efb76
Merge branch 'main' into add-plate-row-col
tlambert03 Mar 30, 2026
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
17 changes: 15 additions & 2 deletions src/useq/_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,19 @@ class _GridPlan(_MultiPointPlan[PositionT]):
Height of the field of view in microns. If not provided, acquisition engines
should use current height of the FOV based on the current objective and camera.
Engines MAY override this even if provided.
name_pattern : str
Format pattern for grid position names. Supported variables are
`{row}`, `{col}`, and `{idx}`. By default, `"{idx:04d}"`.
"""

overlap: tuple[float, float] = Field(default=(0.0, 0.0), frozen=True)
mode: OrderMode = Field(default=OrderMode.row_wise_snake, frozen=True)
name_pattern: str = Field(
default="{idx:04d}",
frozen=True,
description="Format pattern for grid position names. "
"Supported variables: {row}, {col}, {idx}.",
)

@field_validator("overlap", mode="before")
@classmethod
Expand Down Expand Up @@ -137,7 +146,7 @@ def iter_grid_positions(
y=y0 - r * dy,
grid_row=r,
grid_col=c,
name=f"{str(idx).zfill(4)}",
name=self.name_pattern.format(row=r, col=c, idx=idx),
)

def __iter__(self) -> Iterator[PositionT]: # type: ignore [override]
Expand Down Expand Up @@ -518,7 +527,11 @@ def iter_grid_positions(
pos = []
for idx, (x, y, r, c) in enumerate(pos):
yield AbsolutePosition(
x=x, y=y, grid_row=r, grid_col=c, name=f"{str(idx).zfill(4)}"
x=x,
y=y,
grid_row=r,
grid_col=c,
name=self.name_pattern.format(row=r, col=c, idx=idx),
)

def _cached_tiles(
Expand Down
5 changes: 4 additions & 1 deletion src/useq/_iter_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ def _iter_sequence(
# determine x, y, z positions
event_kwargs.update(_xyzpos(position, channel, sequence.z_plan, grid, z_pos))
if position and position.name:
event_kwargs["pos_name"] = position.name
pos_name = position.name
if grid and grid.name and getattr(position, "plate_row", None) is not None:
pos_name = f"{pos_name}_{grid.name}"
event_kwargs["pos_name"] = pos_name
# include position properties only when p-index changes
p_idx = index.get(Axis.POSITION, -1)
if position and position.properties and p_idx != _last_p_idx:
Expand Down
11 changes: 1 addition & 10 deletions src/useq/_plate.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from useq._enums import Shape
from useq._grid import RandomPoints, RelativeMultiPointPlan
from useq._plate_registry import _PLATE_REGISTRY
from useq._position import Position, PositionBase, RelativePosition
from useq._position import Position, PositionBase, RelativePosition, _index_to_row_name

if TYPE_CHECKING:
from pydantic_core import core_schema
Expand Down Expand Up @@ -418,15 +418,6 @@ def plot(self, show_axis: bool = True) -> None:
plot_plate(self, show_axis=show_axis)


def _index_to_row_name(index: int) -> str:
"""Convert a zero-based column index to row name (A, B, ..., Z, AA, AB, ...)."""
name = ""
while index >= 0:
name = chr(index % 26 + 65) + name
index = index // 26 - 1
return name


def _find_pattern(seq: Sequence[int]) -> tuple[list[int] | None, int | None]:
n = len(seq)

Expand Down
61 changes: 54 additions & 7 deletions src/useq/_position.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@
from useq import MDASequence


def _index_to_row_name(index: int) -> str:
"""Convert a zero-based row index to name (A, B, ..., Z, AA, AB, ...)."""
name = ""
while index >= 0:
name = chr(index % 26 + 65) + name
index = index // 26 - 1
return name


class PositionBase(MutableModel):
"""Define a position in 3D space.

Expand All @@ -32,13 +41,23 @@ class PositionBase(MutableModel):
z : float | None
Z position in microns.
name : str | None
Optional name for the position.
Optional name for the position. When `plate_row` and `plate_col` are
both int, the name is derived from them (e.g., "A1") and providing a
mismatched name raises ValueError. When either is a str (custom
naming), the name defaults to ``f"{plate_row}{plate_col}"`` but can
be freely overridden.
sequence : MDASequence | None
Optional MDASequence relative this position.
plate_row : int | None
Optional 0-based row index for well plate positions.
plate_col : int | None
Optional 0-based column index for well plate positions.
plate_row : int | str | None
Row for well plate positions. Can be a 0-based index (e.g., 0 → "A",
1 → "B") or a string name (e.g., "A", "B") used as-is. In YAML,
unquoted letters are parsed as strings (``plate_row: A`` works).
plate_col : int | str | None
Column for well plate positions. Can be a 0-based index (e.g., 0 → "1",
1 → "2") or a string name (e.g., "1", "2") used as-is. In YAML,
unquoted numbers are parsed as int, so use quotes for string columns
(``plate_col: "1"`` for column name "1", vs ``plate_col: 1`` for
0-based index 1 → column name "2").
grid_row : int | None
Optional row index, when used in a grid.
grid_col : int | None
Expand All @@ -51,8 +70,8 @@ class PositionBase(MutableModel):
name: str | None = None
sequence: Optional["MDASequence"] = None
properties: list[PropertyTuple] | None = None
plate_row: int | None = None
plate_col: int | None = None
plate_row: int | str | None = None
plate_col: int | str | None = None
Comment on lines +73 to +74

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit uncertain about int | str here. I see in your tests that you've used this for things like Position(plate_row="fish0", plate_col="neuromast0")... but that feels like it's overloading one concept (which row/col) to do double duty to store metadata that should arguably go elsewhere (either in the position name itself (which is already a totally open string) or in the sequence metadata somewhere (where you could map your row/col indices to treatments/metadata). Also, thinking ahead to how this information would be used to write an OME-Zarr, we have to know the row/col index (https://imaging-formats.github.io/yaozarrs/API_Reference/yaozarrs.v05/?h=row#yaozarrs.v05._plate.PlateWell) ... so allowing the user to provide a string here means we would have difficulty guaranteeing the ability to write ome-zarr.

I'm inclined to reduce this back to just int for now.

grid_row: int | None = None
grid_col: int | None = None

Expand Down Expand Up @@ -108,6 +127,34 @@ def __round__(self, ndigits: "SupportsIndex | None" = None) -> "Self":
# not sure why these Self types are not working
return type(self).model_construct(**kwargs) # type: ignore [return-value]

@model_validator(mode="after")
def _name_from_plate(self) -> "Self":

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this all feels like application-level logic to me. I don't think we should auto-calculate names from other fields. Just store the data, and leave this sort of concern (autogeneration of naming) to whoever is using the data, like a writer, or a GUI.

"""Set or validate name from plate_row/plate_col.

When both plate_row and plate_col are int (standard well-plate indices),
the name is derived as e.g. "A1" and an explicit mismatch raises
ValueError. When either is a str (custom naming), the name is only
auto-generated if not provided; explicit names are accepted as-is.
"""
if self.plate_row is not None and self.plate_col is not None:
if isinstance(self.plate_row, int) and isinstance(self.plate_col, int):
well_name = f"{_index_to_row_name(self.plate_row)}{self.plate_col + 1}"
if self.name is not None and self.name != well_name:
raise ValueError(
f"Position name {self.name!r} does not match "
f"plate_row={self.plate_row}, plate_col="
f"{self.plate_col} (expected {well_name!r}). "
f"Remove the name to auto-generate it from "
f"plate coordinates."
)
object.__setattr__(self, "name", well_name)
elif self.name is None:
# String plate coords: auto-generate only if no name provided
row_str = str(self.plate_row)
col_str = str(self.plate_col)
object.__setattr__(self, "name", f"{row_str}{col_str}")
return self

@model_validator(mode="before")
@classmethod
def _cast(cls, value: Any) -> Any:
Expand Down
2 changes: 2 additions & 0 deletions tests/fixtures/mda.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"fov_height": null,
"fov_width": null,
"mode": "row_wise_snake",
"name_pattern": "{idx:04d}",
"overlap": [
0.0,
0.0
Expand Down Expand Up @@ -94,6 +95,7 @@
"fov_height": null,
"fov_width": null,
"mode": "row_wise_snake",
"name_pattern": "{idx:04d}",
"overlap": [
0.0,
0.0
Expand Down
8 changes: 1 addition & 7 deletions tests/fixtures/mda.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,11 @@ metadata:
stage_positions:
- x: 10.0
y: 20.0
z: null
- name: test_name
sequence:
axis_order:
- t
- p
- g
- c
- z
grid_plan:
columns: 3
mode: row_wise_snake
rows: 2
z_plan:
above: 10.0
Expand Down
Loading
Loading