Ejemplo n.º 1
0
def run_as_program():
    """
    Testing function to allow the script to be called outside of the OMERO
    scripting environment. The connection details and image ID must be valid.
    """
    import getpass
    HOST = 'localhost'
    PORT = 4064
    USERNAME = raw_input("OMERO username: "******"OMERO password: "******"OMERO host (%s): " % HOST)
    if h:
        HOST = h
    p = raw_input("OMERO port (%d): " % PORT)
    if p:
        PORT = p

    conn = BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT)
    conn.connect()

    params = {}
    params[PARAM_IDS] = [1]
    params[PARAM_DATATYPE] = "Image"
    params[PARAM_ALL_IMAGES] = True
    params[PARAM_READABLE] = True

    (count, ok) = run(conn, params)

    print (summary(count, ok))
Ejemplo n.º 2
0
def run(username, password, host, port):

    full_names = ["Francis Crick",
              "Linda Buck",
              "Charles Darwin",
              "Marie Curie",
              "Alexander Fleming",
              "Rosalind Franklin",
              "Robert Hooke",
              "Jane Goodall",
              "Gregor Mendel",
              "Barbara McClintock",
              "Louis Pasteur",
              "Ada Lovelace",
              "Linus Pauling",
              "Frances Kelsey",
              "Maurice Wilkins",
              "Florence Nightingale",
              "John Sulston",
              "Elizabeth Blackwell",
              "Richard Dawkins",
              "Caroline Dean",
              "Stephen Reicher",
              "Wendy Barclay",
              "Paul Nurse",
              "Jennifer Doudna",
              "Adrian Thomas",
              "Ann Clarke",
              "Oswald Avery",
              "Liz Sockett",
              "Erwin Chargaff",
              "Tracey Rogers",
              "Ronald Fisher",
              "Rachel Carson",
              "William Harvey",
              "Nettie Stevens",
              "Jeffrey Hall",
              "Youyou Tu",
              "Michael Rosbash",
              "Carol Greider",
              "Yoshinori Ohsumi",
              "Rosalyn Yalow"]

    conn = BlitzGateway(username, password, host=host, port=port)
    try:
        conn.connect()
        admin_service = conn.getAdminService()
        for i, full_name in enumerate(full_names):
            username = '******' % (i + 1)
            print username, full_name
            exp = admin_service.lookupExperimenter(username)
            names = full_name.split(" ")
            exp.firstName = rstring(names[0])
            exp.lastName = rstring(names[1])
            admin_service.updateExperimenter(exp)

    except Exception as exc:
            print "Error while renaming users: %s" % str(exc)
    finally:
        conn.close()
def run_as_program():
    """
    Testing function to allow the script to be called outside of the OMERO
    scripting environment. The connection details and image ID must be valid.
    """
    import getpass
    HOST = 'localhost'
    PORT = 4064
    USERNAME = raw_input("OMERO username: "******"OMERO password: "******"OMERO host (%s): " % HOST)
    if h:
        HOST = h
    p = raw_input("OMERO port (%d): " % PORT)
    if p:
        PORT = p

    conn = BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT)
    conn.connect()
    conn.keepAlive()

    params = create_script_defaults()
    params[PARAM_DATATYPE] = 'Image'
    params[PARAM_IDS] = [51]
    # params[PARAM_DATATYPE] = 'Dataset'
    # params[PARAM_IDS] = [2]
    params[PARAM_UPLOAD_RESULTS] = True
    params[PARAM_EMAIL_RESULTS] = True
    params[PARAM_EMAIL] = ADMIN_EMAIL

    count = run(conn, params)

    if count >= 0:
        print ("Processed %d image%s" %
               (count, count != 1 and 's' or ''))
Ejemplo n.º 4
0
def main(argv):
    parser = make_parser()
    args = parser.parse_args(argv[1:])
    if not args.out_file:
        args.out_file = "map_screen_%d.tsv" % args.screen_id
    passwd = getpass.getpass()
    conn = BlitzGateway(
        args.user, passwd, host=args.host, port=args.port, group=args.group
    )
    conn.connect()
    screen = conn.getObject("Screen", args.screen_id)
    print "writing to %s" % args.out_file
    print "SCREEN: %s" % screen.name
    with open(args.out_file, "w") as fo:
        fo.write("PLATE\tSERIES\tWELL\tFIELD\tImageID\tWellID\n")
        for p in screen.listChildren():
            rows = []
            print "  plate: %s" % p.name
            for w in p.listChildren():
                n_fields = sum(1 for _ in w.listChildren())
                for i in xrange(n_fields):
                    img = w.getImage(i)
                    well_tag = "%s%02d" % (LETTERS[w.row], w.column + 1)
                    rows.append((
                        p.name, img.getSeries(), well_tag, i + 1, img.id, w.id
                    ))
            rows.sort(key=itemgetter(1))
            rows.sort()
            for r in rows:
                fo.write("%s\t%d\t%s\t%d\t%d\t%d\n" % r)
Ejemplo n.º 5
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 connect():
    conn = BlitzGateway('public', 'public',
                        host='ws://idr.openmicroscopy.org/omero-ws',
                        secure=True)
    conn.connect()
    conn.c.enableKeepAlive(60)
    return conn
def run(username, password, project_id, host, port):

    conn = BlitzGateway(username, password, host=host, port=port)
    try:
        conn.connect()
        project = conn.getObject("Project", project_id)

        for dataset in project.listChildren():
            print("\n\nDataset", dataset.id, dataset.name)
            for image in dataset.listChildren():

                print("Image", image.id, image.name)
                ann = image.getAnnotation(NAMESPACE)
                if ann is None:
                    print(" No annotation found")
                    continue
                keys = ann.getValue()
                values = [kv[1] for kv in keys if kv[0] == MAP_KEY]
                if len(values) == 0:
                    print(" No Key-Value found for key:", MAP_KEY)
                channels = values[0].split("; ")
                print("Channels", channels)
                name_dict = {}
                for c, ch_name in enumerate(channels):
                    name_dict[c + 1] = ch_name.split(":")[1]
                conn.setChannelNames("Image", [image.id],
                                     name_dict,
                                     channelCount=None)
    except Exception as exc:
        print("Error while changing names: %s" % str(exc))
    finally:
        conn.close()
Ejemplo n.º 8
0
def run(datasetname, password, host, port):

    conn = BlitzGateway('trainer-1', password, host=host, port=port)
    conn.connect()

    try:
        trainer_dataset = conn.getObject("Dataset",
                                         attributes={'name': datasetname},
                                         opts={'owner': conn.getUserId()})

        # Create {name: [tag_id, tag_id]} for images in Dataset
        image_tag_links = {}
        image_ratings = {}
        for image in trainer_dataset.listChildren():
            tag_ids = []
            for ann in image.listAnnotations():
                if ann.OMERO_TYPE.__name__ == 'TagAnnotationI':
                    tag_ids.append(ann.id)
                elif ann.ns == RATING_NS:
                    image_ratings[image.getName()] = ann.longValue
            if len(tag_ids) > 0:
                image_tag_links[image.getName()] = tag_ids

        # print image_tag_links
        print('image_ratings', image_ratings)
        link_tags(conn, datasetname, image_tag_links, image_ratings)
    finally:
        conn.close()
Ejemplo n.º 9
0
 def test_unicode_password(self):
     with pytest.raises(Ice.ConnectionRefusedException):
         gateway = BlitzGateway(
             username='******', passwd=u'ążźćółę',
             host='localhost', port=65535
         )
         gateway.connect()
Ejemplo n.º 10
0
 def test_unicode_password(self):
     with pytest.raises(Ice.ConnectionRefusedException):
         gateway = BlitzGateway(username='******',
                                passwd=u'ążźćółę',
                                host='localhost',
                                port=65535)
         gateway.connect()
Ejemplo n.º 11
0
def main():
    try:
        conn = BlitzGateway(username, password, host=server, port=4064)
        conn.connect()  #Returns True when connected
        updateService = conn.getUpdateService()
        from omero.rtypes import rdouble, rint, rstring
        images = conn.getObjects("Image",
                                 opts={
                                     'owner': owner_id,
                                     'dataset': datasetID
                                 })
        for image in images:
            imageId = image.getId()
            roi_service = conn.getRoiService()
            result = roi_service.findByImage(imageId, None)
            for roi in result.rois:
                print("ROI:  ID:", roi.getId().getValue())
                for s in roi.copyShapes():
                    if type(s) == omero.model.EllipseI:
                        ctr_x = s.getX().getValue()
                        ctr_y = s.getY().getValue()
                        x, y, w, h = rect_roi_frm_ctr(image, ctr_x, ctr_y,
                                                      width, height)
                        MAX_GFP = max_proj(image, max_ch, x, y, w, h)
                        BFZ9 = load_stack_plane(image, slc_ch, slc, x, y, w, h)
                        hstk = np.stack((MAX_GFP, BFZ9), axis=0)
                        tmp_str = 'output_' + str(imageId) + '_' + str(
                            roi.getId().getValue()) + '.tif'
                        output_hyperstack(hstk, tmp_str)
    finally:
        if conn:
            conn.close()
Ejemplo n.º 12
0
def main(argv):
    parser = make_parser()
    args = parser.parse_args(argv[1:])
    if not args.out_file:
        args.out_file = "map_screen_%d.tsv" % args.screen_id
    passwd = getpass.getpass()
    conn = BlitzGateway(args.user,
                        passwd,
                        host=args.host,
                        port=args.port,
                        group=args.group)
    conn.connect()
    screen = conn.getObject("Screen", args.screen_id)
    print "writing to %s" % args.out_file
    print "SCREEN: %s" % screen.name
    with open(args.out_file, "w") as fo:
        fo.write("PLATE\tSERIES\tWELL\tFIELD\tImageID\tWellID\n")
        for p in screen.listChildren():
            rows = []
            print "  plate: %s" % p.name
            for w in p.listChildren():
                n_fields = sum(1 for _ in w.listChildren())
                for i in xrange(n_fields):
                    img = w.getImage(i)
                    well_tag = "%s%02d" % (LETTERS[w.row], w.column + 1)
                    rows.append((p.name, img.getSeries(), well_tag, i + 1,
                                 img.id, w.id))
            rows.sort(key=itemgetter(1))
            rows.sort()
            for r in rows:
                fo.write("%s\t%d\t%s\t%d\t%d\t%d\n" % r)
Ejemplo n.º 13
0
    def testChgrpAsync(self):
        """
        Try to reproduce "race condition" bugs seen in web #8037 (fails to reproduce)
        """
        image = self.image
        ctx = self.gateway.getAdminService().getEventContext()
        uuid = ctx.sessionUuid

        self.loginAsAdmin()
        gid = self.gateway.createGroup("chgrp-test-%s" % uuid, member_Ids=[ctx.userId], perms=COLLAB)
        self.loginAsAuthor()
        original_group = ctx.groupId
        self.assertNotEqual(None, self.gateway.getObject("Image", image.id))

        # Do the Chgrp
        rsp = self.doChange("Image", image.getId(), gid, return_complete=False)
        
        while rsp.getResponse() is None:
            # while waiting, try various things to reproduce race condition seen in web.
            img = self.gateway.getObject("Image", image.id)
            c = BlitzGateway()
            c.connect(sUuid=uuid)
            #self.gateway.setGroupForSession(gid)

        # Image should no-longer be available in current group
        self.assertEqual(None, self.gateway.getObject("Image", image.id), "Image should not be available in original group")

        # Switch to new group - confirm that image is there.
        self.gateway.setGroupForSession(gid)
        img = self.gateway.getObject("Image", image.id)
        self.assertNotEqual(None, img, "Image should be available in new group")
        self.assertEqual(img.getDetails().getGroup().id, gid, "Image group.id should match new group")
Ejemplo n.º 14
0
def run(username, password, idr_obj, local_obj, host, port):

    conn = BlitzGateway(username, password, host=host, port=port)
    try:
        conn.connect()
        # Project:1
        if ':' not in idr_obj or ':' not in local_obj:
            print('Objects must be: %s' % obj_help)
            return
        dtype = idr_obj.split(':')[0]
        idr_id = idr_obj.split(':')[1]
        localtype = local_obj.split(':')[0]
        if dtype != localtype:
            print("Object types must match")
            return
        local_id = local_obj.split(':')[1]
        if dtype == 'Project':
            annotate_project(conn, local_id, idr_id)
        elif dtype == 'Plate':
            plate = conn.getObject('Plate', local_id)
            annotate_plate(conn, plate, idr_id)
        elif dtype == 'Screen':
            annotate_screen(conn, local_id, idr_id)
        else:
            print("Only supports Project, Screen or Plate")
    finally:
        conn.close()
Ejemplo n.º 15
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()
def run(password, project_name, dataset_name, host, port):

    for user_number in range(1, 41):
        username = "******" % user_number
        print(username)
        conn = BlitzGateway(username, password, host=host, port=port)
        try:
            conn.connect()
            project = ProjectI()
            project.setName(rstring(project_name))
            update_service = conn.getUpdateService()
            project = update_service.saveAndReturnObject(project)

            ds = conn.getObject("Dataset",
                                attributes={'name': dataset_name},
                                opts={'owner': conn.getUserId()})
            if ds is None:
                print("No dataset with name %s found" % dataset_name)
                continue

            dataset_id = ds.getId()
            print(username, dataset_id)

            link = ProjectDatasetLinkI()
            link.setParent(ProjectI(project.getId().getValue(), False))
            link.setChild(DatasetI(dataset_id, False))
            conn.getUpdateService().saveObject(link)
        except Exception as exc:
            print("Error while creating project: %s" % str(exc))
        finally:
            conn.close()
Ejemplo n.º 17
0
def run(password, target, host, port):

    for user_number in range(1, 51):
        username = "******" % user_number
        print(username)
        conn = BlitzGateway(username, password, host=host, port=port)
        try:
            conn.connect()

            ds = conn.getObject("Dataset",
                                attributes={'name': target},
                                opts={'owner': conn.getUserId()})
            if ds is None:
                print("No dataset with name %s found" % target)
                continue

            print("Dataset", ds.getId())

            conn.setChannelNames("Dataset", [ds.getId()], {
                1: "H2B",
                2: "nuclear lamina"
            })
        except Exception as exc:
            print("Error while changing the channel names: %s" % str(exc))
        finally:
            # Close connection for each user when done
            conn.close()
Ejemplo n.º 18
0
    def create_containers(self, cli, project, dataset):
        """
        Creates containers with names provided if they don't exist already.
        Returns Dataset ID.
        """
        sessionId = cli._event_context.sessionUuid
        conn = BlitzGateway(host='localhost')
        conn.connect(sUuid = sessionId)
        params = omero.sys.Parameters()
        params.theFilter = omero.sys.Filter()
        params.theFilter.ownerId = wrap(conn.getUser().getId())

        d = None
        dsId = None
        if project is not None:
            # We need to find or create a project
            # This is not nice but we really shouldn't be dealing with large numbers of objects here
            plist = list(conn.getObjects("Project", attributes={'name': project}, params=params))
            if len(plist) == 0:
                # Create project and dataset then link
                p = self.create_project(conn, project)
                d = self.create_dataset(conn, dataset)
                dsId = d.id.val
                self.link_dataset(conn, p.id.val, dsId)
            else:
                # Pick the first, it's as good as any
                p = plist[0]
                print "Using existing Project:", project
                # Since Project already exists check children for dataset
                for c in p.listChildren():
                    if c.getName() == dataset:
                        d = c
                        dsId = d.getId()

                # No existing child dataset so create one and link
                if d is None:
                    d = self.create_dataset(conn, dataset)
                    dsId = d.id.val
                    self.link_dataset(conn, p.getId(), dsId)
                else:
                    print "Using existing Dataset:", dataset
        else:
            # There may be more than one dataset with the same name
            # This is not nice but we really shouldn't be dealing with large numbers of objects here
            dlist = list(conn.getObjects("Dataset", attributes={'name': dataset}, params=params))
            if len(dlist) != 0:
                # We want one without a parent, the first will do
                for c in dlist:
                    if len(c.listParents()) == 0:
                        d = c
                        dsId = d.getId()
            if d is None:
                dsId = self.create_dataset(conn, dataset).id.val
            else:
                print "Using existing Dataset:", dataset

        return dsId
Ejemplo n.º 19
0
def run(password, target, host, port):

    for i in range(1, 51):

        username = "******" % i
        print(username)
        conn = BlitzGateway(username, password, host=host, port=port)
        try:
            conn.connect()
            params = omero.sys.ParametersI()
            params.addString('username', username)
            query = "from Dataset where name='%s' \
                    AND details.owner.omeName=:username" % target
            query_service = conn.getQueryService()
            dataset = query_service.findAllByQuery(query, params,
                                                   conn.SERVICE_OPTS)

            if len(dataset) == 0:
                print("No dataset with name %s found" % target)
                continue
            dataset_id = dataset[0].getId().getValue()

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

            kvp_sets = [
                [["mitomycin-A", "0mM"], ["PBS", "10mM"],
                 ["incubation (mins)", "20"], ["temperature", "37"],
                 ["Organism", "H**o sapiens"]],
                [["mitomycin-A", "20mM"], ["PBS", "10mM"],
                 ["incubation (mins)", "10"], ["temperature", "40"],
                 ["Organism", "H**o sapiens"]],
                [["mitomycin-A", "10microM"], ["PBS", "10mM"],
                 ["incubation (mins)", "5"], ["temperature", "37"],
                 ["Organism", "H**o sapiens"]],
                [["mitomycin-A", "0mM"], ["PBS", "10mM"],
                 ["incubation (mins)", "2"], ["temperature", "68"],
                 ["Organism", "H**o sapiens"]],
            ]

            for count, image in enumerate(dataset.listChildren()):
                key_value_data = kvp_sets[count % 4]
                map_ann = omero.gateway.MapAnnotationWrapper(conn)
                # Use 'client' namespace to allow editing in Insight & web
                namespace = omero.constants.metadata.NSCLIENTMAPANNOTATION
                map_ann.setNs(namespace)
                map_ann.setValue(key_value_data)
                map_ann.save()
                # NB: only link a client map annotation to a single object
                image.linkAnnotation(map_ann)
                print('linking to image', image.getName())
        except Exception as exc:
            print("Error while setting key-value pairs: %s" % str(exc))
        finally:
            conn.close()
def run(password, admin_name, target, tag, host, port):

    for i in range(1, 51):

        username = "******" % i
        print(username)
        conn = BlitzGateway(username, password, host=host, port=port)
        try:
            conn.connect()
            updateService = conn.getUpdateService()
            ds = conn.getObject("Dataset",
                                attributes={'name': target},
                                opts={'owner': conn.getUserId()})
            if ds is None:
                print("No dataset with name %s found" % target)
                continue
            params = omero.sys.ParametersI()
            params.addString('username', admin_name)
            query = "from TagAnnotation where textvalue='%s' \
                    AND details.owner.omeName=:username" % tag
            query_service = conn.getQueryService()
            tags = query_service.findAllByQuery(query, params,
                                                conn.SERVICE_OPTS)
            if len(tags) == 0:
                print("No tag with name %s found" % tag)
                continue
            tag_id = tags[0].id.getValue()
            print(tag_id)
            links = []
            for image in ds.listChildren():
                name = image.getName()
                if name in images_to_tag:
                    # Check first that the image is not tagged
                    params = omero.sys.ParametersI()
                    params.addLong('parent', image.id)
                    params.addLong('child', tag_id)
                    query = "select link from ImageAnnotationLink as link \
                             where link.parent.id=:parent \
                             AND link.child.id=:child"

                    values = query_service.findAllByQuery(
                        query, params, conn.SERVICE_OPTS)
                    if len(values) == 0:
                        link = ImageAnnotationLinkI()
                        link.parent = ImageI(image.id, False)
                        link.child = TagAnnotationI(tag_id, False)
                        links.append(link)
                    else:
                        print("Tag %s already linked to %s" % (tag, name))
            if len(links) > 0:
                updateService.saveArray(links)
        except Exception as exc:
            print("Error when tagging the images: %s" % str(exc))
        finally:
            conn.close()
def get_image(image_id):
    from OMERO_Properties import USERNAME, PASSWORD, HOST, PORT
    conn = BlitzGateway(USERNAME, PASSWORD, port=PORT, host=HOST)
    conn.connect()
    conn.SERVICE_OPTS.setOmeroGroup('-1')

    if (image_id):
        image = conn.getObject("Image", image_id)
        return image
    else:
        return None
Ejemplo n.º 22
0
def run(args):
    username = args.username
    password = args.password
    project_id = args.project_id
    host = args.server
    port = args.port
    use_stain = args.use_stain
    add_map_anns = args.add_map_anns

    token_index = 0 if use_stain else 1

    conn = BlitzGateway(username, password, host=host, port=port)
    try:
        conn.connect()
        project = conn.getObject("Project", project_id)

        for dataset in project.listChildren():
            print("\n\nDataset", dataset.id, dataset.name)
            for image in dataset.listChildren():

                print("Image", image.id, image.name)
                ann = image.getAnnotation(NAMESPACE)
                if ann is None:
                    print(" No annotation found")
                    continue
                keys = ann.getValue()
                values = [kv[1] for kv in keys if kv[0] == MAP_KEY]
                if len(values) == 0:
                    print(" No Key-Value found for key:", MAP_KEY)
                channels = values[0].split("; ")
                print("Channels", channels)
                name_dict = {}
                key_value_pairs = []
                for c, ch_name in enumerate(channels):
                    tokens = ch_name.split(":")
                    if add_map_anns and len(tokens) > 1:
                        key_value_pairs.extend(
                            [["Ch%s_Stain" % c, tokens[0]],
                             ["Ch%s_Label" % c, tokens[1]]]
                        )
                    if len(tokens) > token_index:
                        label = tokens[token_index]
                    else:
                        label = ch_name
                    name_dict[c + 1] = label
                conn.setChannelNames("Image", [image.id], name_dict,
                                     channelCount=None)
                if len(key_value_pairs) > 0:
                    create_map_ann(conn, image, key_value_pairs)
    except Exception as exc:
        print("Error while changing names: %s" % str(exc))
    finally:
        conn.close()
Ejemplo n.º 23
0
def connect(hostname, username, password):
    """
    Connect to an OMERO server
    :param hostname: Host name
    :param username: User
    :param password: Password
    :return: Connected BlitzGateway
    """
    conn = BlitzGateway(username, password, host=hostname, secure=True)
    conn.connect()
    conn.c.enableKeepAlive(60)
    return conn
Ejemplo n.º 24
0
def create_containers(cli, dataset, project=None):
    """
    Creates containers with names provided if they don't exist already.
    Returns Dataset ID.
    """
    sessionId = cli._event_context.sessionUuid
    conn = BlitzGateway(host='localhost')
    conn.connect(sUuid=sessionId)
    params = omero.sys.Parameters()
    params.theFilter = omero.sys.Filter()
    params.theFilter.ownerId = wrap(conn.getUser().getId())

    d = None
    prId = None
    if project is not None:
        p = conn.getObject("Project",
                           attributes={'name': project},
                           params=params)
        if p is None:
            print "Creating Project:", project
            p = omero.model.ProjectI()
            p.name = wrap(project)
            prId = conn.getUpdateService().saveAndReturnObject(p).id.val
        else:
            print "Using Project:", project, p
            prId = p.getId()
            # Since Project already exists, check children for Dataset
            for c in p.listChildren():
                if c.getName() == dataset:
                    d = c

    if d is None:
        d = conn.getObject("Dataset",
                           attributes={'name': dataset},
                           params=params)

    if d is None:
        print "Creating Dataset:", dataset
        d = omero.model.DatasetI()
        d.name = wrap(dataset)
        dsId = conn.getUpdateService().saveAndReturnObject(d).id.val
        if prId is not None:
            print "Linking Project-Dataset..."
            link = omero.model.ProjectDatasetLinkI()
            link.child = omero.model.DatasetI(dsId, False)
            link.parent = omero.model.ProjectI(prId, False)
            conn.getUpdateService().saveObject(link)
    else:
        print "Using Dataset:", dataset, d
        dsId = d.getId()
    return dsId
def run(password, project_name, dataset_name, host, port):

    for user_number in range(1, 51):
        username = "******" % user_number
        print(username)
        conn = BlitzGateway(username, password, host=host, port=port)
        try:
            conn.connect()

            params = omero.sys.ParametersI()
            params.addString('username', username)
            # make sure only one result is returned by query
            params.page(0, 1)
            query = "from Project where name='%s' \
                    AND details.owner.omeName=:username \
                    ORDER BY id DESC" % project_name
            service = conn.getQueryService()
            pr_list = service.findAllByQuery(query, params, conn.SERVICE_OPTS)

            if pr_list is None:
                print("No project with name %s found" % project_name)
                continue

            project_id = pr_list[0].getId().getValue()
            print(username, project_id)

            params = omero.sys.ParametersI()
            params.addString('username', username)
            # make sure only one result is returned by query
            params.page(0, 1)
            query = "from Dataset where name='%s' \
                     AND details.owner.omeName=:username \
                     ORDER BY id DESC" % dataset_name
            service = conn.getQueryService()
            ds_list = service.findAllByQuery(query, params, conn.SERVICE_OPTS)

            if ds_list is None:
                print("No dataset with name %s found" % dataset_name)
                continue

            dataset_id = ds_list[0].getId().getValue()
            print(username, dataset_id)

            link = ProjectDatasetLinkI()
            link.setParent(ProjectI(project_id, False))
            link.setChild(DatasetI(dataset_id, False))
            conn.getUpdateService().saveObject(link)
        except Exception as exc:
            print("Error while linking to project: %s" % str(exc))
        finally:
            conn.close()
def connect_to_omero(user, password, host, port=4064):
    conn = BlitzGateway(user, password, host=host, port=port)
    print conn.connect()
    user = conn.getUser()
    print "Current user:"******"   ID:", user.getId()
    print "   Username:"******"   Full Name:", user.getFullName()
    print "Member of:"
    for g in conn.getGroupsMemberOf():
        print "   ID:", g.getName(), " Name:", g.getId()
    group = conn.getGroupFromContext()
    print "Current group: ", group.getName()
    return conn
Ejemplo n.º 27
0
def JoinSession(conn):
    try:
        LogWriter.logDebug("Connect To:" + str(conn.host) + " " +
                           str(conn.port) + " " + str(conn._getSessionId()))
        connection = BlitzGateway('OMERO.script',
                                  host=conn.host,
                                  port=conn.port)
        connection.connect(sUuid=conn._getSessionId())
        return connection
    except Exception as inst:
        LogWriter.logError("Connecting own session failed " +
                           str(inst.message))
        LogWriter.logError(traceback.format_exc())
        return None
Ejemplo n.º 28
0
def getOmeroConn():
    try:
        conn = BlitzGateway("root",
                            omero_rootpass,
                            host="localhost",
                            port="4064")
        conn.connect()
        return conn
    except Exception as e:
        logging.error(
            "Something went wrong when getting OMERO-connection, is server up? Somethimes it takes 30 sek to start."
        )
        logging.error("Exception: " + str(e))
        raise e
def connect_to_omero(user, password, host, port=4064):
    conn = BlitzGateway(user, password, host=host, port=port)
    print conn.connect()
    user = conn.getUser()
    print "Current user:"******"   ID:", user.getId()
    print "   Username:"******"   Full Name:", user.getFullName()
    print "Member of:"
    for g in conn.getGroupsMemberOf():
        print "   ID:", g.getName(), " Name:", g.getId()
    group = conn.getGroupFromContext()
    print "Current group: ", group.getName()
    return conn
Ejemplo n.º 30
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('username2', help='Target server Username')
    parser.add_argument('password2', help='Target server Password')
    parser.add_argument('server2', help='Target server')
    parser.add_argument('source',
                        help=('Copy ROIs FROM this: Image:ID or Dataset:ID'))
    parser.add_argument('target',
                        help=('Copy ROIs TO this: Image:ID or Dataset:ID'))
    args = parser.parse_args(argv)

    with cli_login() as cli:
        conn = BlitzGateway(client_obj=cli._client)
        conn.SERVICE_OPTS.setOmeroGroup(-1)

        conn2 = BlitzGateway(args.username2,
                             args.password2,
                             port=4064,
                             host=args.server2)
        conn2.connect()

        source_images = []
        target_image_ids = []

        source = args.source
        source_id = int(source.split(":")[1])
        target = args.target
        target_id = int(target.split(":")[1])

        if source.startswith('Image:'):
            source_images.append(conn.getObject('Image', source_id))
            target_image_ids.append(target_id)
        elif source.startswith('Dataset:'):
            dataset = conn.getObject('Dataset', source_id)
            target_dataset = conn2.getObject('Dataset', target_id)
            ids_by_name = image_ids_by_name(target_dataset)
            for image in dataset.listChildren():
                if image.name in ids_by_name:
                    source_images.append(image)
                    target_image_ids.append(ids_by_name[image.name])
        else:
            print("Source needs to be Image:ID or Dataset:ID")

        print("Processing", source_images)
        print("...to target images:", target_image_ids)
        for image, to_target_id in zip(source_images, target_image_ids):
            process_image(conn, conn2, image, to_target_id)

        conn2.close()
Ejemplo n.º 31
0
def run(password, target, host, port):

    for i in range(1, 51):

        username = "******" % i
        print(username)
        conn = BlitzGateway(username, password, host=host, port=port)
        try:
            conn.connect()

            params = omero.sys.ParametersI()
            params.addString('username', username)
            query = "from Dataset where name='%s' \
                     AND details.owner.omeName=:username" % target
            service = conn.getQueryService()
            dataset = service.findAllByQuery(query, params, conn.SERVICE_OPTS)

            if len(dataset) == 0:
                print("No dataset with name %s found" % target)
                continue

            dataset_obj = dataset[0]
            datasetId = dataset[0].getId().getValue()

            print('dataset', datasetId)
            params2 = omero.sys.ParametersI()
            params2.addId(dataset_obj.getId())
            query = "select l.child.id from DatasetImageLink \
                     l where l.parent.id = :id"

            images = service.projection(query, params2, conn.SERVICE_OPTS)
            values = []
            for k in range(0, len(images)):

                image_id = images[k][0].getValue()
                image = conn.getObject("Image", image_id)

                u = omero.model.LengthI(0.33, UnitsLength.MICROMETER)
                p = image.getPrimaryPixels()._obj
                p.setPhysicalSizeX(u)
                p.setPhysicalSizeY(u)
                values.append(p)

            if len(images) > 0:
                conn.getUpdateService().saveArray(values)
        except Exception as exc:
            print("Error during calibration: %s" % str(exc))
        finally:
            conn.close()
def main(md_path, admin_user, server, port):

    # load metadata
    md_path = pathlib.Path(md_path)
    if not md_path.is_file():
        logging.error('file does not exist, check md argument')
        return

    try:
        with open(md_path, 'r') as f:
            md = json.load(f)
    except json.JSONDecodeError as err:
        logging.error(f'Unable to load json: {err}')
        return
    annotation_md = md['data']

    # set up connection
    password = getpass(f'Enter password for {admin_user}: ')
    conn = BlitzGateway(admin_user, password, host=server, port=port)
    conn.connect()
    group_id = get_group_id(conn, md['OMERO_group'])
    conn.SERVICE_OPTS.setOmeroGroup(group_id)

    # loop through metadata and annotate
    print('New Annotations:')
    for md in annotation_md:
        project = str(md.pop('project'))
        dataset = str(md.pop('dataset'))
        filename = md.pop('filename')
        ns = CURRENT_MD_NS
        dataset_ids = find_datasets(conn, project, dataset)
        im_id_array = []
        for did in dataset_ids:
            im_id_array.append(get_image_ids(conn, dataset=did))
        im_ids = [im_id for sublist in im_id_array for im_id in sublist]
        im_ids = filter_by_filename(conn, im_ids, filename)

        #        im_ids = [im_id for sublist in im_id_array
        #                  for im_id in sublist
        #                  if image_has_imported_filename(conn, im_id, filename)]

        if len(im_ids) == 0:
            print(f"Cannot annotate {project} / {dataset} / {filename}"
                  " because it can not be found")
        else:
            map_ann_id = post_map_annotation(conn, "Image", im_ids, md, ns)
            print(map_ann_id)
    conn.close()
    print('Complete!')
Ejemplo n.º 33
0
def connect( server, port, username, password ): 
    '''
    Helper method that connects to an OMERO.searcher server.
    @param server
    @param port
    @param username
    @param password
    @returns connection
    '''
    
    try:
        conn = BlitzGateway( username, password, host=server, port=int(port))
        conn.connect()
        return conn
    except:
        return None
Ejemplo n.º 34
0
def index(request):
	conn = BlitzGateway(OMERO_USER,OMERO_PASSWORD,host=os.environ['OMEROHOST'])
	if not conn.connect():
		return HttpResponseServerError("Could not connect to Omero server")
	projects = []
	thumbnails = {}
	for project in conn.listProjects():
		can_get_rois = False
		p = {'id':project.id,
			 'name':project.name,
		     'datasets':[]
		     }
		for dataset in project.listChildren():
			ds = {'id':dataset.id,
			'name':dataset.name,
			'images':[]
			}
			for image in dataset.listChildren():
				#if image.getROICount() > 0:
				img_meta = image.simpleMarshal()
				if dataset.name != 'ROI_images' and len(img_from_roi.getRectangles(conn,image)) >0:
					img_meta['can_get_rois'] = True
				ds['images'].append(img_meta)
				size_x = image.getSizeX()
				size_y = image.getSizeY()
				if size_x*0.005 > 256:
					thumbnails[image.id] = image.getThumbnail(size=(size_x*0.005,size_y*0.005))
				else:
					thumbnails[image.id] = image.getThumbnail(size=(size_x*0.1,size_y*0.1))
			p['datasets'].append(ds)
		projects.append(p)
	conn.close()
	return render(request, 'exportml/index.html',{'projects':projects,'thumbnails':thumbnails})
Ejemplo n.º 35
0
def main(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('id', help="The id of the project.")
    parser.add_argument('--username', default="demo")
    parser.add_argument('--server', default="localhost")
    parser.add_argument('--port', default=4064)
    args = parser.parse_args(args)
    password = getpass.getpass()
    # Create a connection
    try:
        conn = BlitzGateway(args.username, password, host=args.server,
                            port=args.port)
        conn.connect()
        load_images(conn, args.id)
    finally:
        conn.close()
Ejemplo n.º 36
0
def get_coordinates_list(index_ligne,imageId, large, delta_x,z):
    conn = BlitzGateway('tbacoyannis','d33pl34rn1ng',port=4064,host='chinensis.polytechnique.fr')
    connected = conn.connect()

    image = conn.getObject("Image", imageId)
    pixels = image.getPrimaryPixels() # get raw pixels information
    
    size_x= image.getSizeX()
    size_y= image.getSizeY()
    size_z = image.getSizeZ()
    size_c = image.getSizeC()
    size_t = image.getSizeT()
   
   
    
    nb_fenetres=np.arange(size_x/delta_x)
    index=nb_fenetres
    
    x=(index*delta_x)+delta_x
    #x=x[22:-22]
    
    y=((index_ligne*delta_x)+delta_x)*np.ones(len(x)) #(index))
    
    index_colonne=index+2
    index_lignee=(2+index_ligne)*np.ones(len(x)) 
    
    Tuple_Coord=(x,y,index_lignee, index_colonne) 
    
    conn._closeSession()
    return(Tuple_Coord)
def main(group, admin_user, server, port):
    password = getpass(f'Enter password for {admin_user}: ')
    conn = BlitzGateway(admin_user, password, host=server, port=port)
    conn.connect()
    group_id = get_group_id(conn, group)
    conn.SERVICE_OPTS.setOmeroGroup(group_id)
    image_ids = get_image_ids(conn, across_groups=False)
    with open("omeroImages2Import.tsv", 'w') as f:
        f.write('omero_id\timage_file\timage_name\n')
        for im_id in image_ids:
            im_o, _ = get_image(conn, im_id, no_pixels=True)
            imp_filename = Path(get_original_filepaths(conn, im_id)[0]).name
            image_name = im_o.getName()
            out_string = f'{im_id}\t{imp_filename}\t{image_name}\n'
            f.write(out_string)
    conn.close()
Ejemplo n.º 38
0
def connect_to_omero(uname, passwd):
    conn = BlitzGateway(uname, passwd, host=HOST, port=PORT)
    connected = conn.connect()
    if not connected:
        sys.stderr.write("Error : Connection not available, please check your user name and password.\n")
        return None
    return conn
Ejemplo n.º 39
0
class OMEConnect(widgets.VBox):
    """OMERO database connection widget
    """
    def __init__(self, host="localhost", port=4064):
        """Connects to an omero database.

        Parameters
        ----------
        host: str, the omero server host (default localhost)
        port: int, the connection port (default 4064)

        """
        self.host = host
        self.port = port
        self.logbox = widgets.Text(description="OME loggin")
        self.pwdbox = widgets.Password(description="OME password")
        self.gobtn = widgets.Button(description="Let me in")
        self.gobtn.on_click(self.on_go_clicked)
        self.out = widgets.Output()
        super().__init__((self.logbox, self.pwdbox, self.gobtn, self.out))
        self.conn = None

    def on_go_clicked(self, b):
        self.out.clear_output()

        if self.conn is not None:
            self.conn.close()

        self.conn = BlitzGateway(self.logbox.value,
                                 self.pwdbox.value,
                                 host=self.host,
                                 port=self.port)
        self.conn.connect()
        if self.conn.isConnected():
            with self.out:
                print("Logging successful!\n")
                display(
                    Image(
                        "https://media.giphy.com/media/Azwmdv1NTSe9W/giphy.gif"
                    ))
                sleep(3)
                self.out.clear_output()
        else:
            with self.out:
                ("sorry, connection failed, try again?")
            self.logbox.value = ""
            self.pwdbox.value = ""
Ejemplo n.º 40
0
def create_containers(cli, dataset, project=None):
    """
    Creates containers with names provided if they don't exist already.
    Returns Dataset ID.
    """
    sessionId = cli._event_context.sessionUuid
    conn = BlitzGateway()
    conn.connect(sUuid = sessionId)
    params = omero.sys.Parameters()
    params.theFilter = omero.sys.Filter()
    params.theFilter.ownerId = wrap(conn.getUser().getId())

    d = None
    prId = None
    if project is not None:
        p = conn.getObject("Project", attributes={'name': project}, params=params)
        if p is None:
            print "Creating Project:", project
            p = omero.model.ProjectI()
            p.name = wrap(project)
            prId = conn.getUpdateService().saveAndReturnObject(p).id.val
        else:
            print "Using Project:", project, p
            prId = p.getId()
            # Since Project already exists, check children for Dataset
            for c in p.listChildren():
                if c.getName() == dataset:
                    d = c

    if d is None:
        d = conn.getObject("Dataset", attributes={'name': dataset}, params=params)

    if d is None:
        print "Creating Dataset:", dataset
        d = omero.model.DatasetI()
        d.name = wrap(dataset)
        dsId = conn.getUpdateService().saveAndReturnObject(d).id.val
        if prId is not None:
            print "Linking Project-Dataset..."
            link = omero.model.ProjectDatasetLinkI()
            link.child = omero.model.DatasetI(dsId, False)
            link.parent = omero.model.ProjectI(prId, False)
            conn.getUpdateService().saveObject(link)
    else:
        print "Using Dataset:", dataset, d
        dsId = d.getId()
    return dsId
Ejemplo n.º 41
0
def connect_to_omero():
	conn = BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT)
	connected = conn.connect()
	if not connected:
		import sys
		sys.stderr.write("Error : Connection not available, please check your user name and password.\n")
		return None
	return conn
Ejemplo n.º 42
0
def omero_login(user, passwd, host, port):
    """Establish the connection to an OMERO server.

    Parameters
    ==========
    user : str - OMERO user name (e.g. "demo_user_01")
    passwd : str - OMERO user password
    host : str - OMERO server hostname to connect to
    port : int - OMERO server port number (e.g. 4064)

    Returns
    =======
    conn : omero.gateway._BlitzGateway - OMERO connection object
    """
    conn = BlitzGateway(user, passwd, host=host, port=port, secure=True,
                        useragent="HRM-OMERO.connector")
    conn.connect()
    return conn
def temporary_connection():
    temp_client = omero.client()
    omeroProperties = temp_client.getProperties().getPropertiesForPrefix('omero')
    # Configuration
    HOST = omeroProperties.get('omero.host', 'localhost')
    PORT = omeroProperties.get('omero.port', 4064)
    USERNAME = omeroProperties.get('omero.user')
    PASSWORD = omeroProperties.get('omero.pass')
    temp_conn = BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT)
    connected = temp_conn.connect()
    return temp_client,temp_conn
Ejemplo n.º 44
0
def connect_base():
    """Establish the base connection to OMERO.

    Returns the connection in the context defined in localconfig.
    """
    # establish the base connection with an admin account
    su_conn = BlitzGateway(SU_USER, SU_PASS, host=HOST, port=PORT)
    if su_conn.connect() is False:
        raise RuntimeError('Connection to OMERO failed, check settings!')
    log.debug("Successfully connected to OMERO.")
    return su_conn
Ejemplo n.º 45
0
    def create_screen(self, cli, screen):
        """
        Creates screen with name provided if it doesn't exist already.
        Returns Screen ID.
        """
        sessionId = cli._event_context.sessionUuid
        conn = BlitzGateway(host='localhost')
        conn.connect(sUuid = sessionId)
        params = omero.sys.Parameters()
        params.theFilter = omero.sys.Filter()
        params.theFilter.ownerId = wrap(conn.getUser().getId())

        slist = list(conn.getObjects("Screen", attributes={'name': screen}, params=params))
        if len(slist) == 0:
            print "Creating Screen:", screen
            s = ScreenI()
            s.name = wrap(screen.encode('ascii','ignore'))
            scrId = conn.getUpdateService().saveAndReturnObject(s).id.val
        else:
            scrId = slist[0].getId()
            print "Using Screen:", screen

        return scrId
Ejemplo n.º 46
0
    def group_exists(self, user, group):
        if not self.user_exists(user):
            return False
        else:
            if group in self.known_users[user]:
                print "in Group:", group
                return True
        try:
            try:
                conn = BlitzGateway(user, "ome", host='localhost')
                conn.connect()
                groups = conn.getGroupsMemberOf()
            except:
                return False

            if group in [g.name for g in groups]:
                print "in Group:", group
                self.known_users[user].append(group)
                return True
            else:
                print "is not in Group:", group, "- ignoring."
                return False
        finally:
            conn.seppuku()
Ejemplo n.º 47
0
    def user_exists(self, user):
        if user in self.known_users.keys():
            print "User:"******"root", "omero", host='localhost')
                conn.connect()
                params = omero.sys.Parameters()
                params.theFilter = omero.sys.Filter()
                u = conn.getObject("Experimenter", attributes={'omeName': user}, params=params)
            except:
                print "Error getting user - ignoring."
                return False

            if u is None:
                print "User:"******"does not exist - ignoring."
                return False
            else:
                print "User:", user,
                self.known_users[user] = []
                return True
        finally:
            conn.seppuku()
class ScriptsManager(object):
    def __init__(self, user="******", pwd="omero", host="localhost", port=4064):
        self.conn = BlitzGateway(user, pwd, host=host, port=port)
        result = self.conn.connect()
        if not result:
            raise RuntimeError("Cannot connect to <{0}>".format(host)+
                               " with user <{0}>.".format(user))
        self.svc = self.conn.getScriptService()

    def list(self):
         return self.svc.getScripts()

    def delete(self, id):
        try:
            self.svc.deleteScript(id)
        except Exception, e:
            raise RuntimeError("Failed to delete script: "+
                               "{0} ({1})".format(id, e))            
Ejemplo n.º 49
0
def connect_as_user(username):
    """Establish a connection to OMERO with a given user context.

    To establish a connection as a specific user without knowing their
    credential, a two-stage process is required: first the bsae connection is
    created with an admin user, then this existing connection is switched over
    to a (non-privileged) user account.

    Returns the connection in the user's context.
    """
    # establish the base connection with an admin account
    su_conn = BlitzGateway(SU_USER, SU_PASS, host=HOST, port=PORT)
    if su_conn.connect() is False:
        raise RuntimeError('Connection to OMERO failed, check settings!')
    # now switch to the requested user
    conn = su_conn.suConn(username)
    if conn.connect() is False:
        raise RuntimeError('User switching in OMERO failed, check settings!')
    log.debug("Successfully connected to OMERO.")
    return conn
 def new_connection(self, user, passw, host):
     conn = BlitzGateway(user, passw, host=host)
     conn.connect()
     return conn
Ejemplo n.º 51
0
#
# Copyright (C) 2011 University of Dundee & Open Microscopy Environment.
#                    All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#

from sys import argv
import omero
from omero.gateway import BlitzGateway
from Connect_To_OMERO import USERNAME, PASSWORD, HOST, PORT


# Create a connection
# =================================================================
conn = BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT)
conn.connect()


# Configuration
# =================================================================
script, imageId = argv





#  Reitrieve an image by Image ID:
# =================================================================
image = conn.getObject("Image", imageId)
print "\nImage:%s" % imageId
print "=" * 50
Ejemplo n.º 52
0
class Omg(object):
    """
    OMERO gateway that wraps Blitz gateway and CLI, intended for
    scripting and interactive work.

    Attributes
    ----------
    conn : Blitz gateway connection

    """

    def __init__(self, conn=None, user=None, passwd=None,
                 server=SERVER, port=PORT, skey=None):
        """
        Requires active Blitz connection OR username plus password or sesskey
        """
        if conn is None and (user is None or (passwd is None and skey is None)):
            raise ValueError("Bad parameters," + self.__init__.__doc__)
        if conn is not None:
            if conn.isConnected():
                self.conn = conn
            else:
                raise ValueError("Cannot initialize with closed connection!")
        else:
            if passwd is not None:
                self.conn = BlitzGateway(user, passwd, host=server, port=port)
                self.conn.connect()
            else:
                self.conn = BlitzGateway(user, host=server, port=port)
                self.conn.connect(skey)
        if self.conn.isConnected():
            self._server = self.conn.host
            self._port = self.conn.port
            self._user = self.conn.getUser().getName()
            self._key = self.conn.getSession().getUuid().getValue()
            print("Connected to {0} (port {1}) as {2}, session key={3}".format(
                  self._server, self._port, self._user, self._key))
        else:
            print("Failed to open connection :-(")

    def ls(self):
        """
        Print groups, then projects/datasets/images for current group.
        """
        print("Groups for {0}:-".format(self.conn.getUser().getName()))
        for gid, gname in self._ls_groups():
            print("  {0} ({1})".format(gname, str(gid)))
        curr_grp = self.conn.getGroupFromContext()
        gid, gname = curr_grp.getId(), curr_grp.getName()
        print("\nData for current group, {0} ({1}):-".format(gname, gid))
        for pid, pname in self._ls_projects():
            print("  Project: {0} ({1})".format(pname, str(pid)))
            for did, dname in self._ls_datasets(pid):
                print("    Dataset: {0} ({1})".format(dname, str(did)))
                for iid, iname in self._ls_images(did):
                    print("      Image: {0} ({1})".format(iname, str(iid)))
        # TODO, list orphaned Datasets and Images

    def _ls_groups(self):
        """list groups (id, name) this session is a member of"""
        groups = self.conn.getGroupsMemberOf()
        return [(group.getId(), group.getName()) for group in groups]

    def _ls_projects(self):
        """list projects (id, name) in the current session group"""
        projs = self.conn.listProjects(self.conn.getUserId())
        return [(proj.getId(), proj.getName()) for proj in projs]

    def _ls_datasets(self, proj_id):
        """list datasets (id, name) within the project id given"""
        dsets = self.conn.getObject("Project", proj_id).listChildren()
        return [(dset.getId(), dset.getName()) for dset in dsets]

    def _ls_images(self, dset_id):
        """list images (id, name) within the dataset id given"""
        imgs = self.conn.getObject("Dataset", dset_id).listChildren()
        return [(img.getId(), img.getName()) for img in imgs]

    def chgrp(self, group_id):
        """
        Change group for this session to the group_id given.
        """
        self.conn.setGroupForSession(group_id)

    def get(self, im_id, get_att=True):
        """
        Download the specified image as an OME-TIFF to current directory,
        with attachments also downloaded to folder: img_path + '_attachments'
        Return : path to downloaded image
        """
        img = self.conn.getObject("Image", oid=im_id)
        img_name = self._unique_name(img.getName(), im_id)
        img_path = os.path.join(os.getcwd(), img_name)
        img_file = open(str(img_path + ".ome.tiff"), "wb")
        fsize, blockgen = img.exportOmeTiff(bufsize=65536)
        for block in blockgen:
            img_file.write(block)
        img_file.close()
        fa_type = omero.model.FileAnnotationI
        attachments = [ann for ann in img.listAnnotations()
                       if ann.OMERO_TYPE == fa_type]
        if get_att and len(attachments) > 0:
            att_dir = img_path + "_attachments"
            os.mkdir(att_dir)

            def download_attachment(att, att_dir):
                """download OMERO file annotation to att_dir"""
                att_file = open(os.path.join(att_dir, att.getFileName()), "wb")
                for att_chunk in att.getFileInChunks():
                    att_file.write(att_chunk)
                att_file.close()

            for att in attachments:
                download_attachment(att, att_dir)
        return img_path

    def _unique_name(self, img_name, im_id):
        """Make unique name combining a file basename & OMERO Image id"""
        path_and_base, ext = os.path.splitext(img_name)
        base = os.path.basename(path_and_base)  # name in OMERO can has path
        return "{0}_{1}".format(base, str(im_id))

    def dget(self, dataset_id):
        """
        Download an entire OMERO Dataset to the current directory.
        """
        downloads = []
        wdir = os.getcwd()
        dset_name = self.conn.getObject("Dataset", dataset_id).getName()
        dset_path = os.path.join(wdir, dset_name + "_D" + str(dataset_id))
        os.mkdir(dset_path)
        os.chdir(dset_path)
        for img_id, img_name in self._ls_images(dataset_id):
            downloads.append(self.get(img_id))
        os.chdir(wdir)
        return downloads

    def pget(self, project_id):
        """
        Download an entire OMERO Project to the current directory.
        """
        downloads = []
        wdir = os.getcwd()
        proj_name = self.conn.getObject("Project", project_id).getName()
        proj_path = os.path.join(wdir, proj_name + "_P" + str(project_id))
        os.mkdir(proj_path)
        os.chdir(proj_path)
        for dset_id, dset_name in self._ls_datasets(project_id):
            downloads.extend(self.dget(dset_id))
        os.chdir(wdir)
        return downloads

    def put(self, filename, name=None, dataset=None):
        """
        Import filename using OMERO CLI, optionally with a specified name
        to a specified dataset (dataset_id).
        Return : OMERO image Id
        """
        cli = omero.cli.CLI()
        cli.loadplugins()
        import_args = ["import"]
        import_args.extend(["-s", str(self._server)])
        import_args.extend(["-k", str(self._key)])
        if dataset is not None:
            import_args.extend(["-d", str(dataset)])
        if name is not None:
            import_args.extend(["-n", str(name)])
        clio = "cli.out"
        clie = "cli.err"
        import_args.extend(["---errs=" + clie, "---file=" + clio, "--"])
        import_args.append(filename)
        cli.invoke(import_args, strict=True)
        pix_id = int(open(clio, 'r').read().rstrip())
        im_id = self.conn.getQueryService().get("Pixels", pix_id).image.id.val
        os.remove(clio)
        os.remove(clie)
        return im_id

    def describe(self, im_id, description):
        """
        Append to image description.
        """
        img = self.conn.getObject("Image", oid=im_id)
        old_description = img.getDescription() or ""
        img.setDescription(old_description + "\n" + description)
        img.save()

    def attach(self, im_id, attachments):
        """
        Attach a list of files to an image.
        """
        img = self.conn.getObject("Image", oid=im_id)
        for attachment in attachments.split():
            fann = self.conn.createFileAnnfromLocalFile(attachment)
            img.linkAnnotation(fann)
        img.save()

    # TODO: ls_tags() and tag() methods?

    def mkp(self, project_name, description=None):
        """
        Make new OMERO project in current group, returning the new project Id.
        """
        # see: omero/lib/python/omeroweb/webclient/controller/container.py
        proj = omero.model.ProjectI()
        proj.name = omero.rtypes.rstring(str(project_name))
        if description is not None and description != "":
            proj.description = omero.rtypes.rstring(str(description))
        return self._save_and_return_id(proj)

    def mkd(self, dataset_name, project_id=None, description=None):
        """
        Make new OMERO dataset, returning the new dataset Id.
        """
        dset = omero.model.DatasetI()
        dset.name = omero.rtypes.rstring(str(dataset_name))
        if description is not None and description != "":
            dset.description = omero.rtypes.rstring(str(description))
        if project_id is not None:
            l_proj_dset = omero.model.ProjectDatasetLinkI()
            proj = self.conn.getObject("Project", project_id)
            l_proj_dset.setParent(proj._obj)
            l_proj_dset.setChild(dset)
            dset.addProjectDatasetLink(l_proj_dset)
        return self._save_and_return_id(dset)

    def _save_and_return_id(self, obj):
        """Save new omero object and return id assgined to it"""
        # see: OmeroWebGateway.saveAndReturnId
        # in: lib/python/omeroweb/webclient/webclient_gateway.py
        u_s = self.conn.getUpdateService()
        res = u_s.saveAndReturnObject(obj, self.conn.SERVICE_OPTS)
        res.unload()
        return res.id.val

    def im(self, im_id):
        """
        Return an Im object for the image id specified.
        """
        img = self.conn.getObject("Image", im_id)
        # build pixel np.ndarray
        nx, ny = img.getSizeX(), img.getSizeY()
        nz, nt, nc = img.getSizeZ(), img.getSizeT(), img.getSizeC()
        planes = [(z, c, t) for c in range(nc)
                  for t in range(nt)
                  for z in range(nz)]
        pix_gen = img.getPrimaryPixels().getPlanes(planes)
        pix = np.array([i for i in pix_gen]).reshape((nc, nt, nz, ny, nx))
        # initialize Im using pix and extracted metadata
        meta = self._extract_meta(img, im_id)
        return Im(pix=pix, meta=meta)

    def _extract_meta(self, img, im_id):
        """Extract metadata attributes from OMERO Blitz gateway Image"""
        meta = {}
        meta['name'] = self._unique_name(img.getName(), im_id)
        meta['description'] = img.getDescription()

        def _extract_ch_info(ch):
            """extract core metadata for for channel, return as dict"""
            ch_info = {'label': ch.getLabel()}
            ch_info['ex_wave'] = ch.getExcitationWave()
            ch_info['em_wave'] = ch.getEmissionWave()
            ch_info['color'] = ch.getColor().getRGB()
            return ch_info

        meta['channels'] = [_extract_ch_info(ch) for ch in img.getChannels()]
        meta['pixel_size'] = {'x': img.getPixelSizeX(),
                              'y': img.getPixelSizeY(),
                              'z': img.getPixelSizeZ(),
                              'units': "um"}
        tag_type = omero.model.TagAnnotationI
        tags = [ann for ann in img.listAnnotations()
                if ann.OMERO_TYPE == tag_type]
        meta['tags'] = {tag.getValue() + " (" + str(tag.getId()) + ")":
                        tag.getDescription() for tag in tags}
        fa_type = omero.model.FileAnnotationI
        attachments = [ann for ann in img.listAnnotations()
                       if ann.OMERO_TYPE == fa_type]
        meta['attachments'] = [att.getFileName() + " (" + str(att.getId()) +
                               ")" for att in attachments]
        user_id = self.conn.getUser().getName() + " (" + \
            str(self.conn.getUser().getId()) + ") @" + self.conn.host
        meta_ext = {}
        meta_ext['user_id'] = user_id
        meta['meta_ext'] = meta_ext
        # TODO: ROIs, display settings?
        # objective: Image.loadOriginalMetadata()[1][find 'Lens ID Number'][1],
        return meta

    def imput(self, im, dataset_id=None):
        """
        Create a new OMERO Image using an Im object, returning new image id.
        """
        # see: omero/lib/python/omero/util/script_utils.py
        # see: omero/lib/python/omeroweb/webclient/webclient_gateway.py
        # see: https://gist.github.com/will-moore/4141708
        if not isinstance(im, Im):
            raise TypeError("first imput argument must be of type Im")
        nc, nt, nz, ny, nx = im.shape
        ch_nums = range(nc)
        q_s = self.conn.getQueryService()
        p_s = self.conn.getPixelsService()
        c_s = self.conn.getContainerService()
        u_s = self.conn.getUpdateService()
        pu_s = self.conn.c.sf.createRawPixelsStore()
        q_ptype = "from PixelsType as p where p.value='{0}'".format(
                  str(im.dtype))
        pixelsType = q_s.findByQuery(q_ptype, None)
        im_id = p_s.createImage(nx, ny, nz, nt, ch_nums, pixelsType,
                    im.name, im.description)
        img_i = c_s.getImages("Image", [im_id.getValue()], None)[0]
        img = self.conn.getObject("Image", im_id.getValue())
        pix_id = img_i.getPrimaryPixels().getId().getValue()
        pu_s.setPixelsId(pix_id, True)
        for c in range(nc):
            for t in range(nt):
                for z in range(nz):
                    plane = im.pix[c, t, z, :, :]
                    script_utils.uploadPlaneByRow(pu_s, plane, z, c, t)
        l_dset_im = omero.model.DatasetImageLinkI()
        dset = self.conn.getObject("Dataset", dataset_id)
        l_dset_im.setParent(dset._obj)
        l_dset_im.setChild(img._obj)
        self._update_meta(im, im_id)
        u_s.saveObject(l_dset_im, self.conn.SERVICE_OPTS)
        return im_id.getValue()

    def _update_meta(self, im, im_id):
        """Set OMERO Image metadata using Im metadata"""
Ejemplo n.º 53
0
        if e.errno != errno.EEXIST:
            raise


HOST = "lincs-omero.hms.harvard.edu"
PORT = 4064
GROUP = "Public"

# Read username and password.
print "Connecting to OMERO server: %s:%d" % (HOST, PORT)
username = getpass._raw_input("Username: "******"Error: Connection not available, please check your " "username and password.")
    sys.exit(1)
else:
    print "Login successful.\n"

# Set our default group so we can see the data.
# (I thought I had to do this, but now I am not sure it's needed.
# -JLM 2013/12/04)
try:
    group = next(g for g in conn.listGroups() if g.getName() == GROUP)
except StopIteration:
    print >> sys.stderr, "Error: could not find group '%s'" % GROUP
conn.setGroupForSession(group.getId())
Ejemplo n.º 54
0
import omero
import omero.cli
from omero.gateway import BlitzGateway
from omero.rtypes import wrap, rlong, rdouble, rint, rstring
from omero.model import DatasetI, ProjectI, TagAnnotationI

# Only these people will be logged in to do Tagging, Comments etc 
# We will still create Tags for ALL users so they're available for others to use.

USER_NAMES = ["user-10", "user-11", "user-12"]
# USER_NAMES = ["user-7", "user-8", "user-9", "user-10", "user-11", "user-12"]



conn = BlitzGateway('root', 'omero', host='localhost')
conn.connect()

conn.SERVICE_OPTS.setOmeroGroup(-1)


# ---- CONFIGURATION ----
TAG_COUNT = 1       # Number of tags each user should use (link)
TAG_TARGETS = ['Project', 'Dataset', 'Image', "Screen", "Plate"]
ROI_COUNT = 3

allUsers = []
for exp in conn.getObjects("Experimenter"):
    n = exp.getName()
    if n not in ["root", "guest"]:
        print n
        allUsers.append(exp)
 def use_connection(self, cli, host):
     sessionId = cli._event_context.sessionUuid
     conn = BlitzGateway(host=host)
     conn.connect(sUuid = sessionId)
     return conn
Ejemplo n.º 56
0
PORT = 4064
USER = "******"
# PASS = '******'
# PASS = '******'
SU_USER = "******"
SU_PASS = "******"

try:
    from localconfig import USER, SU_USER, SU_PASS, MANAGED_REPO
except ImportError:
    print "Using hard-coded configuration values!"


su_conn = BlitzGateway(SU_USER, SU_PASS, host=HOST, port=PORT)
if su_conn.connect() is False:
    raise RuntimeError("Connection to OMERO failed, check settings!")

conn = su_conn.suConn(USER)
if conn.connect() is False:
    raise RuntimeError("User switching in OMERO failed, check settings!")


su_conn = BlitzGateway(SU_USER, SU_PASS, host=HOST, port=PORT)
su_conn.connect()
conn = su_conn.suConn(USER)
conn.connect()

# projs = [ x for x in conn.listProjects() ]
projs = [x for x in conn.listProjects(eid=conn.getUserId())]
for proj in projs: