-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy path__init__.py
11033 lines (9350 loc) · 379 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# blitz_gateway - python bindings and wrappers to access an OMERO blitz server
#
# Copyright (c) 2007-2022 Glencoe Software, Inc. All rights reserved.
#
# This software is distributed under the terms described by the LICENCE file
# you can find at the root of the distribution bundle, which states you are
# free to use it only for non commercial purposes.
# If the file is missing please request a copy by contacting
# Set up the python include paths
import os
import warnings
from collections import defaultdict
from datetime import datetime
from io import StringIO
from io import BytesIO
import configparser
import omero
import omero.clients
from omero.util.decorators import timeit
from omero.cmd import Chgrp2, Delete2, DoAll, SkipHead, Chown2
from omero.cmd.graphs import ChildOption
from omero.api import Save
from omero.gateway.utils import ServiceOptsDict, GatewayConfig, toBoolean
from omero.model.enums import PixelsTypeint8, PixelsTypeuint8, PixelsTypeint16
from omero.model.enums import PixelsTypeuint16, PixelsTypeint32
from omero.model.enums import PixelsTypeuint32, PixelsTypefloat
from omero.model.enums import PixelsTypecomplex, PixelsTypedouble
import omero.scripts as scripts
import Ice
import Glacier2
import traceback
import time
import array
import math
from decimal import Decimal
from gettext import gettext as _
import logging
from math import sqrt
from omero.rtypes import rstring, rint, rlong, rbool
from omero.rtypes import rtime, rlist, rdouble, unwrap
logger = logging.getLogger(__name__)
THISPATH = os.path.dirname(os.path.abspath(__file__))
from PIL import Image, ImageDraw, ImageFont
def omero_type(val):
"""
Converts rtypes from static factory methods:
- str to rstring
- bool to rbool
- int to rint
else return the argument itself
:param val: value
:rtype: omero.rtype
:return: matched RType or value
"""
if isinstance(val, str):
return rstring(val)
elif isinstance(val, bool):
return rbool(val)
elif isinstance(val, int):
return rint(val)
else:
return val
def fileread(fin, fsize, bufsize):
"""
Reads everything from fin, in chunks of bufsize.
:type fin: file
:param fin: filelike readable object
:type fsize: int
:param fsize: total number of bytes to read
:type bufsize: int
:param fsize: size of each chunk of data read from fin
:rtype: bytes
:return: bytes buffer holding the contents read from the file
"""
# Read it all in one go
p = 0
rv = b''
try:
while p < fsize:
s = min(bufsize, fsize-p)
rv += fin.read(p, s)
p += s
finally:
fin.close()
return rv
def fileread_gen(fin, fsize, bufsize):
"""
Generator helper function that yields chunks of the file of size fsize.
:type fin: file
:param fin: filelike readable object
:type fsize: int
:param fsize: total number of bytes to read
:type bufsize: int
:param fsize: size of each chunk of data read from fin that gets yielded
:rtype: generator
:return: generator of string buffers of size up to bufsize read from fin
"""
p = 0
try:
while p < fsize:
s = min(bufsize, fsize-p)
yield fin.read(p, s)
p += s
finally:
fin.close()
def getAnnotationLinkTableName(objecttype):
"""
Get the name of the AnnotationLink table
for the given objecttype
"""
objecttype = objecttype.lower()
if objecttype == "project":
return "ProjectAnnotationLink"
if objecttype == "dataset":
return"DatasetAnnotationLink"
if objecttype == "image":
return"ImageAnnotationLink"
if objecttype == "screen":
return "ScreenAnnotationLink"
if objecttype == "plate":
return "PlateAnnotationLink"
if objecttype == "plateacquisition":
return "PlateAcquisitionAnnotationLink"
if objecttype == "well":
return "WellAnnotationLink"
return None
def getPixelsQuery(imageName):
"""Helper for building Query for Images or Wells & Images"""
return (' left outer join fetch %s.pixels as pixels'
' left outer join fetch pixels.pixelsType' % imageName)
def getChannelsQuery():
"""Helper for building Query for Images or Wells & Images"""
return (' join fetch pixels.channels as channels'
' join fetch channels.logicalChannel as logicalChannel'
' left outer join fetch '
' logicalChannel.photometricInterpretation'
' left outer join fetch logicalChannel.illumination'
' left outer join fetch logicalChannel.mode'
' left outer join fetch logicalChannel.contrastMethod')
def add_plate_filter(clauses, params, opts):
"""Helper for adding 'plate' to filtering clauses and parameters."""
if opts is not None and 'plate' in opts:
clauses.append('obj.plate.id = :pid')
params.add('pid', rlong(opts['plate']))
class OmeroRestrictionWrapper (object):
def canDownload(self):
"""
Determines if the current user can Download raw data linked to this
object. The canDownload() property is set on objects:
Image, Plate and FileAnnotation as it is read from the server, based
on the current user, event context and group permissions.
:rtype: Boolean
:return: True if user can download.
"""
return not self.getDetails().getPermissions().isRestricted(
omero.constants.permissions.BINARYACCESS)
class BlitzObjectWrapper (object):
"""
Object wrapper class which provides various methods for hierarchy
traversing, saving, handling permissions etc. This is the 'abstract' super
class which is subclassed by E.g. _ProjectWrapper, _DatasetWrapper etc.
All objects have a reference to the :class:`BlitzGateway` connection, and
therefore all services are available for handling calls on the object
wrapper. E.g listChildren() uses queryservice etc.
"""
# E.g. 'Project', 'Dataset', 'Experimenter' etc.
OMERO_CLASS = None
LINK_CLASS = None
LINK_CHILD = 'child'
CHILD_WRAPPER_CLASS = None
PARENT_WRAPPER_CLASS = None
@staticmethod
def LINK_PARENT(x):
return x.parent
def __init__(self, conn=None, obj=None, cache=None, **kwargs):
"""
Initialises the wrapper object, setting the various class variables etc
:param conn: The :class:`BlitzGateway` connection.
:type conn: :class:`BlitzGateway`
:param obj: The object to wrap. E.g. omero.model.Image
:type obj: omero.model object
:param cache: Cache which is passed to new child wrappers
"""
self.__bstrap__()
self._obj = obj
self._cache = cache
if self._cache is None:
self._cache = {}
self._conn = conn
self._creationDate = None
if conn is None:
return
if hasattr(obj, 'id') and obj.id is not None:
self._oid = obj.id.val
if not self._obj.loaded:
self._obj = self._conn.getQueryService().get(
self._obj.__class__.__name__, self._oid,
self._conn.SERVICE_OPTS)
self.__prepare__(**kwargs)
def __eq__(self, a):
"""
Returns true if the object is of the same type and has same id and name
:param a: The object to compare to this one
:return: True if objects are same - see above
:rtype: Boolean
"""
return (type(a) == type(self) and
self._obj.id == a._obj.id and
self.getName() == a.getName())
def __bstrap__(self):
"""
Initialisation method which is implemented by subclasses to set their
class variables etc.
"""
pass
def __prepare__(self, **kwargs):
"""
Initialisation method which is implemented by subclasses to handle
various init tasks
"""
pass
def __repr__(self):
"""
Returns a String representation of the Object, including ID if set.
:return: String E.g. '<DatasetWrapper id=123>'
:rtype: String
"""
if hasattr(self, '_oid'):
return '<%s id=%s>' % (self.__class__.__name__, str(self._oid))
return super(BlitzObjectWrapper, self).__repr__()
def _unwrapunits(self, obj, units=None):
"""
Returns the value of the Value + Unit object.
If units is true, return the omero model unit object,
e.g. omero.model.LengthI
e.g. _unwrapunits(obj).getValue() == 10
e.g. _unwrapunits(obj).getUnit() == NANOMETER # unit enum
e.g. _unwrapunits(obj).getSymbol() == "nm"
If units specifies a valid unit for the type of value, then we convert
E.g. _unwrapunits(obj, units="MICROMETER").getValue() == 10000
:param obj: The Value + Unit object
:param default: Default value if obj is None
:param units: If true, return (value, unit) tuple
:return: Value or omero.model units
"""
if obj is None:
return None
if units is not None:
# If units is an attribute of the same Class as our obj...
if isinstance(units, str):
unitClass = obj.getUnit().__class__
unitEnum = getattr(unitClass, str(units))
# ... we can convert units
obj = obj.__class__(obj, unitEnum)
return obj
return obj.getValue()
@classmethod
def _getQueryString(cls, opts=None):
"""
Used for building queries in generic methods
such as getObjects("Project").
Returns a tuple of (query, clauses, params).
Overridden by sub-classes to specify loading of different
portions of the graph.
Different sub-classes may allow some control over what's loaded
and filtering of the query using various opts arguments.
Opts:
See different sub-classes for additional opts.
:param opts: Dictionary of optional parameters.
:return: Tuple of string, list, ParametersI
"""
query = ("select obj from %s obj "
"join fetch obj.details.owner as owner "
"join fetch obj.details.creationEvent" % cls.OMERO_CLASS)
params = omero.sys.ParametersI()
clauses = []
return (query, clauses, params)
def _getChildWrapper(self):
"""
Returns the wrapper class of children of this object.
Checks that this is one of the Wrapper objects in the
:mod:`omero.gateway` module
Raises NotImplementedError if this is not true
or class is not defined (None)
This is used internally by the :meth:`listChildren` and
:meth:`countChildren` methods.
:return: The child wrapper class.
E.g. omero.gateway.DatasetWrapper.__class__
:rtype: class
"""
if self.CHILD_WRAPPER_CLASS is None: # pragma: no cover
raise NotImplementedError(
'%s has no child wrapper defined' % self.__class__)
if isinstance(self.CHILD_WRAPPER_CLASS, str):
# resolve class
if hasattr(omero.gateway, self.CHILD_WRAPPER_CLASS):
self.__class__.CHILD_WRAPPER_CLASS \
= self.CHILD_WRAPPER_CLASS \
= getattr(omero.gateway, self.CHILD_WRAPPER_CLASS)
else: # pragma: no cover
raise NotImplementedError
return self.CHILD_WRAPPER_CLASS
def _getParentWrappers(self):
"""
Returns the wrapper classes of the parent of this object.
This is used internally by the :meth:`listParents` method.
:return: List of parent wrapper classes.
E.g. omero.gateway.DatasetWrapper.__class__
:rtype: class
"""
if self.PARENT_WRAPPER_CLASS is None: # pragma: no cover
raise NotImplementedError
pwc = self.PARENT_WRAPPER_CLASS
if not isinstance(pwc, list):
pwc = [pwc, ]
for i in range(len(pwc)):
if isinstance(pwc[i], str):
# resolve class
g = globals()
if not pwc[i] in g: # pragma: no cover
raise NotImplementedError
pwc[i] = g[pwc[i]]
# Cache this so we don't need to resolve classes again
if (pwc != self.PARENT_WRAPPER_CLASS or
pwc != self.__class__.PARENT_WRAPPER_CLASS):
self.__class__.PARENT_WRAPPER_CLASS \
= self.PARENT_WRAPPER_CLASS = pwc
return self.PARENT_WRAPPER_CLASS
def __loadedHotSwap__(self):
"""
Loads the object that is wrapped by this class. This includes linked
objects. This method can be overwritten by subclasses that want to
specify how/which linked objects are loaded
"""
self._obj = self._conn.getContainerService().loadContainerHierarchy(
self.OMERO_CLASS, (self._oid,), None, self._conn.SERVICE_OPTS)[0]
def _moveLink(self, newParent):
"""
Moves this object from a parent container (first one if there are more
than one) to a new parent. TODO: might be more useful if it didn't
assume only 1 parent - option allowed you to specify the oldParent.
:param newParent: The new parent Object Wrapper.
:return: True if moved from parent to parent.
False if no parent exists
or newParent has mismatching type
:rtype: Boolean
"""
p = self.getParent()
# p._obj.__class__ == p._obj.__class__
# ImageWrapper(omero.model.DatasetI())
if p.OMERO_CLASS == newParent.OMERO_CLASS:
link = self._conn.getQueryService().findAllByQuery(
"select l from %s as l where l.parent.id=%i and l.child.id=%i"
% (p.LINK_CLASS, p.id, self.id), None, self._conn.SERVICE_OPTS)
if len(link):
link[0].parent = newParent._obj
self._conn.getUpdateService().saveObject(
link[0], self._conn.SERVICE_OPTS)
return True
logger.debug(
"## query didn't return objects: 'select l from %s as l "
"where l.parent.id=%i and l.child.id=%i'"
% (p.LINK_CLASS, p.id, self.id))
else:
logger.debug("## %s != %s ('%s' - '%s')" %
(type(p), type(newParent), str(p), str(newParent)))
return False
def findChildByName(self, name, description=None):
"""
Find the first child object with a matching name, and description if
specified.
:param name: The name which must match the child name
:param description: If specified, child description must match too
:return: The wrapped child object
:rtype: :class:`BlitzObjectWrapper`
"""
for c in self.listChildren():
if c.getName() == name:
if (description is None or
omero_type(description) ==
omero_type(c.getDescription())):
return c
return None
def getDetails(self):
"""
Gets the details of the wrapped object
:return: :class:`DetailsWrapper` or None if object not loaded
:rtype: :class:`DetailsWrapper`
"""
if self._obj.loaded:
return omero.gateway.DetailsWrapper(self._conn,
self._obj.getDetails())
return None
def getDate(self):
"""
Returns the object's acquisitionDate, or creation date
(details.creationEvent.time)
:return: A :meth:`datetime.datetime` object
:rtype: datetime
"""
try:
if (self._obj.acquisitionDate.val is not None and
self._obj.acquisitionDate.val > 0):
t = self._obj.acquisitionDate.val
return datetime.fromtimestamp(t / 1000)
except:
# object doesn't have acquisitionDate
pass
return self.creationEventDate()
def save(self):
"""
Uses the updateService to save the wrapped object.
:rtype: None
"""
ctx = self._conn.SERVICE_OPTS.copy()
if self.getDetails() and self.getDetails().getGroup():
# This is a save for an object that already exists, make sure group
# matches
ctx.setOmeroGroup(self.getDetails().getGroup().getId())
self._obj = self._conn.getUpdateService().saveAndReturnObject(
self._obj, ctx)
def saveAs(self, details):
"""
Save this object, keeping the object owner the same as the one on
provided details If the current user is an admin but is NOT the owner
specified in 'details', then create a new connection for that owner,
clone the current object under that connection and save. Otherwise,
simply save.
:param details: The Details specifying owner to save to
:type details: :class:`DetailsWrapper`
:return: None
"""
if self._conn.isAdmin():
d = self.getDetails()
if (d.getOwner() and
d.getOwner().omeName == details.getOwner().omeName and
d.getGroup().name == details.getGroup().name):
return self.save()
else:
newConn = self._conn.suConn(
details.getOwner().omeName, details.getGroup().name)
# p = omero.sys.Principal()
# p.name = details.getOwner().omeName
# p.group = details.getGroup().name
# p.eventType = "User"
# newConnId = self._conn.getSessionService(
# ).createSessionWithTimeout(p, 60000)
# newConn = self._conn.clone()
# newConn.connect(sUuid=newConnId.getUuid().val)
clone = self.__class__(newConn, self._obj)
clone.save()
self._obj = clone._obj
return
else:
return self.save()
def canWrite(self):
"""
Delegates to the connection :meth:`BlitzGateway.canWrite` method
:rtype: Boolean
"""
return self._conn.canWrite(self)
def canOwnerWrite(self):
"""
Delegates to the connection :meth:`BlitzGateway.canWrite` method
:rtype: Boolean
:return: True if the objects's permissions allow owner to write
"""
return self._conn.canOwnerWrite(self)
def isOwned(self):
"""
Returns True if the object owner is the same user specified in the
connection's Event Context
:rtype: Boolean
:return: True if current user owns this object
"""
return (self._obj.details.owner.id.val == self._conn.getUserId())
def isLeaded(self):
"""
Returns True if the group that this object belongs to is lead by the
currently logged-in user
:rtype: Boolean
:return: see above
"""
g = self._obj.details.group or self._obj.details
if g.id.val in self._conn.getEventContext().leaderOfGroups:
return True
return False
def isPublic(self):
"""
Determines if the object permissions are world readable, ie
permissions.isWorldRead()
:rtype: Boolean
:return: see above
"""
g = self.getDetails().getGroup()
g = g and g.details or self._obj.details
return g.permissions.isWorldRead()
def isShared(self):
"""
Determines if the object is sharable between groups (but not public)
:rtype: Boolean
:return: True if the object is not :meth:`public <isPublic>` AND
the object permissions allow group read.
"""
if not self.isPublic():
g = self.getDetails().getGroup()
g = g and g.details or self._obj.details
return g.permissions.isGroupRead()
return False
def isPrivate(self):
"""
Determines if the object is private
:rtype: Boolean
:returns: True if the object is not :meth:`public <isPublic>` and
not :meth:`shared <isShared>` and permissions allow user
to read.
"""
if not self.isPublic() and not self.isShared():
g = self.getDetails().getGroup()
g = g and g.details or self._obj.details
return g.permissions.isUserRead()
return False
def canEdit(self):
"""
Determines if the current user can Edit (E.g. name, description) link
(E.g. Project, Dataset, Image etc) or Delete this object. The
canEdit() property is set on the permissions of every object as it is
read from the server, based on the current user, event context and
group permissions.
:rtype: Boolean
:return: True if user can Edit this object Delete, link etc.
"""
return self.getDetails().getPermissions().canEdit()
def canDelete(self):
"""
Determines if the current user can Delete the object
"""
return self.getDetails().getPermissions().canDelete()
def canLink(self):
"""
Determines whether user can create 'hard' links (Not annotation
links). E.g. Between Project/Dataset/Image etc. Previously (4.4.6 and
earlier) we only allowed this for object owners, but now we delegate
to what the server will allow.
"""
return self.getDetails().getPermissions().canLink()
def canAnnotate(self):
"""
Determines if the current user can annotate this object: ie create
annotation links. The canAnnotate() property is set on the permissions
of every object as it is read from the server, based on the current
user, event context and group permissions.
:rtype: Boolean
:return: True if user can Annotate this object
"""
return self.getDetails().getPermissions().canAnnotate()
def canChgrp(self):
"""
Specifies whether the current user can move this object to another
group. Web client will only allow this for the data Owner. Admin CAN
move other user's data, but we don't support this in Web yet.
"""
return self.getDetails().getPermissions().canChgrp()
def canChown(self):
"""
Specifies whether the current user can give this object to another
user. Web client does not yet support this.
"""
return self.getDetails().getPermissions().canChown()
def countChildren(self):
"""
Counts available number of child objects.
:return: The number of child objects available
:rtype: Long
"""
childw = self._getChildWrapper()
klass = "%sLinks" % childw().OMERO_CLASS.lower()
# self._cached_countChildren = len(
# self._conn.getQueryService().findAllByQuery(
# "from %s as c where c.parent.id=%i"
# % (self.LINK_CLASS, self._oid), None))
self._cached_countChildren = self._conn.getContainerService(
).getCollectionCount(
self.OMERO_CLASS, klass, [self._oid], None,
self._conn.SERVICE_OPTS)[self._oid]
return self._cached_countChildren
def countChildren_cached(self):
"""
countChildren, but caching the first result, useful if you need to
call this multiple times in a single sequence, but have no way of
storing the value between them. It is actually a hack to support
django template's lack of break in for loops
:return: The number of child objects available
:rtype: Long
"""
if not hasattr(self, '_cached_countChildren'):
return self.countChildren()
return self._cached_countChildren
def _listChildren(self, ns=None, val=None, params=None):
"""
Lists available child objects.
:rtype: generator of Ice client proxy objects for the child nodes
:return: child objects.
"""
if not params:
params = omero.sys.Parameters()
if not params.map:
params.map = {}
params.map["dsid"] = rlong(self._oid)
query = "select c from %s as c" % self.LINK_CLASS
if ns is not None:
params.map["ns"] = omero_type(ns)
query += """ join fetch c.child as ch
left outer join fetch ch.annotationLinks as ial
left outer join fetch ial.child as a """
query += " where c.parent.id=:dsid"
if ns is not None:
query += " and a.ns=:ns"
if val is not None:
if isinstance(val, str):
params.map["val"] = omero_type(val)
query += " and a.textValue=:val"
query += " order by c.child.name"
for child in (x.child for x in self._conn.getQueryService(
).findAllByQuery(query, params, self._conn.SERVICE_OPTS)):
yield child
def listChildren(self, ns=None, val=None, params=None):
"""
Lists available child objects.
:rtype: generator of :class:`BlitzObjectWrapper` objs
:return: child objects.
"""
childw = self._getChildWrapper()
for child in self._listChildren(ns=ns, val=val, params=params):
yield childw(self._conn, child, self._cache)
def getParent(self, withlinks=False):
"""
List a single parent, if available.
While the model supports many to many relationships between most
objects, there are implementations that assume a single project per
dataset, a single dataset per image, etc. This is just a shortcut
method to return a single parent object.
:type withlinks: Boolean
:param withlinks: if true result will be a tuple of (linkobj, obj)
:rtype: :class:`BlitzObjectWrapper`
or tuple(:class:`BlitzObjectWrapper`, :class:`BlitzObjectWrapper`)
:return: the parent object with or without the link depending on args
"""
rv = self.listParents(withlinks=withlinks)
return len(rv) and rv[0] or None
def listParents(self, withlinks=False):
"""
Lists available parent objects.
:type withlinks: Boolean
:param withlinks: if true each yielded result
will be a tuple of (linkobj, obj)
:rtype: list of :class:`BlitzObjectWrapper`
or tuple(:class:`BlitzObjectWrapper`, :class:`BlitzObjectWrapper`)
:return: the parent objects,
with or without the links depending on args
"""
if self.PARENT_WRAPPER_CLASS is None:
return ()
parentw = self._getParentWrappers()
param = omero.sys.Parameters() # TODO: What can I use this for?
parentnodes = []
for pwc in parentw:
pwck = pwc()
if withlinks:
parentnodes.extend(
[(pwc(self._conn, pwck.LINK_PARENT(x), self._cache),
BlitzObjectWrapper(self._conn, x))
for x in self._conn.getQueryService(
).findAllByQuery(
"from %s as c where c.%s.id=%i"
% (pwck.LINK_CLASS, pwck.LINK_CHILD,
self._oid),
param, self._conn.SERVICE_OPTS)])
else:
t = self._conn.getQueryService().findAllByQuery(
"from %s as c where c.%s.id=%i"
% (pwck.LINK_CLASS, pwck.LINK_CHILD,
self._oid),
param, self._conn.SERVICE_OPTS)
parentnodes.extend(
[pwc(self._conn, pwck.LINK_PARENT(x), self._cache)
for x in t])
return parentnodes
def getAncestry(self):
"""
Get a list of Ancestors. First in list is parent of this object.
TODO: Assumes getParent() returns a single parent.
:rtype: List of :class:`BlitzObjectWrapper`
:return: List of Ancestor objects
"""
rv = []
p = self.getParent()
while p:
rv.append(p)
p = p.getParent()
return rv
def getParentLinks(self, pids=None):
"""
Get a list of parent objects links.
:param pids: List of parent IDs
:type pids: :class:`Long`
:rtype: List of :class:`BlitzObjectWrapper`
:return: List of parent object links
"""
if self.PARENT_WRAPPER_CLASS is None:
raise AttributeError("This object has no parent objects")
parentwrappers = self._getParentWrappers()
link_class = None
for v in parentwrappers:
link_class = v().LINK_CLASS
if link_class is not None:
break
if link_class is None:
raise AttributeError(
"This object has no parent objects with a link class!")
query_serv = self._conn.getQueryService()
p = omero.sys.Parameters()
p.map = {}
p.map["child"] = rlong(self.id)
sql = "select pchl from %s as pchl " \
"left outer join fetch pchl.parent as parent " \
"left outer join fetch pchl.child as child " \
"where child.id=:child" % link_class
if isinstance(pids, list) and len(pids) > 0:
p.map["parent"] = rlist([rlong(pa) for pa in pids])
sql += " and parent.id in (:parent)"
for pchl in query_serv.findAllByQuery(sql, p, self._conn.SERVICE_OPTS):
yield BlitzObjectWrapper(self, pchl)
def getChildLinks(self, chids=None):
"""
Get a list of child objects links.
:param chids: List of children IDs
:type chids: :class:`Long`
:rtype: List of :class:`BlitzObjectWrapper`
:return: List of child object links
"""
if self.CHILD_WRAPPER_CLASS is None:
raise AttributeError("This object has no child objects")
query_serv = self._conn.getQueryService()
p = omero.sys.Parameters()
p.map = {}
p.map["parent"] = rlong(self.id)
sql = ("select pchl from %s as pchl left outer join "
"fetch pchl.child as child left outer join "
"fetch pchl.parent as parent where parent.id=:parent"
% self.LINK_CLASS)
if isinstance(chids, list) and len(chids) > 0:
p.map["children"] = rlist([rlong(ch) for ch in chids])
sql += " and child.id in (:children)"
for pchl in query_serv.findAllByQuery(sql, p, self._conn.SERVICE_OPTS):
yield BlitzObjectWrapper(self, pchl)
def _loadAnnotationLinks(self):
"""
Loads the annotation links and annotations for the object
(if not already loaded) and saves them to the object.
Also loads file for file annotations.
"""
# pragma: no cover
if not hasattr(self._obj, 'isAnnotationLinksLoaded'):
raise NotImplementedError
# Need to set group context. If '-1' then canDelete() etc on
# annotations will be False
ctx = self._conn.SERVICE_OPTS.copy()
ctx.setOmeroGroup(self.details.group.id.val)
if not self._obj.isAnnotationLinksLoaded():
query = ("select l from %sAnnotationLink as l join "
"fetch l.details.owner join "
"fetch l.details.creationEvent "
"join fetch l.child as a join fetch a.details.owner "
"left outer join fetch a.file "
"join fetch a.details.creationEvent where l.parent.id=%i"
% (self.OMERO_CLASS, self._oid))
links = self._conn.getQueryService().findAllByQuery(
query, None, ctx)
self._obj._annotationLinksLoaded = True
self._obj._annotationLinksSeq = links
# _listAnnotationLinks
def _getAnnotationLinks(self, ns=None):
"""
Checks links are loaded and returns a list of Annotation Links
filtered by namespace if specified
:param ns: Namespace
:type ns: String
:return: List of Annotation Links on this object
:rtype: List of Annotation Links
"""
self._loadAnnotationLinks()
rv = self.copyAnnotationLinks()
if ns is not None:
rv = [x for x in rv if x.getChild().getNs() and
x.getChild().getNs().val == ns]
return rv
def unlinkAnnotations(self, ns):
"""
Submits request to unlink annotations, with specified ns
:param ns: Namespace
:type ns: String
"""
links = defaultdict(list)
for al in self._getAnnotationLinks(ns=ns):
links[al.ice_id().split("::")[-1]].append(al.id.val)
# Using omero.cmd.Delete2 rather than deleteObjects since we need
# spec/id pairs rather than spec+id_list as arguments
if len(links):
delete = omero.cmd.Delete2(targetObjects=links)
handle = self._conn.c.sf.submit(delete, self._conn.SERVICE_OPTS)
try:
self._conn._waitOnCmd(handle)
finally:
handle.close()
self._obj.unloadAnnotationLinks()
def removeAnnotations(self, ns):
"""
Uses the delete service to delete annotations, with a specified ns,
and their links on the object and any other objects. Will raise a
:class:`omero.LockTimeout` if the annotation removal has not finished
in 5 seconds.
:param ns: Namespace
:type ns: String
"""
ids = list()
for al in self._getAnnotationLinks(ns=ns):
a = al.child
ids.append(a.id.val)
if len(ids):
handle = self._conn.deleteObjects('Annotation', ids)
try:
self._conn._waitOnCmd(handle)
finally:
handle.close()
self._obj.unloadAnnotationLinks()
# findAnnotations(self, ns=[])
def getAnnotation(self, ns=None):
"""
Gets the first annotation on the object, filtered by ns if specified
:param ns: Namespace
:type ns: String
:return: :class:`AnnotationWrapper` or None
"""
rv = self._getAnnotationLinks(ns)
if len(rv):
return AnnotationWrapper._wrap(self._conn, rv[0].child, link=rv[0])
return None
def getAnnotationCounts(self):
"""
Get the annotion counts for the current object
"""
return self._conn.countAnnotations(self.OMERO_CLASS, [self.getId()])
def listAnnotations(self, ns=None):
"""
List annotations in the ns namespace, linked to this object
:return: Generator yielding :class:`AnnotationWrapper`
:rtype: :class:`AnnotationWrapper` generator
"""
for ann in self._getAnnotationLinks(ns):
yield AnnotationWrapper._wrap(self._conn, ann.child, link=ann)