autoemx.core.em_runtime.controller module

Automated Electron Microscopy (EM) Controller and Sample Image Analyzer

This module provides the main EM_Controller class for automated analysis and acquisition in scanning electron microscopy (SEM). It acts as a facade/orchestrator that composes lower-level modules for microscope control, frame navigation, spectrum acquisition, and image utilities.

Main Classes

EM_Controller

High-level orchestrator for automated particle detection, mask generation, and X-ray spectra (EDS, WDS) acquisition.

Example Usage

>>> from autoemx.core.em_runtime.controller import EM_Controller
>>> EM_controller = EM_Controller(...)
>>> EM_controller.initialise_SEM()
>>> particle_finder = EM_Particle_Finder(EM_controller, ...)
>>> while particle_finder.go_to_next_particle():
...     xy_spot_list = particle_finder.get_XS_acquisition_spots_coord_list()
...     for (x, y) in xy_spot_list:
...         EM_controller.acquire_XS_spectrum()

Created on Wed Jul 31 09:28:07 2024

@author: Andrea

class autoemx.core.em_runtime.controller.EM_Controller(ledger_configs: LedgerConfigs, sample_id: str | None = '', init_fw: float = 0.5, results_dir: str | None = None, verbose: bool = True, development_mode: bool = False, xsp_spot_selector: Callable[[XSpSpotSelectionContext], Sequence[Tuple[int, int]]] | None = None)[source]

Bases: object

High-level orchestrator for automated electron microscopy operations.

This class composes lower-level modules for microscope hardware control, frame navigation, spectrum acquisition, and image utilities. It provides a unified interface for automated particle detection, X-ray spectra acquisition, and sample management.

Configuration is provided via a LedgerConfigs bundle read from the sample ledger. Use the from_configs() factory to construct from individual config objects.

Main Methods

initialise_SEM()

Wakes up the SEM microscope, sets measurement parameters.

initialise_sample_navigator()

Initializes frame calculation and navigation for the sample.

initialise_XS_analyzer()

Gets EDS/WDS analyzer object from EM_driver.

acquire_XS_spot_spectrum(x, y)

Acquire X-ray spectral data at position (x,y).

get_XSp_coords(n_tot_sp_collected)

Determine next spectrum acquisition location.

ivar sample_cfg:

Sample configuration.

vartype sample_cfg:

SampleConfig

ivar microscope_cfg:

Microscope configuration.

vartype microscope_cfg:

MicroscopeConfig

ivar measurement_cfg:

Measurement/acquisition configuration.

vartype measurement_cfg:

MeasurementConfig

ivar sample_substrate_cfg:

Sample substrate configuration.

vartype sample_substrate_cfg:

SampleSubstrateConfig

ivar powder_meas_cfg:

Configuration for powder measurement.

vartype powder_meas_cfg:

PowderMeasurementConfig

ivar bulk_meas_cfg:

Configuration for bulk measurement.

vartype bulk_meas_cfg:

BulkMeasurementConfig

ivar init_wd:

Initial working distance in mm.

vartype init_wd:

float

ivar im_width:

Image width in pixels.

vartype im_width:

int

ivar im_height:

Image height in pixels.

vartype im_height:

int

ivar pixel_size_um:

Pixel size in micrometers of current image.

vartype pixel_size_um:

float or None

ivar results_dir:

Directory for saving result images and data.

vartype results_dir:

str or None

ivar verbose:

If True, print progress and information to the console.

vartype verbose:

bool

ivar development_mode (bool):

Whether class is used for testing without real-time acquisition.

classmethod from_configs(microscope_cfg: MicroscopeConfig, sample_cfg: SampleConfig, measurement_cfg: MeasurementConfig, sample_substrate_cfg: SampleSubstrateConfig, powder_meas_cfg: PowderMeasurementConfig | None = None, bulk_meas_cfg: BulkMeasurementConfig | None = None, sample_id: str | None = '', init_fw: float = 0.5, results_dir: str | None = None, verbose: bool = True, development_mode: bool | None = False, xsp_spot_selector: Callable[[XSpSpotSelectionContext], Sequence[Tuple[int, int]]] | None = None) → EM_Controller[source]

Construct an EM_Controller from individual config objects.

This factory wraps the configs into a LedgerConfigs bundle and delegates to __init__(). Use this in tests or standalone scripts where a pre-existing ledger is not available.

Parameters:
initialise_SEM() → None[source]

Activate and configure the Scanning Electron Microscope (SEM).

Delegates to MicroscopeController which performs:
  1. SEM activation

  2. Detector and beam setup

  3. Stage movement to the sample center (sample_cfg.center_pos)

  4. Working distance adjustment

  5. Focus, brightness, contrast adjustment

initialise_sample_navigator(exclude_sample_margin: bool = True) → None[source]

Initialize the sample navigator for automated spectra collection.

Delegates to FrameNavigator which handles frame calculation, grid generation, and particle finder initialization.

Parameters:

exclude_sample_margin (bool, optional) – Whether to exclude sample margin (default: True).

initialise_XS_analyzer(beam_voltage: float | None = None) → None[source]

Initialize the EDS analyzer.

Delegates to SpectrumAcquisition module.

Parameters:

beam_voltage (float, optional) – Desired beam voltage in kV.

get_XSp_coords(n_tot_sp_collected: int) → Tuple[bool, List[Tuple[float, float]] | None, int | None][source]

Determine X-ray spectrum acquisition coordinates for the next spectrum.

Delegates to SpectrumAcquisition module which handles manual and automated spot selection based on measurement mode.

Parameters:

n_tot_sp_collected (int) – The current total number of spectra collected.

Returns:

  • success (bool) – True if a spot was selected/found, False otherwise.

  • spots_xy_list (list of tuple or None) – List of (x, y) pixel coordinates for acquisition, or None if unsuccessful.

  • particle_cntr (int or None) – The particle counter/index, or None if not applicable.

acquire_XS_spot_spectrum(x: float, y: float, max_acquisition_time: float, target_acquisition_counts: int, elements: List[str] | None = None, msa_file_path: str | None = None) → Tuple[source]

Acquire an X-ray spectrum at the specified position.

Delegates to SpectrumAcquisition module.

Parameters:
  • x (float) – X, Y pixel coordinates for spectrum acquisition.

  • y (float) – X, Y pixel coordinates for spectrum acquisition.

  • max_acquisition_time (float) – Maximum allowed acquisition time in seconds.

  • target_acquisition_counts (int) – Target total X-ray counts.

Return type:

spectrum_data, background_data

adjust_BCF() → float[source]

Adjust brightness, contrast, and focus.

Delegates to MicroscopeController.

Returns:

Timestamp of adjustment completion.

Return type:

float

set_frame_width(frame_width: float) → None[source]

Set the frame width at the microscope.

Delegates to MicroscopeController and updates pixel size.

Parameters:

frame_width (float) – The desired frame width in millimeters.

update_pixel_size_from_frame_width() → float[source]

Update pixel size from the microscope’s current frame width.

Returns:

Updated pixel size in micrometers.

Return type:

float

get_current_image()[source]

Acquire image at microscope.

Returns:

image – Image array acquired at the microscope.

Return type:

np.ndarray

get_image_drift_pixels() → Tuple[float, float] | None[source]

Estimate image drift in pixels relative to the reference image captured when EDS spot positions were selected.

Returns:

(dx, dy) drift of the current image relative to ref_image.

Return type:

tuple(float, float) or None

move_to_pos(pos: tuple) → None[source]

Move the EM stage to the specified position.

Delegates to MicroscopeController.

Parameters:

pos (tuple of float) – Target (x, y) coordinates.

convert_pixel_pos_to_mm(pos_pixels)[source]

Convert pixel coordinates to absolute stage coordinates in mm.

Delegates to image_utilities module.

Parameters:

pos_pixels (array-like) – Position in pixel coordinates.

Returns:

pos_abs_mm – Absolute position in millimeters.

Return type:

ndarray

convert_XS_coords_to_pixels(xy_coords)[source]

Convert XS coordinates to pixel coordinates.

Delegates to image_utilities module.

Parameters:

xy_coords (tuple) – The XY coordinates in the XS coordinate system.

Returns:

Pixel coordinates.

Return type:

tuple(int, int)

static standby() → None[source]

Put microscope in standby mode.

go_to_next_frame() → bool[source]

Move the microscope to the next frame position.

Delegates to FrameNavigator.

Returns:

True if moved to next frame, False if no frames remain.

Return type:

bool

save_frame_image(filename, im_annotations=None, scalebar=True, frame_image=None, save_dir=None)[source]

Save an annotated EM frame and optionally the raw frame.

Delegates to image_utilities module.

Parameters:
  • filename (str) – Base name used for saved image file(s).

  • im_annotations (dict | list(dict) | None, optional) – Dictionary with annotations (‘text’, ‘circle’ keys).

  • scalebar (bool, optional) – Whether to annotate with a scalebar (default: True).

  • frame_image (np.ndarray | None, optional) – Frame image to save. Acquires current if not provided.

  • save_dir (str, optional) – Directory to save image file(s).

property frame_pos_mm

Frame positions in mm.

property frame_labels

Frame labels.

property num_frames

Number of frames.

property current_frame_label

Current frame label.

property particle_finder

Particle finder instance.