def test_unlinkAnnotations(self): us = self.conn.getUpdateService() f = omero.model.OriginalFileI() f.setName(wrap(str(uuid.uuid1()))) f.setPath(wrap(str(uuid.uuid1()))) f = self.sess.getUpdateService().saveAndReturnObject(f) tag = omero.model.TagAnnotationI() tag.setTextValue(wrap(str(uuid.uuid1()))); tag = us.saveAndReturnObject(tag); link = omero.model.OriginalFileAnnotationLinkI() link.setChild(tag) link.setParent(f) link = us.saveAndReturnObject(link) self.assertIsNotNone(self.getObject('TagAnnotation', tag.id)) self.assertIsNotNone(self.getObject('OriginalFile', f.id)) self.assertIsNotNone(self.getObject( 'OriginalFileAnnotationLink', link.id)) file = self.conn.getObject('OriginalFile', unwrap(f.id)) WndcharmStorage.unlinkAnnotations(self.conn, file) self.assertIsNotNone(self.getObject('TagAnnotation', tag.id)) self.assertIsNotNone(self.getObject('OriginalFile', file.id)) self.assertIsNone(self.getObject('OriginalFileAnnotationLink', link.id)) self.delete('/OriginalFile', unwrap(f.id)) self.delete('/Annotation', unwrap(tag.id))
def createClassifierTagSet(conn, classifierName, instanceName, labels, project = None): """ Create a tagset and labels associated with an instance of a classifier """ us = conn.getUpdateService() tagSet = omero.model.TagAnnotationI() instanceNs = classifierName + '/' + instanceName tagSet.setTextValue(wrap(instanceNs)); tagSet.setNs(wrap(omero.constants.metadata.NSINSIGHTTAGSET)); tagSet.setDescription(wrap('Classification labels for ' + instanceNs)) tagSetR = us.saveAndReturnObject(tagSet); tagSetR.unload() for lb in labels: tag = omero.model.TagAnnotationI() tag.setTextValue(wrap(lb)); tag.setNs(wrap(instanceNs)); tagR = us.saveAndReturnObject(tag); link = omero.model.AnnotationAnnotationLinkI() link.setChild(tagR) link.setParent(tagSetR) linkR = us.saveAndReturnObject(link) assert(linkR) if project: annLink = omero.model.ProjectAnnotationLinkI() annLink.link(omero.model.ProjectI(project.getId(), False), tagSetR) us.saveAndReturnObject(annLink); return instanceNs
def create_tag(self, name, ns=None): t = omero.model.TagAnnotationI() t.setTextValue(wrap(name)) if ns is not None: t.setNs(wrap(ns)) t = self.sess.getUpdateService().saveAndReturnObject(t) return unwrap(t.getId())
def test_deleteTags(self): us = self.conn.getUpdateService() tagSet = omero.model.TagAnnotationI() classifierName = 'getClassifierTagSet' instanceName = str(uuid.uuid1()) instanceNs = classifierName + '/' + instanceName tagSet.setTextValue(wrap(instanceNs)); tagSet.setNs(wrap(omero.constants.metadata.NSINSIGHTTAGSET)); tagSet = us.saveAndReturnObject(tagSet); tag = omero.model.TagAnnotationI() tag.setTextValue(wrap(str(uuid.uuid1()))); tag.setNs(wrap(instanceNs)); tag = us.saveAndReturnObject(tag); link = omero.model.AnnotationAnnotationLinkI() link.setChild(tag) link.setParent(tagSet) link = us.saveAndReturnObject(link) self.assertIsNotNone(self.getObject('TagAnnotation', tagSet.id)) self.assertIsNotNone(self.getObject('TagAnnotation', tag.id)) self.assertIsNotNone(self.getObject( 'AnnotationAnnotationLink', link.id)) WndcharmStorage.deleteTags(self.conn, tagSet) self.assertIsNone(self.getObject('TagAnnotation', tagSet.id)) self.assertIsNone(self.getObject('TagAnnotation', tag.id)) self.assertIsNone(self.getObject( 'AnnotationAnnotationLink', link.id))
def addFileAnnotationTo(tc, obj): """ Attach a table as an annotation to an object (dataset/project) if not already attached """ # The OriginalFile may be out-of-date, which can lead to data loss, so # reload it #tfile = tc.table.getOriginalFile() tfile = tc.conn.getObject( 'OriginalFile', unwrap(tc.table.getOriginalFile().getId())) oclass = obj.OMERO_CLASS obj = tc.conn.getObject(oclass, obj.getId()) for a in obj.listAnnotations(WNDCHARM_NAMESPACE): if isinstance(a, omero.gateway.FileAnnotationWrapper): if tfile.getId() == unwrap(a._obj.getFile().getId()): return 'Already attached' fa = omero.model.FileAnnotationI() fa.setFile(tfile._obj) fa.setNs(wrap(WNDCHARM_NAMESPACE)) fa.setDescription(wrap(WNDCHARM_NAMESPACE + ':' + tfile.getName())) objClass = getattr(omero.model, oclass + 'I') linkClass = getattr(omero.model, oclass + 'AnnotationLinkI') annLink = linkClass() annLink.link(objClass(obj.getId(), False), fa) annLink = tc.conn.getUpdateService().saveAndReturnObject(annLink) return 'Attached file id:%d to %s id:%d\n' % \ (tfile.getId(), oclass, obj.getId())
def test_create_map_ann(self, ns, kw): sess = MockSession() self.mox.StubOutWithMock(sess.us, 'saveAndReturnObject') map = {'a': rstring('1'), 'bb': rstring('cc')} rid = 2 r = omero.model.MapAnnotationI() if ns: r.setNs(rstring(ns)) r.setMapValue(map) r.setId(rlong(rid)) sess.us.saveAndReturnObject(mox.Func( lambda o: o.getNs() == wrap(ns) and o.getMapValue() == wrap(map).val)).AndReturn(r) self.mox.ReplayAll() ma = OmeroMetadata.MapAnnotations(sess, namespace=ns) if kw: assert ma.create_map_annkw(a='1', bb='cc') == rid else: assert ma.create_map_ann({'a': '1', 'bb': 'cc'}) == rid self.mox.VerifyAll()
def removeTagAnnotations(conn, obj): """ Unlink tag annotations, but do not delete the tags """ linkType = obj.OMERO_CLASS + 'AnnotationLink' q = 'select oal from %s as oal join ' \ 'fetch oal.child as ann where oal.parent.id = :parentid and ' \ 'oal.child.ns like :ns' % linkType params = omero.sys.Parameters() params.map = { 'parentid': wrap(obj.getId()), 'ns': wrap(WndcharmStorage.CLASSIFIER_WNDCHARM_NAMESPACE + '/%') } anns = conn.getQueryService().findAllByQuery(q, params) rmIds = [] rmTags = [] for ann in anns: if isinstance(ann.child, omero.model.TagAnnotation): rmIds.append(unwrap(ann.getId())) rmTags.append(unwrap(ann.child.getTextValue())) deleteObjects(conn, linkType, rmIds) message = 'Removed tags: %s from %s id:%d\n' % ( rmTags, obj.OMERO_CLASS, obj.getId()) return message
def create_map_ann(self, kvs): d = dict((k, wrap(str(v))) for k, v in kvs.iteritems()) m = omero.model.MapAnnotationI() m.setNs(wrap(self.namespace)) m.setMapValue(d) m = self.session.getUpdateService().saveAndReturnObject(m) return unwrap(m.id)
def make_web_figure(request, conn=None, **kwargs): """ Uses the scripting service to generate pdf via json etc in POST data. Script will show up in the 'Activities' for users to monitor and download result etc. """ if not request.method == 'POST': return HttpResponse("Need to use POST") scriptService = conn.getScriptService() sId = scriptService.getScriptID(SCRIPT_PATH) figureJSON = request.POST.get('figureJSON') # see https://github.com/will-moore/figure/issues/16 figureJSON = unicodedata.normalize('NFKD', figureJSON).encode('ascii','ignore') webclient_uri = request.build_absolute_uri(reverse('webindex')) figure_dict = json.loads(figureJSON) inputMap = { 'Figure_JSON': wrap(figureJSON), 'Webclient_URI': wrap(webclient_uri)} # If the figure has been saved, construct URL to it... if 'fileId' in figure_dict: try: figureUrl = reverse('load_figure', args=[figure_dict['fileId']]) figureUrl = request.build_absolute_uri(figureUrl) inputMap['Figure_URI'] = wrap(figureUrl) except: pass rsp = run_script(request, conn, sId, inputMap, scriptName='Figure.pdf') return HttpResponse(json.dumps(rsp), content_type='json')
def make_web_figure(request, conn=None, **kwargs): """ Uses the scripting service to generate pdf via json etc in POST data. Script will show up in the 'Activities' for users to monitor and download result etc. """ if not request.method == 'POST': return HttpResponse("Need to use POST") script_service = conn.getScriptService() sid = script_service.getScriptID(SCRIPT_PATH) figure_json = request.POST.get('figureJSON') # export options e.g. "PDF", "PDF_IMAGES" export_option = request.POST.get('exportOption') webclient_uri = request.build_absolute_uri(reverse('webindex')) input_map = { 'Figure_JSON': wrap(figure_json.encode('utf8')), 'Export_Option': wrap(str(export_option)), 'Webclient_URI': wrap(webclient_uri)} # If the figure has been saved, construct URL to it. figure_dict = json.loads(figure_json) if 'fileId' in figure_dict: try: figure_url = reverse('load_figure', args=[figure_dict['fileId']]) figure_url = request.build_absolute_uri(figure_url) input_map['Figure_URI'] = wrap(figure_url) except NoReverseMatch: pass rsp = run_script(request, conn, sid, input_map, scriptName='Figure.pdf') return HttpResponse(json.dumps(rsp), content_type='json')
def query_by_map_ann(self, kvs, projection=None): params = omero.sys.ParametersI() qs = self.session.getQueryService() conditions = [] if self.namespace is not None: conditions.append('ann.ns = :ns') params.addString('ns', self.namespace) for k, v in kvs.iteritems(): paramk = 'k%d' % len(conditions) paramv = 'v%d' % len(conditions) params.addString(paramk, k) if isinstance(v, list): conditions.append( 'ann.mapValue[:%s] in (:%s)' % (paramk, paramv)) else: conditions.append( 'ann.mapValue[:%s] = :%s' % (paramk, paramv)) params.add(paramv, wrap(v)) # join fetch mapValue is only needed if we need to return the map, the # query should run without it if projection: q = ('select ann.id, index(map), map from MapAnnotation ann ' 'join ann.mapValue map') try: iter(projection) conditions.append('index(map) in (:fields)') params.add('fields', wrap(projection)) except TypeError: pass else: q = 'from MapAnnotation ann join fetch ann.mapValue map' if conditions: q += ' where ' + ' and '.join(conditions) if projection: # Each [id, key, value] is returned separately, use order by to # ensure all keys/values for an annotation are consecutive q += ' order by ann.id' anns = self.paged_query(qs.projection, q, params) # iikvs: A map of ids:((id, key, value), ...) results = dict( (unwrap(iikvs[0]), dict((unwrap(ikv[1]), unwrap(ikv[2])) for ikv in iikvs[1])) for iikvs in itertools.groupby(anns, lambda x: x[0])) else: results = self.paged_query(qs.findAllByQuery, q, params) return results
def createNonNsTag(self): """ Creates a tag in an unrelated namespace. Use this to check only the relevant tags are deleted. """ tag = omero.model.TagAnnotationI() tag.setNs(wrap('/other/namespace')) tag.setTextValue(wrap('x')) return self.saveAndLinkTag(tag)
def createNameTag(self, did=None): """ Creates a tag object with the expected namespace and database name. """ ns, dbn = self.getNames(did) tag = omero.model.TagAnnotationI() tag.setNs(wrap(ns)) tag.setTextValue(wrap(dbn)) return tag
def test_updateNameTag(self): tag = omero.model.TagAnnotationI() tag.setNs(wrap('foo')) tag.setTextValue(wrap('bar')) tag = self.conn.getUpdateService().saveAndReturnObject(tag) pysliddb.updateNameTag(self.conn, tag, 'baz') tag2 = self.conn.getObject('TagAnnotation', unwrap(tag.getId()))._obj self.assertEqual(tag2.getNs(), tag.getNs()) self.assertEqual(unwrap(tag2.getTextValue()), 'baz')
def create_table(sess, path, name, widths, coltype, interleave): table = sess.sharedResources().newTable(0, "name") cols, meta, ftnames = TableStoreHelper.get_columns(widths, coltype, interleave) table.initialize(cols) ofile = table.getOriginalFile() ofile.setPath(wrap(path)) ofile.setName(wrap(name)) ofile = sess.getUpdateService().saveAndReturnObject(ofile) tid = unwrap(ofile.getId()) table.close() return tid, cols, meta, ftnames
def createVersionAnnotation(conn, version): """ Create the Annotation object used to represent a particular Wndcharm version """ assert(getVersionAnnotation(conn, version) is None) us = conn.getUpdateService() tag = omero.model.TagAnnotationI() tag.setNs(wrap(WNDCHARM_VERSION_NAMESPACE)) tag.setTextValue(wrap(version)) tag = us.saveAndReturnObject(tag) return tag
def filterImageUserChannels(conn, iids, uids=None, chnames=None): """ Queries the database to see which images fit the requested criteria TODO: Check whether this query is correct or not... it might not be """ if not iids: return {} qs = conn.getQueryService() query = ('select p from Pixels p join ' 'fetch p.channels as c join ' 'fetch c.logicalChannel as lc join ' 'fetch p.image as im ' 'where im.id in (:iids)') params = omero.sys.ParametersI() params.add('iids', wrap([long(u) for u in iids])) logger.debug('iids:%s uids:%s chnames:%s', iids, uids, chnames) if uids: query += 'and p.details.owner.id in (:uids) ' params.add('uids', wrap([long(u) for u in uids])) if chnames: if UNNAMED_CHANNEL in chnames: query += 'and (lc.name in (:chns) or lc.name is NULL) ' else: query += 'and lc.name in (:chns) ' params.add('chns', wrap([str(chn) for chn in chnames])) ps = qs.findAllByQuery(query, params, conn.SERVICE_OPTS) def getChName(pixels, c): try: ch = p.getChannel(c) except IndexError: return None if not ch: return None name = ch.getLogicalChannel(c).name if name is None: return UNNAMED_CHANNEL return unwrap(name) imChMap = {} for p in ps: iid = unwrap(p.image.id) # The HQL query restricted the channel search, so some channels won't # be loaded. Unloaded trailing channels won't be created either. cs = [getChName(p, c) for c in xrange(unwrap(p.getSizeC()))] imChMap[iid] = cs return imChMap
def testWrap(self): rv = wrap([1, 2, 3]) assert isinstance(rv, omero.RList) assert [1 == 2, 3], unwrap(rv) for x in rv.val: assert isinstance(x, omero.RInt) rv = wrap({"a": 1}) assert isinstance(rv, omero.RMap) assert "a" in rv.val assert isinstance(rv.val["a"], omero.RInt) assert 1 == rv.val["a"].val pytest.raises(ValueError, wrap, {1: 2})
def create_containers(conn, 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) p = conn.getObject("Project", project.getId()) 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) d = conn.getObject("Dataset", dataset.getId()) 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 d,dsId
def addCommentTo(conn, comment, objType, objId): """ Add a comment to an object (dataset/project/image) """ ca = omero.model.CommentAnnotationI() ca.setNs(wrap(WNDCHARM_NAMESPACE)) ca.setTextValue(wrap(comment)) objClass = getattr(omero.model, objType + 'I') linkClass = getattr(omero.model, objType + 'AnnotationLinkI') annLink = linkClass() annLink.link(objClass(objId, False), ca) annLink = conn.getUpdateService().saveAndReturnObject(annLink) return 'Attached comment to %s id:%d\n' % (objType, objId)
def runAsScript(): """ The main entry point of the script. Gets the parameters from the scripting service, makes the figure and returns the output to the client. def __init__(self, name, optional = False, out = False, description = None, type = None, min = None, max = None, values = None) """ formats = wrap(formatMap.keys()) # wrap each key in it's rtype ckeys = COLOURS.keys() ckeys = ckeys; ckeys.sort() cOptions = wrap(ckeys) client = scripts.client('Make_Movie','MakeMovie creates a movie of the image and attaches it to the originating image.', scripts.Long("Image_ID", description="The Image Identifier.", optional=False, grouping="1"), scripts.String("Movie_Name", description="The name of the movie", grouping="2"), scripts.Int("Z_Start", description="Projection range (if not specified, use defaultZ only - no projection)", min=0, default=0, grouping="3.1"), scripts.Int("Z_End", description="Projection range (if not specified or, use defaultZ only - no projection)", min=0, grouping="3.2"), scripts.Int("T_Start", description="The first time-point", min=0, default=0, grouping="4.1"), scripts.Int("T_End", description="The last time-point", min=0, grouping="4.2"), scripts.List("Channels", description="The selected channels", grouping="5").ofType(rint(0)), scripts.Bool("Show_Time", description="If true, display the time.", default=True, grouping="6"), scripts.Bool("Show_Plane_Info", description="If true, display the information about the plane e.g. Exposure Time.", default=True, grouping="7"), scripts.Int("FPS", description="Frames Per Second.", default=2, grouping="8"), scripts.Int("Scalebar", description="Scale bar size in microns. Only shown if image has pixel-size info.", min=1, grouping="9"), scripts.String("Format", description="Format to save movie", values=formats, default=QT, grouping="10"), scripts.String("Overlay_Colour", description="The colour of the scalebar.",default='White',values=cOptions, grouping="11"), scripts.Map("Plane_Map", description="Specify the individual planes (instead of using T_Start, T_End, Z_Start and Z_End)", grouping="12"), version = "4.2.0", authors = ["Donald MacDonald", "OME Team"], institutions = ["University of Dundee"], contact = "*****@*****.**", ) try: session = client.getSession() commandArgs = {} for key in client.getInputKeys(): if client.getInput(key): commandArgs[key] = client.getInput(key).getValue() print commandArgs fileAnnotation = writeMovie(commandArgs, session) if fileAnnotation: client.setOutput("Message", rstring("Movie Created")) client.setOutput("File_Annotation", robject(fileAnnotation)) finally: client.closeSession()
def show_project(request, projectId, conn=None, **kwargs): """ Show a project """ project = conn.getObject("Project", projectId) if project is None: raise Http404 # Set a limit to grab 5 images from each Dataset params = omero.sys.Parameters() params.theFilter = omero.sys.Filter() params.theFilter.limit = wrap(5) datasets = [] for ds in project.listChildren(): # want to display 5 images from each dataset images = ds.listChildren(params=params) datasets.append({"id": ds.getId(), "name": ds.getName(), "description": ds.getDescription(), "images": images}) context = {'template': "webgallery/show_project.html"} context['project'] = project context['datasets'] = datasets return context
def test_create_file_annotation(self, exists): session = MockSession(None, None, None) store = MockFeatureTable(session) self.mox.StubOutWithMock(store, 'get_objects') self.mox.StubOutWithMock(store, '_file_annotation_exists') self.mox.StubOutWithMock(session.us, 'saveAndReturnObject') ofile = omero.model.OriginalFileI(2) image = omero.model.ImageI(3) if exists: r = [MockOmeroObject(21), MockOmeroObject(22)] else: r = [] store._file_annotation_exists('Image', 3, 'ns', 2).AndReturn(r) if not exists: store.get_objects('Image', {'id': 3}).AndReturn([image]) mocklink = MockOmeroObject(23) session.us.saveAndReturnObject(mox.Func( lambda o: o.getParent() == image and o.getChild().getNs() == wrap('ns') and o.getChild().getFile() == ofile)).AndReturn(mocklink) self.mox.ReplayAll() if exists: assert store.create_file_annotation( 'Image', 3, 'ns', ofile) == r[0] else: assert store.create_file_annotation( 'Image', 3, 'ns', ofile) == mocklink self.mox.VerifyAll()
def create_file_annotation(self, object_type, object_id, ns, ofile): """ Create a file annotation :param object_type: The object type :param object_id: The object ID :param ns: The namespace :param ofile: The originalFile """ fid = unwrap(ofile.getId()) links = self._file_annotation_exists(object_type, object_id, ns, fid) if len(links) > 1: log.warn('Multiple links found: ns:%s %s:%d file:%d', ns, object_type, object_id, fid) if links: return links[0] obj = self.get_objects(object_type, {'id': object_id}) if len(obj) != 1: raise OmeroTableException( 'Failed to get object %s:%d' % (object_type, object_id)) link = getattr(omero.model, '%sAnnotationLinkI' % object_type)() ann = omero.model.FileAnnotationI() ann.setNs(wrap(ns)) ann.setFile(ofile) link.setParent(obj[0]) link.setChild(ann) link = self.session.getUpdateService().saveAndReturnObject(link) return link
def test2910(self): group = self.new_group(perms="rwr---") user1 = self.new_client(group) user2 = self.new_client(group) # As the first user, create a file table = user1.sf.sharedResources().newTable(1, "test2910.h5") assert table lc = omero.grid.LongColumn("lc", None, None) file = table.getOriginalFile() table.initialize([lc]) # Not deleting since queried table.close() # As the second user, try to modify it table = user2.sf.sharedResources().openTable(file) assert table lc.values = [1] with pytest.raises(omero.SecurityViolation): table.initialize(None) with pytest.raises(omero.SecurityViolation): table.addColumn(None) with pytest.raises(omero.SecurityViolation): table.addData([lc]) with pytest.raises(omero.SecurityViolation): table.update(None) with pytest.raises(omero.SecurityViolation): table.delete() with pytest.raises(omero.SecurityViolation): table.setMetadata("key", wrap(1)) with pytest.raises(omero.SecurityViolation): table.setAllMetadata({})
def get_users(conn, user_ids): """ Lookup user IDs and return usernames """ params = omero.sys.ParametersI() service_opts = deepcopy(conn.SERVICE_OPTS) service_opts.setOmeroGroup(-1) params.add('uids', wrap(omero.rtypes.wrap(user_ids))) qs = conn.getQueryService() q = """ SELECT user.id, user.omeName FROM Experimenter user WHERE user.id IN (:uids) ORDER BY lower(user.omeName) """ rows = qs.projection(q, params, service_opts) for row in rows: yield { 'id': row[0].val, 'name': row[1].val }
def list_groups(conn): ctx = conn.getEventContext() # noqa myGroups = list(conn.getGroupsMemberOf()) # Need a custom query to get 1 (random) image per Project queryService = conn.getQueryService() params = omero.sys.ParametersI() params.theFilter = omero.sys.Filter() params.theFilter.limit = wrap(1) query = "select count(obj.id) from %s as obj" groups = [] for group in myGroups: conn.SERVICE_OPTS.setOmeroGroup(group.id) pCount = queryService.projection( query % 'Project', None, conn.SERVICE_OPTS) dCount = queryService.projection( query % 'Dataset', None, conn.SERVICE_OPTS) iCount = queryService.projection( query % 'Image', None, conn.SERVICE_OPTS) groups.append({'id': group.getId(), 'name': group.getName(), 'description': group.getDescription(), 'projectCount': pCount[0][0]._val, 'datasetCount': dCount[0][0]._val, 'imageCount': iCount[0][0]._val}) # reset to first group conn.SERVICE_OPTS.setOmeroGroup(myGroups[0].id) return groups
def test_store_by_roi(self, image): session = MockSession(None, None, None) store = MockFeatureTable(session) self.mox.StubOutWithMock(session.qs, 'projection') self.mox.StubOutWithMock(store, 'store_by_object') values = [34] if image == 'lookup': params = omero.sys.ParametersI() params.addId(12) session.getQueryService().projection( 'SELECT r.image.id FROM Roi r WHERE r.id=:id', mox.Func( lambda o: self.parameters_equal(params, o))).AndReturn( [[wrap(1234)]]) imageid = 1234 elif image == 'provided': imageid = 123 else: imageid = None if imageid is None: store.store_by_object('Roi', 12, values) else: store.store_by_object('Roi', 12, values, 'Image', imageid) self.mox.ReplayAll() if image == 'lookup': store.store_by_roi(12, values) elif image == 'provided': store.store_by_roi(12, values, 123) else: store.store_by_roi(12, values, -1) self.mox.VerifyAll()
def get_objects(self, object_type, kvs): """ Retrieve OMERO objects """ params = omero.sys.ParametersI() qs = self.session.getQueryService() conditions = [] for k, v in kvs.iteritems(): ek = k.replace('_', '__').replace('.', '_') if isinstance(v, list): conditions.append( '%s in (:%s)' % (k, ek)) else: conditions.append( '%s = :%s' % (k, ek)) params.add(ek, wrap(v)) q = 'FROM %s' % object_type if conditions: q += ' WHERE ' + ' AND '.join(conditions) results = qs.findAllByQuery(q, params) return results
def download_file(request, file_id, conn=None, **kwargs): file_id = long(file_id) # Query config group_id = -1 params = omero.sys.ParametersI() conn.SERVICE_OPTS.setOmeroGroup(group_id) params.add('fid', wrap(file_id)) q = """ SELECT orig.size FROM OriginalFile orig WHERE orig.id = :fid """ qs = conn.getQueryService() # Query to ensure that the file exists and to confirm its size results = qs.projection(q, params, conn.SERVICE_OPTS) if len(results) != 1: raise Http404("File not found: %s" % file_id) size = results[0][0].val rsp = ConnCleaningHttpResponse(omeroFileStream(file_id, size, conn)) rsp.conn = conn rsp['Content-Length'] = size # Use the id as the filename for want of something better rsp['Content-Disposition'] = 'attachment; filename=%s' % ('partial-%s' % file_id) rsp['Content-Type'] = 'application/force-download' return rsp
def runAsScript(): dataTypes = [rstring('Image')] client = scripts.client( 'Z_Projection.py', """Do Maximum-Intensity or Mean-Intensity projection of Z-stack images.""", scripts.String("Data_Type", optional=False, grouping="1", description="Pick Images by 'Image' ID", values=dataTypes, default="Image"), scripts.List("IDs", optional=False, grouping="2", description="List of Image IDs to " "process.").ofType(rlong(0)), scripts.String( "New_Dataset_Name", grouping="3", description="If you want the new image(s) in a new Dataset, " "put name here"), scripts.String("Z_Projection_Type", optional=False, grouping="4", description="Type of Projection", values=wrap(PROJECTIONS.keys()), default="Maximum"), scripts.Int("Z_Start", grouping="4.1", default=1, min=1, description="Start of Z-projection"), scripts.Int( "Z_End", grouping="4.2", min=1, description="End of Z-projection. Default is last Z-section."), scripts.Int("Every_nth_slice", grouping="4.3", min=1, default=1, description="Project every nth Z-section"), scripts.Int( "T_Start", grouping="6.0", default=1, min=1, description="Start of time-points to include in Z-projecton"), scripts.Int( "T_End", grouping="7.0", min=1, description= "End of time-points to include. Default is last Timepoint."), authors=["William Moore", "OME Team"], institutions=["University of Dundee"], ) try: scriptParams = client.getInputs(unwrap=True) print scriptParams # wrap client to use the Blitz Gateway conn = BlitzGateway(client_obj=client) iids, dataset = processImages(conn, scriptParams) # Return message, new image and new dataset (if applicable) to the # client if len(iids) == 0: message = "No image created." elif len(iids) == 1: message = "New image created." img = conn.getObject("Image", iids[0]) if img is not None: client.setOutput("Image", robject(img._obj)) else: message = "%s new images created." % len(iids) if dataset is None: dataset = conn.getObject("Image", iids[0]).getParent() if dataset is not None: message += " See Dataset:" client.setOutput("New Dataset", robject(dataset._obj)) client.setOutput("Message", rstring(message)) finally: client.closeSession()
def index(request, super_category=None, conn=None, **kwargs): """ Home page shows a list of groups OR a set of 'categories' from user-configured queries. """ category_queries = settings.CATEGORY_QUERIES if len(category_queries) > 0: context = {'template': "webgallery/categories/index.html"} context['favicon'] = settings.FAVICON context['gallery_title'] = settings.GALLERY_TITLE context['gallery_heading'] = settings.GALLERY_HEADING context['top_right_links'] = settings.TOP_RIGHT_LINKS context['top_left_logo'] = settings.TOP_LEFT_LOGO try: href = context['top_left_logo'].get('href', 'webgallery_index') context['top_left_logo']['href'] = reverse(href) except NoReverseMatch: pass context['subheading_html'] = settings.SUBHEADING_HTML context['footer_html'] = settings.FOOTER_HTML context['filter_keys'] = json.dumps(settings.FILTER_KEYS) context['TITLE_KEYS'] = json.dumps(settings.TITLE_KEYS) context['STUDY_SHORT_NAME'] = json.dumps(settings.STUDY_SHORT_NAME) context['filter_mapr_keys'] = json.dumps(settings.FILTER_MAPR_KEYS) context['super_categories'] = settings.SUPER_CATEGORIES category = settings.SUPER_CATEGORIES.get(super_category) if category is not None: label = category.get('label', context['gallery_heading']) title = category.get('title', label) context['gallery_heading'] = title context['super_category'] = json.dumps(category) context['category'] = super_category base_url = reverse('index') if settings.BASE_URL is not None: base_url = settings.BASE_URL context['base_url'] = base_url context['category_queries'] = json.dumps(category_queries) return context my_groups = list(conn.getGroupsMemberOf()) # Need a custom query to get 1 (random) image per Project query_service = conn.getQueryService() params = omero.sys.ParametersI() params.theFilter = omero.sys.Filter() params.theFilter.limit = wrap(1) query = "select count(obj.id) from %s as obj" groups = [] for g in my_groups: conn.SERVICE_OPTS.setOmeroGroup(g.id) images = list(conn.getObjects("Image", params=params)) if len(images) == 0: continue # Don't display empty groups p_count = query_service.projection(query % 'Project', None, conn.SERVICE_OPTS) d_count = query_service.projection(query % 'Dataset', None, conn.SERVICE_OPTS) i_count = query_service.projection(query % 'Image', None, conn.SERVICE_OPTS) groups.append({ 'id': g.getId(), 'name': g.getName(), 'description': g.getDescription(), 'projectCount': p_count[0][0]._val, 'datasetCount': d_count[0][0]._val, 'imageCount': i_count[0][0]._val, 'image': len(images) > 0 and images[0] or None }) # This is used by @render_response context = {'template': "webgallery/index.html"} context['groups'] = groups return context
def save_web_figure(conn, json_data): """ Saves 'figureJSON' in POST as an original file. If 'fileId' is specified in POST, then we update that file. Otherwise create a new one with name 'figureName' from POST. """ image_ids = [] first_img_id = None try: for panel in json_data['panels']: image_ids.append(panel['imageId']) if len(image_ids) > 0: first_img_id = int(image_ids[0]) # remove duplicates image_ids = list(set(image_ids)) # pretty-print json figure_json = json.dumps(json_data, sort_keys=True, indent=2, separators=(',', ': ')) except Exception: pass # See https://github.com/will-moore/figure/issues/16 figure_json = figure_json.encode('utf8') if 'figureName' in json_data and len(json_data['figureName']) > 0: figure_name = json_data['figureName'] else: print("No figure name found") return # we store json in description field... description = {} if first_img_id is not None: # We duplicate the figure name here for quicker access when # listing files # (use this instead of file name because it supports unicode) description['name'] = figure_name description['imageId'] = first_img_id if 'baseUrl' in panel: description['baseUrl'] = panel['baseUrl'] desc = json.dumps(description) # Create new file # Try to set Group context to the same as first image curr_gid = conn.SERVICE_OPTS.getOmeroGroup() i = None if first_img_id: i = conn.getObject("Image", first_img_id) if i is not None: gid = i.getDetails().getGroup().getId() conn.SERVICE_OPTS.setOmeroGroup(gid) else: # Don't leave as -1 conn.SERVICE_OPTS.setOmeroGroup(curr_gid) file_size = len(figure_json) f = BytesIO() f.write(figure_json) orig_file = conn.createOriginalFileFromFileObj(f, '', figure_name, file_size, mimetype="application/json") fa = FileAnnotationI() fa.setFile(OriginalFileI(orig_file.getId(), False)) fa.setNs(wrap(JSON_FILEANN_NS)) fa.setDescription(wrap(desc)) update = conn.getUpdateService() fa = update.saveAndReturnObject(fa, conn.SERVICE_OPTS) ann_id = fa.getId().getValue() return ann_id
def runAsScript(): """ The main entry point of the script, as called by the client via the scripting service, passing the required parameters. """ dataTypes = [rstring('Image')] labels = [rstring('Image Name'), rstring('Datasets'), rstring('Tags')] algorithums = [rstring('Maximum Intensity'), rstring('Mean Intensity')] formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')] ckeys = COLOURS.keys() ckeys.sort() oColours = wrap(OVERLAY_COLOURS.keys()) client = scripts.client( 'Split_View_Figure.py', """Create a figure of split-view images. See http://help.openmicroscopy.org/scripts.html""", # provide 'Data_Type' and 'IDs' parameters so that Insight # auto-populates with currently selected images. scripts.String("Data_Type", optional=False, grouping="01", description="The data you want to work with.", values=dataTypes, default="Image"), scripts.List("IDs", optional=False, grouping="02", description="List of Image IDs").ofType(rlong(0)), scripts.String( "Algorithm", grouping="3", description="Algorithum for projection. Only used if a Z-range is" " chosen below", values=algorithums, default='Maximum Intensity'), scripts.Int( "Z_Start", grouping="3.1", description="Projection range (if not specified, use defaultZ" " only - no projection)", min=0), scripts.Int( "Z_End", grouping="3.2", description="Projection range (if not specified, use defaultZ" " only - no projection)", min=0), scripts.Map("Channel_Names", grouping="4", description="Map of index: channel name for all channels"), scripts.List("Split_Indexes", grouping="5", description="List of the channels in the split" " view").ofType(rint(0)), scripts.Bool("Split_Panels_Grey", grouping="6", description="If true, all split panels are grayscale", default=False), scripts.Map( "Merged_Colours", grouping="7", description="Map of index:int colors for each merged channel"), scripts.Bool( "Merged_Names", grouping="8", description="If true, label the merged panel with channel names." " Otherwise label with 'Merged'", default=True), scripts.Int("Width", grouping="9", description="The max width of each image panel. Default is" " first image width", min=1), scripts.Int( "Height", grouping="91", description="The max height of each image panel. Default is" " first image height", min=1), scripts.String( "Image_Labels", grouping="92", description="Label images with Image name (default) or datasets" " or tags", values=labels, default='Image Name'), scripts.Int("Stepping", grouping="93", description="The Z increment for projection.", default=1, min=1), scripts.Int( "Scalebar", grouping="94", description="Scale bar size in microns. Only shown if image has" " pixel-size info.", min=1), scripts.String("Format", grouping="95", description="Format to save image", values=formats, default='JPEG'), scripts.String("Figure_Name", grouping="96", description="File name of the figure to save.", default='Split_View_Figure'), scripts.String("Overlay_Colour", grouping="97", description="The color of the scale bar.", default='White', values=oColours), version="4.3.0", authors=["William Moore", "OME Team"], institutions=["University of Dundee"], contact="*****@*****.**", ) try: conn = BlitzGateway(client_obj=client) scriptParams = client.getInputs(unwrap=True) print scriptParams # call the main script, attaching resulting figure to Image. Returns # the FileAnnotationI [fileAnnotation, message] = splitViewFigure(conn, scriptParams) # Return message and file annotation (if applicable) to the client client.setOutput("Message", rstring(message)) if fileAnnotation is not None: client.setOutput("File_Annotation", robject(fileAnnotation._obj)) finally: client.closeSession()
def run_with_param(param): process = svc.runScript(script, {'Object': wrap(param)}, None) cb = omero.scripts.ProcessCallbackI(self.client, process) while cb.block(500) is None: pass cb.close()
def testQueryTaggedUnique(self): # get group we're working on... ctx = self.client.sf.getAdminService().getEventContext() groupId = ctx.groupId print(('groupId', groupId)) # Admin sets permissions to read-ann admin = self.root.sf.getAdminService() rootUpdate = self.root.sf.getUpdateService() gr = admin.getGroup(groupId) p = PermissionsI() p.setUserRead(True) p.setUserWrite(True) p.setGroupRead(True) p.setGroupAnnotate(True) p.setGroupWrite(False) p.setWorldRead(False) p.setWorldAnnotate(False) p.setWorldWrite(False) gr.details.permissions = p admin.updateGroup(gr) # Update context for user ctx = self.client.sf.getAdminService().getEventContext() update = self.client.sf.getUpdateService() queryService = self.client.sf.getQueryService() tagCount = 5 # User creates tag linked to images tag = TagAnnotationI() tag.textValue = wrap("test_iQuerySpeed") links = [] for i in range(tagCount): iid = createImageWithPixels(self.client, self.uuid()) link = ImageAnnotationLinkI() link.parent = ImageI(iid, False) link.child = tag links.append(link) links = update.saveAndReturnArray(links) tag = links[0].child # check permissions p = tag.getDetails().getPermissions() assert p.isGroupRead() assert p.isGroupAnnotate() # Root also links user's tag to images rootLinks = [] for lnk in links: link = ImageAnnotationLinkI() link.parent = ImageI(lnk.parent.id, False) link.child = TagAnnotationI(lnk.child.id, False) rootLinks.append(link) rootUpdate.saveAndReturnArray(rootLinks, {'omero.group': native_str(groupId)}) q = """select distinct new map(obj.id as id, obj.name as name, obj.details.owner.id as ownerId, obj as image_details_permissions, obj.fileset.id as filesetId, lower(obj.name) as n , pix.sizeX as sizeX, pix.sizeY as sizeY, pix.sizeZ as sizeZ ) from Image obj left outer join obj.pixels pix join obj.annotationLinks alink where %s order by lower(obj.name), obj.id """ params = ParametersI() params.add('tid', tag.id) # We can get all the tagged images like this. # We use an additional select statement to give 'unique' results uniqueClause = """alink.id = (select max(alink.id) from ImageAnnotationLink alink where alink.child.id=:tid and alink.parent.id=obj.id)""" query = q % uniqueClause result1 = queryService.projection(query, params, {'omero.group': native_str(groupId)}) assert len(result1) == tagCount # Without the select statement, we get the same image returned # multiple times if there is no 'distinct' clause = "alink.child.id=:tid" query = q % clause result2 = queryService.projection(query, params, {'omero.group': native_str(groupId)}) assert len(result2) == tagCount for idx in range(len(result1) - 1): # Omit final since == isn't defined for Ice objects. assert result1[idx] == result2[idx]
def show_group(request, group_id, conn=None, **kwargs): conn.SERVICE_OPTS.setOmeroGroup(group_id) s = conn.groupSummary(group_id) group_owners = s["leaders"] group_members = s["colleagues"] group = conn.getObject("ExperimenterGroup", group_id) # Get NEW user_id, OR current user_id from session OR 'All Members' (-1) user_id = request.GET.get('user_id', request.session.get('user_id', -1)) user_ids = [u.id for u in group_owners] user_ids.extend([u.id for u in group_members]) user_id = int(user_id) # Check user is in group if user_id not in user_ids and user_id is not -1: user_id = -1 # save it to session request.session['user_id'] = int(user_id) request.session.modified = True query_service = conn.getQueryService() params = omero.sys.ParametersI() params.theFilter = omero.sys.Filter() params.theFilter.limit = wrap(1) # params.map = {} query = "select i from Image as i"\ " left outer join i.datasetLinks as dl join dl.parent as dataset"\ " left outer join dataset.projectLinks"\ " as pl join pl.parent as project"\ " where project.id = :pid" param_all = omero.sys.ParametersI() count_images = "select count(i), count(distinct dataset) from Image as i"\ " left outer join i.datasetLinks"\ " as dl join dl.parent as dataset"\ " left outer join dataset.projectLinks"\ " as pl join pl.parent as project"\ " where project.id = :pid" if user_id == -1: user_id = None projects = [] # Will be from active group, owned by user_id (as perms allow) for p in conn.listProjects(eid=user_id): pdata = {'id': p.getId(), 'name': p.getName()} pdata['description'] = p.getDescription() pdata['owner'] = p.getDetails().getOwner().getOmeName() # Look-up a single image params.addLong('pid', p.getId()) img = query_service.findByQuery(query, params, conn.SERVICE_OPTS) if img is None: continue # Ignore projects with no images pdata['image'] = { 'id': img.getId().getValue(), 'name': img.getName().getValue() } param_all.addLong('pid', p.getId()) image_count = query_service.projection(count_images, param_all, conn.SERVICE_OPTS) pdata['imageCount'] = image_count[0][0].val pdata['datasetCount'] = image_count[0][1].val projects.append(pdata) query = "select i from Image as i"\ " left outer join i.datasetLinks as dl"\ " join dl.parent as dataset"\ " where dataset.id = :did" count_images = "select count(i) from Image as i"\ " left outer join i.datasetLinks as dl "\ "join dl.parent as dataset"\ " where dataset.id = :did" datasets = [] for d in conn.listOrphans("Dataset", eid=user_id): ddata = {'id': d.getId(), 'name': d.getName()} ddata['description'] = d.getDescription() ddata['owner'] = d.getDetails().getOwner().getOmeName() # Look-up a single image # params.map['did'] = wrap(d.id) params.addLong('did', d.getId()) img = query_service.findByQuery(query, params, conn.SERVICE_OPTS) if img is None: continue # ignore datasets with no images ddata['image'] = { 'id': img.getId().getValue(), 'name': img.getName().getValue() } param_all.addLong('did', d.getId()) image_count = query_service.projection(count_images, param_all, conn.SERVICE_OPTS) ddata['imageCount'] = image_count[0][0].val datasets.append(ddata) context = {'template': "webgallery/show_group.html"} context['group'] = group context['group_owners'] = group_owners context['group_members'] = group_members context['projects'] = projects context['datasets'] = datasets return context
def type(self, *arg): self.prototype = wrap(arg) return self
userConn = BlitzGateway(username, "ome") userConn.connect() for g in userConn.getGroupsMemberOf(): if g.getName() == "user": continue print " ", g.getName() userConn.SERVICE_OPTS.setOmeroGroup(g.getId()) params = omero.sys.Parameters() params.theFilter = omero.sys.Filter() params.theFilter.ownerId = rlong(exp.getId()) tags = list(userConn.getObjects("TagAnnotation", params=params)) for i in range(TAG_COUNT - len(tags)): t = TagAnnotationI() newTagVal = "%s_%s_TEST" % (username, g.getName()) print "creating TAG:", newTagVal t.textValue = wrap(str(newTagVal)) userConn.getUpdateService().saveObject(t, userConn.SERVICE_OPTS) # for t in tags: # print " TAG", t.getId(), t.getTextValue() userConn.c.closeSession() print "\n---- DOING ANNOTATING... ----\n" # We want to Tag loads of stuff with OUR tags and Others' tags for exp in allUsers: username = exp.getOmeName() if username not in USER_NAMES: continue print "\n\n------------ USER:"******"------------" userConn = BlitzGateway(username, "ome") userConn.connect() updateService = userConn.getUpdateService()
def save_web_figure(request, conn=None, **kwargs): """ Saves 'figureJSON' in POST as an original file. If 'fileId' is specified in POST, then we update that file. Otherwise create a new one with name 'figureName' from POST. """ update = conn.getUpdateService() if not request.method == 'POST': return HttpResponse("Need to use POST") figureJSON = request.POST.get('figureJSON') if figureJSON is None: return HttpResponse("No 'figureJSON' in POST") # See https://github.com/will-moore/figure/issues/16 figureJSON = figureJSON.encode('utf8') imageIds = [] firstImgId = None try: json_data = json.loads(figureJSON) for panel in json_data['panels']: imageIds.append(panel['imageId']) if len(imageIds) > 0: firstImgId = long(imageIds[0]) # remove duplicates imageIds = list(set(imageIds)) except: pass fileId = request.POST.get('fileId') if fileId is None: # Create new file if 'figureName' in json_data and len(json_data['figureName']) > 0: figureName = json_data['figureName'] else: n = datetime.now() # time-stamp name by default: WebFigure_2013-10-29_22-43-53.json figureName = "Figure_%s-%s-%s_%s-%s-%s.json" % \ (n.year, n.month, n.day, n.hour, n.minute, n.second) # we store json in description field... description = {} if firstImgId is not None: # We duplicate the figure name here for quicker access when # listing files # (use this instead of file name because it supports unicode) description['name'] = figureName description['imageId'] = firstImgId if 'baseUrl' in panel: description['baseUrl'] = panel['baseUrl'] # Try to set Group context to the same as first image currGid = conn.SERVICE_OPTS.getOmeroGroup() try: conn.SERVICE_OPTS.setOmeroGroup('-1') i = conn.getObject("Image", firstImgId) if i is not None: gid = i.getDetails().group.id.val conn.SERVICE_OPTS.setOmeroGroup(gid) else: # Don't leave as -1 conn.SERVICE_OPTS.setOmeroGroup(currGid) except: # revert back conn.SERVICE_OPTS.setOmeroGroup(currGid) fileSize = len(figureJSON) f = StringIO() f.write(figureJSON) # Can't use unicode for file name figureName = unicodedata.normalize('NFKD', figureName).encode( 'ascii', 'ignore') origF = createOriginalFileFromFileObj(conn, f, '', figureName, fileSize, mimetype="application/json") fa = omero.model.FileAnnotationI() fa.setFile(omero.model.OriginalFileI(origF.getId(), False)) fa.setNs(wrap(JSON_FILEANN_NS)) desc = json.dumps(description) fa.setDescription(wrap(desc)) fa = update.saveAndReturnObject(fa, conn.SERVICE_OPTS) fileId = fa.id.val else: # Update existing Original File conn.SERVICE_OPTS.setOmeroGroup('-1') # Following seems to work OK with group -1 (regardless of group ctx) fa = conn.getObject("FileAnnotation", fileId) if fa is None: return Http404("Couldn't find FileAnnotation of ID: %s" % fileId) conn.SERVICE_OPTS.setOmeroGroup(fa.getDetails().group.id.val) origFile = fa._obj.file size = len(figureJSON) origFile.setSize(rlong(size)) origFile = update.saveAndReturnObject(origFile, conn.SERVICE_OPTS) # upload file rawFileStore = conn.createRawFileStore() rawFileStore.setFileId(origFile.getId().getValue(), conn.SERVICE_OPTS) rawFileStore.write(figureJSON, 0, size, conn.SERVICE_OPTS) rawFileStore.truncate(size, conn.SERVICE_OPTS) # ticket #11751 # Once #11928 is fixed, these last 2 lines can be replaced with # awFileStore.close(conn.SERVICE_OPTS) rawFileStore.save(conn.SERVICE_OPTS) rawFileStore.close() # Link file annotation to all images (remove from any others) LINK_TO_IMAGES = False # Disabled for now if LINK_TO_IMAGES: currentLinks = conn.getAnnotationLinks("Image", ann_ids=[fileId]) for l in currentLinks: if l.parent.id.val not in imageIds: # remove old link update.deleteObject(l._obj, conn.SERVICE_OPTS) else: # we don't need to create links for these imageIds.remove(l.parent.id.val) # create new links if necessary links = [] if len(imageIds) > 0: for i in conn.getObjects("Image", imageIds): if not i.canAnnotate(): continue l = omero.model.ImageAnnotationLinkI() l.parent = omero.model.ImageI(i.getId(), False) l.child = omero.model.FileAnnotationI(fileId, False) links.append(l) # Don't want to fail at this point due to strange permissions combo try: update.saveArray(links, conn.SERVICE_OPTS) except: pass return HttpResponse(str(fileId))
def __init__(self, name, optional=True, out=False, description=None, default=None, **kwargs): # Non-Param attributes omero.grid.Param.__init__(self) # Non-Param attributes self._name = name self._in = True self._out = out # Other values will be filled in by the kwargs # Mostly leaving these for backwards compatibility self.description = description self.optional = optional # Assign all the kwargs for k, v in list(kwargs.items()): if not hasattr(self, k): TYPE_LOG.warn("Unknown property: %s", k) setattr(self, k, v) _DEF = self.__get(self.PROTOTYPE_DEFAULT, False) _FUN = self.__get(self.PROTOTYPE_FUNCTION) _MAX = self.__get(self.PROTOTYPE_MAX) _MIN = self.__get(self.PROTOTYPE_MIN) _VAL = self.__get(self.PROTOTYPE_VALUES) # Someone specifically set the prototype, then # we assume that useDefault should be True # For whatever reason, inheritance isn't working. if default is not None: newfunc = _FUN newdefault = default if isinstance(self, List): if isinstance(default, (list, tuple)): newdefault = wrap(default).val elif isinstance(default, omero.RCollection): newfunc = lambda x: x elif isinstance(default, omero.RType): default = [default] else: newfunc = lambda x: x newdefault = rlist([rtype(default)]) self.useDefault = True self.prototype = newfunc(newdefault) else: if not callable(_FUN): raise ValueError("Bad prototype function: %s" % _FUN) # To prevent weirdness, if the class default is # callable, we'll assume its a constructor and # create a new one to prevent modification. try: _def = _DEF() except TypeError: _def = _DEF self.prototype = _FUN(_def) # The following use wrap to guarantee that an rtype is present if self.min is not None: if _MIN is None: self.min = _FUN(self.min) else: self.min = _MIN(self.min) if self.max is not None: if _MAX is None: self.max = _FUN(self.max) else: self.max = _MAX(self.max) if self.values is not None: if _VAL is None: self.values = wrap(self.values) else: self.values = _VAL(self.values) # Now if useDefault has been set, either manually, or # via setting default="..." we check that the default # value matches a value if present if self.values is not None and self.values and self.useDefault: if isinstance(self.prototype, omero.RCollection): test = unwrap(self.prototype.val[0]) else: test = unwrap(self.prototype) values = unwrap(self.values) if test not in values: raise ValueError("%s is not in %s" % (test, values))
def get_image_detail_and_tags(request, conn=None, **kwargs): # According to REST, this should be a GET, but because of the amount of # data being submitted, this is problematic if not request.POST: return HttpResponseNotAllowed('Methods allowed: POST') image_ids = request.POST.getlist("imageIds[]") if not image_ids: return HttpResponseBadRequest('Image IDs required') image_ids = map(long, image_ids) group_id = request.session.get('active_group') if group_id is None: group_id = conn.getEventContext().groupId # All the tags available to the user tags = tree.marshal_tags(conn, group_id=group_id) # Details about the images specified params = omero.sys.ParametersI() service_opts = deepcopy(conn.SERVICE_OPTS) # Set the desired group context service_opts.setOmeroGroup(group_id) params.add('iids', wrap(image_ids)) qs = conn.getQueryService() # Get the tags that are applied to individual images q = """ SELECT DISTINCT itlink.parent.id, itlink.child.id FROM ImageAnnotationLink itlink WHERE itlink.child.class=TagAnnotation AND itlink.parent.id IN (:iids) """ tags_on_images = {} for e in qs.projection(q, params, service_opts): tags_on_images.setdefault(unwrap(e[0]), []).append(unwrap(e[1])) # Get the images' details q = """ SELECT new map(image.id AS id, image.name AS name, image.details.owner.id AS ownerId, image AS image_details_permissions, image.fileset.id AS filesetId, filesetentry.clientPath AS clientPath) FROM Image image JOIN image.fileset fileset JOIN fileset.usedFiles filesetentry WHERE index(filesetentry) = 0 AND image.id IN (:iids) ORDER BY lower(image.name), image.id """ images = [] for e in qs.projection(q, params, service_opts): e = unwrap(e)[0] d = [ e["id"], e["name"], e["ownerId"], e["image_details_permissions"], e["filesetId"], e["clientPath"] ] images.append(_marshal_image(conn, d, tags_on_images)) # Get the users from this group for reference users = tree.marshal_experimenters(conn, group_id=group_id, page=None) return JsonResponse({'tags': tags, 'images': images, 'users': users})
def runAsScript(): """ The main entry point of the script. Gets the parameters from the scripting service, makes the figure and returns the output to the client. def __init__(self, name, optional = False, out = False, description = None, type = None, min = None, max = None, values = None) """ formats = wrap(formatMap.keys()) # wrap each key in it's rtype ckeys = COLOURS.keys() ckeys = ckeys; ckeys.sort() cOptions = wrap(ckeys) dataTypes= [rstring("Image")] client = scripts.client('Make_Movie','MakeMovie creates a movie of the image and attaches it to the originating image.', scripts.String("Data_Type", optional=False, grouping="1", description="Choose Images via their 'Image' IDs.", values=dataTypes, default="Image"), scripts.List("IDs", optional=False, grouping="1", description="List of Image IDs to process.").ofType(rlong(0)), scripts.Long("RenderingDef_ID", description="The Rendering Definitions for the Image.", default=-1, optional=True, grouping="1"), scripts.String("Movie_Name", description="The name of the movie", grouping="2"), scripts.Int("Z_Start", description="Projection range (if not specified, use defaultZ only - no projection)", min=0, default=0, grouping="3.1"), scripts.Int("Z_End", description="Projection range (if not specified or, use defaultZ only - no projection)", min=0, grouping="3.2"), scripts.Int("T_Start", description="The first time-point", min=0, default=0, grouping="4.1"), scripts.Int("T_End", description="The last time-point", min=0, grouping="4.2"), scripts.List("Channels", description="The selected channels", grouping="5").ofType(rint(0)), scripts.Bool("Show_Time", description="If true, display the time.", default=True, grouping="6"), scripts.Bool("Show_Plane_Info", description="If true, display the information about the plane e.g. Exposure Time.", default=True, grouping="7"), scripts.Int("FPS", description="Frames Per Second.", default=2, grouping="8"), scripts.Int("Scalebar", description="Scale bar size in microns. Only shown if image has pixel-size info.", min=1, grouping="9"), scripts.String("Format", description="Format to save movie", values=formats, default=QT, grouping="10"), scripts.String("Overlay_Colour", description="The colour of the scalebar.",default='White',values=cOptions, grouping="11"), scripts.String("Canvas_Colour", description="The background colour when using minimum size.",default='Black',values=cOptions), scripts.Int("Min_Width", description="Minimum width for output movie.", default=-1), scripts.Int("Min_Height", description="Minimum height for output movie.", default=-1), scripts.Map("Plane_Map", description="Specify the individual planes (instead of using T_Start, T_End, Z_Start and Z_End)", grouping="12"), scripts.Object("Watermark", description="Specifiy a watermark as an Original File (png or jpeg)", default=omero.model.OriginalFileI()), scripts.Object("Intro_Slide", description="Specifiy an Intro slide as an Original File (png or jpeg)", default=omero.model.OriginalFileI()), scripts.Int("Intro_Duration", default=3, description="Duration of Intro in seconds. Default is 3 secs."), scripts.Object("Ending_Slide", description="Specifiy a finishing slide as an Original File, (png or jpeg)", default=omero.model.OriginalFileI()), scripts.Int("Ending_Duration", default=3, description="Duration of finishing slide in seconds. Default is 3 secs."), scripts.Bool("Do_Link", description="If true, creates a FileAnnotation with the OriginalFile holding the movie and links it to the Image.", default=True), version = "4.2.0", authors = ["Donald MacDonald", "OME Team"], institutions = ["University of Dundee"], contact = "*****@*****.**", ) try: conn = BlitzGateway(client_obj=client) commandArgs = {} for key in client.getInputKeys(): if client.getInput(key): commandArgs[key] = client.getInput(key,unwrap=True) print commandArgs fileAnnotation, message = writeMovie(commandArgs, conn) # return this fileAnnotation to the client. client.setOutput("Message", rstring(message)) if fileAnnotation is not None: client.setOutput("File_Annotation", robject(fileAnnotation)) finally: client.closeSession()
def runAsScript(): """ The main entry point of the script, as called by the client via the scripting service, passing the required parameters. """ dataTypes = [rstring('Image')] labels = [rstring('Image Name'), rstring('Datasets'), rstring('Tags')] algorithums = [rstring('Maximum Intensity'), rstring('Mean Intensity')] roiLabel = """Specify an ROI to pick by specifying it's shape label. \ 'FigureROI' by default, (not case sensitive). If matching ROI not found, use \ any ROI.""" formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')] ckeys = COLOURS.keys() ckeys.sort() oColours = wrap(OVERLAY_COLOURS.keys()) client = scripts.client( 'Movie_ROI_Figure.py', """Create a figure of movie frames from ROI region of image. See http://www.openmicroscopy.org/site/support/omero4/\ users/client-tutorials/insight/insight-export-figures.html""", scripts.String("Data_Type", optional=False, grouping="01", description="The data you want to work with.", values=dataTypes, default="Image"), scripts.List("IDs", optional=False, grouping="02", description="List of Image IDs").ofType(rlong(0)), #scripts.List("Merged_Colours", grouping="03", # description="A list of colours to apply to merged channels.", # values=cOptions), scripts.List( "Merged_Channels", grouping="03", description="A list of channel indexes to display, starting at 1." " E.g. 1, 2, 3").ofType(rint(0)), scripts.Float( "Roi_Zoom", grouping="04", default=1, description="How much to zoom the ROI. E.g. x 2. If 0 then ROI" " panel will zoom to same size as main image"), scripts.Int( "Max_Columns", grouping="04.1", default=10, description="The maximum number of columns in the figure, for" " ROI-movie frames.", min=1), scripts.Bool( "Resize_Images", grouping="05", default=True, description="Images are shown full-size by default, but can be" " resized below"), scripts.Int("Width", grouping="05.1", description="Max width of each image panel in pixels", min=1), scripts.Int("Height", grouping="05.2", description="The max height of each image panel in pixels", min=1), scripts.String( "Image_Labels", grouping="06", description="Label images with the Image Name or Datasets or" " Tags", values=labels), scripts.Bool("Show_ROI_Duration", grouping="06.1", description="If true, times shown as duration from first " "timepoint of the ROI, otherwise use movie timestamp."), scripts.Int( "Scalebar", grouping="07", description="Scale bar size in microns. Only shown if image has" " pixel-size info.", min=1), scripts.String( "Scalebar_Colour", grouping="07.1", description="The colour of the scalebar and ROI outline.", default='White', values=oColours), scripts.String("Roi_Selection_Label", grouping="08", description=roiLabel), scripts.String( "Algorithm", grouping="09", description="Algorithum for projection, if ROI spans several Z" " sections.", values=algorithums), scripts.String("Figure_Name", grouping="10", description="File name of the figure to save.", default='movieROIFigure'), scripts.String("Format", grouping="10.1", description="Format to save figure.", values=formats, default='JPEG'), version="4.3.0", authors=["William Moore", "OME Team"], institutions=["University of Dundee"], contact="*****@*****.**", ) try: commandArgs = {} conn = BlitzGateway(client_obj=client) # process the list of args above. for key in client.getInputKeys(): if client.getInput(key): commandArgs[key] = unwrap(client.getInput(key)) print commandArgs # call the main script, attaching resulting figure to Image. Returns # the id of the originalFileLink child. (ID object, not value) fileAnnotation, message = roiFigure(conn, commandArgs) # Return message and file annotation (if applicable) to the client client.setOutput("Message", rstring(message)) if fileAnnotation is not None: client.setOutput("File_Annotation", robject(fileAnnotation._obj)) finally: client.closeSession()
def marshal_images(conn, parent, parent_id, mapann_value, query=False, mapann_ns=[], mapann_names=[], load_pixels=False, group_id=-1, experimenter_id=-1, page=1, date=False, thumb_version=False, limit=settings.PAGE): ''' Marshals images @param conn OMERO gateway. @type conn L{omero.gateway.BlitzGateway} @param plate_id The Plate ID to filter by. @type plate_id L{long} @param mapann_value The Map annotation value to filter by. @type mapann_value L{string} @param query Flag allowing to search for value patters. @type query L{boolean} @param mapann_ns The Map annotation namespace to filter by. @type mapann_ns L{string} @param mapann_names The Map annotation names to filter by. @type mapann_names L{string} @param load_pixels Whether to load the X,Y,Z dimensions @type load_pixels Boolean @param group_id The Group ID to filter by or -1 for all groups, defaults to -1 @type group_id L{long} @param experimenter_id The Experimenter (user) ID to filter by or -1 for all experimenters @type experimenter_id L{long} @param page Page number of results to get. `None` or 0 for no paging defaults to 1 @type page L{long} @param limit The limit of results per page to get defaults to the value set in settings.PAGE @type page L{long} ''' images = [] # early exit if (parent_id is None or not isinstance(parent_id, long)) or not parent: return images params, where_clause = _set_parameters( mapann_ns=mapann_ns, mapann_names=mapann_names, query=query, mapann_value=mapann_value, params=None, experimenter_id=experimenter_id, page=page, limit=limit) service_opts = deepcopy(conn.SERVICE_OPTS) # Set the desired group context if group_id is None: group_id = -1 service_opts.setOmeroGroup(group_id) from_join_clauses = [] qs = conn.getQueryService() extra_values = [] if load_pixels: extra_values.append(""" , pix.sizeX as sizeX, pix.sizeY as sizeY, pix.sizeZ as sizeZ """) if date: extra_values.append(""", image.details.creationEvent.time as date, image.acquisitionDate as acqDate """) q = """ select new map(image.id as id, image.name as name, image.details.owner.id as ownerId, image as image_details_permissions, image.fileset.id as filesetId %s) from Image image """ % "".join(extra_values) if load_pixels: # We use 'left outer join', since we still want images if no pixels q += ' left outer join image.pixels pix ' q += """ where image.id in ( """ if parent == 'plate': from_join_clauses.append(""" ImageAnnotationLink ial join ial.child a join a.mapValue mv join ial.parent image join image.wellSamples ws join ws.well well join well.plate plate """) params.addLong("pid", parent_id) where_clause.append('plate.id = :pid') if parent == 'dataset': from_join_clauses.append(""" ImageAnnotationLink ial join ial.child a join a.mapValue mv join ial.parent image join image.datasetLinks dil join dil.parent dataset """) params.addLong("did", parent_id) where_clause.append('dataset.id = :did') q += """ %s %s order by lower(image.name)) """ % (' select image.id from ' + ' '.join(from_join_clauses), build_clause(where_clause, 'where', 'and')) logger.debug("HQL QUERY: %s\nPARAMS: %r" % (q, params)) for e in qs.projection(q, params, service_opts): e = unwrap(e)[0] d = [e["id"], e["name"], e["ownerId"], e["image_details_permissions"], e["filesetId"]] kwargs = {'conn': conn, 'row': d[0:5]} if load_pixels: d = [e["sizeX"], e["sizeY"], e["sizeZ"]] kwargs['row_pixels'] = d if date: kwargs['acqDate'] = e['acqDate'] kwargs['date'] = e['date'] im = _marshal_image(**kwargs) images.append(im) # Load thumbnails separately # We want version of most recent thumbnail (max thumbId) owned by user if thumb_version and len(images) > 0: user_id = conn.getUserId() iids = [i['id'] for i in images] params = omero.sys.ParametersI() params.addIds(iids) params.add('thumbOwner', wrap(user_id)) q = """select image.id, thumbs.version from Image image join image.pixels pix join pix.thumbnails thumbs where image.id in (:ids) and thumbs.id = ( select max(t.id) from Thumbnail t where t.pixels = pix.id and t.details.owner.id = :thumbOwner ) """ thumb_versions = {} logger.debug("HQL QUERY: %s\nPARAMS: %r" % (q, params)) for t in qs.projection(q, params, service_opts): iid, tv = unwrap(t) thumb_versions[iid] = tv # For all images, set thumb version if we have it... for i in images: if i['id'] in thumb_versions: i['thumbVersion'] = thumb_versions[i['id']] return images
def run_script(): """ The main entry point of the script, as called by the client via the scripting service, passing the required parameters. """ data_types = [rstring('Image')] labels = [rstring('Image Name'), rstring('Datasets'), rstring('Tags')] algorithms = [rstring('Maximum Intensity'), rstring('Mean Intensity')] roi_label = """Specify an ROI to pick by specifying its shape label. \ 'FigureROI' by default, (not case sensitive). If matching ROI not found, use \ any ROI.""" formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')] ckeys = list(COLOURS.keys()) ckeys.sort() o_colours = wrap(list(OVERLAY_COLOURS.keys())) client = scripts.client( 'ROI_Split_Figure.py', """Create a figure of an ROI region as separate zoomed split-channel \ panels. NB: OMERO.insight client provides a nicer UI for this script under \ 'Publishing Options' See http://help.openmicroscopy.org/publish.html#figures""", # provide 'Data_Type' and 'IDs' parameters so that Insight # auto-populates with currently selected images. scripts.String("Data_Type", optional=False, grouping="01", description="The data you want to work with.", values=data_types, default="Image"), scripts.List("IDs", optional=False, grouping="02", description="List of Dataset IDs or Image IDs").ofType( rlong(0)), scripts.Map("Channel_Names", grouping="03", description="Map of index: channel name for All channels"), scripts.Bool( "Merged_Names", grouping="04", description="If true, label the merged panel with channel names." " Otherwise label with 'Merged'"), scripts.List( "Split_Indexes", grouping="05", description="List of the channels in the split view panels"), scripts.Bool("Split_Panels_Grey", grouping="06", description="If true, all split panels are grayscale"), scripts.Map( "Merged_Colours", grouping="07", description="Map of index:int colors for each merged channel." " Otherwise use existing color settings"), scripts.Int("Width", grouping="08", description="Max width of each image panel", min=1), scripts.Int("Height", grouping="09", description="The max height of each image panel", min=1), scripts.String( "Image_Labels", grouping="10", description="Label images with the Image's Name or its Datasets" " or Tags", values=labels), scripts.String("Algorithm", grouping="11", description="Algorithm for projection.", values=algorithms), scripts.Int( "Stepping", grouping="12", description="The Z-plane increment for projection. Default is 1", min=1), scripts.Int( "Scalebar", grouping="13", description="Scale bar size in microns. Only shown if image has" " pixel-size info.", min=1), scripts.String("Format", grouping="14", description="Format to save image e.g 'PNG'.", values=formats, default='JPEG'), scripts.String("Figure_Name", grouping="15", description="File name of the figure to save."), scripts.String("Overlay_Colour", grouping="16", description="The color of the scale bar.", default='White', values=o_colours), scripts.Float( "ROI_Zoom", grouping="17", description="How much to zoom the ROI e.g. x 2. If 0 then zoom" " roi panel to fit", min=0), scripts.String("ROI_Label", grouping="18", description=roi_label), version="4.3.0", authors=["William Moore", "OME Team"], institutions=["University of Dundee"], contact="*****@*****.**", ) try: conn = BlitzGateway(client_obj=client) command_args = client.getInputs(unwrap=True) # call the main script, attaching resulting figure to Image. Returns # the id of the originalFileLink child. (ID object, not value) file_annotation, message = roi_figure(conn, command_args) # Return message and file annotation (if applicable) to the client client.setOutput("Message", rstring(message)) if file_annotation is not None: client.setOutput("File_Annotation", robject(file_annotation._obj)) finally: client.closeSession()
def searchImages(conn, scriptParams): """ Here we build our hql query and get the results from the queryService """ # Script has defaults for some parameters, so we know these are filled minSizeC = scriptParams["Min_Channel_Count"] minSizeZ = scriptParams["Min_Size_Z"] minSizeT = scriptParams["Min_Size_T"] # For others, we check if specified channelNames = "Channel_Names" in scriptParams and \ scriptParams["Channel_Names"] or [] nominalMagnification = "Magnification" in scriptParams and \ scriptParams["Magnification"] or None lensNA = "Lens_NA" in scriptParams and scriptParams["Lens_NA"] or None excitationWave = "Excitation_Wavelength" in scriptParams and \ scriptParams["Excitation_Wavelength"] or None objectiveModel = "Objective_Model" in scriptParams and \ scriptParams["Objective_Model"] or None qs = conn.getQueryService() params = omero.sys.Parameters() params.map = {} clauses = [] query = "select i from Image i left outer join i.pixels as pixels" if minSizeZ > 1 or minSizeC > 1 or minSizeT > 1: # We have already joined pixels if minSizeZ > 1: params.map["sizeZ"] = rint(minSizeZ) clauses.append("pixels.sizeZ>=:sizeZ") if minSizeC > 1: params.map["sizeC"] = rint(minSizeC) clauses.append("pixels.sizeC>=:sizeC") if minSizeT > 1: params.map["sizeT"] = rint(minSizeT) clauses.append("pixels.sizeT>=:sizeT") if len(channelNames) > 0 or excitationWave is not None: query = query + " left outer join pixels.channels as c join" \ " c.logicalChannel as lc" if len(channelNames) > 0: params.map["cNames"] = wrap(channelNames) clauses.append("lc.name in (:cNames)") if excitationWave is not None: params.map["exWave"] = wrap(excitationWave) clauses.append("lc.excitationWave=:exWave)") if nominalMagnification is not None or lensNA is not None or \ objectiveModel is not None: query += " join i.objectiveSettings as objS join objS.objective as ob" if nominalMagnification is not None: params.map["nomMag"] = rint(nominalMagnification) clauses.append("ob.nominalMagnification=:nomMag") if lensNA is not None: params.map["lensNA"] = rdouble(lensNA) clauses.append("ob.lensNA=:lensNA") if objectiveModel is not None: params.map["objectiveModel"] = wrap(objectiveModel) clauses.append("ob.model=:objectiveModel") if len(clauses) > 0: query = query + " where " + " and ".join(clauses) print "Searh parameters map:", unwrap(params.map) print query imgs = qs.findAllByQuery(query, params) return imgs
def testRunScript(self, gatewaywrapper): # Login as user... gatewaywrapper.doLogin(dbhelpers.USERS['script_test_user']) userId = gatewaywrapper.gateway.getEventContext().userId uuid = gatewaywrapper.gateway.getEventContext().sessionUuid default_groupId = gatewaywrapper.gateway.getEventContext().groupId # Create Dataset in 'default' group update = gatewaywrapper.gateway.getUpdateService() new_ds = omero.model.DatasetI() dataset_name = "script_test_%s" % uuid new_ds.name = rstring(dataset_name) new_ds = update.saveAndReturnObject(new_ds) new_ds_Id = new_ds.id.val # As Admin, create a second group with this user & upload script gatewaywrapper.loginAsAdmin() gid = gatewaywrapper.gateway.createGroup( "script-test-%s" % uuid, member_Ids=[userId], perms=READWRITE) SCRIPT = """if True: import omero.scripts import omero.rtypes client = omero.scripts.client("ticket8573", \ omero.scripts.Long("datasetId"), \ omero.scripts.String("datasetName", out=True)) ec = client.sf.getAdminService().getEventContext() gid = ec.groupId qs = client.sf.getQueryService() ds_Id = client.getInput("datasetId").getValue() print "Running test..." # generate stdout try: dataset = qs.find("Dataset", ds_Id) ds_Name = dataset.name.val print ds_Name except: ds_Name = "Not Found" client.setOutput("gid", omero.rtypes.rlong(gid)) client.setOutput("datasetName", omero.rtypes.rstring(ds_Name)) """ svc = gatewaywrapper.gateway.getScriptService() scriptID = svc.uploadOfficialScript( "/test/ticket8573/%s" % uuid, SCRIPT) # switch user into new group gatewaywrapper.doLogin(dbhelpers.USERS['script_test_user']) switched = gatewaywrapper.gateway.c.sf.setSecurityContext( omero.model.ExperimenterGroupI(gid, False)) assert switched, "Failed to switch into new group" # Shouldn't be able to access Dataset... assert None == gatewaywrapper.gateway.getObject("Dataset", new_ds_Id) gatewaywrapper.gateway.SERVICE_OPTS.setOmeroGroup( str(default_groupId)) assert None != gatewaywrapper.gateway.getObject("Dataset", new_ds_Id) # run script svc = gatewaywrapper.gateway.getScriptService() process = svc.runScript(scriptID, wrap({"datasetId": new_ds_Id}).val, None, gatewaywrapper.gateway.SERVICE_OPTS) cb = omero.scripts.ProcessCallbackI(gatewaywrapper.gateway.c, process) while cb.block(500) is None: pass results = process.getResults(0, gatewaywrapper.gateway.SERVICE_OPTS) assert 'stdout' in results, \ "Failed to return stdout Original File. #8614" assert results["gid"].val == default_groupId, \ "We want script to have eventContext of group:%s not %s" % \ (default_groupId, results["gid"].val) assert results["datasetName"].val == dataset_name, \ "Script should be able to access Dataset"
def create_project(self, conn, project_name): print "Createing new Project: ", project_name p = ProjectI() p.name = wrap(project_name) return conn.getUpdateService().saveAndReturnObject(p)
def create_dataset(self, conn, dataset_name): print "Creating new Dataset:", dataset_name d = DatasetI() d.name = wrap(dataset_name) return conn.getUpdateService().saveAndReturnObject(d)
host=os.environ.get('IDR_HOST', 'localhost')) conn.connect() conn.setGroupForSession(3) # Public query_service = conn.getQueryService() # Find the plates of idr0004. query = """ SELECT child.id FROM ScreenPlateLink WHERE parent.name LIKE :name """ params = ParametersI() params.add('name', wrap('idr0004-%')) rows = query_service.projection(query, params) plate_ids = [row[0].val for row in rows] assert plate_ids # Loop through each field of those plates. query = """ SELECT id, image.name, image.fileset.id, well.row, well.column, well.plate.name FROM WellSample WHERE well.plate.id IN (:ids) """
def create_figure_file(conn, image_ids): """Create an OMERO.figure file with the specified images.""" width = 100 height = 100 spacing_x = 5 spacing_y = 5 JSON_FILEANN_NS = "omero.web.figure.json" figure_json = { "version": 2, "paper_width": 595, "paper_height": 842, "page_size": "A4", "figureName": "Scipy Gaussian Filter", } curr_x = 0 curr_y = 0 panels_json = [] offset = 40 gid = -1 for row, image_id in enumerate(image_ids): image = conn.getObject('Image', image_id) curr_y = row * (height + spacing_y) + offset if row == 0: gid = image.getDetails().getGroup().getId() for col in range(image.getSizeC()): curr_x = col * (width + spacing_x) + offset j = get_panel_json(image, curr_x, curr_y, width, height, col) j['labels'] = get_labels_json(j, col, row) panels_json.append(j) figure_json['panels'] = panels_json figure_name = figure_json['figureName'] if len(figure_json['panels']) == 0: raise Exception('No Panels') first_img_id = figure_json['panels'][0]['imageId'] # we store json in description field... description = {} description['name'] = figure_name description['imageId'] = first_img_id # Try to set Group context to the same as first image conn.SERVICE_OPTS.setOmeroGroup(gid) json_string = json.dumps(figure_json) file_size = len(json_string) f = StringIO() json.dump(figure_json, f) update = conn.getUpdateService() orig_file = conn.createOriginalFileFromFileObj(f, '', figure_name, file_size, mimetype="application/json") fa = omero.model.FileAnnotationI() fa.setFile(omero.model.OriginalFileI(orig_file.getId(), False)) fa.setNs(wrap(JSON_FILEANN_NS)) desc = json.dumps(description) fa.setDescription(wrap(desc)) fa = update.saveAndReturnObject(fa, conn.SERVICE_OPTS) return fa.getId().getValue()