def test_update_existing_mapann(self):
        ns1, ns3, mids = self.create_mas()
        pks = ['a']
        mgr = MapAnnotationManager()
        mgr.add_from_namespace_query(self.sf, ns1, pks)

        ma4 = MapAnnotationI()
        ma4 = MapAnnotationI()
        ma4.setNs(wrap(ns1))
        ma4.setMapValue([NamedValue('a', '2'), NamedValue('b', '3'), ])

        cma = CanonicalMapAnnotation(ma4, pks)
        # This should modify ma2
        r = mgr.add(cma)
        assert r is cma

        cmas = mgr.get_map_annotations()
        assert len(cmas) == 2
        rs = self.update.saveAndReturnArray([c.get_mapann() for c in cmas])
        rs = sorted(rs, key=lambda x: unwrap(x.getId()))

        assert_equal_map_value(rs[0].getMapValue(), [NamedValue('a', '1')])
        assert unwrap(rs[0].getNs()) == ns1

        assert_equal_map_value(rs[1].getMapValue(), [
            NamedValue('a', '2'), NamedValue('b', '3')])
        assert unwrap(rs[1].getNs()) == ns1
Beispiel #2
0
def create_fileset(files):
    """Create a new Fileset from local files."""
    fileset = omero.model.FilesetI()
    for f in files:
        entry = omero.model.FilesetEntryI()
        entry.setClientPath(rstring(f))
        fileset.addFilesetEntry(entry)

    # Fill version info
    system, node, release, version, machine, processor = platform.uname()

    client_version_info = [
        NamedValue('omero.version', omero_version),
        NamedValue('os.name', system),
        NamedValue('os.version', release),
        NamedValue('os.architecture', machine)
    ]
    try:
        client_version_info.append(
            NamedValue('locale',
                       locale.getdefaultlocale()[0]))
    except:
        pass

    upload = omero.model.UploadJobI()
    upload.setVersionInfo(client_version_info)
    fileset.linkJob(upload)
    return fileset
Beispiel #3
0
    def test_init_defaults_duplicates(self):
        ma = MapAnnotationI(1)
        ma.setMapValue([NamedValue('a', '1'), NamedValue('a', '1')])

        with pytest.raises(ValueError) as excinfo:
            CanonicalMapAnnotation(ma)
        assert str(excinfo.value).startswith('Duplicate ')
Beispiel #4
0
    def test_get_mapann(self):
        ma = MapAnnotationI(1)
        ma.setMapValue([NamedValue('a', '1')])
        cma = CanonicalMapAnnotation(ma, primary_keys=['a'])
        cma.add_parent('Parent', 1)
        cma.kvpairs.append(('b', '2'))
        newma = cma.get_mapann()

        assert newma is ma
        mv = newma.getMapValue()
        assert len(mv) == 2
        assert_equal_name_value(mv[0], NamedValue('a', '1'))
        assert_equal_name_value(mv[1], NamedValue('b', '2'))
Beispiel #5
0
    def test_init_defaults_kvpairs(self, ns):
        ma = MapAnnotationI(1)
        ma.setMapValue([NamedValue('b', '2'), NamedValue('a', '1')])
        if ns is not None:
            ma.setNs(rstring(ns))

        cma = CanonicalMapAnnotation(ma)
        assert cma.ma is ma
        expectedns = ns if ns else ''
        assert cma.ns == expectedns
        assert cma.kvpairs == [('b', '2'), ('a', '1')]
        assert cma.primary is None
        assert cma.parents == set()
Beispiel #6
0
    def create_cmas(self, pk2):
        ma1 = MapAnnotationI(1)
        ma1.setMapValue([NamedValue('a', '1')])
        cma1 = CanonicalMapAnnotation(ma1, primary_keys=['a'])
        cma1.add_parent('Parent', 1)

        ma2 = MapAnnotationI(2)
        ma2.setMapValue([NamedValue('b', '2'), NamedValue('a', '1')])
        cma2 = CanonicalMapAnnotation(ma2, primary_keys=[pk2])
        cma2.add_parent('Parent', 1)
        cma2.add_parent('Parent', 2)

        return cma1, cma2
Beispiel #7
0
def create_map_annotation(ctx, annotation, target_id, target_type="Project"):
    """Creates a map annotation, uploads it to Omero, and links it to target object"""
    # populate new MapAnnotationData object with dictionary
    result = ArrayList()
    for item in annotation:
        # add key:value pairs; both need to be strings
        result.add(NamedValue(str(item), str(annotation[item])))
    data = MapAnnotationData()
    data.setContent(result)
    data.setDescription("Demo Example")

    #Use the following namespace if you want the annotation to be editable in the webclient and insight
    data.setNameSpace(MapAnnotationData.NS_CLIENT_CREATED)
    dm = gateway.getFacility(DataManagerFacility)
    target_obj = None

    # use the appropriate target DataObject and attach the MapAnnotationData object to it
    if target_type == "Project":
        target_obj = ProjectData(ProjectI(target_id, False))
    elif target_type == "Dataset":
        target_obj = DatasetData(DatasetI(target_id, False))
    elif target_type == "Image":
        target_obj = ImageData(ImageI(target_id, False))
    result = dm.attachAnnotation(ctx, data, target_obj)
    return result
    def create_mas(self):
        ns1 = self.uuid()
        ns3 = self.uuid()
        ma1 = MapAnnotationI()
        ma1.setNs(wrap(ns1))
        ma1.setMapValue([NamedValue('a', '1')])
        ma2 = MapAnnotationI()
        ma2.setNs(wrap(ns1))
        ma2.setMapValue([NamedValue('a', '2')])
        ma3 = MapAnnotationI()
        ma3.setNs(wrap(ns3))
        ma3.setMapValue([NamedValue('a', '1')])

        mids = self.update.saveAndReturnIds([ma1, ma2, ma3])
        print ns1, ns3, mids
        return ns1, ns3, mids
Beispiel #9
0
    def test_init_missing_primary_key(self):
        ma = MapAnnotationI(1)
        ma.setMapValue([NamedValue('b', '2')])

        with pytest.raises(MapAnnotationPrimaryKeyException) as excinfo:
            CanonicalMapAnnotation(ma, primary_keys=['a', 'b'])
        assert str(excinfo.value).startswith('Missing ')
 def decode(self, data):
     v = super(MapAnnotationDecoder, self).decode(data)
     map_value = data.get('Value', list())
     map_value = [
         NamedValue(key, value) for key, value in map_value
     ]
     v.setMapValue(map_value)
     return v
Beispiel #11
0
    def test_init_primary_keys(self, ns, primary_keys):
        ma = MapAnnotationI(1)
        ma.setNs(rstring(ns))
        ma.setMapValue([NamedValue('b', '2'), NamedValue('a', '1')])

        cma = CanonicalMapAnnotation(ma, primary_keys=primary_keys)
        assert cma.ma is ma
        expectedns = ns if ns else ''
        assert cma.ns == expectedns
        assert cma.kvpairs == [('b', '2'), ('a', '1')]
        expectedpks = [('a', '1'), ('b', '2')][:len(primary_keys)]
        if primary_keys:
            expectedpri = (expectedns, frozenset(expectedpks))
        else:
            expectedpri = None
        assert cma.primary == expectedpri
        assert cma.parents == set()
Beispiel #12
0
    def test_map_annotation(self):
        """Tests MapAnnotationWrapper.getValue() returns unicode"""
        values = [(u'one', u'₹₹'), (u'two', u'¥¥')]
        obj = MapAnnotationI()
        data = [NamedValue(d[0], d[1]) for d in values]
        obj.setMapValue(data)

        map_ann = MockConnection(obj).getObject("Annotation", 1)
        assert map_ann.getValue() == values
Beispiel #13
0
 def get_mapann(self):
     """
     Update and return an omero.model.MapAnnotation with merged/combined
     fields
     """
     mv = [NamedValue(*kv) for kv in self.kvpairs]
     self.ma.setMapValue(mv)
     self.ma.setNs(rstring(self.ns))
     return self.ma
Beispiel #14
0
def _dict_to_map_annotation(dictionary, description=None):
    result = []
    for element in dictionary:
        result.append(NamedValue(element, dictionary[element]))
    map_data = MapAnnotationData()
    map_data.setContent(result)
    if description:
        map_data.setDescription(description)
    map_data.setNameSpace(MapAnnotationData.NS_CLIENT_CREATED)

    return map_data
Beispiel #15
0
    def test_merge(self, reverse):
        ma1 = MapAnnotationI(1)
        ma1.setMapValue([NamedValue('a', '1')])
        cma1 = CanonicalMapAnnotation(ma1, primary_keys=['a'])
        cma1.add_parent('Parent', 1)
        ma2 = MapAnnotationI(2)
        ma2.setMapValue([NamedValue('b', '2'), NamedValue('a', '1')])
        cma2 = CanonicalMapAnnotation(ma2, primary_keys=['b'])
        cma2.add_parent('Parent', 1)
        cma2.add_parent('Parent', 2)

        if reverse:
            cma2.merge(cma1)
            assert cma2.kvpairs == [('b', '2'), ('a', '1')]
            assert cma2.parents == set([('Parent', 1), ('Parent', 2)])
            assert cma2.primary == ('', frozenset([('b', '2')]))
        else:
            cma1.merge(cma2)
            assert cma1.kvpairs == [('a', '1'), ('b', '2')]
            assert cma1.parents == set([('Parent', 1), ('Parent', 2)])
            assert cma1.primary == ('', frozenset([('a', '1')]))
    def test_add_from_namespace_query(self):
        ns1, ns3, mids = self.create_mas()
        pks = ['a']
        mgr = MapAnnotationManager()
        mgr.add_from_namespace_query(self.sf, ns1, pks)

        assert len(mgr.mapanns) == 2
        pk1 = (ns1, frozenset([('a', '1')]))
        pk2 = (ns1, frozenset([('a', '2')]))
        assert len(mgr.mapanns) == 2
        assert pk1 in mgr.mapanns
        assert pk2 in mgr.mapanns

        cma1 = mgr.mapanns[pk1]
        assert cma1.kvpairs == [('a', '1')]
        assert cma1.parents == set()
        mv1 = cma1.get_mapann().getMapValue()
        assert_equal_map_value(mv1, [NamedValue('a', '1')])

        cma2 = mgr.mapanns[pk2]
        assert cma2.kvpairs == [('a', '2')]
        assert cma2.parents == set()
        mv2 = cma2.get_mapann().getMapValue()
        assert_equal_map_value(mv2, [NamedValue('a', '2')])
    def create_map_annotation(targets,
                              rowkvs,
                              ns=omero.constants.namespaces.NSBULKANNOTATIONS):
        ma = MapAnnotationI()
        ma.setNs(rstring(ns))
        mv = []
        for k, vs in rowkvs:
            if not isinstance(vs, (tuple, list)):
                vs = [vs]
            mv.extend(NamedValue(k, str(v)) for v in vs)
        ma.setMapValue(mv)

        links = []
        for target in targets:
            otype = target.ice_staticId().split('::')[-1]
            link = getattr(omero.model, '%sAnnotationLinkI' % otype)()
            link.setParent(target)
            link.setChild(ma)
            links.append(link)
        return links
Beispiel #18
0
def add_annotations(o):
    '''
    Annotation
        BasicAnnotation
            BooleanAnnotation
                BooleanAnnotationI
            NumericAnnotation
                DoubleAnnotation
                    DoubleAnnotationI
                LongAnnotation
                    LongAnnotationI
            TermAnnotation
                TermAnnotationI
            TimestampAnnotation
                TimestampAnnotationI
        ListAnnotation
            ListAnnotationI
        MapAnnotation
            MapAnnotationI
        TextAnnotation
            CommentAnnotation
                CommentAnnotationI
            TagAnnotation
                TagAnnotationI
            XmlAnnotation
                XmlAnnotationI
        TypeAnnotation
            FileAnnotation
                FileAnnotationI
    '''
    annotation = BooleanAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('boolean_annotation')
    annotation.boolValue = rbool(True)
    o.linkAnnotation(annotation)
    annotation = CommentAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('comment_annotation')
    annotation.textValue = rstring('text_value')
    o.linkAnnotation(annotation)
    annotation = DoubleAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('double_annotation')
    annotation.doubleValue = rdouble(1.0)
    o.linkAnnotation(annotation)
    annotation = LongAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('long_annotation')
    annotation.longValue = rlong(1L)
    o.linkAnnotation(annotation)
    annotation = MapAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('map_annotation')
    annotation.setMapValue([NamedValue('a', '1'), NamedValue('b', '2')])
    o.linkAnnotation(annotation)
    annotation = TagAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('tag_annotation')
    annotation.textValue = rstring('tag_value')
    o.linkAnnotation(annotation)
    annotation = TermAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('term_annotation')
    annotation.termValue = rstring('term_value')
    o.linkAnnotation(annotation)
    annotation = TimestampAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('timestamp_annotation')
    annotation.timeValue = rtime(1)
    o.linkAnnotation(annotation)
    annotation = XmlAnnotationI()
    annotation.description = rstring('the_description')
    annotation.ns = rstring('xml_annotation')
    annotation.textValue = rstring('<xml_value></xml_value>')
    o.linkAnnotation(annotation)
Beispiel #19
0
def screen_metadata(client, file, object):
    query = client.sf.getQueryService()
    update = client.sf.getUpdateService()
    name, oid = object.split(":")
    do_update = False
    query = ("select x from %s x join fetch x.annotationLinks xal "
             "join fetch xal.child where x.id = %d")
    obj = query.findByQuery(query % (name, long(oid)), None)
    ann = None
    for link in obj.copyAnnotationLinks():
        if isinstance(link.child, MapAnnotationI):
            if ann is not None:
                raise Exception("2 maps!")
            ann = link.child
            print "Found map:", ann.id.val
    if ann is None:
        ann = MapAnnotationI()
        ann.setNs(rstring("openmicroscopy.org/omero/client/mapAnnotation"))
        ann.setMapValue(list())
        obj.linkAnnotation(ann)
        do_update = True
        print "Creating new map"

    old = unwrap(obj.description)
    desc = ""
    values = dict()
    for line in input([file]):
        parts = line.strip().split("\t")
        key = parts[0]
        if len(parts) > 1:
            val = parts[1]
        else:
            val = None
        if key == "Study " + P_T:
            desc += P_T
            desc += "\n"
            desc += val
            desc += "\n\n"
        elif key == E_D:
            desc += E_D
            desc += "\n"
            desc += val
        elif key == P_M[0]:
            x, y = P_M
            values[y] = "%s http://www.ncbi.nlm.nih.gov/pubmed/%s" % (val, val)
        elif key == P_D[0]:
            x, y = P_D
            doi = val.split("dx.doi.org")[-1][1:]
            values[y] = "%s %s" % (doi, val)
        else:
            for x, y in (S_T, I_T, P_A):
                if key == x:
                    values[y] = val.strip('"')

    old_values = dict()
    for x in ann.getMapValue():
        old_values[x.name] = x
    for x, y in (S_T, I_T, P_A, P_M, P_D):
        if y not in old_values:
            ann.getMapValue().append(NamedValue(y, values[y]))
            do_update = True
            print "found new named value"
        elif old_values[y].value != values[y]:
            old_values[y].value = values[y]
            do_update = True
            print "changed named value"

    if old != desc:
        do_update = True
        obj.description = rstring(desc)
    else:
        print "descriptions match"

    if do_update:
        print "updating"
        update.saveObject(obj)
    print values