Skip to content

Instantly share code, notes, and snippets.

@will-moore
Created April 30, 2014 23:02
Show Gist options
  • Save will-moore/2d28e9365d1083db6650 to your computer and use it in GitHub Desktop.
Save will-moore/2d28e9365d1083db6650 to your computer and use it in GitHub Desktop.
OMERO.script takes a list of Datasets and puts the first image from each Dataset into a new Dataset, the second image of each into a new Dataset etc.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script takes a list of Datasets and puts the first image from each Dataset
into a new Dataset, the second image of each into a new Dataset etc.
"""
import omero.scripts as scripts
from omero.gateway import BlitzGateway
import omero
from omero.rtypes import wrap, rlong, robject
def createDatasets(conn, projectName, datasetNames):
"""
Returns a list of datasetIds
"""
updateService = conn.getUpdateService()
project = omero.model.ProjectI()
project.setName(wrap(projectName))
project = updateService.saveAndReturnObject(project)
links = []
datasetIds = []
for name in datasetNames:
dataset = omero.model.DatasetI()
dataset.setName(wrap(name))
dataset = updateService.saveAndReturnObject(dataset)
datasetIds.append(dataset.id.val)
link = omero.model.ProjectDatasetLinkI()
link.parent = omero.model.ProjectI(project.id.val, False)
link.child = dataset # omero.model.DatasetI(dataset.id.val, False)
links.append(link)
links = updateService.saveAndReturnArray(links, conn.SERVICE_OPTS)
return project, datasetIds
def linkDatasetsImages(conn, dsIds, imgIds):
"""
Creates a DatasetImageLink for each pair of ids
"""
links = []
for datasetId, imageId in zip(dsIds, imgIds):
link = omero.model.DatasetImageLinkI()
link.parent = omero.model.DatasetI(datasetId, False)
link.child = omero.model.ImageI(imageId, False)
links.append(link)
conn.getUpdateService().saveArray(links, conn.SERVICE_OPTS)
def removeFromDatasets(conn, images):
""" Removes every image from all of it's Datasets """
for image in images:
links = list(image.getParentLinks())
for l in links:
conn.deleteObjectDirect(l._obj)
def invert_Datasets(conn, scriptParams):
datasetIds = scriptParams['IDs']
project_Name = scriptParams['Project_Name']
alternate_Images = 'Alternate_Images' in scriptParams and scriptParams['Alternate_Images']
datasets = list(conn.getObjects("Dataset", datasetIds))
datasets.sort(key=lambda x: x.getName())
project = None
newDatasetIds = []
# For each dataset, add images in order to the
for ds in datasets:
# for first dataset, create new datasets, one per image
images = list(ds.listChildren())
images.sort(key=lambda x: x.getName())
if alternate_Images:
images = [img for i, img in enumerate(images) if i%2 == 0]
removeFromDatasets(conn, images)
imgIds = [i.id for i in images]
if len(newDatasetIds) == 0:
dsNames = [i.getName() for i in images]
project, newDatasetIds = createDatasets(conn, project_Name, dsNames)
linkDatasetsImages(conn, newDatasetIds, imgIds)
return project
def runAsScript():
"""
The main entry point of the script, as called by the client via the
scripting service, passing the required parameters.
"""
dataTypes = [wrap('Dataset')]
client = scripts.client(
'Invert_Datasets.py',
"""Script takes a list of Datasets and puts the first image from each Dataset
into a new Dataset, the second image of each into a new Dataset etc.
""",
scripts.String(
"Data_Type", optional=False, grouping="1",
description="Choose Datasets to Invert",
values=dataTypes, default="Dataset"),
scripts.List(
"IDs", optional=False, grouping="2",
description="List of Dataset IDs to convert to new").ofType(rlong(0)),
scripts.String(
"Project_Name", grouping="3", default='Inverted_Datasets', optional=False,
description="Put new Datasets in Project with this name"),
scripts.Bool(
"Alternate_Images", grouping="4", default=False,
description="If true, ignore every other image"),
)
try:
# process the list of args above.
scriptParams = {}
for key in client.getInputKeys():
if client.getInput(key):
scriptParams[key] = client.getInput(key, unwrap=True)
print scriptParams
# wrap client to use the Blitz Gateway
conn = BlitzGateway(client_obj=client)
# convert Dataset(s) to Plate(s). Returns new plates or screen
project = invert_Datasets(conn, scriptParams)
if project is not None:
msg = "Created Datasets in Project: %s" % project.name.val
client.setOutput("Message", wrap(msg))
client.setOutput("New_Object", robject(project))
else:
client.setOutput("Message", wrap("Failed - see info"))
finally:
client.closeSession()
if __name__ == "__main__":
runAsScript()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment