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()
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()
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(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()
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 test_numpy_to_image(self): client = self.new_client() image = self.create_test_image(100, 100, 2, 3, 4, client.getSession()) conn = BlitzGateway(client_obj=client) image = conn.getObject("Image", image.id.val) pixels = image.getPrimaryPixels() channel_min_max = [] for c in image.getChannels(): min_c = c.getWindowMin() max_c = c.getWindowMax() channel_min_max.append((min_c, max_c)) z = image.getSizeZ() / 2 t = 0 c = 0 try: for min_max in channel_min_max: plane = pixels.getPlane(z, c, t) i = scriptUtil.numpy_to_image(plane, min_max, int32) assert i is not None try: # check if the image can be handled. i.load() assert True except IOError: assert False c += 1 finally: conn.close()
def get_file_contents(client, original_file_id): """Returns Original File contents as a string.""" conn = BlitzGateway(client_obj=client) orig_file = conn.getObject("OriginalFile", original_file_id) text = "".join(orig_file.getFileInChunks()) conn.close() return text
def check_file_annotation(client, file_annotation, parent_type="Image", is_linked=True, file_name=None): """ Check validity of file annotation. If hasFileAnnotation, check the size, name and number of objects linked to the original file. """ assert file_annotation is not None orig_file = file_annotation.getValue().getFile() assert orig_file.getSize().getValue() > 0 assert orig_file.getName().getValue() is not None id = file_annotation.getValue().getId().getValue() assert id > 0 conn = BlitzGateway(client_obj=client) wrapper = conn.getObject("FileAnnotation", id) name = None if file_name is not None: name = wrapper.getFile().getName() links = sum(1 for i in wrapper.getParentLinks(parent_type)) conn.close() if is_linked: assert links == 1 else: assert links == 0 if file_name is not None: assert name == file_name
def check(self): from omero.cli import CLI from omero.gateway import BlitzGateway cli = CLI() cli.loadplugins() cli.onecmd('login -q') try: gateway = BlitzGateway(client_obj=cli.get_client()) for experiment in self.m["experiments"]: self.check_object(gateway, experiment, "Project") for experiment in self.m["screens"]: self.check_object(gateway, experiment, "Screen") if "map" in self.m: if self.m["experiments"]: study_type = "Project" else: study_type = "Screen" self.check_object(gateway, self.m, study_type) finally: if cli: cli.close() gateway.close()
def check(obj): from omero.cli import CLI from omero.gateway import BlitzGateway cli = CLI() cli.loadplugins() cli.onecmd('login') try: gateway = BlitzGateway(client_obj=cli.get_client()) remote_obj = gateway.getObject( obj.type, attributes={"name": obj.name}) errors = [] if remote_obj.description != obj.description: errors.append("current:%s\nexpected:%s" % ( remote_obj.description, obj.description)) for al in remote_obj._getAnnotationLinks( ns="openmicroscopy.org/omero/client/mapAnnotation"): mapValue = al.child.mapValue kv_pairs = [(m.name, m.value) for m in mapValue] for i in range(len(kv_pairs)): if kv_pairs[i] != obj.map[i]: errors.append( "current:%s\nexpected:%s" % (kv_pairs[i], obj.map[i])) if not errors: log.info("No annotations mismatch detected") else: for e in errors: log.info("Found some annotations mismatch") print e finally: if cli: cli.close() gateway.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()
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})
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()
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()
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 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 test_get_objects(self): client = self.new_client() image = self.create_test_image(100, 100, 1, 1, 1, client.getSession()) conn = BlitzGateway(client_obj=client) params = {} params["Data_Type"] = "Image" params["IDs"] = [image.id.val] objects, message = scriptUtil.get_objects(conn, params) assert objects[0].id == image.id.val assert message is '' conn.close()
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()
def make_roi_images(request,image_id): conn = BlitzGateway(OMERO_USER,OMERO_PASSWORD,host=os.environ['OMEROHOST']) if not conn.connect(): return HttpResponseServerError("Could not connect to Omero server") parameterMap = {'Data_Type':'Image', 'IDs':[long(image_id)], 'New_Dataset':True, 'New_Dataset_Name':'ROI_images', 'Entire_Stack':False } msg = img_from_roi.makeImagesFromRois(conn,parameterMap) conn.close() return render(request, 'exportml/gen_roi_message.html', {'messages':msg})
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 run_as_script(): """ The main entry point of the script, as called by the client via the scripting service, passing the required parameters. """ data_types = [rstring('Dataset')] client = scripts.client( 'Shapes_To_Table.py', ("This script processes images, measuring the length of ROI Lines and" " saving the results to an OMERO.table."), scripts.String( "Data_Type", optional=False, grouping="1", description="Choose source of images (only Dataset supported)", values=data_types, default="Dataset"), scripts.List("IDs", optional=False, grouping="2", description="List of Dataset IDs to convert to new" " Plates.").ofType(rlong(0)), version="4.3.2", authors=["William Moore", "OME Team"], institutions=["University of Dundee"], contact="*****@*****.**", ) try: # process the list of args above. script_params = {} for key in client.getInputKeys(): if client.getInput(key): script_params[key] = client.getInput(key, unwrap=True) print(script_params) # wrap client to use the Blitz Gateway conn = BlitzGateway(client_obj=client) # process images in Datasets message = process_data(conn, script_params) if message is not None: client.setOutput("Message", rstring(message)) else: client.setOutput("Message", rstring("No datasets found")) finally: conn.close()
def connection_test(username, password, host=HOST, port=PORT, secure=False): print(f'connecting to {host}:{port} secure={secure}') conn = BlitzGateway(username, password, host=host, port=port, secure=secure) try: connected = conn.connect() conn.close() return connected except: conn.close() return False
def test_populate_metadata_for_screen(self): sid = super(TestImportScripts, self).get_script(populate_metadata) assert sid > 0 client, user = self.new_client_and_user() update_service = client.getSession().getUpdateService() plates = self.import_plates(client, plate_cols=3, plate_rows=1) plate = plates[0] name = plate.name.val screen = omero.model.ScreenI() screen.name = omero.rtypes.rstring("test_for_screen") spl = omero.model.ScreenPlateLinkI() spl.setParent(screen) spl.setChild(plate) spl = update_service.saveAndReturnObject(spl) screen_id = spl.getParent().id.val assert screen_id > 0 assert spl.getChild().id.val == plate.id.val cvs_file = create_path("test_screen", ".csv") # create a file annotation with open(cvs_file.abspath(), 'w+') as f: f.write("Well,Plate, Well Type, Facility-Salt-Batch-ID\n") f.write("A01,%s,Treatment,FOOL10041-101-2\n" % name) f.write("A02,%s,Control,\n" % name) f.write("A03,%s,Treatment,FOOL10041-101-2\n" % name) conn = BlitzGateway(client_obj=client) fa = conn.createFileAnnfromLocalFile(cvs_file, mimetype="text/csv") assert fa is not None assert fa.id > 0 link = omero.model.ScreenAnnotationLinkI() link.setParent(omero.model.ScreenI(screen_id, False)) link.setChild(omero.model.FileAnnotationI(fa.id, False)) link = update_service.saveAndReturnObject(link) assert link.id.val > 0 # run the script screen_ids = [] screen_ids.append(spl.getParent().id) args = { "Data_Type": omero.rtypes.rstring("Screen"), "IDs": omero.rtypes.rlist(screen_ids), "File_Annotation": omero.rtypes.rstring(str(fa.id)) } message = run_script(client, sid, args, "Message") assert message is not None assert message.getValue().startswith('Table data populated') conn.close()
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!')
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()
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()
def check(self, update=False): from omero.cli import CLI from omero.gateway import BlitzGateway cli = CLI() cli.loadplugins() cli.onecmd('login -q') try: gateway = BlitzGateway(client_obj=cli.get_client()) self.check_study(gateway, update=update) finally: if cli: cli.close() gateway.close()
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()
def check_file_annotation(client, file_annotation, parent_type="Image", link_count=0): """ Check validity of file annotation. If hasFileAnnotation, check the size, name and number of objects linked to the original file. """ assert file_annotation is not None id = file_annotation.getId().getValue() assert id > 0 orig_file = file_annotation.getFile() assert orig_file.getSize().getValue() > 0 assert orig_file.getName().getValue() is not None conn = BlitzGateway(client_obj=client) wrapper = conn.getObject("FileAnnotation", id) links = sum(1 for i in wrapper.getParentLinks(parent_type)) conn.close() assert links == link_count