import os
import csv

# Script definition

# Script name, description and parameters are defined here.
# These parameters will be recognised by the Insight and web clients and
# populated with the currently selected Image(s)

# this script allows importing tags to many groups althought the csv file (with the tag names) has been attached to system group only
#the recommandation is that ADMIN is always member of the various groups
client = scripts.client(
    "add_tags_to_MANYgroups_from_ONEcsv.py",
    ("Customised script for adding tags from imported csv"),
    scripts.Long("File_Annotation"),
)
# we can now create our Blitz Gateway by wrapping the client object
conn = BlitzGateway(client_obj=client)
script_params = client.getInputs(unwrap=True)
print script_params

# get the 'IDs' parameter of the csv file imported as annotation

file_id = script_params["File_Annotation"]
file_ann = conn.getObject("FileAnnotation", file_id)
csv_text = "".join(list(file_ann.getFileInChunks()))
print csv_text
lines = csv_text.split("\n")
print lines
Пример #2
0
def runAsScript():
    """
    The main entry point of the script. Gets the parameters from the scripting
    service, makes the figure and returns the output to the client.
    def __init__(self, name, optional = False, out = False, description =
    None, type = None, min = None, max = None, values = None)
    """

    formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')]
    dataTypes = [rstring('Dataset'), rstring('Image')]

    client = scripts.client(
        'Thumbnail_Figure.py',
        """Export a figure of thumbnails, optionally sorted by tag.
See http://help.openmicroscopy.org/scripts.html""",
        scripts.String("Data_Type",
                       optional=False,
                       grouping="1",
                       description="The data you want to work with.",
                       values=dataTypes,
                       default="Dataset"),
        scripts.List("IDs",
                     optional=False,
                     grouping="2",
                     description="List of Dataset IDs or Image"
                     " IDs").ofType(rlong(0)),
        scripts.List("Tag_IDs",
                     grouping="3",
                     description="Group thumbnails by these tags."),
        scripts.Bool("Show_Untagged_Images",
                     grouping="3.1",
                     default=False,
                     description="If true (and you're sorting by tagIds) also"
                     " show images without the specified tags"),
        scripts.Long("Parent_ID",
                     grouping="4",
                     description="Attach figure to this Project (if datasetIds"
                     " above) or Dataset if imageIds. If not specifed, attach"
                     " figure to first dataset or image."),
        # this will be ignored if only a single ID in list - attach to
        # that object instead.
        scripts.Int(
            "Thumbnail_Size",
            grouping="5",
            min=10,
            max=250,
            default=100,
            description="The dimension of each thumbnail. Default is 100"),
        scripts.Int(
            "Max_Columns",
            grouping="5.1",
            min=1,
            default=10,
            description="The max number of thumbnail columns. Default is 10"),
        scripts.String("Format",
                       grouping="6",
                       description="Format to save image.",
                       values=formats,
                       default="JPEG"),
        scripts.String("Figure_Name",
                       grouping="6.1",
                       default='Thumbnail_Figure',
                       description="File name of figure to create"),
        version="4.3.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        conn = BlitzGateway(client_obj=client)

        commandArgs = client.getInputs(unwrap=True)
        print commandArgs

        # Makes the figure and attaches it to Project/Dataset. Returns
        # FileAnnotationI object
        fileAnnotation, message = makeThumbnailFigure(conn, commandArgs)

        # Return message and file annotation (if applicable) to the client
        client.setOutput("Message", rstring(message))
        if fileAnnotation is not None:
            client.setOutput("File_Annotation", robject(fileAnnotation._obj))
    finally:
        client.closeSession()
params:
    Plate_ID: id of the plate which should be parsed.

    Copyright 2009 Glencoe Software, Inc. All rights reserved.
    Use is subject to license terms supplied in LICENSE.txt

"""

import omero.scripts as scripts
from omero.util.populate_roi import PlateAnalysisCtxFactory

client = scripts.client(
    'Populate_ROI.py',
    scripts.Long(
        "Plate_ID",
        optional=False,
        description="ID of a valid plate with attached results files"),
    version="4.2.0",
    contact="*****@*****.**",
    description="""Generates regions of interest from the measurement files \
associated with a plate

This script is executed by the server on initial import, and should typically\
not need to be run by users.""")

factory = PlateAnalysisCtxFactory(client.getSession())
analysis_ctx = factory.get_analysis_ctx(client.getInput("Plate_ID").val)
n_measurements = analysis_ctx.get_measurement_count()

for i in range(n_measurements):
    measurement_ctx = analysis_ctx.get_measurement_ctx(i)
Пример #4
0
def runAsScript():
    """
    The main entry point of the script. Gets the parameters from the scripting service, makes the figure and 
    returns the output to the client. 
    def __init__(self, name, optional = False, out = False, description = None, type = None, min = None, max = None, values = None)
    """
    formats = wrap(formatMap.keys())  # wrap each key in it's rtype
    ckeys = COLOURS.keys()
    ckeys = ckeys
    ckeys.sort()
    cOptions = wrap(ckeys)
    dataTypes = [rstring("Image")]

    client = scripts.client(
        'Make_Movie',
        'MakeMovie creates a movie of the image and attaches it to the originating image.',
        scripts.String("Data_Type",
                       optional=False,
                       grouping="1",
                       description="Choose Images via their 'Image' IDs.",
                       values=dataTypes,
                       default="Image"),
        scripts.List("IDs",
                     optional=False,
                     grouping="1",
                     description="List of Image IDs to process.").ofType(
                         rlong(0)),
        scripts.Long("RenderingDef_ID",
                     description="The Rendering Definitions for the Image.",
                     default=-1,
                     optional=True,
                     grouping="1"),
        scripts.String("Movie_Name",
                       description="The name of the movie",
                       grouping="2"),
        scripts.Int(
            "Z_Start",
            description=
            "Projection range (if not specified, use defaultZ only - no projection)",
            min=0,
            default=0,
            grouping="3.1"),
        scripts.Int(
            "Z_End",
            description=
            "Projection range (if not specified or, use defaultZ only - no projection)",
            min=0,
            grouping="3.2"),
        scripts.Int("T_Start",
                    description="The first time-point",
                    min=0,
                    default=0,
                    grouping="4.1"),
        scripts.Int("T_End",
                    description="The last time-point",
                    min=0,
                    grouping="4.2"),
        scripts.List("Channels",
                     description="The selected channels",
                     grouping="5").ofType(rint(0)),
        scripts.Bool("Show_Time",
                     description="If true, display the time.",
                     default=True,
                     grouping="6"),
        scripts.Bool(
            "Show_Plane_Info",
            description=
            "If true, display the information about the plane e.g. Exposure Time.",
            default=True,
            grouping="7"),
        scripts.Int("FPS",
                    description="Frames Per Second.",
                    default=2,
                    grouping="8"),
        scripts.Int(
            "Scalebar",
            description=
            "Scale bar size in microns. Only shown if image has pixel-size info.",
            min=1,
            grouping="9"),
        scripts.String("Format",
                       description="Format to save movie",
                       values=formats,
                       default=QT,
                       grouping="10"),
        scripts.String("Overlay_Colour",
                       description="The colour of the scalebar.",
                       default='White',
                       values=cOptions,
                       grouping="11"),
        scripts.String(
            "Canvas_Colour",
            description="The background colour when using minimum size.",
            default='Black',
            values=cOptions),
        scripts.Int("Min_Width",
                    description="Minimum width for output movie.",
                    default=-1),
        scripts.Int("Min_Height",
                    description="Minimum height for output movie.",
                    default=-1),
        scripts.Map(
            "Plane_Map",
            description=
            "Specify the individual planes (instead of using T_Start, T_End, Z_Start and Z_End)",
            grouping="12"),
        scripts.Object(
            "Watermark",
            description=
            "Specifiy a watermark as an Original File (png or jpeg)",
            default=omero.model.OriginalFileI()),
        scripts.Object(
            "Intro_Slide",
            description=
            "Specifiy an Intro slide as an Original File (png or jpeg)",
            default=omero.model.OriginalFileI()),
        scripts.Int(
            "Intro_Duration",
            default=3,
            description="Duration of Intro in seconds. Default is 3 secs."),
        scripts.Object(
            "Ending_Slide",
            description=
            "Specifiy a finishing slide as an Original File, (png or jpeg)",
            default=omero.model.OriginalFileI()),
        scripts.Int(
            "Ending_Duration",
            default=3,
            description=
            "Duration of finishing slide in seconds. Default is 3 secs."),
        scripts.Bool(
            "Do_Link",
            description=
            "If true, creates a FileAnnotation with the OriginalFile holding the movie and links it to the Image.",
            default=True),
        version="4.2.0",
        authors=["Donald MacDonald", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        conn = BlitzGateway(client_obj=client)
        commandArgs = {}

        for key in client.getInputKeys():
            if client.getInput(key):
                commandArgs[key] = client.getInput(key, unwrap=True)
        print commandArgs

        fileAnnotation, message = writeMovie(commandArgs, conn)

        # return this fileAnnotation to the client.
        client.setOutput("Message", rstring(message))
        if fileAnnotation is not None:
            client.setOutput("File_Annotation", robject(fileAnnotation))
    finally:
        client.closeSession()
Пример #5
0
def run_script():

    dataTypes = [rstring('Project'), rstring('Dataset')]
    # TODO: enable attaching to images
    dataTypes_attach = [rstring('Dataset'), rstring('Project')]
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """
    client = scripts.client(
        'Remote_Import.py',
        """Remote import from dedicated workstations:

        * Import the content of the OMERO_ImportData/<username>/ folder on the selected workstation.
        * Appends files with the specified suffix to the Project or Dataset.
        * The scanned subfolder depth is 10
        ---------------------------------------------------------------
        INPUT:
        ---------------------------------------------------------------
        Select PROJECT as TARGET for import : : A Dataset object is created for each subdirectory on OMERO_ImportData/<username>/

        Select DATASET as TARGET for import : : All images (also images in subdirectories) are imported into this Dataset


        """,
        scripts.String(
            PARAM_WS,
            optional=False,
            grouping="1",
            description="Choose a workstation where you want to import from",
            values=WORKSTATION_NAMES),
        scripts.String(PARAM_DATATYPE,
                       optional=True,
                       grouping="2",
                       description="Choose kind of destination object.",
                       values=dataTypes),
        scripts.Long(
            PARAM_ID,
            optional=False,
            grouping="3",
            description=
            "ID of destination object. Please select only ONE object."),
        scripts.Bool(
            PARAM_SKIP_EXISTING,
            grouping="4",
            description=
            "skip files that are already uploaded (checked 'import from' path).",
            default=False),
        scripts.Bool(PARAM_ATTACH,
                     grouping="5",
                     description="Attach containing non image files",
                     default=False),
        scripts.String(PARAM_DEST_ATTACH,
                       grouping="5.1",
                       description="Object to that should be attach",
                       values=dataTypes_attach,
                       default="Dataset"),
        scripts.String(
            PARAM_ATTACH_FILTER,
            grouping="5.2",
            description=
            "Filter files by given file extension (for example txt, pdf). Separated by ','."
        ),
        namespaces=[omero.constants.namespaces.NSDYNAMIC],
        version="1.1.0",
        authors=["Susanne Kunis", "CellNanOs"],
        institutions=["University of Osnabrueck"],
        contact="*****@*****.**",
    )  # noqa

    try:
        params = client.getInputs(unwrap=True)
        if os.path.exists(MOUNT_PATH):
            conn = BlitzGateway(client_obj=client)

            datapath = checkWorkstation(conn, params.get(PARAM_WS), MOUNT_PATH,
                                        conn.getUser().getName())
            if datapath:
                robj, message = remoteImport(conn, params, datapath)
            else:
                message = "No data available on %s for user" % (
                    params.get(PARAM_WS))
                robj = None

            client.setOutput("Message", rstring(message))
            if robj is not None:
                client.setOutput("Result", robject(robj._obj))
        else:
            client.setOutput(
                "ERROR", rstring("No such Mount directory: %s" % MOUNT_PATH))
    finally:
        client.closeSession()
Пример #6
0
from omero.rtypes import rstring, unwrap
from omero.gateway import BlitzGateway
import omero
import omero.scripts as scripts
from omero import ValidationException
# Script definition

# Script name, description and 2 parameters are defined here.
# These parameters will be recognised by the Insight and web clients and
# populated with the currently selected Image(s)

client = scripts.client(
    "Write_Data_3.py",
    """Adds Image to Dataset (if not alreay in the Dataset).""",
    # first parameter
    scripts.Long("ImageId", optional=False),
    # second parameter
    scripts.Long("DatasetId", optional=False),
)
# we can now create our Blitz Gateway by wrapping the client object
conn = BlitzGateway(client_obj=client)

# get the parameters
imageId = unwrap(client.getInput("ImageId"))
datasetId = unwrap(client.getInput("DatasetId"))


try:
    link = omero.model.DatasetImageLinkI()
    link.setParent(omero.model.DatasetI(datasetId, False))
    link.setChild(omero.model.ImageI(imageId, False))
    for image in images:
        print("---- Processing image", image.id)
    return images


# main
if __name__ == "__main__":
    # Start declaration
    # Define the script name and description, and a single 'required' parameter
    client = scripts.client(
        'Hello World.py',
        """
    This script does connect to OMERO.
        """,
        scripts.Long("datasetId", optional=False),

        authors=["OME Team", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )
    # Start script
    try:
        # process the list of arguments
        script_params = {}
        for key in client.getInputKeys():
            if client.getInput(key):
                script_params[key] = client.getInput(key, unwrap=True)

        dataset_id = script_params["datasetId"]
Пример #8
0
#
#   $Id$
#
#   Copyright 2008 Glencoe Software, Inc. All rights reserved.
#   Use is subject to license terms supplied in LICENSE.txt
#

import omero, omero.scripts as sc

client = sc.client(
    "script_1",
    """
    This is a test script used to test the basic parsing functionality
    and attempts to interaction with the server
    """,
    #sc.Int("myint"),
    sc.Long("mylong"),
    sc.Bool("mybool"),
    sc.String("mystring"),
    sc.String("myoptional", optional=True))

import os, sys, types
assert type(client) == types.TupleType

self = sys.argv[0]
cfg = self.replace("py", "cfg")

real_client = omero.client(["--Ice.Config=%s" % cfg])
parse_only = real_client.getProperty("omero.script.parse")
assert parse_only == "true"
Пример #9
0
def run():
    '''
    '''
    client = scripts.client(
        'Edit_Object_Attribute.py',
        'Edit the attributes of an object',
        scripts.String('Data_Type',
                       optional=False,
                       grouping='1',
                       description='The data type you want to work with.'),
        scripts.Long('ID',
                     optional=False,
                     grouping='2',
                     description='Object ID'),
        scripts.String('Attribute',
                       optional=False,
                       grouping='3',
                       description='Attribute to set'),
        scripts.String('Attribute_Type',
                       optional=False,
                       grouping='4',
                       description='Type of the attribute to set',
                       values=[
                           rstring('Bool'),
                           rstring('Double'),
                           rstring('Float'),
                           rstring('Int'),
                           rstring('Long'),
                           rstring('Time'),
                           rstring('String')
                       ],
                       default='String'),
        scripts.String('Value',
                       optional=False,
                       grouping='5',
                       description='Value to set'),
        version='0.1',
        authors=['Chris Allan'],
        institutions=['Glencoe Software Inc.'],
        contact='*****@*****.**',
    )

    try:
        script_params = {}
        for key in client.getInputKeys():
            if client.getInput(key):
                script_params[key] = client.getInput(key, unwrap=True)

        session = client.getSession()
        update_service = session.getUpdateService()
        query_service = session.getQueryService()

        value = script_params['Value']
        if script_params['Attribute_Type'] == 'Bool':
            value = rtype(bool(value))
        elif script_params['Attribute_Type'] == 'Double':
            value = rdouble(float(value))
        elif script_params['Attribute_Type'] == 'Float':
            value = rtype(float(value))
        elif script_params['Attribute_Type'] == 'Int':
            value = rtype(int(value))
        elif script_params['Attribute_Type'] == 'Long':
            value = rtype(int(value))
        elif script_params['Attribute_Type'] == 'Time':
            value = rtime(int(value))
        else:
            value = rtype(value)

        ctx = {'omero.group': '-1'}
        o = query_service.get(script_params['Data_Type'], script_params['ID'],
                              ctx)
        setattr(o, script_params['Attribute'], value)
        ctx = None
        try:
            ctx = {'omero.group': str(o.details.group.id.val)}
        except AttributeError:
            pass
        update_service.saveObject(o, ctx)

        client.setOutput('Message',
                         rstring('Setting of attribute successful.'))
    finally:
        client.closeSession()
Пример #10
0
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import sys

import omero
import omero.scripts as sc

client = sc.client(
    "script_1", """
    This is a test script used to test the basic parsing functionality
    and attempts to interaction with the server
    """, sc.Int("myint"), sc.Long("mylong"), sc.Bool("mybool"),
    sc.String("mystring"), sc.String("myoptional", optional=True))

assert isinstance(client, tuple)

self = sys.argv[0]
cfg = self.replace("py", "cfg")

real_client = omero.client(["--Ice.Config=%s" % cfg])
parse_only = real_client.getProperty("omero.script.parse")
assert parse_only == "true"
Пример #11
0
def runAsScript():

	dataTypes = [rstring('Dataset'), rstring('Image')]
	
	microscopyTypes = [rstring('CONFOCAL'), rstring('TWOPHOTON'), rstring('WIDEFIELD')]
	
	immersionTypes = [rstring('Oil'), rstring('Water'), rstring('Air'), rstring('CLARITY')]
	
	psfTypes = [rstring('Measured PSF'), rstring('Manual theoretical PSF'), rstring('Automatic theoretical PSF')]
	
	client = scripts.client('Omdecon',
	"""Omdecon: deconvolution on the OMERO server.
	
	Omdecon uses AIDA, the Adaptative Image Deconvolution Algorithm, to deconvolve images. 
	More info: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3166524/
	Also: https://github.com/erikhom/aida ; https://code.google.com/archive/p/aida-deconvolution/
	
	
	Omdecon can calculate the theoretical PSF if you don't have one on hand. This feature uses Christoph Gohlke's PSF.py module.
	More info: http://www.lfd.uci.edu/~gohlke/code/psf.py.html
	
	READ BEFORE YOU USE OMDECON:
		1- Omdecon only works with square images (i.e. 512x512, 600x600).
		2- The automatic background subtraction requires a single rectangular ROI. 
		   Make sure this ROI doesn't overlap any important feature on any plane or frame.
		3- The automatic theoretical PSF calculation requires the following metadata:
		   -Objective, Numerical Aperture, Excitation and Emission for all channels and Pixel Calibration.
		4- You need to input the right number of channels when setting the PSF manually.
		5- Images are saved in the same dataset with "_Deconv" added to the name.
	
	""",
		
		scripts.String("Data_Type", optional=False, grouping="1", 
		description="Type of data to deconvolve", values=dataTypes, default=rstring('Image')),
		
		scripts.List("IDs", optional=False, grouping="1.1",
		description = "List of images to deconvolve.").ofType(rlong(0)),
				
		scripts.String("Background", grouping = "2",
		description="Background", values=None, default=None),
		
		scripts.Int("Background_value_to_subtract", optional=False, grouping="2.1",
		description = "Manually supply the background to subtract.", default=0),
		
		scripts.Bool("Automatically_measure_background_from_ROI", grouping="2.2",
		description = "Trace a rectangular ROI to automatically perform background measurement.", default=False),
		
		scripts.String("PSF Configuration", grouping = "3",
		description="PSF settings", values=None, default=None),
		
		scripts.String("Type_of_PSF", grouping = "3.1",
		description="Choose the type of PSF you want to use.", values=psfTypes, default=rstring('Measured PSF')),
		
		scripts.Long("Measured_PSF_Image", optional=True, grouping="3.2",
		description="Input '0' to calculate the theoretical PSF", default=0),
		
		scripts.String("Manual settings for theoretical PSF (ignored for automatic)", grouping = "4",
		description="Supply the parameters here to generate a theoretical PSF with manual settings", values=None, default=None),
		
		scripts.String("Fluorescence_Microscopy_", grouping="4.01",
		description="Choose the type of fluorescence microscopy used", values=microscopyTypes, default=rstring('CONFOCAL')),
		
		scripts.String("Imaging_Medium_________", grouping="4.02",
		description="Select the media used for imaging", values=immersionTypes, default=rstring('Oil')),
		
		scripts.Float("Objective_NA_____________", optional=False, grouping="4.03",
		description="Supply the numerical aperture of the objective", default=1.42),
		
		scripts.Float("Pixel_Size_in_microns", optional=False, grouping="4.04",
		description="Enter the size of your pixels", default=0.05),
		
		scripts.Float("Confocal_Pinhole______", optional=False, grouping="4.05",
		description="Enter the pinhole radius for confocal microscopy", default=0.55),
		
		scripts.Int("_____Channel_1_-_Excitation",default=488, grouping="5.1", 
		description="Input '0' if not using this channel"),
		
		scripts.Int("_____Channel_1_-_Emission__",default=510, grouping="5.2", 
		description="Input '0' if not using this channel"),
			
		scripts.Int("_____Channel_2_-_Excitation",default=0, grouping="5.3", 
		description="Input '0' if not using this channel"),
		
		scripts.Int("_____Channel_2_-_Emission__",default=0, grouping="5.4", 
		description="Input '0' if not using this channel"),		

		scripts.Int("_____Channel_3_-_Excitation",default=0, grouping="5.5", 
		description="Input '0' if not using this channel"),
		
		scripts.Int("_____Channel_3_-_Emission__",default=0, grouping="5.6", 
		description="Input '0' if not using this channel"),
		
		
		version="1.0.0",
		authors=["Etienne Labrie-Dion"],
		institutions=["Douglas Hospital Research Center, McGill University, Montreal"],
		contact="*****@*****.**",		
	)
	
	try:
		#Obtain the user parameters
		scriptParams = {}
		conn = BlitzGateway(client_obj=client)

		client.enableKeepAlive(240)
		
		for key in client.getInputKeys():
				if client.getInput(key):
					scriptParams[key] = client.getInput(key, unwrap=True)
		print scriptParams
		
		robj, message = process(conn, scriptParams)
		client.setOutput("Message", rstring(message))
		
		if robj is not None:
				client.setOutput("Result", robject(robj))

	finally:
	
	#TODO: send an email confirming the end of the deconvolution and success/failure
		client.closeSession()
Пример #12
0
# End helper methods for capturing sys.stdout

# Script definition

# Script name, description and 2 parameters are defined here.
# These parameters will be recognised by the Insight and web clients and
# populated with the currently selected Image(s)
# A username and password will be entered too.

# this script only takes Images (not Datasets etc.)
data_types = [rstring('Image')]
client = scripts.client("export_to_other_omero.py",
                        ("Script to export a file to another omero server."),
                        scripts.String("serverUrl", optional=False),
                        scripts.Long("port", optional=False),
                        scripts.String("sessionUuid", optional=False),
                        scripts.List("IDs", optional=False).ofType(rlong(0)))
# we can now create our local Blitz Gateway by wrapping the client object
local_conn = BlitzGateway(client_obj=client)

# get the 'IDs' parameter (which we have restricted to 'Image' IDs)
host = client.getInput("serverUrl", unwrap=True)
port = client.getInput("port", unwrap=True)
sessionUuid = client.getInput("sessionUuid", unwrap=True)
ids = unwrap(client.getInput("IDs"))

# The managed_dir is where the local images are stored.
managed_dir = client.sf.getConfigService().getConfigValue("omero.managed.dir")

# Connect to remote omero