def roiFigure(session, commandArgs):    
    """
        This processes the script parameters, adding defaults if needed. 
        Then calls a method to make the figure, and finally uploads and attaches this to the primary image.
        
        @param: session        The OMERO session
        @param: commandArgs        Map of String:Object parameters for the script. 
                                Objects are not rtypes, since getValue() was called when the map was processed below. 
                                But, list and map objects may contain rtypes (need to call getValue())
        
        @return:     the id of the originalFileLink child. (ID object, not value) 
    """
    
    # create the services we're going to need. 
    metadataService = session.getMetadataService()
    queryService = session.getQueryService()
    updateService = session.getUpdateService()
    rawFileStore = session.createRawFileStore()
    containerService = session.getContainerService()
    
    log("ROI figure created by OMERO on %s" % date.today())
    log("")
    
    pixelIds = []
    imageIds = []
    imageLabels = []
    imageNames = {}
    omeroImage = None    # this is set as the first image, to link figure to

    # function for getting image labels.
    def getLabels(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]
        
    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":
            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]
            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":
            def getTags(name, tagsList, pdList):
                return tagsList
            getLabels = getTags
            
    # process the list of images. If imageIds is not set, script can't run. 
    log("Image details:")
    for idCount, imageId in enumerate(commandArgs["IDs"]):
        iId = long(imageId.getValue())
        image = containerService.getImages("Image", [iId], None)[0]
        if image == None:
            print "Image not found for ID:", iId
            continue
        imageIds.append(iId)
        if idCount == 0:
            omeroImage = image        # remember the first image to attach figure to
        pixelIds.append(image.getPrimaryPixels().getId().getValue())
        imageNames[iId] = image.getName().getValue()
    
    if len(imageIds) == 0:
        print "No image IDs specified."    
            
    pdMap = figUtil.getDatasetsProjectsFromImages(queryService, imageIds)    # a map of imageId : list of (project, dataset) names. 
    tagMap = figUtil.getTagsFromImages(metadataService, imageIds)
    # Build a legend entry for each image
    for iId in imageIds:
        name = imageNames[iId]
        imageDate = image.getAcquisitionDate().getValue()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]
        
        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        log("  Date: %s" % date.fromtimestamp(imageDate/1000))
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)
        
        imageLabels.append(getLabels(name, tagsList, pdList))
    
    # use the first image to define dimensions, channel colours etc. 
    pixelsId = pixelIds[0]
    pixels = queryService.get("Pixels", pixelsId)

    sizeX = pixels.getSizeX().getValue();
    sizeY = pixels.getSizeY().getValue();
    sizeZ = pixels.getSizeZ().getValue();
    sizeC = pixels.getSizeC().getValue();

    
    width = sizeX
    if "Width" in commandArgs:
        w = commandArgs["Width"]
        try:
            width = int(w)
        except:
            log("Invalid width: %s Using default value: %d" % (str(w), sizeX))
    
    height = sizeY
    if "Height" in commandArgs:
        h = commandArgs["Height"]
        try:
            height = int(h)
        except:
            log("Invalid height: %s Using default value" % (str(h), sizeY))
            
    log("Image dimensions for all panels (pixels): width: %d  height: %d" % (width, height))
        
                        
    mergedIndexes = []    # the channels in the combined image, 
    mergedColours = {}    
    if "Merged_Colours" in commandArgs:
        cColourMap = commandArgs["Merged_Colours"]
        for c in cColourMap:
            rgb = cColourMap[c].getValue()
            rgba = imgUtil.RGBIntToRGBA(rgb)
            mergedColours[int(c)] = rgba
            mergedIndexes.append(int(c))
        mergedIndexes.sort()
    # make sure we have some merged channels
    if len(mergedIndexes) == 0:
        mergedIndexes = range(sizeC)
    mergedIndexes.reverse()
    
    mergedNames = False
    if "Merged_Names" in commandArgs:
        mergedNames = commandArgs["Merged_Names"]
        
    # Make channel-names map. If argument wasn't specified, name by index
    channelNames = {}
    if "Channel_Names" in commandArgs:
        cNameMap = commandArgs["Channel_Names"]
        for c in range(sizeC):
            if str(c) in cNameMap:
                channelNames[c] = cNameMap[str(c)].getValue()
            else: 
                channelNames[c] = str(c)
    else:
        for c in range(sizeC):
            channelNames[c] = str(c)
    
    # Make split-indexes list. If argument wasn't specified, include them all. 
    splitIndexes = []
    if "Split_Indexes" in commandArgs:
        for index in commandArgs["Split_Indexes"]:
            splitIndexes.append(index.getValue())
    else:
        for c in range(sizeC):
            splitIndexes = range(sizeC)
            
    colourChannels = True
    if "Split_Panels_Grey" in commandArgs and commandArgs["Split_Panels_Grey"]:
        colourChannels = False
    
    algorithm = omero.constants.projection.ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = omero.constants.projection.ProjectionType.MEANINTENSITY
    
    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s
    
    scalebar = None
    if "Scalebar" in commandArgs:
        sb = commandArgs["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None
    
    overlayColour = (255,255,255)
    if "Overlay_Colour" in commandArgs:
        r,g,b,a = OVERLAY_COLOURS[commandArgs["Overlay_Colour"]]
        overlayColour = (r,g,b)
    
    roiZoom = None
    if "ROI_Zoom" in commandArgs:
        roiZoom = float(commandArgs["ROI_Zoom"])
        if roiZoom == 0:
            roiZoom = None
    
    roiLabel = "FigureROI"
    if "ROI_Label" in commandArgs:
        roiLabel = commandArgs["ROI_Label"]
        
    spacer = (width/50) + 2
    
    fig = getSplitView(session, imageIds, pixelIds, splitIndexes, channelNames, mergedNames, colourChannels, mergedIndexes, 
            mergedColours, width, height, imageLabels, spacer, algorithm, stepping, scalebar, overlayColour, roiZoom, roiLabel)
    
    if fig == None:        # e.g. No ROIs found
        return                                                
    #fig.show()        # bug-fixing only
    
    log("")
    figLegend = "\n".join(logStrings)
    
    #print figLegend    # bug fixing only
    
    format = JPEG
    if "Format" in commandArgs:
        if commandArgs["Format"] == "PNG":
            format = PNG
            
    output = "roiFigure"
    if "Figure_Name" in commandArgs:
        output = str(commandArgs["Figure_Name"])
        
    if format == PNG:
        output = output + ".png"
        fig.save(output, "PNG")
    else:
        output = output + ".jpg"
        fig.save(output)
    
    # Use util method to upload the figure 'output' to the server, attaching it to the omeroImage, adding the 
    # figLegend as the fileAnnotation description. 
    # Returns the id of the originalFileLink child. (ID object, not value)
    fileAnnotation = scriptUtil.uploadAndAttachFile(queryService, updateService, rawFileStore, omeroImage, output, format, figLegend)
    return fileAnnotation
Esempio n. 2
0
def roiFigure(conn, commandArgs):
    """
    This processes the script parameters, adding defaults if needed.
    Then calls a method to make the figure, and finally uploads and attaches
    this to the primary image.

    @param: session         The OMERO session
    @param: commandArgs     Map of String:Object parameters for the script.
                            Objects are not rtypes, since getValue() was
                            called when the map was processed below.
                            But, list and map objects may contain rtypes (need
                            to call getValue())

    @return:                the id of the originalFileLink child. (ID object,
                            not value)
    """

    log("ROI figure created by OMERO on %s" % date.today())
    log("")

    message = ""  # message to be returned to the client
    pixelIds = []
    imageIds = []
    imageLabels = []

    # function for getting image labels.
    def getImageNames(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]

    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":
            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]
            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":
            def getTags(name, tagsList, pdList):
                return tagsList
            getLabels = getTags
        else:
            getLabels = getImageNames
    else:
        getLabels = getImageNames

    # Get the images
    images, logMessage = scriptUtil.getObjects(conn, commandArgs)
    message += logMessage
    if not images:
        return None, message

    # Check for rectangular ROIs and filter images list
    images = [image for image in images if image.getROICount("Rectangle") > 0]
    if not images:
        message += "No rectangle ROI found."
        return None, message

    # Attach figure to the first image
    omeroImage = images[0]

    # process the list of images. If imageIds is not set, script can't run.
    log("Image details:")
    for image in images:
        imageIds.append(image.getId())
        pixelIds.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pdMap = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
                                                  imageIds)
    tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        imageDate = image.getAcquisitionDate()
        iId = image.getId()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]

        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        if imageDate:
            log("  Date: %s" % imageDate)
        else:
            log("  Date: not set")
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)

        imageLabels.append(getLabels(name, tagsList, pdList))

    # use the first image to define dimensions, channel colours etc.
    sizeX = omeroImage.getSizeX()
    sizeY = omeroImage.getSizeY()
    sizeZ = omeroImage.getSizeZ()
    sizeC = omeroImage.getSizeC()

    width = sizeX
    if "Width" in commandArgs:
        w = commandArgs["Width"]
        try:
            width = int(w)
        except:
            log("Invalid width: %s Using default value: %d" % (str(w), sizeX))

    height = sizeY
    if "Height" in commandArgs:
        h = commandArgs["Height"]
        try:
            height = int(h)
        except:
            log("Invalid height: %s Using default value" % (str(h), sizeY))

    log("Image dimensions for all panels (pixels): width: %d  height: %d"
        % (width, height))

    mergedIndexes = []    # the channels in the combined image,
    mergedColours = {}
    if "Merged_Colours" in commandArgs:
        cColourMap = commandArgs["Merged_Colours"]
        for c in cColourMap:
            rgb = cColourMap[c]
            try:
                rgb = int(rgb)
                cIndex = int(c)
            except ValueError:
                print "Merged_Colours map should be index:rgbInt. Not %s:%s" \
                    % (c, rgb)
                continue
            rgba = imgUtil.RGBIntToRGBA(rgb)
            mergedColours[cIndex] = rgba
            mergedIndexes.append(cIndex)
        mergedIndexes.sort()
    # make sure we have some merged channels
    if len(mergedIndexes) == 0:
        mergedIndexes = range(sizeC)
    mergedIndexes.reverse()

    mergedNames = False
    if "Merged_Names" in commandArgs:
        mergedNames = commandArgs["Merged_Names"]

    # Make channel-names map. If argument wasn't specified, name by index
    channelNames = {}
    if "Channel_Names" in commandArgs:
        cNameMap = commandArgs["Channel_Names"]
        for c in range(sizeC):
            if str(c) in cNameMap:
                channelNames[c] = cNameMap[str(c)]
            else:
                channelNames[c] = str(c)
    else:
        for c in range(sizeC):
            channelNames[c] = str(c)

    # Make split-indexes list. If no "Split_Indexes", show none:
    # http://www.openmicroscopy.org/community/viewtopic.php?f=4&t=940
    splitIndexes = []
    if "Split_Indexes" in commandArgs:
        for index in commandArgs["Split_Indexes"]:
            splitIndexes.append(index)

    colourChannels = True
    if "Split_Panels_Grey" in commandArgs and commandArgs["Split_Panels_Grey"]:
        colourChannels = False

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = ProjectionType.MEANINTENSITY

    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s

    scalebar = None
    if "Scalebar" in commandArgs:
        sb = commandArgs["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None

    overlayColour = (255, 255, 255)
    if "Overlay_Colour" in commandArgs:
        r, g, b, a = OVERLAY_COLOURS[commandArgs["Overlay_Colour"]]
        overlayColour = (r, g, b)

    roiZoom = None
    if "ROI_Zoom" in commandArgs:
        roiZoom = float(commandArgs["ROI_Zoom"])
        if roiZoom == 0:
            roiZoom = None

    roiLabel = "FigureROI"
    if "ROI_Label" in commandArgs:
        roiLabel = commandArgs["ROI_Label"]

    spacer = (width/50) + 2

    fig = getSplitView(
        conn, imageIds, pixelIds, splitIndexes, channelNames, mergedNames,
        colourChannels, mergedIndexes, mergedColours, width, height,
        imageLabels, spacer, algorithm, stepping, scalebar, overlayColour,
        roiZoom, roiLabel)

    if fig is None:
        logMessage = "No figure produced"
        log("\n"+logMessage)
        message += logMessage
        return None, message
    # fig.show()        # bug-fixing only

    log("")
    figLegend = "\n".join(logStrings)

    # print figLegend    # bug fixing only
    format = commandArgs["Format"]

    figureName = "roiFigure"
    if "Figure_Name" in commandArgs:
        figureName = commandArgs["Figure_Name"]
        figureName = os.path.basename(figureName)
    output = "localfile"
    if format == 'PNG':
        output = output + ".png"
        figureName = figureName + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figureName = figureName + ".tiff"
        fig.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figureName = figureName + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Use util method to upload the figure 'output' to the server, attaching
    # it to the omeroImage, adding the
    # figLegend as the fileAnnotation description.
    # Returns the id of the originalFileLink child. (ID object, not value)
    namespace = NSCREATED + "/omero/figure_scripts/ROI_Split_Figure"
    fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(
        conn, output, omeroImage, output="ROI Split figure",
        mimetype=mimetype, ns=namespace, desc=figLegend,
        origFilePathAndName=figureName)
    message += faMessage

    return fileAnnotation, message
def movieFigure(conn, commandArgs):
    """
    Makes the figure using the parameters in @commandArgs, attaches the figure
    to the parent Project/Dataset, and returns the file-annotation ID

    @param session      The OMERO session
    @param commandArgs  Map of parameters for the script
    @ returns           Returns the id of the originalFileLink child. (ID
                        object, not value)
    """

    log("Movie figure created by OMERO on %s" % date.today())
    log("")

    timeLabels = {"SECS_MILLIS": "seconds",
                  "SECS": "seconds",
                  "MINS": "minutes",
                  "HOURS": "hours",
                  "MINS_SECS": "mins:secs",
                  "HOURS_MINS": "hours:mins"}
    timeUnits = "SECS"
    if "Time_Units" in commandArgs:
        timeUnits = commandArgs["Time_Units"]
        # convert from UI name to timeLabels key
        timeUnits = timeUnits.replace(" ", "_")
    if timeUnits not in timeLabels.keys():
        timeUnits = "SECS"
    log("Time units are in %s" % timeLabels[timeUnits])

    pixelIds = []
    imageIds = []
    imageLabels = []
    message = ""  # message to be returned to the client

    # function for getting image labels.
    def getImageNames(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]

    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":
            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]
            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":
            def getTags(name, tagsList, pdList):
                return tagsList
            getLabels = getTags
        else:
            getLabels = getImageNames
    else:
        getLabels = getImageNames

    # Get the images
    images, logMessage = scriptUtil.getObjects(conn, commandArgs)
    message += logMessage
    if not images:
        return None, message

    # Attach figure to the first image
    omeroImage = images[0]

    # process the list of images
    log("Image details:")
    for image in images:
        imageIds.append(image.getId())
        pixelIds.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pdMap = figUtil.getDatasetsProjectsFromImages(
        conn.getQueryService(), imageIds)
    tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        iId = image.getId()
        imageDate = image.getAcquisitionDate()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]

        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        if imageDate:
            log("  Date: %s" % imageDate)
        else:
            log("  Date: not set")
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)

        imageLabels.append(getLabels(name, tagsList, pdList))

    # use the first image to define dimensions, channel colours etc.
    sizeX = omeroImage.getSizeX()
    sizeY = omeroImage.getSizeY()
    sizeZ = omeroImage.getSizeZ()
    sizeT = omeroImage.getSizeT()

    tIndexes = []
    if "T_Indexes" in commandArgs:
        for t in commandArgs["T_Indexes"]:
            tIndexes.append(t)
        print "T_Indexes", tIndexes
    if len(tIndexes) == 0:      # if no t-indexes given, use all t-indices
        tIndexes = range(sizeT)

    zStart = -1
    zEnd = -1
    if "Z_Start" in commandArgs:
        zStart = commandArgs["Z_Start"]
    if "Z_End" in commandArgs:
        zEnd = commandArgs["Z_End"]

    width = sizeX
    if "Width" in commandArgs:
        width = commandArgs["Width"]

    height = sizeY
    if "Height" in commandArgs:
        height = commandArgs["Height"]

    spacer = (width/25) + 2

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = ProjectionType.MEANINTENSITY

    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s

    scalebar = None
    if "Scalebar" in commandArgs:
        sb = commandArgs["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None

    overlayColour = (255, 255, 255)
    if "Scalebar_Colour" in commandArgs:
        r, g, b, a = OVERLAY_COLOURS[commandArgs["Scalebar_Colour"]]
        overlayColour = (r, g, b)

    maxColCount = 10
    if "Max_Columns" in commandArgs:
        maxColCount = commandArgs["Max_Columns"]

    figure = createMovieFigure(
        conn, pixelIds, tIndexes, zStart, zEnd, width, height, spacer,
        algorithm, stepping, scalebar, overlayColour, timeUnits, imageLabels,
        maxColCount)

    log("")
    figLegend = "\n".join(logLines)

    # print figLegend    # bug fixing only
    format = commandArgs["Format"]

    figureName = "movieFigure"
    if "Figure_Name" in commandArgs:
        figureName = str(commandArgs["Figure_Name"])
        figureName = os.path.basename(figureName)
    output = "localfile"
    if format == 'PNG':
        output = output + ".png"
        figureName = figureName + ".png"
        figure.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figureName = figureName + ".tiff"
        figure.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figureName = figureName + ".jpg"
        figure.save(output)
        mimetype = "image/jpeg"

    namespace = NSCREATED + "/omero/figure_scripts/Movie_Figure"
    fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(
        conn, output, omeroImage, output="Movie figure", mimetype=mimetype,
        ns=namespace, desc=figLegend, origFilePathAndName=figureName)
    message += faMessage

    return fileAnnotation, message
Esempio n. 4
0
def split_view_figure(conn, script_params):
    """
    Processes the arguments, populating defaults if necessary. Prints the
    details to log (fig-legend).
    Even handles missing arguments that are not optional (from when this ran
    from commandline with everything optional)
    then calls make_split_view_figure() to make the figure, attaches it to the
    Image as an 'originalFile' annotation, with fig-legend as the description.

    @return: the id of the originalFileLink child. (ID object, not value)
    """

    log("Split-View figure created by OMERO on %s" % date.today())
    log("")

    message = ""  # message to be returned to the client
    image_ids = []
    pixel_ids = []
    image_labels = []

    # function for getting image labels.
    def get_image_names(full_name, tags_list, pd_list):
        name = full_name.split("/")[-1]
        return [name.decode('utf8')]

    # default function for getting labels is getName (or use datasets / tags)
    if script_params["Image_Labels"] == "Datasets":

        def get_datasets(name, tags_list, pd_list):
            return [dataset.decode('utf8') for project, dataset in pd_list]

        get_labels = get_datasets
    elif script_params["Image_Labels"] == "Tags":

        def get_tags(name, tags_list, pd_list):
            return [t.decode('utf8') for t in tags_list]

        get_labels = get_tags
    else:
        get_labels = get_image_names

    # Get the images
    images, log_message = script_utils.get_objects(conn, script_params)
    message += log_message
    if not images:
        return None, message

    # Attach figure to the first image
    omero_image = images[0]

    # process the list of images
    log("Image details:")
    for image in images:
        image_ids.append(image.getId())
        pixel_ids.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pd_map = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
                                                   image_ids)
    tag_map = figUtil.getTagsFromImages(conn.getMetadataService(), image_ids)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        image_date = image.getAcquisitionDate()
        iid = image.getId()
        tags_list = tag_map[iid]
        pd_list = pd_map[iid]

        tags = ", ".join(tags_list)
        pd_string = ", ".join(["%s/%s" % pd for pd in pd_list])
        log(" Image: %s  ID: %d" % (name, iid))
        if image_date:
            log("  Date: %s" % image_date)
        else:
            log("  Date: not set")
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pd_string)

        image_labels.append(get_labels(name, tags_list, pd_list))

    # use the first image to define dimensions, channel colours etc.
    size_x = omero_image.getSizeX()
    size_y = omero_image.getSizeY()
    size_z = omero_image.getSizeZ()
    size_c = omero_image.getSizeC()

    # set image dimensions
    z_start = -1
    z_end = -1
    if "Z_Start" in script_params:
        z_start = script_params["Z_Start"]
    if "Z_End" in script_params:
        z_end = script_params["Z_End"]

    width = "Width" in script_params and script_params["Width"] or size_x
    height = "Height" in script_params and script_params["Height"] or size_y

    log("Image dimensions for all panels (pixels): width: %d  height: %d" %
        (width, height))

    # Make split-indexes list. If argument wasn't specified, include them all.
    split_indexes = []
    if "Split_Indexes" in script_params:
        split_indexes = script_params["Split_Indexes"]
    else:
        split_indexes = range(size_c)

    # Make channel-names map. If argument wasn't specified, name by index
    channel_names = {}
    for c in range(size_c):
        channel_names[c] = str(c)
    if "Channel_Names" in script_params:
        c_name_map = script_params["Channel_Names"]
        for c in c_name_map:
            index = int(c)
            channel_names[index] = c_name_map[c].decode('utf8')

    merged_indexes = []  # the channels in the combined image,
    merged_colours = {}
    if "Merged_Colours" in script_params:
        c_colour_map = script_params["Merged_Colours"]
        for c in c_colour_map:
            rgb = c_colour_map[c]
            try:
                rgb = int(rgb)
                c_index = int(c)
            except ValueError:
                continue
            rgba = image_utils.int_to_rgba(rgb)
            merged_colours[c_index] = rgba
            merged_indexes.append(c_index)
        merged_indexes.sort()
    else:
        merged_indexes = range(size_c)

    colour_channels = not script_params["Split_Panels_Grey"]

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Mean Intensity" == script_params["Algorithm"]:
        algorithm = ProjectionType.MEANINTENSITY

    stepping = min(script_params["Stepping"], size_z)

    scalebar = None
    if "Scalebar" in script_params:
        scalebar = script_params["Scalebar"]
        log("Scalebar is %d microns" % scalebar)

    r, g, b, a = OVERLAY_COLOURS[script_params["Overlay_Colour"]]
    overlay_colour = (r, g, b)

    merged_names = script_params["Merged_Names"]

    fig = make_split_view_figure(conn, pixel_ids, z_start, z_end,
                                 split_indexes, channel_names, colour_channels,
                                 merged_indexes, merged_colours, merged_names,
                                 width, height, image_labels, algorithm,
                                 stepping, scalebar, overlay_colour)

    fig_legend = "\n".join(log_strings)

    figure_name = script_params["Figure_Name"]
    figure_name = os.path.basename(figure_name)
    output = "localfile"
    format = script_params["Format"]
    if format == 'PNG':
        output = output + ".png"
        figure_name = figure_name + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figure_name = figure_name + ".tiff"
        fig.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figure_name = figure_name + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Upload the figure 'output' to the server, creating a file annotation and
    # attaching it to the omero_image, adding the
    # fig_legend as the fileAnnotation description.
    namespace = NSCREATED + "/omero/figure_scripts/Split_View_Figure"
    file_annotation, fa_message = script_utils.create_link_file_annotation(
        conn,
        output,
        omero_image,
        output="Split view figure",
        mimetype=mimetype,
        namespace=namespace,
        description=fig_legend,
        orig_file_path_and_name=figure_name)
    message += fa_message

    return file_annotation, message
Esempio n. 5
0
def movie_figure(conn, command_args):
    """
    Makes the figure using the parameters in @command_args, attaches the figure
    to the parent Project/Dataset, and returns the file-annotation ID

    @param session      The OMERO session
    @param command_args Map of parameters for the script
    @ returns           Returns the id of the originalFileLink child. (ID
                        object, not value)
    """

    log("Movie figure created by OMERO on %s" % date.today())
    log("")

    time_labels = {
        "SECS_MILLIS": "seconds",
        "SECS": "seconds",
        "MINS": "minutes",
        "HOURS": "hours",
        "MINS_SECS": "mins:secs",
        "HOURS_MINS": "hours:mins"
    }
    time_units = "SECS"
    if "Time_Units" in command_args:
        time_units = command_args["Time_Units"]
        # convert from UI name to time_labels key
        time_units = time_units.replace(" ", "_")
    if time_units not in time_labels.keys():
        time_units = "SECS"
    log("Time units are in %s" % time_labels[time_units])

    pixel_ids = []
    image_ids = []
    image_labels = []
    message = ""  # message to be returned to the client

    # function for getting image labels.
    def get_image_names(full_name, tags_list, pd_list):
        name = full_name.split("/")[-1]
        return [name]

    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in command_args:
        if command_args["Image_Labels"] == "Datasets":

            def get_datasets(name, tags_list, pd_list):
                return [dataset for project, dataset in pd_list]

            get_labels = get_datasets
        elif command_args["Image_Labels"] == "Tags":

            def get_tags(name, tags_list, pd_list):
                return tags_list

            get_labels = get_tags
        else:
            get_labels = get_image_names
    else:
        get_labels = get_image_names

    # Get the images
    images, log_message = script_utils.get_objects(conn, command_args)
    message += log_message
    if not images:
        return None, message

    # Attach figure to the first image
    omero_image = images[0]

    # process the list of images
    log("Image details:")
    for image in images:
        image_ids.append(image.getId())
        pixel_ids.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pd_map = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
                                                   image_ids)
    tag_map = figUtil.getTagsFromImages(conn.getMetadataService(), image_ids)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        iid = image.getId()
        image_date = image.getAcquisitionDate()
        tags_list = tag_map[iid]
        pd_list = pd_map[iid]

        tags = ", ".join(tags_list)
        pd_string = ", ".join(["%s/%s" % pd for pd in pd_list])
        log(" Image: %s  ID: %d" % (name, iid))
        if image_date:
            log("  Date: %s" % image_date)
        else:
            log("  Date: not set")
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pd_string)

        image_labels.append(get_labels(name, tags_list, pd_list))

    # use the first image to define dimensions, channel colours etc.
    size_x = omero_image.getSizeX()
    size_y = omero_image.getSizeY()
    size_z = omero_image.getSizeZ()
    size_t = omero_image.getSizeT()

    t_indexes = []
    if "T_Indexes" in command_args:
        for t in command_args["T_Indexes"]:
            t_indexes.append(t)
    if len(t_indexes) == 0:  # if no t-indexes given, use all t-indices
        t_indexes = range(size_t)

    z_start = -1
    z_end = -1
    if "Z_Start" in command_args:
        z_start = command_args["Z_Start"]
    if "Z_End" in command_args:
        z_end = command_args["Z_End"]

    width = size_x
    if "Width" in command_args:
        width = command_args["Width"]

    height = size_y
    if "Height" in command_args:
        height = command_args["Height"]

    spacer = (width / 25) + 2

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in command_args:
        a = command_args["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = ProjectionType.MEANINTENSITY

    stepping = 1
    if "Stepping" in command_args:
        s = command_args["Stepping"]
        if (0 < s < size_z):
            stepping = s

    scalebar = None
    if "Scalebar" in command_args:
        sb = command_args["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except ValueError:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None

    overlay_colour = (255, 255, 255)
    if "Scalebar_Colour" in command_args:
        r, g, b, a = OVERLAY_COLOURS[command_args["Scalebar_Colour"]]
        overlay_colour = (r, g, b)

    max_col_count = 10
    if "Max_Columns" in command_args:
        max_col_count = command_args["Max_Columns"]

    figure = createmovie_figure(conn, pixel_ids, t_indexes, z_start, z_end,
                                width, height, spacer, algorithm, stepping,
                                scalebar, overlay_colour, time_units,
                                image_labels, max_col_count)

    log("")
    fig_legend = "\n".join(log_lines)

    # print figLegend    # bug fixing only
    format = command_args["Format"]

    figure_name = "movie_figure"
    if "Figure_Name" in command_args:
        figure_name = str(command_args["Figure_Name"])
        figure_name = os.path.basename(figure_name)
    output = "localfile"
    if format == 'PNG':
        output = output + ".png"
        figure_name = figure_name + ".png"
        figure.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figure_name = figure_name + ".tiff"
        figure.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figure_name = figure_name + ".jpg"
        figure.save(output)
        mimetype = "image/jpeg"

    namespace = NSCREATED + "/omero/figure_scripts/Movie_Figure"
    file_annotation, fa_message = script_utils.create_link_file_annotation(
        conn,
        output,
        omero_image,
        output="Movie figure",
        mimetype=mimetype,
        namespace=namespace,
        description=fig_legend,
        orig_file_path_and_name=figure_name)
    message += fa_message

    return file_annotation, message
Esempio n. 6
0
def splitViewFigure(conn, scriptParams):    
    """
    Processes the arguments, populating defaults if necessary. Prints the details to log (fig-legend).
    Even handles missing arguments that are not optional (from when this ran from commandline with everything optional)
    then calls makeSplitViewFigure() to make the figure, attaches it to the Image as an 'originalFile' annotation,
    with fig-legend as the description. 
    
    @return: the id of the originalFileLink child. (ID object, not value) 
    """

    log("Split-View figure created by OMERO on %s" % date.today())
    log("")
    
    message="" # message to be returned to the client
    imageIds = []
    pixelIds = []
    imageLabels = []

    # function for getting image labels.
    def getLabels(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]
        
    # default function for getting labels is getName (or use datasets / tags)
    if scriptParams["Image_Labels"] == "Datasets":
        def getDatasets(name, tagsList, pdList):
            return [dataset for project, dataset in pdList]
        getLabels = getDatasets
    elif scriptParams["Image_Labels"] == "Tags":
        def getTags(name, tagsList, pdList):
            return tagsList
        getLabels = getTags
   
    # Get the images
    images, logMessage = scriptUtil.getObjects(conn, scriptParams)
    message += logMessage
    if not images:
        return None, message

    # Attach figure to the first image
    omeroImage = images[0] 
            
    # process the list of images
    log("Image details:")
    for image in images:
        imageIds.append(image.getId())
        pixelIds.append(image.getPrimaryPixels().getId())
    
    pdMap = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(), imageIds)    # a map of imageId : list of (project, dataset) names. 
    tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        imageDate = image.getAcquisitionDate()
        iId = image.getId()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]
        
        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        log("  Date: %s" % date.fromtimestamp(imageDate/1000))
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)
        
        imageLabels.append(getLabels(name, tagsList, pdList))
    
    
    # use the first image to define dimensions, channel colours etc. 
    sizeX = omeroImage.getSizeX()
    sizeY = omeroImage.getSizeY()
    sizeZ = omeroImage.getSizeZ()
    sizeC = omeroImage.getSizeC()
        
    
    # set image dimensions
    zStart = -1
    zEnd = -1
    if "Z_Start" in scriptParams:
        zStart = scriptParams["Z_Start"]
    if "Z_End" in scriptParams:
        zEnd = scriptParams["Z_End"]
    
    width = "Width" in scriptParams and scriptParams["Width"] or sizeX
    height = "Height" in scriptParams and scriptParams["Height"] or sizeY

    log("Image dimensions for all panels (pixels): width: %d  height: %d" % (width, height))
    
    # Make split-indexes list. If argument wasn't specified, include them all. 
    splitIndexes = []
    if "Split_Indexes" in scriptParams:
        splitIndexes = scriptParams["Split_Indexes"]
    else:
        splitIndexes = range(sizeC)
    
    # Make channel-names map. If argument wasn't specified, name by index
    channelNames = {}
    for c in range(sizeC):
        channelNames[c] = str(c)
    if "Channel_Names" in scriptParams:
        cNameMap = scriptParams["Channel_Names"]
        for c in cNameMap:
            index = int(c)
            channelNames[index] = cNameMap[c]      
                        
    mergedIndexes = []    # the channels in the combined image, 
    mergedColours = {}    
    if "Merged_Colours" in scriptParams:
        cColourMap = scriptParams["Merged_Colours"]
        for c in cColourMap:
            rgb = cColourMap[c]
            rgba = imgUtil.RGBIntToRGBA(rgb)
            mergedColours[int(c)] = rgba
            mergedIndexes.append(int(c))
        mergedIndexes.sort()
    else:
        mergedIndexes = range(sizeC)

    colourChannels = not scriptParams["Split_Panels_Grey"]

    algorithm = omero.constants.projection.ProjectionType.MAXIMUMINTENSITY
    if "Mean Intensity" == scriptParams["Algorithm"]:
        algorithm = omero.constants.projection.ProjectionType.MEANINTENSITY

    stepping = min(scriptParams["Stepping"], sizeZ)

    scalebar = None
    if "Scalebar" in scriptParams:
        scalebar = scriptParams["Scalebar"]
        log("Scalebar is %d microns" % scalebar)

    r,g,b,a = OVERLAY_COLOURS[scriptParams["Overlay_Colour"]]
    overlayColour = (r,g,b)
        
    mergedNames = scriptParams["Merged_Names"]
    
    print "splitIndexes", splitIndexes
    print "channelNames", channelNames
    print "colourChannels", colourChannels
    print "mergedIndexes", mergedIndexes
    print "mergedColours", mergedColours
    print "mergedNames", mergedNames
    fig = makeSplitViewFigure(conn, pixelIds, zStart, zEnd, splitIndexes, channelNames, colourChannels, 
                        mergedIndexes, mergedColours, mergedNames, width, height, imageLabels, algorithm, stepping, scalebar, overlayColour)

    figLegend = "\n".join(logStrings)
    format = JPEG
    if scriptParams["Format"] == "PNG":
        format = PNG
    output = scriptParams["Figure_Name"]

    if format == PNG:
        output = output + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    else:
        output = output + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Upload the figure 'output' to the server, creating a file annotation and attaching it to the omeroImage, adding the 
    # figLegend as the fileAnnotation description.
    namespace = omero.constants.namespaces.NSCREATED+"/omero/figure_scripts/Split_View_Figure"
    fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(conn, output, omeroImage,
        output="Split view figure", mimetype=mimetype, ns=namespace, desc=figLegend)
    message += faMessage
    
    return fileAnnotation, message
Esempio n. 7
0
def roiFigure(conn, commandArgs):
    """
    This processes the script parameters, adding defaults if needed.
    Then calls a method to make the figure, and finally uploads and attaches
    this to the primary image.

    @param: session         The OMERO session
    @param: commandArgs     Map of String:Object parameters for the script.
                            Objects are not rtypes, since getValue() was
                            called when the map was processed below.
                            But, list and map objects may contain rtypes (need
                            to call getValue())

    @return:                the id of the originalFileLink child. (ID object,
                            not value)
    """

    log("ROI figure created by OMERO on %s" % date.today())
    log("")

    message = ""  # message to be returned to the client
    pixelIds = []
    imageIds = []
    imageLabels = []

    # function for getting image labels.
    def getImageNames(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]

    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":
            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]
            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":
            def getTags(name, tagsList, pdList):
                return tagsList
            getLabels = getTags
        else:
            getLabels = getImageNames
    else:
        getLabels = getImageNames

    # Get the images
    images, logMessage = scriptUtil.getObjects(conn, commandArgs)
    message += logMessage
    if not images:
        return None, message

    # Check for rectangular ROIs and filter images list
    images = [image for image in images if image.getROICount("Rect") > 0]
    if not images:
        message += "No rectangle ROI found."
        return None, message

    # Attach figure to the first image
    omeroImage = images[0]

    # process the list of images
    log("Image details:")
    for image in images:
        imageIds.append(image.getId())
        pixelIds.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pdMap = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
                                                  imageIds)
    tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        iId = image.getId()
        imageDate = image.getAcquisitionDate()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]

        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        log("  Date: %s" % date.fromtimestamp(imageDate/1000))
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)

        imageLabels.append(getLabels(name, tagsList, pdList))

    # use the first image to define dimensions, channel colours etc.
    sizeX = omeroImage.getSizeX()
    sizeY = omeroImage.getSizeY()
    sizeZ = omeroImage.getSizeZ()
    sizeC = omeroImage.getSizeC()

    width = sizeX
    if "Width" in commandArgs:
        w = commandArgs["Width"]
        try:
            width = int(w)
        except:
            log("Invalid width: %s Using default value: %d" % (str(w), sizeX))

    height = sizeY
    if "Height" in commandArgs:
        h = commandArgs["Height"]
        try:
            height = int(h)
        except:
            log("Invalid height: %s Using default value" % (str(h), sizeY))

    log("Image dimensions for all panels (pixels): width: %d  height: %d"
        % (width, height))

    # the channels in the combined image,
    if "Merged_Channels" in commandArgs:
        # convert to 0-based
        mergedIndexes = [c-1 for c in commandArgs["Merged_Channels"]]
    else:
        mergedIndexes = range(sizeC)  # show all
    mergedIndexes.reverse()

    #  if no colours added, use existing rendering settings.
    mergedColours = {}
    # Actually, nicer to always use existing rendering settings.
    # if "Merged_Colours" in commandArgs:
    #     for i, c in enumerate(commandArgs["Merged_Colours"]):
    #         if c in COLOURS:
    #             mergedColours[i] = COLOURS[c]

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = ProjectionType.MEANINTENSITY

    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s

    scalebar = None
    if "Scalebar" in commandArgs:
        sb = commandArgs["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None

    overlayColour = (255, 255, 255)
    if "Scalebar_Colour" in commandArgs:
        if commandArgs["Scalebar_Colour"] in OVERLAY_COLOURS:
            r, g, b, a = OVERLAY_COLOURS[commandArgs["Scalebar_Colour"]]
            overlayColour = (r, g, b)

    roiZoom = None
    if "Roi_Zoom" in commandArgs:
        roiZoom = float(commandArgs["Roi_Zoom"])
        if roiZoom == 0:
            roiZoom = None

    maxColumns = None
    if "Max_Columns" in commandArgs:
        maxColumns = commandArgs["Max_Columns"]

    showRoiDuration = False
    if "Show_ROI_Duration" in commandArgs:
        showRoiDuration = commandArgs["Show_ROI_Duration"]

    roiLabel = "FigureROI"
    if "Roi_Selection_Label" in commandArgs:
        roiLabel = commandArgs["Roi_Selection_Label"]

    spacer = (width/50) + 2

    print "showRoiDuration", showRoiDuration
    fig = getSplitView(
        conn, imageIds, pixelIds, mergedIndexes, mergedColours, width, height,
        imageLabels, spacer, algorithm, stepping, scalebar, overlayColour,
        roiZoom, maxColumns, showRoiDuration, roiLabel)

    # fig.show()        # bug-fixing only

    if fig is None:
        logMessage = "No figure produced"
        log("\n"+logMessage)
        message += logMessage
        return None, message
    figLegend = "\n".join(logStrings)

    # print figLegend    # bug fixing only
    format = commandArgs["Format"]

    figureName = "movieROIFigure"
    if "Figure_Name" in commandArgs:
        figureName = commandArgs["Figure_Name"]
        figureName = os.path.basename(figureName)
    output = "localfile"
    if format == 'PNG':
        output = output + ".png"
        figureName = figureName + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figureName = figureName + ".tiff"
        fig.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figureName = figureName + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Use util method to upload the figure 'output' to the server, attaching
    # it to the omeroImage, adding the
    # figLegend as the fileAnnotation description.
    # Returns the id of the originalFileLink child. (ID object, not value)
    namespace = NSCREATED + "/omero/figure_scripts/Movie_ROI_Figure"
    fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(
        conn, output, omeroImage, output="Movie ROI figure",
        mimetype=mimetype, ns=namespace, desc=figLegend,
        origFilePathAndName=figureName)
    message += faMessage

    return fileAnnotation, message
Esempio n. 8
0
def splitViewFigure(conn, scriptParams):
    """
    Processes the arguments, populating defaults if necessary. Prints the details to log (fig-legend).
    Even handles missing arguments that are not optional (from when this ran from commandline with everything optional)
    then calls makeSplitViewFigure() to make the figure, attaches it to the Image as an 'originalFile' annotation,
    with fig-legend as the description. 
    
    @return: the id of the originalFileLink child. (ID object, not value) 
    """

    log("Split-View figure created by OMERO on %s" % date.today())
    log("")

    message = ""  # message to be returned to the client
    imageIds = []
    pixelIds = []
    imageLabels = []

    # function for getting image labels.
    def getLabels(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]

    # default function for getting labels is getName (or use datasets / tags)
    if scriptParams["Image_Labels"] == "Datasets":

        def getDatasets(name, tagsList, pdList):
            return [dataset for project, dataset in pdList]

        getLabels = getDatasets
    elif scriptParams["Image_Labels"] == "Tags":

        def getTags(name, tagsList, pdList):
            return tagsList

        getLabels = getTags

    # Get the images
    images, logMessage = scriptUtil.getObjects(conn, scriptParams)
    message += logMessage
    if not images:
        return None, message

    # Attach figure to the first image
    omeroImage = images[0]

    # process the list of images
    log("Image details:")
    for image in images:
        imageIds.append(image.getId())
        pixelIds.append(image.getPrimaryPixels().getId())

    pdMap = figUtil.getDatasetsProjectsFromImages(
        conn.getQueryService(),
        imageIds)  # a map of imageId : list of (project, dataset) names.
    tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        imageDate = image.getAcquisitionDate()
        iId = image.getId()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]

        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        log("  Date: %s" % date.fromtimestamp(imageDate / 1000))
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)

        imageLabels.append(getLabels(name, tagsList, pdList))

    # use the first image to define dimensions, channel colours etc.
    sizeX = omeroImage.getSizeX()
    sizeY = omeroImage.getSizeY()
    sizeZ = omeroImage.getSizeZ()
    sizeC = omeroImage.getSizeC()

    # set image dimensions
    zStart = -1
    zEnd = -1
    if "Z_Start" in scriptParams:
        zStart = scriptParams["Z_Start"]
    if "Z_End" in scriptParams:
        zEnd = scriptParams["Z_End"]

    width = "Width" in scriptParams and scriptParams["Width"] or sizeX
    height = "Height" in scriptParams and scriptParams["Height"] or sizeY

    log("Image dimensions for all panels (pixels): width: %d  height: %d" %
        (width, height))

    # Make split-indexes list. If argument wasn't specified, include them all.
    splitIndexes = []
    if "Split_Indexes" in scriptParams:
        splitIndexes = scriptParams["Split_Indexes"]
    else:
        splitIndexes = range(sizeC)

    # Make channel-names map. If argument wasn't specified, name by index
    channelNames = {}
    for c in range(sizeC):
        channelNames[c] = str(c)
    if "Channel_Names" in scriptParams:
        cNameMap = scriptParams["Channel_Names"]
        for c in cNameMap:
            index = int(c)
            channelNames[index] = cNameMap[c]

    mergedIndexes = []  # the channels in the combined image,
    mergedColours = {}
    if "Merged_Colours" in scriptParams:
        cColourMap = scriptParams["Merged_Colours"]
        for c in cColourMap:
            rgb = cColourMap[c]
            rgba = imgUtil.RGBIntToRGBA(rgb)
            mergedColours[int(c)] = rgba
            mergedIndexes.append(int(c))
        mergedIndexes.sort()
    else:
        mergedIndexes = range(sizeC)

    colourChannels = not scriptParams["Split_Panels_Grey"]

    algorithm = omero.constants.projection.ProjectionType.MAXIMUMINTENSITY
    if "Mean Intensity" == scriptParams["Algorithm"]:
        algorithm = omero.constants.projection.ProjectionType.MEANINTENSITY

    stepping = min(scriptParams["Stepping"], sizeZ)

    scalebar = None
    if "Scalebar" in scriptParams:
        scalebar = scriptParams["Scalebar"]
        log("Scalebar is %d microns" % scalebar)

    r, g, b, a = OVERLAY_COLOURS[scriptParams["Overlay_Colour"]]
    overlayColour = (r, g, b)

    mergedNames = scriptParams["Merged_Names"]

    print "splitIndexes", splitIndexes
    print "channelNames", channelNames
    print "colourChannels", colourChannels
    print "mergedIndexes", mergedIndexes
    print "mergedColours", mergedColours
    print "mergedNames", mergedNames
    fig = makeSplitViewFigure(conn, pixelIds, zStart, zEnd, splitIndexes,
                              channelNames, colourChannels, mergedIndexes,
                              mergedColours, mergedNames, width, height,
                              imageLabels, algorithm, stepping, scalebar,
                              overlayColour)

    figLegend = "\n".join(logStrings)
    format = JPEG
    if scriptParams["Format"] == "PNG":
        format = PNG
    output = scriptParams["Figure_Name"]

    if format == PNG:
        output = output + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    else:
        output = output + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Upload the figure 'output' to the server, creating a file annotation and attaching it to the omeroImage, adding the
    # figLegend as the fileAnnotation description.
    namespace = omero.constants.namespaces.NSCREATED + "/omero/figure_scripts/Split_View_Figure"
    fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(
        conn,
        output,
        omeroImage,
        output="Split view figure",
        mimetype=mimetype,
        ns=namespace,
        desc=figLegend)
    message += faMessage

    return fileAnnotation, message
Esempio n. 9
0
def roiFigure(session, commandArgs):    
    """
        This processes the script parameters, adding defaults if needed. 
        Then calls a method to make the figure, and finally uploads and attaches this to the primary image.
        
        @param: session        The OMERO session
        @param: commandArgs        Map of String:Object parameters for the script. 
                                Objects are not rtypes, since getValue() was called when the map was processed below. 
                                But, list and map objects may contain rtypes (need to call getValue())
        
        @return:     the id of the originalFileLink child. (ID object, not value) 
    """
    
    # create the services we're going to need. 
    metadataService = session.getMetadataService()
    queryService = session.getQueryService()
    updateService = session.getUpdateService()
    rawFileStore = session.createRawFileStore()
    containerService = session.getContainerService()
    
    log("ROI figure created by OMERO on %s" % date.today())
    log("")
    
    pixelIds = []
    imageIds = []
    imageLabels = []
    imageNames = {}
    omeroImage = None    # this is set as the first image, to link figure to

    # function for getting image labels.
    def getLabels(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]
        
    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":
            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]
            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":
            def getTags(name, tagsList, pdList):
                return tagsList
            getLabels = getTags
            
    # process the list of images. If imageIds is not set, script can't run. 
    log("Image details:")
    dataType = commandArgs["Data_Type"]
    ids = commandArgs["IDs"]
    images = containerService.getImages(dataType, ids, None)

    for idCount, image in enumerate(images):
        iId = image.getId().getValue()
        imageIds.append(iId)
        if idCount == 0:
            omeroImage = image        # remember the first image to attach figure to
        pixelIds.append(image.getPrimaryPixels().getId().getValue())
        imageNames[iId] = image.getName().getValue()

    if len(imageIds) == 0:
        print "No image IDs specified."
        return
            
    pdMap = figUtil.getDatasetsProjectsFromImages(queryService, imageIds)    # a map of imageId : list of (project, dataset) names. 
    tagMap = figUtil.getTagsFromImages(metadataService, imageIds)
    # Build a legend entry for each image
    for iId in imageIds:
        name = imageNames[iId]
        imageDate = image.getAcquisitionDate().getValue()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]
        
        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        log("  Date: %s" % date.fromtimestamp(imageDate/1000))
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)
        
        imageLabels.append(getLabels(name, tagsList, pdList))
    
    # use the first image to define dimensions, channel colours etc. 
    pixelsId = pixelIds[0]
    pixels = queryService.get("Pixels", pixelsId)

    sizeX = pixels.getSizeX().getValue();
    sizeY = pixels.getSizeY().getValue();
    sizeZ = pixels.getSizeZ().getValue();
    sizeC = pixels.getSizeC().getValue();
    
    width = sizeX
    if "Width" in commandArgs:
        w = commandArgs["Width"]
        try:
            width = int(w)
        except:
            log("Invalid width: %s Using default value: %d" % (str(w), sizeX))
    
    height = sizeY
    if "Height" in commandArgs:
        h = commandArgs["Height"]
        try:
            height = int(h)
        except:
            log("Invalid height: %s Using default value" % (str(h), sizeY))
            
    log("Image dimensions for all panels (pixels): width: %d  height: %d" % (width, height))
        
    # the channels in the combined image,
    if "Merged_Channels" in commandArgs:
        mergedIndexes = [c-1 for c in commandArgs["Merged_Channels"]]  # convert to 0-based
    else:
        mergedIndexes = range(sizeC) # show all
    mergedIndexes.reverse()
        
    mergedColours = {}    # if no colours added, use existing rendering settings.
    # Actually, nicer to always use existing rendering settings.
    #if "Merged_Colours" in commandArgs:
    #    for i, c in enumerate(commandArgs["Merged_Colours"]):
    #        if c in COLOURS:
    #            mergedColours[i] = COLOURS[c]
    
    algorithm = omero.constants.projection.ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = omero.constants.projection.ProjectionType.MEANINTENSITY
    
    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s
    
    scalebar = None
    if "Scalebar" in commandArgs:
        sb = commandArgs["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None
    
    overlayColour = (255,255,255)
    if "Scalebar_Colour" in commandArgs:
        if commandArgs["Scalebar_Colour"] in OVERLAY_COLOURS: 
            r,g,b,a = OVERLAY_COLOURS[commandArgs["Scalebar_Colour"]]
            overlayColour = (r,g,b)
    
    roiZoom = None
    if "Roi_Zoom" in commandArgs:
        roiZoom = float(commandArgs["Roi_Zoom"])
        if roiZoom == 0:
            roiZoom = None
            
    maxColumns = None
    if "Max_Columns" in commandArgs:
        maxColumns = commandArgs["Max_Columns"]
        
    showRoiDuration = False
    if "Show_Roi_Duration" in commandArgs:
        showRoiDuration = commandArgs["Show_Roi_Duration"]
    
    roiLabel = "FigureROI"
    if "Roi_Selection_Label" in commandArgs:
        roiLabel = commandArgs["Roi_Selection_Label"]
                
    spacer = (width/50) + 2
    
    fig = getSplitView(session, imageIds, pixelIds, mergedIndexes, 
            mergedColours, width, height, imageLabels, spacer, algorithm, stepping, scalebar, overlayColour, roiZoom, 
            maxColumns, showRoiDuration, roiLabel)
                                                    
    #fig.show()        # bug-fixing only
    
    log("")
    figLegend = "\n".join(logStrings)
    
    #print figLegend    # bug fixing only
    
    format = JPEG
    if "Format" in commandArgs:
        if commandArgs["Format"] == "PNG":
            format = PNG
            
    output = "movieROIFigure"
    if "Figure_Name" in commandArgs:
        output = str(commandArgs["Figure_Name"])
        
    if format == PNG:
        output = output + ".png"
        fig.save(output, "PNG")
    else:
        output = output + ".jpg"
        fig.save(output)
    
    # Use util method to upload the figure 'output' to the server, attaching it to the omeroImage, adding the 
    # figLegend as the fileAnnotation description. 
    # Returns the id of the originalFileLink child. (ID object, not value)
    fileAnnotation = scriptUtil.uploadAndAttachFile(queryService, updateService, rawFileStore, omeroImage, output, format, figLegend)
    return (fileAnnotation, omeroImage)
Esempio n. 10
0
def roiFigure(conn, commandArgs):
    """
    This processes the script parameters, adding defaults if needed.
    Then calls a method to make the figure, and finally uploads and attaches
    this to the primary image.

    @param: session         The OMERO session
    @param: commandArgs     Map of String:Object parameters for the script.
                            Objects are not rtypes, since getValue() was
                            called when the map was processed below.
                            But, list and map objects may contain rtypes (need
                            to call getValue())

    @return:                the id of the originalFileLink child. (ID object,
                            not value)
    """

    log("ROI figure created by OMERO on %s" % date.today())
    log("")

    message = ""  # message to be returned to the client
    pixelIds = []
    imageIds = []
    imageLabels = []

    # function for getting image labels.
    def getImageNames(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]

    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":

            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]

            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":

            def getTags(name, tagsList, pdList):
                return tagsList

            getLabels = getTags
        else:
            getLabels = getImageNames
    else:
        getLabels = getImageNames

    # Get the images
    images, logMessage = scriptUtil.getObjects(conn, commandArgs)
    message += logMessage
    if not images:
        return None, message

    # Check for rectangular ROIs and filter images list
    images = [image for image in images if image.getROICount("Rectangle") > 0]
    if not images:
        message += "No rectangle ROI found."
        return None, message

    # Attach figure to the first image
    omeroImage = images[0]

    # process the list of images
    log("Image details:")
    for image in images:
        imageIds.append(image.getId())
        pixelIds.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pdMap = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
                                                  imageIds)
    tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        iId = image.getId()
        imageDate = image.getAcquisitionDate()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]

        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        if imageDate:
            log("  Date: %s" % imageDate)
        else:
            log("  Date: not set")
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)

        imageLabels.append(getLabels(name, tagsList, pdList))

    # use the first image to define dimensions, channel colours etc.
    sizeX = omeroImage.getSizeX()
    sizeY = omeroImage.getSizeY()
    sizeZ = omeroImage.getSizeZ()
    sizeC = omeroImage.getSizeC()

    width = sizeX
    if "Width" in commandArgs:
        w = commandArgs["Width"]
        try:
            width = int(w)
        except:
            log("Invalid width: %s Using default value: %d" % (str(w), sizeX))

    height = sizeY
    if "Height" in commandArgs:
        h = commandArgs["Height"]
        try:
            height = int(h)
        except:
            log("Invalid height: %s Using default value" % (str(h), sizeY))

    log("Image dimensions for all panels (pixels): width: %d  height: %d" %
        (width, height))

    # the channels in the combined image,
    if "Merged_Channels" in commandArgs:
        # convert to 0-based
        mergedIndexes = [c - 1 for c in commandArgs["Merged_Channels"]]
    else:
        mergedIndexes = range(sizeC)  # show all
    mergedIndexes.reverse()

    #  if no colours added, use existing rendering settings.
    mergedColours = {}
    # Actually, nicer to always use existing rendering settings.
    # if "Merged_Colours" in commandArgs:
    #     for i, c in enumerate(commandArgs["Merged_Colours"]):
    #         if c in COLOURS:
    #             mergedColours[i] = COLOURS[c]

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = ProjectionType.MEANINTENSITY

    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s

    scalebar = None
    if "Scalebar" in commandArgs:
        sb = commandArgs["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None

    overlayColour = (255, 255, 255)
    if "Scalebar_Colour" in commandArgs:
        if commandArgs["Scalebar_Colour"] in OVERLAY_COLOURS:
            r, g, b, a = OVERLAY_COLOURS[commandArgs["Scalebar_Colour"]]
            overlayColour = (r, g, b)

    roiZoom = None
    if "Roi_Zoom" in commandArgs:
        roiZoom = float(commandArgs["Roi_Zoom"])
        if roiZoom == 0:
            roiZoom = None

    maxColumns = None
    if "Max_Columns" in commandArgs:
        maxColumns = commandArgs["Max_Columns"]

    showRoiDuration = False
    if "Show_ROI_Duration" in commandArgs:
        showRoiDuration = commandArgs["Show_ROI_Duration"]

    roiLabel = "FigureROI"
    if "Roi_Selection_Label" in commandArgs:
        roiLabel = commandArgs["Roi_Selection_Label"]

    spacer = (width / 50) + 2

    print "showRoiDuration", showRoiDuration
    fig = getSplitView(conn, imageIds, pixelIds, mergedIndexes, mergedColours,
                       width, height, imageLabels, spacer, algorithm, stepping,
                       scalebar, overlayColour, roiZoom, maxColumns,
                       showRoiDuration, roiLabel)

    # fig.show()        # bug-fixing only

    if fig is None:
        logMessage = "No figure produced"
        log("\n" + logMessage)
        message += logMessage
        return None, message
    figLegend = "\n".join(logStrings)

    # print figLegend    # bug fixing only
    format = commandArgs["Format"]

    figureName = "movieROIFigure"
    if "Figure_Name" in commandArgs:
        figureName = commandArgs["Figure_Name"]
        figureName = os.path.basename(figureName)
    output = "localfile"
    if format == 'PNG':
        output = output + ".png"
        figureName = figureName + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figureName = figureName + ".tiff"
        fig.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figureName = figureName + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Use util method to upload the figure 'output' to the server, attaching
    # it to the omeroImage, adding the
    # figLegend as the fileAnnotation description.
    # Returns the id of the originalFileLink child. (ID object, not value)
    namespace = NSCREATED + "/omero/figure_scripts/Movie_ROI_Figure"
    fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(
        conn,
        output,
        omeroImage,
        output="Movie ROI figure",
        mimetype=mimetype,
        ns=namespace,
        desc=figLegend,
        origFilePathAndName=figureName)
    message += faMessage

    return fileAnnotation, message
Esempio n. 11
0
def movieFigure(conn, commandArgs):
    """
    Makes the figure using the parameters in @commandArgs, attaches the figure to the 
    parent Project/Dataset, and returns the file-annotation ID
    
    @param session        The OMERO session
    @param commandArgs    Map of parameters for the script
    @ returns            Returns the id of the originalFileLink child. (ID object, not value)
    """
    
    log("Movie figure created by OMERO on %s" % date.today())
    log("")
    
    timeLabels = {"SECS_MILLIS": "seconds",
                "SECS": "seconds",
                "MINS": "minutes",
                "HOURS": "hours",
                "MINS_SECS": "mins:secs",
                "HOURS_MINS": "hours:mins"}
    timeUnits = "SECS"
    if "timeUnits" in commandArgs:
        timeUnits = commandArgs["timeUnits"]
    if timeUnits not in timeLabels.keys():
        timeUnits = "SECS"
    log("Time units are in %s" % timeLabels[timeUnits])
    
    pixelIds = []
    imageIds = []
    imageLabels = []
    message = "" # message to be returned to the client

    # function for getting image labels.
    def getLabels(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]
        
    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":
            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]
            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":
            def getTags(name, tagsList, pdList):
                return tagsList
            getLabels = getTags
  
    # Get the images
    images, logMessage = scriptUtil.getObjects(conn, commandArgs)
    message += logMessage
    if not images:
        return None, message
    
    # Attach figure to the first image
    omeroImage = images[0]
    
    # process the list of images
    log("Image details:")
    for image in images:
        imageIds.append(image.getId())
        pixelIds.append(image.getPrimaryPixels().getId())
  
    pdMap = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(), imageIds)    # a map of imageId : list of (project, dataset) names. 
    tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        iId = image.getId()
        imageDate = image.getAcquisitionDate()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]
        
        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        log("  Date: %s" % date.fromtimestamp(imageDate/1000))
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)
        
        imageLabels.append(getLabels(name, tagsList, pdList))
    
    
    # use the first image to define dimensions, channel colours etc.
    sizeX = omeroImage.getSizeX()
    sizeY = omeroImage.getSizeY()
    sizeZ = omeroImage.getSizeZ()
    sizeC = omeroImage.getSizeC()
    sizeT = omeroImage.getSizeT()

    tIndexes = []
    if "T_Indexes" in commandArgs:
        for t in commandArgs["T_Indexes"]:
            tIndexes.append(t)
        print "T_Indexes", tIndexes
    if len(tIndexes) == 0:      # if no t-indexes given, use all t-indices
        tIndexes = range(sizeT)
            
    zStart = -1
    zEnd = -1
    if "Z_Start" in commandArgs:
        zStart = commandArgs["Z_Start"]
    if "Z_End" in commandArgs:
        zEnd = commandArgs["Z_End"]
    
    width = sizeX
    if "Width" in commandArgs:
        width = commandArgs["Width"]
    
    height = sizeY
    if "Height" in commandArgs:
        height = commandArgs["Height"]
    
    spacer = (width/25) + 2
    
    algorithm = omero.constants.projection.ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = omero.constants.projection.ProjectionType.MEANINTENSITY
    
    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s
    
    scalebar = None
    if "Scalebar_Size" in commandArgs:
        sb = commandArgs["Scalebar_Size"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None
    
    overlayColour = (255,255,255)
    if "Scalebar_Colour" in commandArgs:
        r,g,b,a = OVERLAY_COLOURS[commandArgs["Scalebar_Colour"]]
        overlayColour = (r,g,b)
                
    figure = createMovieFigure(conn, pixelIds, tIndexes, zStart, zEnd, width, height, spacer,
                            algorithm, stepping, scalebar, overlayColour, timeUnits, imageLabels)
    
    #figure.show()
    
    log("")
    figLegend = "\n".join(logLines)
    
    #print figLegend    # bug fixing only
    
    format = JPEG
    if "Format" in commandArgs:
        if commandArgs["Format"] == "PNG":
            format = PNG
            
    output = "movieFigure"
    if "Figure_Name" in commandArgs:
        output = str(commandArgs["Figure_Name"])
        
    if format == PNG:
        output = output + ".png"
        figure.save(output, "PNG")
        mimetype = "image/png"
    else:
        output = output + ".jpg"
        figure.save(output)
        mimetype = "image/jpeg"
    
    namespace = omero.constants.namespaces.NSCREATED+"/omero/figure_scripts/Movie_Figure"
    fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(conn, output, omeroImage, 
    output="Movie figure", mimetype=mimetype, ns=namespace, desc=figLegend)
    message += faMessage
    
    return fileAnnotation, message
def movieFigure(session, commandArgs):    
    """
    Makes the figure using the parameters in @commandArgs, attaches the figure to the 
    parent Project/Dataset, and returns the file-annotation ID
    
    @param session        The OMERO session
    @param commandArgs    Map of parameters for the script
    @ returns            Returns the id of the originalFileLink child. (ID object, not value)
    """
    
    # create the services we're going to need. 
    metadataService = session.getMetadataService()
    queryService = session.getQueryService()
    updateService = session.getUpdateService()
    rawFileStore = session.createRawFileStore()
    containerService = session.getContainerService()
    
    log("Movie figure created by OMERO on %s" % date.today())
    log("")
    
    timeLabels = {"SECS_MILLIS": "seconds",
                "SECS": "seconds",
                "MINS": "minutes",
                "HOURS": "hours",
                "MINS_SECS": "mins:secs",
                "HOURS_MINS": "hours:mins"}
    timeUnits = "SECS"
    if "timeUnits" in commandArgs:
        timeUnits = commandArgs["timeUnits"]
    if timeUnits not in timeLabels.keys():
        timeUnits = "SECS"
    log("Time units are in %s" % timeLabels[timeUnits])
    
    pixelIds = []
    imageIds = []
    imageLabels = []
    imageNames = {}
    omeroImage = None    # this is set as the first image, to link figure to

    # function for getting image labels.
    def getLabels(fullName, tagsList, pdList):
        name = fullName.split("/")[-1]
        return [name]
        
    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in commandArgs:
        if commandArgs["Image_Labels"] == "Datasets":
            def getDatasets(name, tagsList, pdList):
                return [dataset for project, dataset in pdList]
            getLabels = getDatasets
        elif commandArgs["Image_Labels"] == "Tags":
            def getTags(name, tagsList, pdList):
                return tagsList
            getLabels = getTags
            
    # process the list of images. If imageIds is not set, script can't run. 
    log("Image details:")
    for idCount, imageId in enumerate(commandArgs["IDs"]):
        iId = long(imageId.getValue())
        image = containerService.getImages("Image", [iId], None)[0]
        if image == None:
            print "Image not found for ID:", iId
            continue
        imageIds.append(iId)
        if idCount == 0:
            omeroImage = image        # remember the first image to attach figure to
        pixelIds.append(image.getPrimaryPixels().getId().getValue())
        imageNames[iId] = image.getName().getValue()
        
    if len(imageIds) == 0:
        print "No image IDs specified."
    
    pdMap = figUtil.getDatasetsProjectsFromImages(queryService, imageIds)    # a map of imageId : list of (project, dataset) names. 
    tagMap = figUtil.getTagsFromImages(metadataService, imageIds)
    # Build a legend entry for each image
    for iId in imageIds:
        name = imageNames[iId]
        imageDate = image.getAcquisitionDate().getValue()
        tagsList = tagMap[iId]
        pdList = pdMap[iId]
        
        tags = ", ".join(tagsList)
        pdString = ", ".join(["%s/%s" % pd for pd in pdList])
        log(" Image: %s  ID: %d" % (name, iId))
        log("  Date: %s" % date.fromtimestamp(imageDate/1000))
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pdString)
        
        imageLabels.append(getLabels(name, tagsList, pdList))
    
    
    # use the first image to define dimensions, channel colours etc. 
    pixelsId = pixelIds[0]
    pixels = queryService.get("Pixels", pixelsId)
                
    sizeX = pixels.getSizeX().getValue()
    sizeY = pixels.getSizeY().getValue()
    sizeZ = pixels.getSizeZ().getValue()
    sizeC = pixels.getSizeC().getValue()
    sizeT = pixels.getSizeT().getValue()

    tIndexes = []
    if "T_Indexes" in commandArgs:
        for t in commandArgs["T_Indexes"]:
            tIndexes.append(t.getValue())
        print "T_Indexes", tIndexes
    if len(tIndexes) == 0:      # if no t-indexes given, use all t-indices
        tIndexes = range(sizeT)
            
    zStart = -1
    zEnd = -1
    if "Z_Start" in commandArgs:
        zStart = commandArgs["Z_Start"]
    if "Z_End" in commandArgs:
        zEnd = commandArgs["Z_End"]
    
    width = sizeX
    if "Width" in commandArgs:
        width = commandArgs["Width"]
    
    height = sizeY
    if "Height" in commandArgs:
        height = commandArgs["Height"]
    
    spacer = (width/25) + 2
    
    algorithm = omero.constants.projection.ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in commandArgs:
        a = commandArgs["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = omero.constants.projection.ProjectionType.MEANINTENSITY
    
    stepping = 1
    if "Stepping" in commandArgs:
        s = commandArgs["Stepping"]
        if (0 < s < sizeZ):
            stepping = s
    
    scalebar = None
    if "Scalebar_Size" in commandArgs:
        sb = commandArgs["Scalebar_Size"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None
    
    overlayColour = (255,255,255)
    if "Scalebar_Colour" in commandArgs:
        r,g,b,a = OVERLAY_COLOURS[commandArgs["Scalebar_Colour"]]
        overlayColour = (r,g,b)
                
    figure = createMovieFigure(session, pixelIds, tIndexes, zStart, zEnd, width, height, spacer, 
                            algorithm, stepping, scalebar, overlayColour, timeUnits, imageLabels)
    
    #figure.show()
    
    log("")
    figLegend = "\n".join(logLines)
    
    #print figLegend    # bug fixing only
    
    format = JPEG
    if "Format" in commandArgs:
        if commandArgs["Format"] == "PNG":
            format = PNG
            
    output = "movieFigure"
    if "Figure_Name" in commandArgs:
        output = str(commandArgs["Figure_Name"])
        
    if format == PNG:
        output = output + ".png"
        figure.save(output, "PNG")
    else:
        output = output + ".jpg"
        figure.save(output)
    

    fileAnnotation = scriptUtil.uploadAndAttachFile(queryService, updateService, rawFileStore, omeroImage, output, format, figLegend)
    return (fileAnnotation, omeroImage)