From feedback

This commit is contained in:
Joe Knapper 2026-02-25 13:19:38 +00:00 committed by Julian Stirling
parent 43fa793698
commit 63338f8ea0
4 changed files with 111 additions and 191 deletions

View file

@ -21,7 +21,7 @@ from pydantic import BaseModel, computed_field, field_validator, model_validator
import labthings_fastapi as lt
from labthings_fastapi.types.numpy import NDArray
from .camera import BaseCamera, CaptureParams, validate_capture_params
from .camera import BaseCamera, CaptureParams
from .stage import BaseStage
LOGGER = logging.getLogger(__name__)
@ -75,6 +75,22 @@ class StackParams(BaseModel):
origin: StackOrigin = StackOrigin.START
"""Where the stack is positioned relative to the current z position."""
@field_validator("images_to_save")
@classmethod
def validate_images_to_save(cls, value: int) -> int:
"""Validate that the number of images to save is greater than zero."""
if value <= 0:
raise ValueError(f"Invalid number of images to save: {value}. Must be > 0.")
return value
@field_validator("settling_time")
@classmethod
def validate_settling_time(cls, value: float) -> float:
"""Validate that settling time is zero or positive."""
if value < 0:
raise ValueError(f"Invalid settling time: {value}. Must be positive or 0.")
return value
class SmartStackParams(StackParams):
"""A class for holding smart stack parameters, and returning computed ones."""
@ -765,10 +781,6 @@ class AutofocusThing(lt.Thing):
- Final z position
- List of z positions captured
"""
# Validate parameters and raise Exception if unsuitable
validate_stack_params(stack_parameters=stack_parameters)
validate_capture_params(capture_parameters=capture_parameters)
captures: list[CaptureInfo] = []
z_positions: list[int] = []
@ -869,24 +881,3 @@ def _count_turning_points(sharpnesses: np.ndarray) -> int:
d_sharpnesses = d_sharpnesses[prominent]
# count the sign changes
return int(np.sum(d_sharpnesses[1:] * d_sharpnesses[:-1] < 0))
def validate_stack_params(stack_parameters: StackParams) -> None:
"""Validate stack parameters for a z-stack acquisition.
Ensures that the parameters allow a physical stack, without negative or zero
values where they would cause crashes.
:param stack_parameters: StackParams object containing stacking settings.
:raises ValueError: If any stack_parameters are found to be unusable.
"""
if stack_parameters.images_to_save <= 0:
raise ValueError(
f"Invalid number of images to save: {stack_parameters.images_to_save}. Must be > 0."
)
if stack_parameters.settling_time < 0:
raise ValueError(
f"Invalid settling time: {stack_parameters.settling_time}. Must be positive or 0."
)

View file

@ -20,7 +20,7 @@ from typing import Any, Literal, Mapping, Optional, Self, Tuple
import numpy as np
import piexif
from PIL import Image
from pydantic import BaseModel
from pydantic import BaseModel, field_validator
import labthings_fastapi as lt
from labthings_fastapi.types.numpy import NDArray
@ -54,37 +54,28 @@ class CaptureParams(BaseModel):
images_dir: str
save_resolution: tuple[int, int]
@field_validator("save_resolution")
@classmethod
def validate_save_resolution(cls, value: Tuple[int, int]) -> Tuple[int, int]:
"""Validate that save_resolution is a tuple with exactly two positive integers."""
if not isinstance(value, tuple):
raise TypeError("Save resolution should be a tuple")
if len(value) != 2 or any(not isinstance(x, int) or x <= 0 for x in value):
raise ValueError(
f"Invalid save_resolution: {value}. "
"Must be a tuple of two positive integers."
)
return value
def validate_capture_params(capture_parameters: CaptureParams) -> None:
"""Validate capture parameters for a capture.
Ensures that the save resolution is a tuple of two positive integers
and that the images directory is a non-empty string.
:param capture_parameters: CaptureParams object containing acquisition settings.
:raises ValueError: If `save_resolution` is not a tuple of two positive integers,
or if `images_dir` is not a non-empty string.
"""
if (
not isinstance(capture_parameters.save_resolution, tuple)
or len(capture_parameters.save_resolution) != 2
or not all(
isinstance(x, int) and x > 0 for x in capture_parameters.save_resolution
)
):
raise ValueError(
f"Invalid save_resolution: {capture_parameters.save_resolution}. Must "
"be a tuple of two positive integers."
)
if (
not isinstance(capture_parameters.images_dir, str)
or not capture_parameters.images_dir
):
raise ValueError(
f"Invalid images_dir: {capture_parameters.images_dir}. Must be a non-empty string."
)
@field_validator("images_dir")
@classmethod
def validate_images_dir(cls, value: str) -> str:
"""Validate that images_dir is a non-empty string."""
if not isinstance(value, str) or not value:
raise ValueError(
f"Invalid images_dir: {value}. Must be a non-empty string."
)
return value
class NoImageInMemoryError(RuntimeError):

View file

@ -240,10 +240,14 @@ class RectGridWorkflow(ScanWorkflow[SettingModelType], Generic[SettingModelType]
correlation_resize=STITCHING_RESOLUTION[0] / self.save_resolution[0],
)
def _build_scan_settings(self, base_kwargs: dict) -> SettingModelType:
"""Construct the _settings_model."""
return self._settings_model(**base_kwargs)
def all_settings(
self, images_dir: str
) -> tuple[SettingModelType, Optional[StitchingSettings]]:
"""Return the scan settings and the stitching settings.
"""Return scan settings and the stitching settings.
:param images_dir: The directory that images are to be written to.
:return: A tuple containing the settings model for this workflow and the
@ -252,19 +256,17 @@ class RectGridWorkflow(ScanWorkflow[SettingModelType], Generic[SettingModelType]
stitching_settings = self._get_stitching_settings_model()
dx, dy = self._calc_displacement_from_overlap(self.overlap)
capture_params = CaptureParams(
images_dir=images_dir, save_resolution=self.save_resolution
)
base_kwargs = {
"overlap": self.overlap,
"dx": dx,
"dy": dy,
"capture_params": CaptureParams(
images_dir=images_dir, save_resolution=self.save_resolution
),
"autofocus_params": AutofocusParams(dz=self.autofocus_dz),
}
autofocus_params = AutofocusParams(dz=self.autofocus_dz)
scan_settings = self._settings_model(
overlap=self.overlap,
dx=dx,
dy=dy,
capture_params=capture_params,
autofocus_params=autofocus_params,
)
scan_settings = self._build_scan_settings(base_kwargs)
return scan_settings, stitching_settings
@ -389,38 +391,14 @@ class HistoScanWorkflow(RectGridWorkflow[HistoScanSettingsModel]):
return True
return self._background_detector.ready
def all_settings(
self, images_dir: str
) -> tuple[HistoScanSettingsModel, StitchingSettings]:
"""Return the workflow settings and stitching settings.
:param images_dir: The directory that images are to be written to.
:return: A tuple containing the settings model for this workflow and the
settings model for stitching.
"""
stitching_settings = self._get_stitching_settings_model()
dx, dy = self._calc_displacement_from_overlap(self.overlap)
capture_params = CaptureParams(
images_dir=images_dir,
save_resolution=self.save_resolution,
)
autofocus_params = AutofocusParams(dz=self.autofocus_dz)
smart_stack_params = self.create_smart_stack_params()
scan_settings = HistoScanSettingsModel(
overlap=self.overlap,
def _build_scan_settings(self, base_kwargs: dict) -> HistoScanSettingsModel:
return HistoScanSettingsModel(
**base_kwargs,
max_dist=self.max_range,
dx=dx,
dy=dy,
skip_background=self.skip_background,
capture_params=capture_params,
autofocus_params=autofocus_params,
smart_stack_params=smart_stack_params,
smart_stack_params=self.create_smart_stack_params(),
)
return scan_settings, stitching_settings
def create_smart_stack_params(
self,
) -> SmartStackParams:
@ -615,38 +593,14 @@ class RegularGridWorkflow(RectGridWorkflow[RegularGridSettingsModel]):
_planner_cls = RegularGridPlanner
_grid_style: Literal["snake", "raster"]
def all_settings(
self, images_dir: str
) -> tuple[RegularGridSettingsModel, Optional[StitchingSettings]]:
"""Return the workflow and stitching settings.
:param images_dir: The directory that images are to be written to.
:return: A tuple containing the settings model for this workflow and the
settings model for stitching.
"""
stitching_settings = self._get_stitching_settings_model()
dx, dy = self._calc_displacement_from_overlap(self.overlap)
capture_params = CaptureParams(
images_dir=images_dir,
save_resolution=self.save_resolution,
)
autofocus_params = AutofocusParams(dz=self.autofocus_dz)
scan_settings = self._settings_model(
overlap=self.overlap,
dx=dx,
dy=dy,
def _build_scan_settings(self, base_kwargs: dict) -> RegularGridSettingsModel:
return RegularGridSettingsModel(
**base_kwargs,
x_count=self.x_count,
y_count=self.y_count,
style=self._grid_style,
capture_params=capture_params,
autofocus_params=autofocus_params,
)
return scan_settings, stitching_settings
def pre_scan_routine(self, settings: RegularGridSettingsModel) -> None:
"""Perform these steps before starting the scan.