-
Notifications
You must be signed in to change notification settings - Fork 100
/
container.py
1457 lines (1340 loc) · 59.6 KB
/
container.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 -*-
#
# container
#
# Copyright (c) 2008-2015 University of Dundee.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2008.
#
# Version: 1.0
#
import omero
from omero.rtypes import rstring, rlong, unwrap
from django.conf import settings
from django.utils.encoding import smart_str
import logging
from webclient.controller import BaseController
logger = logging.getLogger(__name__)
class BaseContainer(BaseController):
project = None
screen = None
dataset = None
plate = None
acquisition = None
well = None
image = None
tag = None
file = None
comment = None
tags = None
index = None
containers = None
experimenter = None
c_size = 0
obj_type = None
text_annotations = None
txannSize = 0
long_annotations = None
file_annotations = None
orphaned = False
def __init__(self, conn, project=None, dataset=None, image=None,
screen=None, plate=None, acquisition=None, well=None,
tag=None, tagset=None, file=None, comment=None,
annotation=None, index=None, orphaned=None, **kw):
BaseController.__init__(self, conn)
if project is not None:
self.obj_type = "project"
self.project = self.conn.getObject("Project", project)
self.assertNotNone(self.project, project, "Project")
self.assertNotNone(self.project._obj, project, "Project")
if dataset is not None:
self.obj_type = "dataset"
self.dataset = self.conn.getObject("Dataset", dataset)
self.assertNotNone(self.dataset, dataset, "Dataset")
self.assertNotNone(self.dataset._obj, dataset, "Dataset")
if screen is not None:
self.obj_type = "screen"
self.screen = self.conn.getObject("Screen", screen)
self.assertNotNone(self.screen, screen, "Screen")
self.assertNotNone(self.screen._obj, screen, "Screen")
if plate is not None:
self.obj_type = "plate"
self.plate = self.conn.getObject("Plate", plate)
self.assertNotNone(self.plate, plate, "Plate")
self.assertNotNone(self.plate._obj, plate, "Plate")
if acquisition is not None:
self.obj_type = "acquisition"
self.acquisition = self.conn.getObject(
"PlateAcquisition", acquisition)
self.assertNotNone(
self.acquisition, acquisition, "Plate Acquisition")
self.assertNotNone(
self.acquisition._obj, acquisition, "Plate Acquisition")
if image is not None:
self.obj_type = "image"
self.image = self.conn.getObject("Image", image)
self.assertNotNone(self.image, image, "Image")
self.assertNotNone(self.image._obj, image, "Image")
if well is not None:
self.obj_type = "well"
self.well = self.conn.getObject("Well", well)
self.assertNotNone(self.well, well, "Well")
self.assertNotNone(self.well._obj, well, "Well")
if index is not None:
self.well.index = index
if tag is not None:
self.obj_type = "tag"
self.tag = self.conn.getObject("Annotation", tag)
self.assertNotNone(self.tag, tag, "Tag")
self.assertNotNone(self.tag._obj, tag, "Tag")
if tagset is not None:
self.obj_type = "tagset"
self.tag = self.conn.getObject("Annotation", tagset)
self.assertNotNone(self.tag, tagset, "Tag")
self.assertNotNone(self.tag._obj, tagset, "Tag")
if comment is not None:
self.obj_type = "comment"
self.comment = self.conn.getObject("Annotation", comment)
self.assertNotNone(self.comment, comment, "Comment")
self.assertNotNone(self.comment._obj, comment, "Comment")
if file is not None:
self.obj_type = "file"
self.file = self.conn.getObject("Annotation", file)
self.assertNotNone(self.file, file, "File")
self.assertNotNone(self.file._obj, file, "File")
if annotation is not None:
self.obj_type = "annotation"
self.annotation = self.conn.getObject("Annotation", annotation)
self.assertNotNone(self.annotation, annotation, "Annotation")
self.assertNotNone(self.annotation._obj, annotation, "Annotation")
if orphaned:
self.orphaned = True
def assertNotNone(self, obj, obj_id, obj_name):
if obj is None:
raise AttributeError(
"We are sorry, but that %s (id:%s) does not exist, or if it"
" does, you have no permission to see it."
% (obj_name, obj_id))
def _get_object(self):
"""
Since the container is often used to wrap a single Project, Dataset
etc, several methods need access to the underlying object. E.g.
obj_type(), obj_id(), canAnnotate(), canEdit().
This removes many if statements from the metadata_general.html
template for places that are displaying data for a single Object. E.g.
Edit Name etc.
"""
if self.project is not None:
return self.project
if self.dataset is not None:
return self.dataset
if self.image is not None:
return self.image
if self.screen is not None:
return self.screen
if self.acquisition is not None:
return self.acquisition
if self.plate is not None:
return self.plate
if self.well is not None:
return self.well
if self.tag is not None:
return self.tag
if self.file is not None:
return self.file
def obj_id(self):
obj = self._get_object()
return obj is not None and obj.id or None
def canAnnotate(self):
obj = self._get_object()
return obj is not None and obj.canAnnotate() or False
def canEdit(self):
obj = self._get_object()
return obj is not None and obj.canEdit() or None
def getPermsCss(self):
""" Shortcut to get permissions flags, E.g. for css """
return self._get_object().getPermsCss()
def getNumberOfFields(self):
""" Applies to Plates (all fields) or PlateAcquisitions"""
if self.plate is not None:
return self.plate.getNumberOfFields()
elif self.acquisition:
p = self.conn.getObject(
"Plate", self.acquisition._obj.plate.id.val)
return p.getNumberOfFields(self.acquisition.getId())
def getPlateId(self):
""" Used by templates that display Plates or PlateAcquisitions """
if self.plate is not None:
return self.plate.getId()
elif self.acquisition:
return self.acquisition._obj.plate.id.val
def canExportAsJpg(self, request, objDict=None):
"""
Can't export as Jpg, Png, Tiff if bigger than approx 12k * 12k.
Limit set by OOM error in omeis.providers.re.RGBIntBuffer
"""
can = True
try:
limit = request.session['server_settings'][
'download_as']['max_size']
except:
limit = 144000000
if self.image:
if (self.image.getSizeX() * self.image.getSizeY()) > limit:
can = False
elif objDict is not None:
if 'image' in objDict:
for i in objDict['image']:
if (i.getSizeX() * i.getSizeY()) > limit:
can = False
return can
def canDownload(self, objDict=None):
"""
Returns False if any of selected object cannot be downloaded
"""
# As used in batch_annotate panel
if objDict is not None:
for key in objDict:
for o in objDict[key]:
if hasattr(o, 'canDownload'):
if not o.canDownload():
return False
return True
# As used in metadata_general panel
else:
return self.image.canDownload() or \
self.well.canDownload() or self.plate.canDonwload()
def listFigureScripts(self, objDict=None):
"""
This configures all the Figure Scripts, setting their enabled status
given the currently selected object (self.image etc) or batch objects
(uses objDict).
"""
figureScripts = []
# id is used in url and is mapped to full script path by
# views.figure_script()
splitView = {
'id': 'SplitView',
'name': 'Split View Figure',
'enabled': False,
'tooltip': ("Create a figure of images, splitting their channels"
" into separate views")}
# Split View Figure is enabled if we have at least one image with
# SizeC > 1
if self.image:
splitView['enabled'] = (self.image.getSizeC() > 1)
elif objDict is not None:
if 'image' in objDict:
for i in objDict['image']:
if i.getSizeC() > 1:
splitView['enabled'] = True
break
thumbnailFig = {
'id': 'Thumbnail',
'name': 'Thumbnail Figure',
'enabled': False,
'tooltip': ("Export a figure of thumbnails, optionally sorted by"
" tag")}
# Thumbnail figure is enabled if we have Datasets or Images selected
if self.image or self.dataset:
thumbnailFig['enabled'] = True
elif objDict is not None:
if 'image' in objDict or 'dataset' in objDict:
thumbnailFig['enabled'] = True
makeMovie = {
'id': 'MakeMovie',
'name': 'Make Movie',
'enabled': False,
'tooltip': "Create a movie of the image"}
if (self.image and (self.image.getSizeT() > 0 or
self.image.getSizeZ() > 0)):
makeMovie['enabled'] = True
figureScripts.append(splitView)
figureScripts.append(thumbnailFig)
figureScripts.append(makeMovie)
return figureScripts
def formatMetadataLine(self, l):
if len(l) < 1:
return None
return l.split("=")
def companionFiles(self):
# Look for companion files on the Image
self.companion_files = list()
if self.image is not None:
comp_obj = self.image
p = self.image.getPlate()
# in SPW model, companion files can be found on Plate
if p is not None:
comp_obj = p
for ann in comp_obj.listAnnotations():
if (hasattr(ann._obj, "file") and
ann.ns == omero.constants.namespaces.NSCOMPANIONFILE):
if (ann.getFileName() !=
omero.constants.annotation.file.ORIGINALMETADATA):
self.companion_files.append(ann)
def channelMetadata(self, noRE=False):
self.channel_metadata = None
if self.image is None and self.well is None:
return
img = self.image
if img is None:
img = self.well.getWellSample().image()
# Exceptions handled by webclient_gateway ImageWrapper.getChannels()
self.channel_metadata = img.getChannels(noRE=noRE)
if self.channel_metadata is None:
self.channel_metadata = list()
def loadTags(self, eid=None):
if eid is not None:
if eid == -1: # Load data for all users
eid = None
else:
self.experimenter = self.conn.getObject("Experimenter", eid)
else:
eid = self.conn.getEventContext().userId
self.tags = list(self.conn.listTags(eid))
self.tags.sort(
key=lambda x: x.getTextValue() and x.getTextValue().lower())
self.t_size = len(self.tags)
def loadTagsRecursive(self, eid=None, offset=None, limit=1000):
if eid is not None:
if eid == -1: # Load data for all users
if self.canUseOthersAnns():
eid = None
else:
eid = self.conn.getEventContext().userId
else:
self.experimenter = self.conn.getObject("Experimenter", eid)
else:
eid = self.conn.getEventContext().userId
self.tags_recursive, self.tags_recursive_owners = \
self.conn.listTagsRecursive(eid, offset, limit)
def getTagCount(self, eid=None):
return self.conn.getTagCount(eid)
def loadDataByTag(self):
pr_list = list(self.conn.getObjectsByAnnotations(
'Project', [self.tag.id]))
ds_list = list(self.conn.getObjectsByAnnotations(
'Dataset', [self.tag.id]))
im_list = list(self.conn.getObjectsByAnnotations(
'Image', [self.tag.id]))
sc_list = list(self.conn.getObjectsByAnnotations(
'Screen', [self.tag.id]))
pl_list = list(self.conn.getObjectsByAnnotations(
'Plate', [self.tag.id]))
pa_list = list(self.conn.getObjectsByAnnotations(
'PlateAcquisition', [self.tag.id]))
def sortKeys(x):
return (x.getName() and x.getName().lower() or " ", x.id)
pr_list.sort(key=lambda x: sortKeys(x))
ds_list.sort(key=lambda x: sortKeys(x))
im_list.sort(key=lambda x: sortKeys(x))
sc_list.sort(key=lambda x: sortKeys(x))
pl_list.sort(key=lambda x: sortKeys(x))
pa_list.sort(key=lambda x: sortKeys(x))
self.containers = {
'projects': pr_list,
'datasets': ds_list,
'images': im_list,
'screens': sc_list,
'plates': pl_list,
'aquisitions': pa_list}
self.c_size = (len(pr_list) + len(ds_list) + len(im_list) +
len(sc_list) + len(pl_list) + len(pa_list))
def listImagesInDataset(self, did, eid=None, page=None,
load_pixels=False):
if eid is not None:
if eid == -1: # Load data for all users
eid = None
# else:
# self.experimenter = self.conn.getObject("Experimenter", eid)
im_list = list(self.conn.listImagesInDataset(
oid=did, eid=eid, page=page, load_pixels=load_pixels))
# List is already sorted by name, id in query
# im_list.sort(key=lambda x: (x.getName().lower(), x.getId()))
self.containers = {'images': im_list}
self.c_size = self.conn.getCollectionCount(
"Dataset", "imageLinks", [long(did)])[long(did)]
if page is not None:
self.paging = self.doPaging(page, len(im_list), self.c_size)
def listContainerHierarchy(self, eid=None):
if eid is not None:
if eid == -1:
eid = None
else:
self.experimenter = self.conn.getObject("Experimenter", eid)
else:
eid = self.conn.getEventContext().userId
pr_list = list(self.conn.listProjects(eid))
ds_list = list(self.conn.listOrphans("Dataset", eid))
sc_list = list(self.conn.listScreens(eid))
pl_list = list(self.conn.listOrphans("Plate", eid))
pr_list.sort(key=lambda x: x.getName() and x.getName().lower())
ds_list.sort(key=lambda x: x.getName() and x.getName().lower())
sc_list.sort(key=lambda x: x.getName() and x.getName().lower())
pl_list.sort(key=lambda x: x.getName() and x.getName().lower())
self.orphans = self.conn.countOrphans("Image", eid)
self.containers = {
'projects': pr_list,
'datasets': ds_list,
'screens': sc_list,
'plates': pl_list}
self.c_size = len(pr_list)+len(ds_list)+len(sc_list)+len(pl_list)
def listOrphanedImages(self, eid=None, page=None):
if eid is not None:
if eid == -1:
eid = None
else:
self.experimenter = self.conn.getObject("Experimenter", eid)
else:
eid = self.conn.getEventContext().userId
params = omero.sys.ParametersI()
if page is not None:
params.page((int(page)-1)*settings.PAGE, settings.PAGE)
im_list = list(self.conn.listOrphans(
"Image", eid=eid, params=params, loadPixels=True))
im_list.sort(key=lambda x: (x.getName().lower(), x.getId()))
self.containers = {'orphaned': True, 'images': im_list}
self.c_size = self.conn.countOrphans("Image", eid=eid)
if page is not None:
self.paging = self.doPaging(page, len(im_list), self.c_size)
# Annotation list
def annotationList(self):
self.text_annotations = list()
self.rating_annotations = list()
self.file_annotations = list()
self.tag_annotations = list()
self.xml_annotations = list()
self.boolean_annotations = list()
self.double_annotations = list()
self.long_annotations = list()
self.term_annotations = list()
self.time_annotations = list()
self.my_client_map_annotations = list() # 'should' only be 1
self.client_map_annotations = list()
self.map_annotations = list()
self.companion_files = list()
annTypes = {omero.model.CommentAnnotationI: self.text_annotations,
omero.model.LongAnnotationI: self.long_annotations,
omero.model.FileAnnotationI: self.file_annotations,
omero.model.TagAnnotationI: self.tag_annotations,
omero.model.XmlAnnotationI: self.xml_annotations,
omero.model.BooleanAnnotationI: self.boolean_annotations,
omero.model.DoubleAnnotationI: self.double_annotations,
omero.model.TermAnnotationI: self.term_annotations,
omero.model.TimestampAnnotationI: self.time_annotations,
omero.model.MapAnnotationI: self.map_annotations}
aList = list()
if self.image is not None:
aList = list(self.image.listAnnotations())
elif self.dataset is not None:
aList = list(self.dataset.listAnnotations())
elif self.project is not None:
aList = list(self.project.listAnnotations())
elif self.screen is not None:
aList = list(self.screen.listAnnotations())
elif self.plate is not None:
aList = list(self.plate.listAnnotations())
elif self.acquisition is not None:
aList = list(self.acquisition.listAnnotations())
elif self.well is not None:
aList = list(self.well.getWellSample().image().listAnnotations())
for ann in aList:
annClass = ann._obj.__class__
if annClass in annTypes:
if ann.ns == omero.constants.metadata.NSINSIGHTRATING:
self.rating_annotations.append(ann)
elif ann.ns == omero.constants.namespaces.NSCOMPANIONFILE:
if (ann.getFileName() !=
omero.constants.annotation.file.ORIGINALMETADATA):
self.companion_files.append(ann)
elif ann.ns == omero.constants.metadata.NSCLIENTMAPANNOTATION:
if (ann.getDetails().getOwner().id ==
self.conn.getUserId()):
self.my_client_map_annotations.append(ann)
else:
self.client_map_annotations.append(ann)
else:
annTypes[annClass].append(ann)
self.text_annotations.sort(
key=lambda x: x.creationEventDate(), reverse=True)
self.file_annotations.sort(key=lambda x: x.creationEventDate())
self.rating_annotations.sort(key=lambda x: x.creationEventDate())
self.tag_annotations.sort(key=lambda x: x.textValue)
self.map_annotations.sort(key=lambda x: x.creationEventDate())
self.txannSize = len(self.text_annotations)
self.fileannSize = len(self.file_annotations)
self.tgannSize = len(self.tag_annotations)
def getGroupedRatings(self, rating_annotations=None):
"""
Groups ratings in preparation for display. Picks out the user's rating
and groups the remaining ones by value.
NB: This should be called after annotationList() has loaded
annotations.
"""
if rating_annotations is None:
rating_annotations = self.rating_annotations
userId = self.conn.getUserId()
myRating = None
ratingsByValue = {}
for r in range(1, 6):
ratingsByValue[r] = []
for rating in rating_annotations:
if rating.getDetails().getOwner().id == userId:
myRating = rating
else:
rVal = rating.getValue()
if rVal in ratingsByValue:
ratingsByValue[rVal].append(rating)
avgRating = 0
if (len(rating_annotations) > 0):
sumRating = sum([r.getValue() for r in rating_annotations])
avgRating = float(sumRating)/len(rating_annotations)
avgRating = int(round(avgRating))
# Experimental display of ratings as in PR #3322
# groupedRatings = []
# for r in range(5,0, -1):
# ratings = ratingsByValue[r]
# if len(ratings) > 0:
# groupedRatings.append({
# 'value': r,
# 'count': len(ratings),
# 'owners': ", ".join([
# str(r.getDetails().getOwner().getNameWithInitial())
# for r in ratings])
# })
myRating = myRating is not None and myRating.getValue() or 0
# NB: this should be json serializable as used in
# views.annotate_rating
return {
'myRating': myRating,
'average': avgRating,
'count': len(rating_annotations)}
def canUseOthersAnns(self):
"""
Test to see whether other user's Tags, Files etc should be provided
for annotating.
Used to ensure that E.g. Group Admins / Owners don't try to link other
user's Annotations when in a private group (even though they could
retrieve those annotations)
"""
gid = self.conn.SERVICE_OPTS.getOmeroGroup()
if gid is None:
return False
try:
group = self.conn.getObject("ExperimenterGroup", long(gid))
except:
return False
if group is None:
return False
perms = str(group.getDetails().getPermissions())
if perms in ("rwrw--", "rwra--"):
return True
if (perms == "rwr---" and (self.conn.isAdmin() or
self.conn.isLeader(group.id))):
return True
return False
def loadBatchAnnotations(self, objDict, ann_ids=None, addedByMe=False):
"""
Look up the Tags, Files, Comments, Ratings etc that are on one or more
of the objects in objDect.
"""
batchAnns = {
omero.model.CommentAnnotationI: 'Comment',
omero.model.LongAnnotationI: 'Long',
omero.model.FileAnnotationI: 'File',
omero.model.TagAnnotationI: 'Tag',
omero.model.XmlAnnotationI: 'Xml',
omero.model.BooleanAnnotationI: 'Boolean',
omero.model.DoubleAnnotationI: 'Double',
omero.model.TermAnnotationI: 'Term',
omero.model.TimestampAnnotationI: 'TimeStamp'
}
# return, E.g {"Tag": {AnnId: {'ann': ObjWrapper, 'parents':
# [ImageWrapper, etc] } }, etc...}
rv = {}
rv["UserRatings"] = {}
rv["OtherRatings"] = {}
# populate empty return map
for key, value in batchAnns.items():
rv[value] = {}
params = omero.sys.Parameters()
params.theFilter = omero.sys.Filter()
if addedByMe:
params.theFilter.ownerId = omero.rtypes.rlong(
self.conn.getUserId())
for objType, objList in objDict.items():
if len(objList) == 0:
continue
parent_ids = [o.getId() for o in objList]
# If we're working with a 'well', we're actually annotating the
# image
for i in range(len(objList)):
o = objList[i]
if isinstance(o._obj, omero.model.WellI):
objType = "Image"
# index has already been set
parent_ids[i] = o.getWellSample().image().getId()
if isinstance(objList[0]._obj, omero.model.PlateAcquisitionI):
objType = 'PlateAcquisition'
for annLink in self.conn.getAnnotationLinks(
objType, parent_ids=parent_ids, ann_ids=ann_ids,
params=params):
ann = annLink.getAnnotation()
if ann.ns == omero.constants.namespaces.NSCOMPANIONFILE:
continue
annClass = ann._obj.__class__
if annClass in batchAnns:
if ann.ns == omero.constants.metadata.NSINSIGHTRATING:
if (ann.getDetails().owner.id.val ==
self.conn.getUserId()):
annotationsMap = rv["UserRatings"]
else:
annotationsMap = rv["OtherRatings"]
else:
# E.g. map for 'Tags'
annotationsMap = rv[batchAnns[annClass]]
if ann.getId() not in annotationsMap:
annotationsMap[ann.getId()] = {
'ann': ann,
'links': [annLink],
'unlink': 0}
else:
annotationsMap[ann.getId()]['links'].append(annLink)
if annLink.canDelete():
annotationsMap[ann.getId()]['unlink'] += 1
# bit more preparation for display...
batchAnns = {}
for key, annMap in rv.items():
# E.g. key = 'Tag', 'Comment', 'File' etc
annList = []
for annId, annDict in annMap.items():
# ann is {'ann':AnnWrapper, 'links'[AnnotationLinkWrapper, ..]}
# Each ann has links to several objects
annDict['links'].sort(key=lambda x: x.parent.id.val)
annDict['added_by'] = ",".join([
str(l.getDetails().getOwner().id)
for l in annDict['links']])
annDict['can_remove'] = annDict['unlink'] > 0
annList.append(annDict)
batchAnns[key] = annList
return batchAnns
def getTagsByObject(self, parent_type=None, parent_ids=None):
eid = ((not self.canUseOthersAnns()) and
self.conn.getEventContext().userId or None)
def sort_tags(tag_gen):
tag_anns = list(tag_gen)
try:
tag_anns.sort(key=lambda x: x.getValue().lower())
except:
pass
return tag_anns
if self.image is not None:
return sort_tags(self.image.listOrphanedAnnotations(
eid=eid, anntype='Tag'))
elif self.dataset is not None:
return sort_tags(self.dataset.listOrphanedAnnotations(
eid=eid, anntype='Tag', ns=['any']))
elif self.project is not None:
return sort_tags(self.project.listOrphanedAnnotations(
eid=eid, anntype='Tag'))
elif self.well is not None:
return sort_tags(
self.well.getWellSample().image().listOrphanedAnnotations(
eid=eid, anntype='Tag'))
elif self.plate is not None:
return sort_tags(self.plate.listOrphanedAnnotations(
eid=eid, anntype='Tag'))
elif self.screen is not None:
return sort_tags(self.screen.listOrphanedAnnotations(
eid=eid, anntype='Tag'))
elif self.acquisition is not None:
return sort_tags(self.acquisition.listOrphanedAnnotations(
eid=eid, anntype='Tag'))
elif parent_type and parent_ids:
parent_type = parent_type.title()
if parent_type == "Acquisition":
parent_type = "PlateAcquisition"
return sort_tags(self.conn.listOrphanedAnnotations(
parent_type, parent_ids, eid=eid, anntype='Tag'))
else:
if eid is not None:
params = omero.sys.Parameters()
params.theFilter = omero.sys.Filter()
params.theFilter.ownerId = omero.rtypes.rlong(eid)
return sort_tags(
self.conn.getObjects("TagAnnotation", params=params))
return sort_tags(self.conn.getObjects("TagAnnotation"))
def getFilesByObject(self, parent_type=None, parent_ids=None):
eid = ((not self.canUseOthersAnns()) and
self.conn.getEventContext().userId or None)
ns = [omero.constants.namespaces.NSCOMPANIONFILE,
omero.constants.namespaces.NSEXPERIMENTERPHOTO]
def sort_file_anns(file_ann_gen):
file_anns = list(file_ann_gen)
try:
file_anns.sort(key=lambda x: x.getFile().getName().lower())
except:
pass
return file_anns
if self.image is not None:
return sort_file_anns(self.image.listOrphanedAnnotations(
eid=eid, ns=ns, anntype='File'))
elif self.dataset is not None:
return sort_file_anns(self.dataset.listOrphanedAnnotations(
eid=eid, ns=ns, anntype='File'))
elif self.project is not None:
return sort_file_anns(self.project.listOrphanedAnnotations(
eid=eid, ns=ns, anntype='File'))
elif self.well is not None:
return sort_file_anns(
self.well.getWellSample().image().listOrphanedAnnotations(
eid=eid, ns=ns, anntype='File'))
elif self.plate is not None:
return sort_file_anns(self.plate.listOrphanedAnnotations(
eid=eid, ns=ns, anntype='File'))
elif self.screen is not None:
return sort_file_anns(self.screen.listOrphanedAnnotations(
eid=eid, ns=ns, anntype='File'))
elif self.acquisition is not None:
return sort_file_anns(self.acquisition.listOrphanedAnnotations(
eid=eid, ns=ns, anntype='File'))
elif parent_type and parent_ids:
parent_type = parent_type.title()
if parent_type == "Acquisition":
parent_type = "PlateAcquisition"
return sort_file_anns(self.conn.listOrphanedAnnotations(
parent_type, parent_ids, eid=eid, ns=ns, anntype='File'))
else:
return sort_file_anns(self.conn.listFileAnnotations(eid=eid))
####################################################################
# Creation
def createDataset(self, name, description=None, img_ids=None):
dsId = self.conn.createDataset(name, description, img_ids)
if self.project is not None:
l_ds = omero.model.ProjectDatasetLinkI()
l_ds.setParent(self.project._obj)
l_ds.setChild(omero.model.DatasetI(dsId, False))
# ds.addProjectDatasetLink(l_ds)
self.conn.saveAndReturnId(l_ds)
return dsId
def createProject(self, name, description=None):
return self.conn.createProject(name, description)
def createScreen(self, name, description=None):
return self.conn.createScreen(name, description)
def checkMimetype(self, file_type):
if file_type is None or len(file_type) == 0:
file_type = "application/octet-stream"
return file_type
def createCommentAnnotations(self, content, oids, well_index=0):
ann = omero.model.CommentAnnotationI()
ann.textValue = rstring(str(content))
ann = self.conn.saveAndReturnObject(ann)
new_links = list()
for k in oids.keys():
if len(oids[k]) > 0:
for ob in oids[k]:
if isinstance(ob._obj, omero.model.WellI):
t = 'Image'
obj = ob.getWellSample(well_index).image()
elif isinstance(ob._obj, omero.model.PlateAcquisitionI):
t = 'PlateAcquisition'
obj = ob
else:
t = k.lower().title()
obj = ob
l_ann = getattr(omero.model, t+"AnnotationLinkI")()
l_ann.setParent(obj._obj)
l_ann.setChild(ann._obj)
new_links.append(l_ann)
if len(new_links) > 0:
self.conn.saveArray(new_links)
return self.conn.getObject("CommentAnnotation", ann.getId())
def createTagAnnotations(self, tag, desc, oids, well_index=0,
tag_group_id=None):
"""
Creates a new tag (with description) OR uses existing tag with the
specified name if found.
Links the tag to the specified objects.
@param tag: Tag text/name
@param desc: Tag description
@param oids: Dict of Objects and IDs. E.g. {"Image": [1,2,3],
"Dataset", [6]}
"""
ann = None
try:
ann = self.conn.findTag(tag, desc)
except:
pass
if ann is None:
ann = omero.model.TagAnnotationI()
ann.textValue = rstring(tag.encode('utf8'))
ann.setDescription(rstring(desc.encode('utf8')))
ann = self.conn.saveAndReturnObject(ann)
if tag_group_id: # Put new tag in given tag set
tag_group = None
try:
tag_group = self.conn.getObject(
'TagAnnotation', tag_group_id)
except:
pass
if tag_group is not None:
link = omero.model.AnnotationAnnotationLinkI()
link.parent = tag_group._obj
link.child = ann._obj
self.conn.saveObject(link)
new_links = list()
parent_objs = []
for k in oids:
if len(oids[k]) > 0:
for ob in oids[k]:
if isinstance(ob._obj, omero.model.WellI):
t = 'Image'
obj = ob.getWellSample(well_index).image()
elif isinstance(ob._obj, omero.model.PlateAcquisitionI):
t = 'PlateAcquisition'
obj = ob
else:
t = k.lower().title()
obj = ob
parent_objs.append(obj)
l_ann = getattr(omero.model, t+"AnnotationLinkI")()
l_ann.setParent(obj._obj)
l_ann.setChild(ann._obj)
new_links.append(l_ann)
if len(new_links) > 0:
# If we retrieved an existing Tag above, link may already exist...
try:
self.conn.saveArray(new_links)
except omero.ValidationException:
for l in new_links:
try:
self.conn.saveObject(l)
except:
pass
return ann.getId()
def createFileAnnotations(self, newFile, oids, well_index=0):
format = self.checkMimetype(newFile.content_type)
oFile = omero.model.OriginalFileI()
oFile.setName(rstring(smart_str(newFile.name)))
oFile.setPath(rstring(smart_str(newFile.name)))
oFile.hasher = omero.model.ChecksumAlgorithmI()
oFile.hasher.value = omero.rtypes.rstring("SHA1-160")
oFile.setMimetype(rstring(str(format)))
ofid = self.conn.saveAndReturnId(oFile)
of = self.conn.saveAndReturnFile(newFile, ofid)
fa = omero.model.FileAnnotationI()
fa.setFile(of)
fa = self.conn.saveAndReturnObject(fa)
new_links = list()
for k in oids:
if len(oids[k]) > 0:
for ob in oids[k]:
if isinstance(ob._obj, omero.model.WellI):
t = 'Image'
obj = ob.getWellSample(well_index).image()
elif isinstance(ob._obj, omero.model.PlateAcquisitionI):
t = 'PlateAcquisition'
obj = ob
else:
t = k.lower().title()
obj = ob
l_ann = getattr(omero.model, t+"AnnotationLinkI")()
l_ann.setParent(obj._obj)
l_ann.setChild(fa._obj)
new_links.append(l_ann)
if len(new_links) > 0:
new_links = self.conn.getUpdateService().saveAndReturnArray(
new_links, self.conn.SERVICE_OPTS)
return fa.getId()
def createAnnotationsLinks(self, atype, tids, oids, well_index=0):
"""
Links existing annotations to 1 or more objects
@param atype: Annotation type E.g. "tag", "file"
@param tids: Annotation IDs
@param oids: Dict of Objects and IDs. E.g. {"Image": [1,2,3],
"Dataset", [6]}
"""
atype = str(atype).lower()
if not atype.lower() in ("tag", "comment", "file"):
raise AttributeError("Object type must be: tag, comment, file.")
new_links = list()
annotations = list(self.conn.getObjects("Annotation", tids))
parent_objs = []
for k in oids:
if len(oids[k]) > 0:
if k.lower() == 'acquisition':
parent_type = 'PlateAcquisition'
else:
parent_type = k.lower().title()
parent_ids = [o.id for o in oids[k]]
# check for existing links belonging to Current user
params = omero.sys.Parameters()
params.theFilter = omero.sys.Filter()
params.theFilter.ownerId = rlong(self.conn.getUserId())
links = self.conn.getAnnotationLinks(
parent_type, parent_ids=parent_ids, ann_ids=tids,
params=params)
pcLinks = [(l.parent.id.val, l.child.id.val) for l in links]
# Create link between each object and annotation
for ob in self.conn.getObjects(parent_type, parent_ids):
parent_objs.append(ob)
for a in annotations:
if (ob.id, a.id) in pcLinks:
continue # link already exists
if isinstance(ob._obj, omero.model.WellI):
parent_type = 'Image'
obj = ob.getWellSample(well_index).image()
else:
obj = ob
l_ann = getattr(
omero.model, parent_type+"AnnotationLinkI")()
l_ann.setParent(obj._obj)
l_ann.setChild(a._obj)
new_links.append(l_ann)
failed = 0
saved_links = []
try:
# will fail if any of the links already exist
saved_links = self.conn.getUpdateService().saveAndReturnArray(
new_links, self.conn.SERVICE_OPTS)