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']],
      }

High-level acquisition APIs

class pycromanager.Bridge(port=4827, convert_camel_case=True, debug=False, ip_address='127.0.0.1', timeout=500)

Create an object which acts as a client to a corresponding server (running in a Java process). This enables construction and interaction with arbitrary java objects. Each bridge object should be run using a context manager (i.e. with Bridge() as b:) or bridge.close() should be explicitly called when finished

Parameters
  • port (int) – The port on which the bridge operates

  • 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()

  • debug (bool) – If True print helpful stuff for debugging

construct_java_object(classpath, new_socket=False, args=None)

Create a new 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

Parameters
  • classpath (str) – Full classpath of the java 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 master port

  • args (list) – list of arguments to the constructor, if applicable

Returns

Return type

Python “Shadow” to the Java object

get_core()

Connect to CMMCore and return object that has its methods

Returns

Python “shadow” object for micromanager core

get_magellan()

return an instance of the Micro-Magellan API

get_studio()

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

class pycromanager.Acquisition(directory=None, name=None, image_process_fn=None, event_generation_hook_fn=None, pre_hardware_hook_fn=None, post_hardware_hook_fn=None, post_camera_hook_fn=None, show_display=True, storage_monitor_callback_fn=None, tile_overlap=None, max_multi_res_index=None, magellan_acq_index=None, magellan_explore=False, process=False, saving_queue_size=20, bridge_timeout=500, port=4827, debug=False, core_log_debug=False)
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.acquire.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)

  • 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

  • max_multi_res_index (int) – Maximum index to downsample to in multi-res pyramid mode (which is only active if a value for “tile_overlap” is passed in, or if running a Micro-Magellan acquisition). 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

  • show_display (bool) – show the image viewer window

  • storage_monitor_callback_fn (Callable) – function that takes one argument (the Axes of the image that just finished saving) and gets called whenever a new image is writtent to disk

  • 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

  • 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, 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

  • 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

pycromanager.multi_d_acquisition_events(num_time_points=1, time_interval_s=0, z_start=None, z_end=None, z_step=None, channel_group=None, channels=None, channel_exposures_ms=None, xy_positions=None, xyz_positions=None, order='tpcz', keep_shutter_open_between_channels=False, keep_shutter_open_between_z_steps=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

Reading acquired data

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, verbose=True, **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

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

  • verbose (bool) – If True print updates on progress loading the image

  • **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

Low-level (micro-manager core) APIs

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.