Skip to content

Instantly share code, notes, and snippets.

@dominikl
Last active June 30, 2022 09:37
Show Gist options
  • Save dominikl/5bcd8eaba66aab96355c32a745de8edc to your computer and use it in GitHub Desktop.
Save dominikl/5bcd8eaba66aab96355c32a745de8edc to your computer and use it in GitHub Desktop.
import re
import subprocess
from experimental import Plate, Image, create_companion
# https://github.com/ome/ome-model/blob/master/ome_model/experimental.py
# (pip install ome-model)
# R44821_160620150002i3t001A06f01d2.ome.tif
pat = re.compile(r"^(?P<plate>.*?)i3t(?P<timepoint>\d+)(?P<wellrow>\w)(?P<wellcol>\d{2,})f(?P<field>\d{2})d(?P<channel>\d)\.*")
plate_name = "R44821_160620150002"
order = "XYCZT"
img_x = 1104
img_y = 1104
size_z = 1
size_c = 1
pix_type = "uint16"
# Read the whole file
files = []
with open("image-file-listing.txt") as fp:
line = fp.readline()
while line:
files.append(line.strip())
line = fp.readline()
# Get number of rows, columns and timepoints
n_rows = set()
n_cols = set()
n_timepoints = set()
for file in files:
m = pat.match(file).groupdict()
n_rows.add(m['wellrow'])
n_cols.add(int(m['wellcol']))
n_timepoints.add(int(m['timepoint']))
n_rows = len(n_rows)
n_cols = len(n_cols)
n_timepoints = len(n_timepoints)
# assemble 5d images (key: wellrow|wellcol)
images = {}
for file in files:
m = pat.match(file).groupdict()
key = f"{m['wellrow']}|{m['wellcol']}"
if not key in images:
images[key] = Image(key, img_x, img_y, size_z, size_c, n_timepoints, order=order, type=pix_type)
images[key].add_channel(samplesPerPixel=1)
images[key].add_plane(c=0, t=int(m['timepoint'])-1, z=0)
images[key].add_tiff(file, c=0, z=0, t=int(m['timepoint'])-1, planeCount=1)
# assemble plate
plate = Plate(plate_name, n_rows, n_cols)
row_indices = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for well_pos, image in images.items():
row = well_pos.split("|")[0]
col = int(well_pos.split("|")[1])-1
well = plate.add_well(row_indices.index(row), col)
well.add_wellsample(0, image)
# write companion file
companion_file = "{}.companion.ome".format(plate_name)
create_companion(plates=[plate], out=companion_file)
# Indent XML for readability
proc = subprocess.Popen(
['xmllint', '--format', '-o', companion_file, companion_file],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
(output, error_output) = proc.communicate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment