Beispiel #1
0
def run(name, password, dataset_name, dataset_id, host, port):

    conn = BlitzGateway(name, password, host=host, port=port)
    try:
        conn.connect()
        roi_service = conn.getRoiService()
        datasets = []
        if dataset_id >= 0:
            datasets.append(conn.getObject("Dataset", dataset_id))
        else:
            datasets = conn.getObjects("Dataset",
                                       attributes={"name": dataset_name})
        for dataset in datasets:
            print(dataset.getId())
            for image in dataset.listChildren():
                result = roi_service.findByImage(image.getId(), None,
                                                 conn.SERVICE_OPTS)
                if result is not None:
                    roi_ids = [roi.id.val for roi in result.rois]
                    if len(roi_ids) > 0:
                        print("Deleting %s ROIs..." % len(roi_ids))
                        conn.deleteObjects("Roi", roi_ids, wait=True)
    except Exception as exc:
        print("Error while deleting Rois: %s" % str(exc))
    finally:
        conn.close()
Beispiel #2
0
def run(name, password, dataset_name, anntype, ns, host, port):

    conn = BlitzGateway(name, password, host=host, port=port)
    try:
        conn.connect()
        datasets = conn.getObjects("Dataset",
                                   attributes={"name": dataset_name})
        for dataset in datasets:
            print dataset.getId()
            ann_ids = []
            given_type = None
            if anntype == "map":
                given_type = omero.model.MapAnnotationI
            if anntype == "file":
                given_type = omero.model.FileAnnotationI
            if ns == "none":
                ns = None
            for image in dataset.listChildren():
                for a in image.listAnnotations(ns):
                    if a.OMERO_TYPE == given_type:
                        print a.getId(), a.OMERO_TYPE, a.ns
                        ann_ids.append(a.id)
            # Delete the annotations link to the dataset
            for a in dataset.listAnnotations(ns):
                if a.OMERO_TYPE == given_type:
                    print a.getId(), a.OMERO_TYPE, a.ns
                    ann_ids.append(a.id)
            if len(ann_ids) > 0:
                print "Deleting %s annotations..." % len(ann_ids)
                conn.deleteObjects('Annotation', ann_ids, wait=True)
    except Exception as exc:
        print "Error while deleting annotations: %s" % str(exc)
    finally:
        conn.close()
    def testSimpleDelete(self):
        filename = self.unique_dir + "/file.txt"
        mrepo = self.getManagedRepo()
        ofile = self.createFile(mrepo, filename)
        gateway = BlitzGateway(client_obj=self.client)

        # Assert contents of file
        rfs = mrepo.fileById(ofile.id.val)
        try:
            assert "hi" ==  rfs.read(0, 2)
        finally:
            rfs.close()

        handle = gateway.deleteObjects("/OriginalFile", [ofile.id.val])
        try:
            gateway._waitOnCmd(handle)
        finally:
            handle.close()

        # Trying to open the file should not throw an UnregisteredFileException
        # But should just be an empty file.
        rfs = mrepo.file(filename, "rw")
        try:
            assert "\x00\x00" ==  rfs.read(0, 2)
        finally:
            rfs.close()
Beispiel #4
0
    def testSimpleDelete(self):
        filename = self.unique_dir + "/file.txt"
        mrepo = self.get_managed_repo()
        ofile = self.create_file(mrepo, filename)
        gateway = BlitzGateway(client_obj=self.client)

        # Assert contents of file
        rfs = mrepo.fileById(ofile.id.val)
        try:
            assert "hi" == rfs.read(0, 2)
        finally:
            rfs.close()

        handle = gateway.deleteObjects("OriginalFile", [ofile.id.val])
        try:
            gateway._waitOnCmd(handle)
        finally:
            handle.close()

        # Trying to open the file should not throw an UnregisteredFileException
        # But should just be an empty file.
        rfs = mrepo.file(filename, "rw")
        try:
            assert "\x00\x00" == rfs.read(0, 2)
        finally:
            rfs.close()
Beispiel #5
0
    def testCmdDeleteCantDeleteDirectories(self):
        id = self.dir_map[self.dir_key]["id"]

        gateway = BlitzGateway(client_obj=self.client)
        handle = gateway.deleteObjects("OriginalFile", [id])
        try:
            with pytest.raises(CmdError):
                gateway._waitOnCmd(handle, failonerror=True)
        finally:
            handle.close()
    def testCmdDeleteCantDeleteDirectories(self):
        id = self.dir_map[self.dir_key]["id"]

        gateway = BlitzGateway(client_obj=self.client)
        handle = gateway.deleteObjects("/OriginalFile", [id])
        try:
            pytest.raises(Exception,
                    gateway._waitOnCmd, handle, failonerror=True)
        finally:
            handle.close()
Beispiel #7
0
#
# 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.
#
# ------------------------------------------------------------------------------

# Delete Annotations of a particular namespace from all Images in a Dataset

from omero.gateway import BlitzGateway

USERNAME = "******"
PASSWORD = "******"
conn = BlitzGateway(USERNAME,
                    PASSWORD,
                    host="outreach.openmicroscopy.org",
                    port=4064)
conn.connect()

# Edit these values
dataset_id = 4501
ns = "omero.batch_roi_export.map_ann"

dataset = conn.getObject("Dataset", dataset_id)

for image in dataset.listChildren():
    ann_ids = [a.id for a in image.listAnnotations(ns)]
    if len(ann_ids) > 0:
        print "Deleting %s anns..." % len(ann_ids)
        conn.deleteObjects('Annotation', ann_ids)

project_id1 = create_project()
project_id2 = create_project()

# Delete Project
# ==============
# You can delete a number of objects of the same type at the same
# time. In this case 'Project'. Use deleteChildren=True if you are
# deleting a Project and you want to delete Datasets and Images.
# We use wait=True so that the async delete completes.
obj_ids = [project_id1]
delete_children = False
conn.deleteObjects("Project",
                   obj_ids,
                   deleteAnns=True,
                   deleteChildren=delete_children,
                   wait=True)

# Delete Project, handling response
# =================================
# If you want to know when delete is finished or if there were
# any errors, then we can use a callback to wait for response
handle = conn.deleteObjects("Project", [project_id2])
cb = omero.callbacks.CmdCallbackI(conn.c, handle)
print("Deleting, please wait.")
while not cb.block(500):
    print(".")
err = isinstance(cb.getResponse(), omero.cmd.ERR)
print("Error?", err)
if err:
    for ann in obj.listAnnotations(ns=namespace):
        kv = ann.getValue()
        to_delete.append(ann.id)

#for dataset in conn.getObjects("Dataset", ids):
    suconn = conn.suConn(
        owner
    )  #this line has been introduced to allow sysadmin to copy kvpairs on behalf of the owner's image
    map_ann = omero.gateway.MapAnnotationWrapper(
        suconn
    )  #this line tells that the connection to the Map annotation is done by sysadmin but with the name of the owner of the data
    map_ann.setNs(namespace)
    map_ann.setValue(data)
    map_ann.save()
    obj.linkAnnotation(map_ann)
    suconn.close(
    )  #this line is necessary to "close" also the connection as "other user" as the sysadmin is now concluding to operate on behalf of the owner of the image

    if len(to_delete) > 0:
        conn.deleteObjects('Annotation', to_delete)

# Return some value(s).

# Here, we return anything useful the script has produced.
# NB: The Insight and web clients will display the "Message" output.

msg = "Script ran OK"
client.setOutput("Message", rstring(msg))

client.closeSession()
Beispiel #10
0
project = conn.getObject("Project", projectId)
if project is None:
    import sys
    sys.stderr.write("Error: Object does not exist.\n")
    sys.exit(1)

print "\nProject:", project.getName()

# Delete Project
# =================================================================
# You can delete a number of objects of the same type at the same
# time. In this case 'Project'. Use deleteChildren=True if you are
# deleting a Project and you want to delete Datasets and Images.
obj_ids = [projectId]
deleteChildren = False
handle = conn.deleteObjects("Project", obj_ids,\
        deleteAnns=True, deleteChildren=deleteChildren)

# Retrieve callback and wait until delete completes
# =================================================================
# This is not necessary for the Delete to complete. Can be used
# if you want to know when delete is finished or if there were any errors
cb = omero.callbacks.CmdCallbackI(conn.c, handle)
print "Deleting, please wait."
while not cb.block(500):
    print "."
err = isinstance(cb.getResponse(), omero.cmd.ERR)
print "Error?", err
if err:
    print cb.getResponse()
cb.close(True)  # close handle too
Beispiel #11
0

projectId1 = createProject()
projectId2 = createProject()


# Delete Project
# ==============
# You can delete a number of objects of the same type at the same
# time. In this case 'Project'. Use deleteChildren=True if you are
# deleting a Project and you want to delete Datasets and Images.
# We use wait=True so that the async delete completes.
obj_ids = [projectId1]
deleteChildren = False
conn.deleteObjects(
    "Project", obj_ids, deleteAnns=True,
    deleteChildren=deleteChildren, wait=True)


# Delete Project, handling response
# =================================
# If you want to know when delete is finished or if there were
# any errors, then we can use a callback to wait for response
handle = conn.deleteObjects("Project", [projectId2])
cb = omero.callbacks.CmdCallbackI(conn.c, handle)
print "Deleting, please wait."
while not cb.block(500):
    print "."
err = isinstance(cb.getResponse(), omero.cmd.ERR)
print "Error?", err
if err:
class TableConnection(object):
    """
    A basic client-side wrapper for OMERO.tables which handles opening
    and closing tables.
    """

    def __init__(self, user = None, passwd = None, host = 'localhost',
                 client = None, tableName = None, tableId = None):
        """
        Create a new table handler, either by specifying user and passwd or by
        providing a client object (for scripts)
        @param user Username
        @param passwd Password
        @param host The server hostname
        @param client Client object with an active session
        @param tableName The name of the table file
        @param tableId The OriginalFile ID of the table file
        """
        if not client:
            client = omero.client(host)
            sess = client.createSession(user, passwd)
            client.enableKeepAlive(60)
        else:
             sess = client.getSession()

        self.conn = BlitzGateway(client_obj = client)

        self.res = sess.sharedResources()
        if (not self.res.areTablesEnabled()):
            raise TableConnectionError('OMERO.tables not enabled')

        repos = self.res.repositories()
        self.rid = repos.descriptions[0].id.val

        self.tableName = tableName
        self.tableId = tableId
        self.table = None

    def __enter__(self):
        print 'Entering Connection'
        return self

    def __exit__(self, type, value, traceback):
        print 'Exiting Connection'
        self.close()

    def close(self):
        print 'Closing Connection'
        try:
            self.closeTable()
        finally:
            self.conn._closeSession()


    def openTable(self, tableId = None, tableName = None):
        """
        Opens an existing table by ID or name.
        If there are multiple tables with the same name this throws an error
        (should really use an annotation to keep track of this).
        If tableId is supplied it will be used in preference to tableName
        @param tableName The name of the table file
        @param tableId The OriginalFile ID of the table file
        @return handle to the table
        """
        if not tableId and not tableName:
            tableId = self.tableId
            tableName = self.tableName

        if not tableId:
            if not tableName:
                tableName = self.tableName
            attrs = {'name': tableName}
            ofiles = list(
                self.conn.getObjects("OriginalFile", attributes = attrs))
            if len(ofiles) > 1:
                raise TableConnectionError(
                    'Multiple tables with name:%s found' % tableName)
            if not ofiles:
                raise TableConnectionError(
                    'No table found with name:%s' % tableName)
            ofile = ofiles[0]
        else:
            attrs = {'id': long(tableId)}
            if tableName:
                attrs['name'] = tableName
            ofile = self.conn.getObject("OriginalFile", attributes = attrs)

        if not ofile:
            raise TableConnectionError('No table found with name:%s id:%s' %
                                       (tableName, tableId))

        if self.tableId == ofile.getId():
            print 'Using existing connection to table name:%s id:%d' % \
                (tableName, tableId)
        else:
            self.closeTable()
            self.table = self.res.openTable(ofile._obj)
            self.tableId = ofile.getId()
            print 'Opened table name:%s id:%d' % (tableName, self.tableId)

        try:
            print '\t%d rows %d columns' % \
                (self.table.getNumberOfRows(), len(self.table.getHeaders()))
        except omero.ApiUsageException:
            pass

        self.tableId = tableId
        return self.table


    def deleteAllTables(self):
        """
        Delete all tables with self.tableName
        Will fail if there are any annotation links
        """
        ofiles = self.conn.getObjects("OriginalFile", \
            attributes = {'name': self.tableName})
        ids = [f.getId() for f in ofiles]
        print 'Deleting ids:%s' % ids
        self.conn.deleteObjects('OriginalFile', ids)


    def dumpTable(self, table):
        """
        Print out the table
        """
        headers = table.getHeaders()
        print ', '.join([t.name for t in headers])
        nrows = table.getNumberOfRows()
        #data = table.readCoordinates(xrange(table.getNumberOfRows))

        for r in xrange(nrows):
            data = table.read(range(len(headers)), r, r + 1)
            print ', '.join(['%.2f' % c.values[0] for c in data.columns])


    def closeTable(self):
        """
        Close the table if open, and set table and tableId to None
        """
        try:
            if self.table:
                self.table.close()
        finally:
            self.table = None
            self.tableId = None


    def newTable(self, schema):
        """
        Create a new uninitialised table
        @param schema the table description
        @return A handle to the table
        """
        self.closeTable()

        self.table = self.res.newTable(self.rid, self.tableName)
        ofile = self.table.getOriginalFile()
        self.tableId = ofile.getId().getValue()

        try:
            self.table.initialize(schema)
            print "Initialised '%s' (%d)" % (self.tableName, self.tableId)
        except Exception as e:
            print "Failed to create table: %s" % e
            try:
                self.table.delete
            except Exception as ed:
                print "Failed to delete table: %s" % ed

            self.table = None
            self.tableId = None
            raise e

        return self.table


    def chunkedRead(self, colNumbers, start, stop, chunk):
        """
        Split a call to table.read(), into multiple chunks to limit the number
        of rows returned in one go.
        @param colNumbers A list of columns indices to be read
        @param start The first row to be read
        @param stop The last + 1 row to be read
        @param chunk The maximum number of rows to read in each call
        @return a data object, note lastModified will be set to the timestamp
        the first chunked call
        """
        p = start
        q = min(start + chunk, stop)
        data = self.table.read(colNumbers, p, q)
        p, q = q, min(q + chunk, stop)

        while p < stop:
            data2 = self.table.read(colNumbers, p, q)
            data.rowNumbers.extend(data2.rowNumbers)
            for (c, c2) in izip(data.columns, data2.columns):
                c.values.extend(c2.values)
            p, q = q, min(q + chunk, stop)

        return data
Beispiel #13
0
            shape['height'] = s.getHeight().getValue()
        elif type(s) in (omero.model.LabelI, omero.model.PolygonI):
            print type(s), " Not supported by this code"
        # Do some processing here, or just print:
        print "   Shape:",
        for key, value in shape.items():
            print "  ", key, value,
        print ""

# Remove shape from ROI
# =====================
result = roiService.findByImage(imageId, None)
for roi in result.rois:
    for s in roi.copyShapes():
        # Find and remove the Shape we added above
        if s.getTextValue() and s.getTextValue().getValue() == "test-Ellipse":
            print "Removing Shape from ROI..."
            roi.removeShape(s)
            roi = updateService.saveAndReturnObject(roi)

# Delete ROIs and all the Shapes they contain
# ===========================================
roiToDelete = createROI(image, [rect])
print "Deleting ROI:", roi.id.val
conn.deleteObjects("Roi", [roi.id.val], wait=True)

# Close connection
# ================
# When you are done, close the session to free up server resources.
conn._closeSession()
Beispiel #14
0
for obj in object_list:
    # for each object load the annotation (append)
    for ann in obj.listAnnotations():
        if ann.OMERO_TYPE == omero.model.TagAnnotationI:
            if ann.getTextValue() in tag_names:
                if isinstance(obj, omero.gateway.ImageWrapper):
                    link_to_delete_images.append(ann.link.getId())
                elif isinstance(obj, omero.gateway.DatasetWrapper):
                    link_to_delete_datasets.append(ann.link.getId())
                elif isinstance(obj, omero.gateway.ProjectWrapper):
                    link_to_delete_projects.append(ann.link.getId())

#if there is a tag name in the object specific list, then delete
if len(link_to_delete_images) > 0:
    conn.deleteObjects("ImageAnnotationLink", link_to_delete_images)
if len(link_to_delete_datasets) > 0:
    conn.deleteObjects("DatasetAnnotationLink", link_to_delete_datasets)
if len(link_to_delete_projects) > 0:
    conn.deleteObjects("ProjectAnnotationLink", link_to_delete_projects)

# Return some value(s).

# Here, we return anything useful the script has produced.
# NB: The Insight and web clients will display the "Message" output.

msg = "Script ran OK"
client.setOutput("Message", rstring(msg))

client.closeSession()
Beispiel #15
0
class OMEROConnection(object):
    def __init__(self, args, configs):
        self.args = args
        self.configs = configs
        self.connect_with = self.configs['CONNECT_WITH']
        self.host = self.configs['OMERO_{}_HOST'.format(self.connect_with)]
        self.user = self.configs['OMERO_{}_USER'.format(self.connect_with)]
        self.password = self.configs['OMERO_{}_PASSWORD'.format(
            self.connect_with)]
        self.port = self.configs['OMERO_{}_PORT'.format(self.connect_with)]

    def __enter__(self):
        from omero.gateway import BlitzGateway  # @UnresolvedImport
        self.conn = BlitzGateway(host=self.host,
                                 username=self.user,
                                 passwd=self.password,
                                 port=self.port)
        self.connected = self.conn.connect()
        # failed to connect
        if not self.connected:
            print_date(
                "Unable to connect to host '{}' on port {} using user '{}'".
                format(self.host, self.port, self.user))
            print_date("Check that server is up")
            sys.exit(1)
        # keepalive
        self.conn.c.enableKeepAlive(5)
        self.omero_user = self.conn.getUser()
        self.userId = self.omero_user.getId()
        self.updateService = self.conn.getUpdateService()
        self.roiService = self.conn.getRoiService()
        return self

    def __exit__(self, exc_type, exc_value, traceback):  # @UnusedVariable
        self.conn._closeSession()
        if self.args.verbose:
            print_date('Connection closed.')
        self.connected = False

    def list(self):
        """List images or ROIs
        
        :return int count: the number of images/ROIs
        """
        if self.args.images:
            print_date("Listing images...")
            images = self.images()
            if self.args.summary:
                pass
            else:
                print_date("Structuring output...")
                image_view = ImageView(images)
                print(image_view)
            return len(images)
        elif self.args.rois:
            print_date("Listing ROIs...")
            rois = self.rois()
            if self.args.summary:
                pass
            else:
                print_date("Structuring output...")
                roi_view = ROIView(rois)
                print(roi_view)
            return len(rois)

    @property
    def projects(self):
        if self.args.project is not None:
            projects = self.conn.searchObjects(["Project"], self.args.project)
            return projects
        else:
            return self.conn.listProjects(self.userId)

    def datasets(self, project=None):
        """List the datasets associated with the current user
        
        :param project: a project
        :param bool in_project: are these datasets contained within a project?
        """
        datasets = list()
        if self.args.dataset is not None:
            datasets += self.conn.searchObjects(["Dataset"], self.args.dataset)
        else:
            if project is not None:
                projects = self.conn.searchObjects(["Project"], project)
                for p in projects:
                    datasets += p.listChildren()
            else:
                params = omero.sys.ParametersI()  # @UndefinedVariable
                params.exp(self.userId)
                datasets += self.conn.getObjects("Dataset", params=params)
        return datasets

    def images(self, project=None, dataset=None):
        """The list of images associated with the current user
        
        If the image ID is specified only the required image is returned. (The project and dataset are ignored.)
        
        Otherwise:
        
        - If a project object is provided all images in all datasets in the project are returned. (The dataset is ignored.)
        - If a project object and dataset object are provided then only those images in the project and dataset are return.
        - If no project object is provided but a dataset object is provided then only those images in the dataset are returned. 
         
        :param str project: OMERO project name
        :param str dataset: OMERO dataset name
        :return list images: a list of OMERO ``Image`` objects
        """
        # assertions
        images = list()
        print_date("Retrieving images...")
        if self.args.image_id is not None:
            try:
                assert isinstance(self.args.image_id, int) or isinstance(
                    self.args.image_id, long)
            except AssertionError:
                print_date("Invalid type for image ID: {}".format(
                    type(self.args.image_id)))
                sys.exit(1)
            image = self.getImage(self.args.image_id)
            if image is not None:
                images.append(image)
        elif self.args.image_name is not None:
            images = self.conn.searchObjects(["Image"], self.args.image_name)
        else:
            if project is not None:  # project specified
                print_date(
                    "Searching for images in project '{}'".format(project))
                # get all projects matching
                projects = self.conn.searchObjects(["Project"], project)
                # get all datasets in projects matching
                datasets_in_projects = dict()
                for p in projects:
                    for d in p.listChildren():
                        datasets_in_projects[d.getName()] = d
                print_date("Found {} datasets in project '{}'".format(
                    len(datasets_in_projects), project))
                # dataset specified
                if dataset is not None:
                    print_date(
                        "Searching for images in dataset '{}'".format(dataset))
                    if dataset in datasets_in_projects.keys():
                        images += datasets_in_projects[dataset].listChildren()
                else:  # dataset not specified
                    print_date(
                        "Searching for images in all {} datasets".format(
                            len(datasets_in_projects)))
                    for dataset in datasets_in_projects.keys():
                        images += datasets_in_projects[dataset].listChildren()
            else:  # project not specified
                # dataset specified
                if dataset is not None:
                    print_date(
                        "Searching for images in dataset '{}'".format(dataset))
                    datasets = self.conn.searchObjects(["Dataset"], dataset)
                    for dataset in datasets:
                        images += dataset.listChildren()
                else:
                    datasets = self.datasets()
                    print_date(
                        "Searching for images in all {} datasets".format(
                            len(datasets)))
                    for dataset in datasets:
                        images += dataset.listChildren()
        print_date("Found {} image(s).".format(len(images)))
        return images

    def getImage(self, image_id):
        """Get the image with the image ID specified on the command line
        
        :param int image_id: command line arguments
        :return image: an image
        :rtype image: ``OMEROImage``
        """
        return self.conn.getObject("Image", image_id)

    def rois(self, project=None, dataset=None):
        """Get an iterator over the ROIs associated with the specified image ID
        
        :param int image_id: image ID
        """
        rois = list()
        print_date("Retrieving ROIs...")
        if self.args.image_id is not None:
            return self.getROIs(self.args.image_id)
        else:
            for image in self.images(project, dataset):
                if image.getROICount() > 0:
                    rois.append((image, self.getROIs(image.getId())))
        roi_count = sum(map(lambda r: len(r[1]), rois))
        print_date("Found {:,} ROIs in {:,} images.".format(
            roi_count, len(rois)))
        return rois

    def getROIs(self, image_id):
        result = self.roiService.findByImage(image_id, None)
        return result.rois

    def attachRois(self, omero_rois):
        """Attach the rois from the iterable"""
        non_rois = filter(lambda r: not isinstance(r, OMEROROI), omero_rois)
        try:
            assert len(non_rois) == 0
        except AssertionError:
            print_date("Found {:,} non-ROI objects".format(len(non_rois)))
            return 1
        for roi in omero_rois:
            self.saveRoi(roi)
        return os.EX_OK

    # save
    def saveRoi(self, roi):
        """Save the given ROI
        
        :param roi: an ROI object
        :type roi: `omero.model.Roi`
        """
        import Ice
        try:
            self.updateService.saveObject(roi)
        except Ice.MemoryLimitException as e:  # @UndefinedVariable
            print_date(str(e))
            sys.exit(1)

    # delete
    def deleteRoi(self, roi_id):
        """
        Delete the given ROI
        
        :param roi: an ROI object
        :type roi: `omero.model.Roi`
        """
        from omero.callbacks import CmdCallbackI  # @UnresolvedImport

        handle = self.conn.deleteObjects("Roi", [roi_id],
                                         deleteAnns=True,
                                         deleteChildren=True)
        callback = CmdCallbackI(self.conn.c, handle)

        while not callback.block(500):
            if self.args.verbose:
                print_date(".", newline=False, incl_date=False)
                time.sleep(2)

        callback.close(True)
Beispiel #16
0
        #print tag.textValue, owner
        tags.append([tag.textValue, str(tag.id), str(owner)])

    #sort the tags in descending order to allow to see duplicates

    tags.sort(key=lambda tag: tag[0].lower())
    print "sorted tags", tags

    prev_tag = ""
    prev_id = 0
    for t in tags:
        tag_id = str(t[1])
        if t[0] == prev_tag:
            # move all tagged objects to previous tags and delete
            for link in conn.getAnnotationLinks('Image', ann_ids=[tag_id]):
                link._obj.child = omero.model.TagAnnotationI(prev_id, False)
                link.save()
            conn.deleteObjects('TagAnnotation', [tag_id])
        prev_tag = t[0]
        prev_id = tag_id

# Return some value(s).

# Here, we return anything useful the script has produced.
# NB: The Insight and web clients will display the "Message" output.

msg = "Script ran OK"
client.setOutput("Message", rstring(msg))

client.closeSession()
Beispiel #17
0
    import sys

    sys.stderr.write("Error: Object does not exist.\n")
    sys.exit(1)

print "\nProject:", project.getName()


# Delete Project
# =================================================================
# You can delete a number of objects of the same type at the same
# time. In this case 'Project'. Use deleteChildren=True if you are
# deleting a Project and you want to delete Datasets and Images.
obj_ids = [projectId]
deleteChildren = False
handle = conn.deleteObjects("Project", obj_ids, deleteAnns=True, deleteChildren=deleteChildren)


# Retrieve callback and wait until delete completes
# =================================================================
# This is not necessary for the Delete to complete. Can be used
# if you want to know when delete is finished or if there were any errors
cb = omero.callbacks.CmdCallbackI(conn.c, handle)
print "Deleting, please wait."
while not cb.block(500):
    print "."
err = isinstance(cb.getResponse(), omero.cmd.ERR)
print "Error?", err
if err:
    print cb.getResponse()
cb.close(True)  # close handle too
Beispiel #18
0
# List all annotations on an object. Get text from tags
# ===========================================================
for ann in project.listAnnotations():
    print(ann.getId(), ann.OMERO_TYPE, end=' ')
    print(" added by ", ann.link.getDetails().getOwner().getOmeName())
    if ann.OMERO_TYPE == omero.model.TagAnnotationI:
        print("Tag value:", ann.getTextValue())

# Remove Annotations from an Object (delete link)
project = conn.getObject("Project", projectId)
to_delete = []
for ann in project.listAnnotations():
    if ann.ns != namespace:
        to_delete.append(ann.link.id)
conn.deleteObjects("ProjectAnnotationLink", to_delete, wait=True)

# Delete Annotations from an Object
to_delete = []
# Optionally to filter by namespace
for ann in project.listAnnotations(ns=namespace):
    to_delete.append(ann.id)
conn.deleteObjects('Annotation', to_delete, wait=True)

# How to create a file annotation and link to a Dataset
# =====================================================
dataset = conn.getObject("Dataset", dataset_id)
# Specify a local file e.g. could be result of some analysis
file_to_upload = "README.txt"  # This file should already exist
with open(file_to_upload, 'w') as f:
    f.write('annotation test')
Beispiel #19
0
#  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.
#
# ------------------------------------------------------------------------------

# Delete ROIs from all Images in a Dataset

from omero.gateway import BlitzGateway

USERNAME = "******"
PASSWORD = "******"
conn = BlitzGateway(USERNAME, PASSWORD, host="outreach.openmicroscopy.org",
				    port=4064)
conn.connect()

# Edit these values
dataset_id = 25096

dataset = conn.getObject("Dataset", dataset_id)
roi_service = conn.getRoiService()

for image in dataset.listChildren():
    result = roi_service.findByImage(image.getId(), None, conn.SERVICE_OPTS)
    if result is not None:
        roi_ids = [roi.id.val for roi in result.rois]
        print "Deleting %s anns..." % len(roi_ids)
        conn.deleteObjects("Roi", roi_ids)
Beispiel #20
0
          ''')
    sys.exit(1)


if len(sys.argv) < 2:
    printusage()
else:
    annoFile = sys.argv[1]

if not (os.environ.get('OMERO_USER') and os.environ.get('OMERO_PASSWORD')):
    printusage()

host = os.environ.get('OMERO_HOST', 'localhost')
port = int(os.environ.get('OMERO_PORT', '4064'))

ids = []
data = pandas.read_csv(annoFile)
for index, row in data.iterrows():
    imgId = row["ID"]
    ids.append(imgId)

conn = BlitzGateway(os.environ['OMERO_USER'],
                    os.environ['OMERO_PASSWORD'],
                    host=host,
                    port=port)
conn.connect()
print("Deleting Images...")
print(ids)
conn.deleteObjects("Image", ids, wait=True)
print("Done.")
Beispiel #21
0
stats = roi_service.getShapeStatsRestricted(shape_ids, the_z, the_t, [ch_idx])
for s in stats:
    print("Points", s.pointsCount[ch_idx], end=' ')
    print("Min", s.min[ch_idx], end=' ')
    print("Mean", s.mean[ch_idx], end=' ')
    print("Max", s.max[ch_idx], end=' ')
    print("Sum", s.max[ch_idx], end=' ')
    print("StdDev", s.stdDev[ch_idx])

# Remove shape from ROI
# =====================
result = roi_service.findByImage(imageId, None)
for roi in result.rois:
    for s in roi.copyShapes():
        # Find and remove the Shape we added above
        if s.getTextValue() and s.getTextValue().getValue() == "test-Ellipse":
            print("Removing Shape from ROI...")
            roi.removeShape(s)
            roi = updateService.saveAndReturnObject(roi)

# Delete ROIs and all the Shapes they contain
# ===========================================
roi_to_delete = create_roi(image, [rect])
print("Deleting ROI:", roi.getId().getValue())
conn.deleteObjects("Roi", [roi.getId().getValue()], wait=True)

# Close connection
# ================
# When you are done, close the session to free up server resources.
conn.close()
    for ds in objects:
        if delete_children:
            object_list.extend(list(ds.listChildren()))
        if delete_self:
            object_list.append(ds)
else:
    object_list = objects

for obj in object_list:
    print obj.getId()
    ann_ids = []
    if ns == "none":
        ns = None
    for a in obj.listAnnotations(ns):
        #if a.OMERO_TYPE == given_type:
        print a.getId(), a.OMERO_TYPE, a.ns
        ann_ids.append(a.id)
    if len(ann_ids) > 0:
        print "Deleting %s annotations..." % len(ann_ids)
        conn.deleteObjects('Annotation', ann_ids, wait=True)

# Return some value(s).

# Here, we return anything useful the script has produced.
# NB: The Insight and web clients will display the "Message" output.

msg = "Script ran OK"
client.setOutput("Message", rstring(msg))

client.closeSession()