API Reference

Acquisition event specification

The following shows all possible fields in an acquisition event (not all of which are required). An acquisition event which does not contain either the ‘channel’ key or the ‘axes’ key will not acquire an image, and can be used to control hardware only.

event = {
      #A dictionary with the positions along various axes (e.g. time point indez,
      #z-slice index, etc) a 'channel' axis is not required as it is inferred
      #automatically
      'axes': {'axis1_name': integer_value,
                       'axis2_name': integer_value},

      #The config of group and setting corresponding to this channel
      'channel': {
              'group': 'name_of_micro_manager_config_group',
              'config': 'setting_of_micro_manager_config_group'
      },

      'exposure': exposure_time_in_ms,

      #For z stacks
      'z': z_position_in_µm,

      #For timelapses: how long to wait before starting next time point in s
      'min_start_time': time_in_s

      #For XY stages
      'x': x_position_in_µm,
      'y': y_position_in_µm,
      #If xy stage positions are in a grid
      'row': row_index_of_xy_position,
      'col': col_index_of_xy_position,

      #Turn of autoshutter, and keep the shutter open while acquiring
      'keep_shutter_open': True,

      #Other arbitrary hardware settings can be encoded in a list of strings with
      #each entry containing the name of the device, the name of the property,
      #and the value of the property
      'properties': [['DeviceName', 'PropertyName', 'PropertyValue'],
              ['OtherDeviceName', 'OtherPropertyName', 'OtherPropertyValue']],
      }

Acquisition APIs

Acquisition

class pycromanager.Acquisition(directory: str = None, name: str = None, image_process_fn: callable = None, event_generation_hook_fn: callable = None, pre_hardware_hook_fn: callable = None, post_hardware_hook_fn: callable = None, post_camera_hook_fn: callable = None, show_display: bool = True, image_saved_fn: callable = None, process: bool = False, saving_queue_size: int = 20, bridge_timeout: int = 500, port: int = 4827, debug: int = False, core_log_debug: int = False)

Base class for Pycro-Manager acquisitions

Parameters
  • directory (str) – saving directory for this acquisition. Required unless an image process function will be implemented that diverts images from saving

  • name (str) – Saving name for the acquisition. Required unless an image process function will be implemented that diverts images from saving

  • image_process_fn (Callable) – image processing function that will be called on each image that gets acquired. Can either take two arguments (image, metadata) where image is a numpy array and metadata is a dict containing the corresponding iamge metadata. Or a 4 argument version is accepted, which accepts (image, metadata, bridge, queue), where bridge and queue are an instance of the pycromanager.bridge.Bridge object for the purposes of interacting with arbitrary code on the Java side (such as the micro-manager core), and queue is a Queue objects that holds upcomning acquisition events. Both version must either return

  • event_generation_hook_fn (Callable) – hook function that will as soon as acquisition events are generated (before hardware sequencing optimization in the acquisition engine. This is useful if one wants to modify acquisition events that they didn’t generate (e.g. those generated by a GUI application). Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • pre_hardware_hook_fn (Callable) – hook function that will be run just before the hardware is updated before acquiring a new image. In the case of hardware sequencing, it will be run just before a sequence of instructions are dispatched to the hardware. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • post_hardware_hook_fn (Callable) – hook function that will be run just before the hardware is updated before acquiring a new image. In the case of hardware sequencing, it will be run just after a sequence of instructions are dispatched to the hardware, but before the camera sequence has been started. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • post_camera_hook_fn (Callable) – hook function that will be run just after the camera has been triggered to snapImage or startSequence. A common use case for this hook is when one want to send TTL triggers to the camera from an external timing device that synchronizes with other hardware. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • show_display (bool or str) – If True, show the image viewer window. If False, show no viewer. If ‘napari’, show napari as the viewer

  • image_saved_fn (Callable) – function that takes two arguments (the Axes of the image that just finished saving, and the Dataset) and gets called whenever a new image is written to disk

  • process (bool) – Use multiprocessing instead of multithreading for acquisition hooks and image processors. This can be used to speed up CPU-bounded processing by eliminating bottlenecks caused by Python’s Global Interpreter Lock, but also creates complications on Windows-based systems

  • saving_queue_size (int) – The number of images to queue (in memory) while waiting to write to disk. Higher values should in theory allow sequence acquisitions to go faster, but requires the RAM to hold images while they are waiting to save

  • bridge_timeout – Timeout in ms of all operations going throught the Bridge

  • port – Allows overriding the defualt port for using Java side servers on a different port

  • debug (bool) – whether to print debug messages

  • core_log_debug (bool) – Print debug messages on java side in the micro-manager core log

acquire(events: dict, keep_shutter_open=False)

Submit an event or a list of events for acquisition. Optimizations (i.e. taking advantage of hardware synchronization, where available), will take place across this list of events, but not over multiple calls of this method. A single event is a python dictionary with a specific structure

Parameters
  • events (list, dict) – A single acquistion event (a dict) or a list of acquisition events

  • keep_shutter_open – (Default value = False)

await_completion()

Wait for acquisition to finish and resources to be cleaned up

get_dataset()

Get access to the dataset backing this acquisition. If the acquisition is in progress, return a Dataset object that wraps the java class containing it. If the acquisition is finished, load the dataset from disk on the Python side for better performance

mark_finished()

Signal to acquisition that no more events will be added and it is time to initiate shutdown. This is only needed if the context manager (i.e. “with Acquisition…”) is not used

multi_d_acquisition_events

pycromanager.multi_d_acquisition_events(num_time_points: int = 1, time_interval_s: float = 0, z_start: float = None, z_end: float = None, z_step: float = None, channel_group: str = None, channels: list = None, channel_exposures_ms: list = None, xy_positions=None, xyz_positions=None, order: str = 'tpcz', keep_shutter_open_between_channels: bool = False, keep_shutter_open_between_z_steps: bool = False)

Convenience function for generating the events of a typical multi-dimensional acquisition (i.e. an acquisition with some combination of multiple timepoints, channels, z-slices, or xy positions)

Parameters
  • num_time_points (int) – How many time points if it is a timelapse (Default value = 1)

  • time_interval_s (float) – the minimum interval between consecutive time points in seconds. Keep at 0 to go as fast as possible (Default value = 0)

  • z_start (float) – z-stack starting position, in µm. If xyz_positions is given z_start is relative to the points’ z position. (Default value = None)

  • z_end (float) – z-stack ending position, in µm. If xyz_positions is given z_start is relative to the points’ z position. (Default value = None)

  • z_step (float) – step size of z-stack, in µm (Default value = None)

  • channel_group (str) – name of the channel group (which should correspond to a config group in micro-manager) (Default value = None)

  • channels (list of strings) – list of channel names, which correspond to possible settings of the config group (e.g. [‘DAPI’, ‘FITC’]) (Default value = None)

  • channel_exposures_ms (list of floats or ints) – list of camera exposure times corresponding to each channel. The length of this list should be the same as the the length of the list of channels (Default value = None)

  • xy_positions (arraylike) – N by 2 array where N is the number of XY stage positions, and the 2 are the X and Y coordinates (Default value = None)

  • xyz_positions (arraylike) – N by 3 array where N is the number of XY stage positions, and the 3 are the X, Y and Z coordinates. If passed then z_start, z_end, and z_step will be relative to the z_position in xyz_positions. (Default value = None)

  • z_positions (arraylike) – The z_positions for each xy point. Either 1D (shape: (N,) ) to specify the center z position for each xy point, or 2D (shape: (N, n_z) ) to fully specify the xyz points. If z_positions is 1D and z_start, z_end and z_step are not None then relative z_positions will be created using np.arange(z_position + z_start, z_position + z_end, z_step)

  • order (str) – string that specifies the order of different dimensions. Must have some ordering of the letters c, t, p, and z. For example, ‘tcz’ would run a timelapse where z stacks would be acquired at each channel in series. ‘pt’ would move to different xy stage positions and run a complete timelapse at each one before moving to the next (Default value = ‘tpcz’)

  • keep_shutter_open_between_channels (bool) – don’t close the shutter in between channels (Default value = False)

  • keep_shutter_open_between_z_steps (bool) – don’t close the shutter during steps of a z stack (Default value = False)

Returns

events

Return type

dict

XYTiledAcquisition

class pycromanager.XYTiledAcquisition(tile_overlap: int, directory: str = None, name: str = None, max_multi_res_index: int = None, image_process_fn: callable = None, pre_hardware_hook_fn: callable = None, post_hardware_hook_fn: callable = None, post_camera_hook_fn: callable = None, show_display: bool = True, image_saved_fn: callable = None, process: bool = False, saving_queue_size: int = 20, bridge_timeout: int = 500, port: int = 4827, debug: bool = False, core_log_debug: bool = False)

For making tiled images with an XY stage and multiresolution saving (e.g. for making one large contiguous image of a sample larger than the field of view)

Parameters
  • tile_overlap (int or tuple of int) – If given, XY tiles will be laid out in a grid and multi-resolution saving will be actived. Argument can be a two element tuple describing the pixel overlaps between adjacent tiles. i.e. (pixel_overlap_x, pixel_overlap_y), or an integer to use the same overlap for both. For these features to work, the current hardware configuration must have a valid affine transform between camera coordinates and XY stage coordinates

  • directory (str) – saving directory for this acquisition. Required unless an image process function will be implemented that diverts images from saving

  • name (str) – Saving name for the acquisition. Required unless an image process function will be implemented that diverts images from saving

  • max_multi_res_index (int) – Maximum index to downsample to in multi-res pyramid mode. 0 is no downsampling, 1 is downsampled up to 2x, 2 is downsampled up to 4x, etc. If not provided, it will be dynamically calculated and updated from data

  • image_process_fn (Callable) – image processing function that will be called on each image that gets acquired. Can either take two arguments (image, metadata) where image is a numpy array and metadata is a dict containing the corresponding iamge metadata. Or a 4 argument version is accepted, which accepts (image, metadata, bridge, queue), where bridge and queue are an instance of the pycromanager.bridge.Bridge object for the purposes of interacting with arbitrary code on the Java side (such as the micro-manager core), and queue is a Queue objects that holds upcomning acquisition events. Both version must either return

  • pre_hardware_hook_fn (Callable) – hook function that will be run just before the hardware is updated before acquiring a new image. In the case of hardware sequencing, it will be run just before a sequence of instructions are dispatched to the hardware. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • post_hardware_hook_fn (Callable) – hook function that will be run just before the hardware is updated before acquiring a new image. In the case of hardware sequencing, it will be run just after a sequence of instructions are dispatched to the hardware, but before the camera sequence has been started. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • post_camera_hook_fn (Callable) – hook function that will be run just after the camera has been triggered to snapImage or startSequence. A common use case for this hook is when one want to send TTL triggers to the camera from an external timing device that synchronizes with other hardware. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • show_display (bool or str) – If True, show the image viewer window. If False, show no viewer. If ‘napari’, show napari as the viewer

  • image_saved_fn (Callable) – function that takes two arguments (the Axes of the image that just finished saving, and the Dataset) and gets called whenever a new image is written to disk

  • process (bool) – Use multiprocessing instead of multithreading for acquisition hooks and image processors. This can be used to speed up CPU-bounded processing by eliminating bottlenecks caused by Python’s Global Interpreter Lock, but also creates complications on Windows-based systems

  • saving_queue_size (int) – The number of images to queue (in memory) while waiting to write to disk. Higher values should in theory allow sequence acquisitions to go faster, but requires the RAM to hold images while they are waiting to save

  • bridge_timeout – Timeout in ms of all operations going throught the Bridge

  • port – Allows overriding the defualt port for using Java side servers on a different port

  • debug (bool) – whether to print debug messages

  • core_log_debug (bool) – Print debug messages on java side in the micro-manager core log

MagellanAcquisition

class pycromanager.MagellanAcquisition(magellan_acq_index: int = None, magellan_explore: bool = False, image_process_fn: callable = None, event_generation_hook_fn: callable = None, pre_hardware_hook_fn: callable = None, post_hardware_hook_fn: callable = None, post_camera_hook_fn: callable = None, image_saved_fn: callable = None, bridge_timeout: int = 500, port: int = 4827, debug: bool = False, core_log_debug: bool = False)

Class used for launching Micro-Magellan acquisitions. Must pass either magellan_acq_index or magellan_explore as an argument

Parameters
  • magellan_acq_index (int) – run this acquisition using the settings specified at this position in the main GUI of micro-magellan (micro-manager plugin). This index starts at 0

  • magellan_explore (bool) – Run a Micro-magellan explore acquisition

  • image_process_fn (Callable) – image processing function that will be called on each image that gets acquired. Can either take two arguments (image, metadata) where image is a numpy array and metadata is a dict containing the corresponding iamge metadata. Or a 4 argument version is accepted, which accepts (image, metadata, bridge, queue), where bridge and queue are an instance of the pycromanager.bridge.Bridge object for the purposes of interacting with arbitrary code on the Java side (such as the micro-manager core), and queue is a Queue objects that holds upcomning acquisition events. Both version must either return

  • event_generation_hook_fn (Callable) – hook function that will as soon as acquisition events are generated (before hardware sequencing optimization in the acquisition engine. This is useful if one wants to modify acquisition events that they didn’t generate (e.g. those generated by a GUI application). Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • pre_hardware_hook_fn (Callable) – hook function that will be run just before the hardware is updated before acquiring a new image. In the case of hardware sequencing, it will be run just before a sequence of instructions are dispatched to the hardware. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • post_hardware_hook_fn (Callable) – hook function that will be run just before the hardware is updated before acquiring a new image. In the case of hardware sequencing, it will be run just after a sequence of instructions are dispatched to the hardware, but before the camera sequence has been started. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • post_camera_hook_fn (Callable) – hook function that will be run just after the camera has been triggered to snapImage or startSequence. A common use case for this hook is when one want to send TTL triggers to the camera from an external timing device that synchronizes with other hardware. Accepts either one argument (the current acquisition event) or three arguments (current event, bridge, event Queue)

  • image_saved_fn (Callable) – function that takes two arguments (the Axes of the image that just finished saving, and the Dataset) and gets called whenever a new image is written to disk

  • bridge_timeout – Timeout in ms of all operations going throught the Bridge

  • port – Allows overriding the defualt port for using Java side servers on a different port

  • debug (bool) – whether to print debug messages

  • core_log_debug (bool) – Print debug messages on java side in the micro-manager core log

start_headless

pycromanager.start_headless(mm_app_path: str, config_file: str = None, java_loc: str = None, core_log_path: str = None, buffer_size_mb: int = 1024, port: int = 4827, timeout: int = 5000, **core_kwargs)

Start a Java process that contains the neccessary libraries for pycro-manager to run, so that it can be run independently of the Micro-Manager GUI/application. This calls will create and initialize MMCore with the configuration file provided.

On windows plaforms, the Java Runtime Environment will be grabbed automatically as it is installed along with the Micro-Manager application.

On non-windows platforms, it may need to be installed/specified manually in order to ensure compatibility. Installing Java 11 is the most likely version to work without issue

Parameters
  • mm_app_path (str) – Path to top level folder of Micro-Manager installation (made with graphical installer)

  • config_file (str) – Path to micro-manager config file, with which core will be initialized. If None then initialization is left to the user.

  • java_loc (str) – Path to the java version that it should be run with

  • core_log_path (str) – Path to where core log files should be created

  • buffer_size_mb (int) – Size of circular buffer in MB in MMCore

  • port (int) – Default port to use for ZMQServer

  • timeout (int, default 5000) – Timeout for connection to server in milliseconds

  • **core_kwargs – Passed on to the Core constructor

Dataset

class pycromanager.Dataset(dataset_path=None, full_res_only=True, remote_storage_monitor=None)

Class that opens a single NDTiffStorage dataset

Creat a Object providing access to and NDTiffStorage dataset, either one currently being acquired or one on disk

Parameters
  • dataset_path (str) – Abosolute path of top level folder of a dataset on disk

  • full_res_only (bool) – One open the full resolution data, if it is multi-res

  • remote_storage_monitor (JavaObjectShadow) – Object that allows callbacks from remote NDTiffStorage

as_array(axes=None, stitched=False, **kwargs)

Read all data image data as one big Dask array with last two axes as y, x and preceeding axes depending on data. The dask array is made up of memory-mapped numpy arrays, so the dataset does not need to be able to fit into RAM. If the data doesn’t fully fill out the array (e.g. not every z-slice collected at every time point), zeros will be added automatically.

To convert data into a numpy array, call np.asarray() on the returned result. However, doing so will bring the data into RAM, so it may be better to do this on only a slice of the array at a time.

Parameters
  • axes (list) – list of axes names over which to iterate and merge into a stacked array. If None, all axes will be used. The order of axes supplied in this list will be the order of the axes of the returned dask array

  • stitched (bool) – If true and tiles were acquired in a grid, lay out adjacent tiles next to one another (Default value = False)

  • **kwargs – names and integer positions of axes on which to slice data

Returns

dataset

Return type

dask array

get_index_keys(res_level=0)

Return a list of every combination of axes that has a image in this dataset

has_image(channel=0, z=None, time=None, position=None, channel_name=None, resolution_level=0, row=None, col=None, **kwargs)

Check if this image is present in the dataset

Parameters
  • channel (int) – index of the channel, if applicable (Default value = None)

  • z (int) – index of z slice, if applicable (Default value = None)

  • time (int) – index of the time point, if applicable (Default value = None)

  • position (int) – index of the XY position, if applicable (Default value = None)

  • channel_name (str) – Name of the channel. Overrides channel index if supplied (Default value = None)

  • row (int) – index of tile row for XY tiled datasets (Default value = None)

  • col (int) – index of tile col for XY tiled datasets (Default value = None)

  • resolution_level – 0 is full resolution, otherwise represents downampling of pixels at 2 ** (resolution_level) (Default value = 0)

  • **kwargs – names and integer positions of any other axes

Returns

indicating whether the dataset has an image matching the specifications

Return type

bool

read_image(channel=0, z=None, time=None, position=None, row=None, col=None, channel_name=None, resolution_level=0, memmapped=False, **kwargs)

Read image data as numpy array

Parameters
  • channel (int) – index of the channel, if applicable (Default value = None)

  • z (int) – index of z slice, if applicable (Default value = None)

  • time (int) – index of the time point, if applicable (Default value = None)

  • position (int) – index of the XY position, if applicable (Default value = None)

  • channel_name – Name of the channel. Overrides channel index if supplied (Default value = None)

  • row (int) – index of tile row for XY tiled datasets (Default value = None)

  • col (int) – index of tile col for XY tiled datasets (Default value = None)

  • resolution_level – 0 is full resolution, otherwise represents downampling of pixels at 2 ** (resolution_level) (Default value = 0)

  • memmapped (bool) – (Default value = False)

  • **kwargs – names and integer positions of any other axes

Returns

image – image as a 2D numpy array, or tuple with image and image metadata as dict

Return type

numpy array or tuple

read_metadata(channel=0, z=None, time=None, position=None, channel_name=None, row=None, col=None, resolution_level=0, **kwargs)

Read metadata only. Faster than using read_image to retrieve metadata

Parameters
  • channel (int) – index of the channel, if applicable (Default value = None)

  • z (int) – index of z slice, if applicable (Default value = None)

  • time (int) – index of the time point, if applicable (Default value = None)

  • position (int) – index of the XY position, if applicable (Default value = None)

  • channel_name – Name of the channel. Overrides channel index if supplied (Default value = None)

  • row (int) – index of tile row for XY tiled datasets (Default value = None)

  • col (int) – index of tile col for XY tiled datasets (Default value = None)

  • resolution_level – 0 is full resolution, otherwise represents downampling of pixels at 2 ** (resolution_level) (Default value = 0)

  • **kwargs – names and integer positions of any other axes

Returns

metadata

Return type

dict

Micro-Manager Core

The core API is discovered dynamically at runtime, though not every method is implemented. Typing core. and using autocomplete with IPython is the best way to discover which functions are available. Documentation on for the Java version of the core API (which pycromanager calls) can be found here.

class pycromanager.Core(socket, serialized_object, bridge: pycromanager.bridge.Bridge)

Remote instance of Micro-Manager Core

Parameters
  • convert_camel_case (bool) – If True, methods for Java objects that are passed across the bridge will have their names converted from camel case to underscores. i.e. class.methodName() becomes class.method_name()

  • port (int) – The port of the Bridge used to create the object

  • new_socket (bool) – If True, will create new java object on a new port so that blocking calls will not interfere with the bridges main port

  • debug – print debug messages

  • timeout – timeout for underlying bridge

get_core_callback(callback_fn=None, bridge_port=4827)

Get a CoreCallback function that will fire callback_fn with (name, *args) each time MMCore emits a callback signal

callback_fn: Callable

a function that takes (name, *args)

bridge_port: int

port of the Core instance to get callbacks from

Java objects and classes

class pycromanager.JavaObject(socket, serialized_object, bridge: pycromanager.bridge.Bridge)
Instance of a an object on the Java side. Returns a Python “Shadow” of the object, which behaves

just like the object on the Java side (i.e. same methods, fields). Methods of the object can be inferred at runtime using iPython autocomplete

classpath: str

Full classpath of the java object

args: list

list of constructor arguments

port: int

The port of the Bridge used to create the object

new_socket: bool

If True, will create new java object on a new port so that blocking calls will not interfere with the bridges main port

convert_camel_casebool

If True, methods for Java objects that are passed across the bridge will have their names converted from camel case to underscores. i.e. class.methodName() becomes class.method_name()

debug:

print debug messages

class pycromanager.JavaClass(socket, serialized_object, bridge: pycromanager.bridge.Bridge)
Get an an object corresponding to a java class, for example to be used

when calling static methods on the class directly

classpath: str

Full classpath of the java calss

port: int

The port of the Bridge used to create the object

new_socket: bool

If True, will create new java object on a new port so that blocking calls will not interfere with the bridges main port

convert_camel_casebool

If True, methods for Java objects that are passed across the bridge will have their names converted from camel case to underscores. i.e. class.methodName() becomes class.method_name()

debug:

print debug messages

Convenience classes for special Java objects

class pycromanager.Magellan(socket, serialized_object, bridge: pycromanager.bridge.Bridge)

An instance of the Micro-Magellan API

convert_camel_casebool

If True, methods for Java objects that are passed across the bridge will have their names converted from camel case to underscores. i.e. class.methodName() becomes class.method_name()

port: int

The port of the Bridge used to create the object

new_socket: bool

If True, will create new java object on a new port so that blocking calls will not interfere with the bridges main port

debug: bool

print debug messages

class pycromanager.Studio(socket, serialized_object, bridge: pycromanager.bridge.Bridge)

An instance of the Studio object that provides access to micro-manager Java APIs

convert_camel_casebool

If True, methods for Java objects that are passed across the bridge will have their names converted from camel case to underscores. i.e. class.methodName() becomes class.method_name()

port: int

The port of the Bridge used to create the object

new_socket: bool

If True, will create new java object on a new port so that blocking calls will not interfere with the bridges main port

debug: bool

print debug messages