-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathtree.py
More file actions
2205 lines (1944 loc) · 68.7 KB
/
tree.py
File metadata and controls
2205 lines (1944 loc) · 68.7 KB
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 -*-
# Copyright (C) 2008-2016 University of Dundee & Open Microscopy Environment.
# All rights reserved.
#
# 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/>.
"""Helper functions for views that handle object trees"""
import logging
import time
import pytz
import omero
from collections import defaultdict
from omero.rtypes import rlong, unwrap, wrap
from django.conf import settings
from datetime import datetime
from copy import deepcopy
from omero.gateway import _letterGridLabel, _PlateWrapper
logger = logging.getLogger(__name__)
def unwrap_to_str(rstr):
"""Handle rstring unwrapping which by default gives b'bytes' in
python3 and string in python2.
"""
rstr = unwrap(rstr)
if rstr is not None:
rstr = bytes(rstr, "utf8").decode()
return rstr
def build_clause(components, name="", join=","):
"""Build a string from a list of components.
This is to simplify building where clauses in particular that
may optionally have zero, one or more parts
"""
if not components:
return ""
return " " + name + " " + (" " + join + " ").join(components) + " "
def parse_permissions_css(permissions, ownerid, conn):
"""Parse numeric permissions into a string of space separated
CSS classes.
@param permissions Permissions to parse
@type permissions L{omero.rtypes.rmap}
@param ownerid Owner Id for the object having Permissions
@type ownerId Integer
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
"""
restrictions = (
"canEdit",
"canAnnotate",
"canLink",
"canDelete",
"canChgrp",
"canChown",
)
permissionsCss = [r for r in restrictions if permissions.get(r)]
if ownerid == conn.getUserId():
permissionsCss.append("isOwned")
return " ".join(permissionsCss)
def _marshal_group(conn, row):
"""Given an ExperimenterGroup row (list) marshals it into a dictionary.
Order and type of columns in row is:
* id (rlong)
* name (rstring)
* permissions (dict)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param row The Group row to marshal
@type row L{list}
"""
group_id, name, permissions = row
group = dict()
group["id"] = unwrap(group_id)
group["name"] = unwrap_to_str(name)
group["perm"] = unwrap(unwrap(permissions)["perm"])
return group
def marshal_groups(conn, member_id=-1, page=1, limit=settings.PAGE):
"""Marshals groups
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param member_id The ID of the experimenter to filter by
or -1 for all
defaults to -1
@type member_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}
"""
groups = []
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
service_opts.setOmeroGroup(-1)
# Paging
if page is not None and page > 0:
params.page((page - 1) * limit, limit)
join_clause = ""
where_clause = ""
if member_id != -1:
params.add("mid", rlong(member_id))
join_clause = " join grp.groupExperimenterMap grexp "
where_clause = " and grexp.child.id = :mid "
qs = conn.getQueryService()
q = """
select grp.id,
grp.name,
grp.details.permissions
from ExperimenterGroup grp
%s
where grp.name != 'user'
%s
order by lower(grp.name)
""" % (
join_clause,
where_clause,
)
for e in qs.projection(q, params, service_opts):
groups.append(_marshal_group(conn, e[0:3]))
return groups
def _marshal_experimenter(conn, row):
"""Given an Experimenter row (list) marshals it into a dictionary. Order
and type of columns in row is:
* id (rlong)
* omeName (rstring)
* firstName (rstring)
* lastName (rstring)
* email (rstring)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param row The Experimenter row to marshal
@type row L{list}
"""
experimenter_id, ome_name, first_name, last_name, email = row
experimenter = dict()
experimenter["id"] = unwrap(experimenter_id)
experimenter["omeName"] = unwrap_to_str(ome_name)
experimenter["firstName"] = unwrap_to_str(first_name)
experimenter["lastName"] = unwrap_to_str(last_name)
return experimenter
def marshal_experimenters(conn, group_id=-1, page=1, limit=settings.PAGE):
"""Marshals experimenters, possibly filtered by group.
To make this consistent with the other tree.py functions
this will default to restricting the results by the calling
experimenters group membership. e.g. if user is in groupA
and groupB, then users from groupA and groupB will be
returned.
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param group_id The Group ID to filter by or -1 for all groups,
defaults to -1
@type group_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}
"""
experimenters = []
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
if group_id is None:
group_id = -1
# This does not actually restrict the results so the restriction to
# a certain group is done in the query
service_opts.setOmeroGroup(-1)
# Paging
if page is not None and page > 0:
params.page((page - 1) * limit, limit)
where_clause = ""
if group_id != -1:
params.add("gid", rlong(group_id))
where_clause = """
join experimenter.groupExperimenterMap grexp
where grexp.parent.id = :gid
"""
# Don't currently need this filtering
# Restrict by the current user's group membership
# else:
# params.add('eid', rlong(conn.getUserId()))
# where_clause = '''
# join experimenter.groupExperimenterMap grexp
# where grexp.child.id = :eid
# '''
qs = conn.getQueryService()
q = """
select experimenter.id,
experimenter.omeName,
experimenter.firstName,
experimenter.lastName,
experimenter.email
from Experimenter experimenter %s
order by lower(experimenter.omeName), experimenter.id
""" % (where_clause)
for e in qs.projection(q, params, service_opts):
experimenters.append(_marshal_experimenter(conn, e[0:5]))
return experimenters
def marshal_experimenter(conn, experimenter_id):
"""Marshals experimenter.
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param experimenter_id The Experimenter ID to get details for
@type experimenter_id L{long}
"""
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
service_opts.setOmeroGroup(-1)
params.add("id", rlong(experimenter_id))
qs = conn.getQueryService()
join_clause = ""
where_clause = ""
if not conn.isAdmin():
group_ids = conn.getEventContext().memberOfGroups
user_gid = conn.getAdminService().getSecurityRoles().userGroupId
if user_gid in group_ids:
group_ids.remove(user_gid)
params.addIds(group_ids)
join_clause = "join experimenter.groupExperimenterMap gem"
where_clause = "and gem.parent.id in :ids"
q = """
select distinct experimenter.id,
experimenter.omeName,
experimenter.firstName,
experimenter.lastName,
experimenter.email
from Experimenter experimenter
%s
where experimenter.id = :id
%s
""" % (
join_clause,
where_clause,
)
rows = qs.projection(q, params, service_opts)
if len(rows) != 1:
return None
return _marshal_experimenter(conn, rows[0][0:5])
def _marshal_project(conn, row):
"""Given a Project row (list) marshals it into a dictionary. Order
and type of columns in row is:
* id (rlong)
* name (rstring)
* details.owner.id (rlong)
* details.permissions (dict)
* child_count (rlong)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param row The Project row to marshal
@type row L{list}
"""
project_id, name, owner_id, permissions, child_count = row
project = dict()
project["id"] = unwrap(project_id)
project["name"] = unwrap_to_str(name)
project["ownerId"] = unwrap(owner_id)
project["childCount"] = unwrap(child_count)
project["permsCss"] = parse_permissions_css(permissions, unwrap(owner_id), conn)
return project
def marshal_projects(
conn, group_id=-1, experimenter_id=-1, page=1, limit=settings.PAGE
):
"""Marshals projects
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@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}
"""
projects = []
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
# Set the desired group context
if group_id is None:
group_id = -1
service_opts.setOmeroGroup(group_id)
# Paging
if page is not None and page > 0:
params.page((page - 1) * limit, limit)
where_clause = ""
if experimenter_id is not None and experimenter_id != -1:
params.addId(experimenter_id)
where_clause = "where project.details.owner.id = :id"
qs = conn.getQueryService()
q = """
select new map(project.id as id,
project.name as name,
project.details.owner.id as ownerId,
project as project_details_permissions,
(select count(id) from ProjectDatasetLink pdl
where pdl.parent = project.id) as childCount)
from Project project
%s
order by lower(project.name), project.id
""" % (where_clause)
for e in qs.projection(q, params, service_opts):
e = unwrap(e)
e = [
e[0]["id"],
e[0]["name"],
e[0]["ownerId"],
e[0]["project_details_permissions"],
e[0]["childCount"],
]
projects.append(_marshal_project(conn, e[0:5]))
return projects
def _marshal_dataset(conn, row):
"""Given a Dataset row (list) marshals it into a dictionary. Order
and type of columns in row is:
* id (rlong)
* name (rstring)
* details.owner.id (rlong)
* details.permissions (dict)
* child_count (rlong)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param row The Dataset row to marshal
@type row L{list}
"""
dataset_id, name, owner_id, permissions, child_count = row
dataset = dict()
dataset["id"] = unwrap(dataset_id)
dataset["name"] = unwrap_to_str(name)
dataset["ownerId"] = unwrap(owner_id)
dataset["childCount"] = unwrap(child_count)
dataset["permsCss"] = parse_permissions_css(permissions, unwrap(owner_id), conn)
return dataset
def marshal_datasets(
conn,
project_id=None,
orphaned=False,
group_id=-1,
experimenter_id=-1,
page=1,
limit=settings.PAGE,
):
"""Marshals datasets
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param project_id The Project ID to filter by or `None` to
not filter by a specific project.
defaults to `None`
@type project_id L{long}
@param orphaned If this is to filter by orphaned data. Overridden
by project_id.
defaults to False
@type orphaned 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}
"""
datasets = []
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
# Set the desired group context
if group_id is None:
group_id = -1
service_opts.setOmeroGroup(group_id)
# Paging
if page is not None and page > 0:
params.page((page - 1) * limit, limit)
where_clause = []
if experimenter_id is not None and experimenter_id != -1:
params.addId(experimenter_id)
where_clause.append("dataset.details.owner.id = :id")
qs = conn.getQueryService()
q = """
select new map(dataset.id as id,
dataset.name as name,
dataset.details.owner.id as ownerId,
dataset as dataset_details_permissions,
(select count(id) from DatasetImageLink dil
where dil.parent=dataset.id) as childCount)
from Dataset dataset
"""
# If this is a query to get datasets from a parent project
if project_id:
params.add("pid", rlong(project_id))
q += "join dataset.projectLinks plink"
where_clause.append("plink.parent.id = :pid")
# If this is a query to get datasets with no parent project
elif orphaned:
where_clause.append("""
not exists (
select pdlink from ProjectDatasetLink as pdlink
where pdlink.child = dataset.id
)
""")
q += """
%s
order by lower(dataset.name), dataset.id
""" % build_clause(where_clause, "where", "and")
for e in qs.projection(q, params, service_opts):
e = unwrap(e)
e = [
e[0]["id"],
e[0]["name"],
e[0]["ownerId"],
e[0]["dataset_details_permissions"],
e[0]["childCount"],
]
datasets.append(_marshal_dataset(conn, e[0:5]))
return datasets
def _marshal_date(time):
try:
d = datetime.fromtimestamp(time // 1000)
try:
# Add time-zone awareness
tz = pytz.timezone(settings.TIME_ZONE)
d = tz.localize(d)
except pytz.exceptions.UnknownTimeZoneError:
logger.debug("UnknownTimeZoneError: " + settings.TIME_ZONE)
return d.isoformat()
except ValueError:
return ""
def _marshal_image(
conn,
row,
row_pixels=None,
share_id=None,
date=None,
acqDate=None,
thumbVersion=None,
):
"""Given an Image row (list) marshals it into a dictionary. Order
and type of columns in row is:
* id (rlong)
* name (rstring)
* details.owner.id (rlong)
* details.permissions (dict)
* fileset_id (rlong)
May also take a row_pixels (list) if X,Y,Z,T dimensions are loaded
* pixels.sizeX (rlong)
* pixels.sizeY (rlong)
* pixels.sizeZ (rlong)
* pixels.sizeT (rlong)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param row The Image row to marshal
@type row L{list}
@param row_pixels The Image row pixels data to marshal
@type row_pixels L{list}
"""
image_id, name, owner_id, permissions, fileset_id = row
data = {
"id": image_id,
"name": name,
"ownerId": owner_id,
"image_details_permissions": permissions,
"filesetId": fileset_id,
}
if row_pixels:
sizeX, sizeY, sizeZ, sizeT = row_pixels
data["sizeX"] = sizeX
data["sizeY"] = sizeY
data["sizeZ"] = sizeZ
data["sizeT"] = sizeT
return _marshal_image_map(
conn,
data,
share_id=share_id,
date=date,
acqDate=acqDate,
thumbVersion=thumbVersion,
)
def _marshal_image_map(
conn,
data,
share_id=None,
date=None,
acqDate=None,
thumbVersion=None,
):
"""Given an Image data dictionary marshals it into a dictionary. Suppored keys are:
* id (rlong)
* archived (boolean; optional)
* name (rstring)
* ownerId (rlong)
* image_details_permissions (dict)
* filesetId (rlong)
* sizeX (rlong; optional)
* sizeY (rlong; optional)
* sizeZ (rlong; optional)
* sizeT (rlong; optional)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param data The data to marshal
@type row L{dict}
"""
image = dict()
image["id"] = unwrap(data["id"])
image["archived"] = unwrap(data.get("archived")) is True
image["name"] = unwrap_to_str(data["name"])
image["ownerId"] = unwrap(data["ownerId"])
image["permsCss"] = parse_permissions_css(
data["image_details_permissions"], unwrap(data["ownerId"]), conn
)
fileset_id_val = unwrap(data["filesetId"])
if fileset_id_val is not None:
image["filesetId"] = fileset_id_val
if "sizeX" in data:
image["sizeX"] = unwrap(data["sizeX"])
if "sizeY" in data:
image["sizeY"] = unwrap(data["sizeY"])
if "sizeZ" in data:
image["sizeZ"] = unwrap(data["sizeZ"])
if "sizeT" in data:
image["sizeT"] = unwrap(data["sizeT"])
if share_id is not None:
image["shareId"] = share_id
if date is not None:
image["date"] = _marshal_date(unwrap(date))
if acqDate is not None:
image["acqDate"] = _marshal_date(unwrap(acqDate))
if thumbVersion is not None:
image["thumbVersion"] = thumbVersion
return image
def _marshal_image_deleted(conn, image_id):
"""Given an Image id and marshals it into a dictionary.
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param image_id The image id to marshal
@type image_id L{long}
"""
return {"id": unwrap(image_id), "deleted": True}
def marshal_images(
conn,
dataset_id=None,
orphaned=False,
share_id=None,
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 dataset_id The Dataset ID to filter by or `None` to
not filter by a specific dataset.
defaults to `None`
@type dataset_id L{long}
@param orphaned If this is to filter by orphaned data. Overridden
by dataset_id.
defaults to False
@type orphaned Boolean
@param share_id The Share ID to filter by or `None` to
not filter by a specific share.
defaults to `None`
@type share_id L{long}
@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 = []
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
# Set the desired group context
if group_id is None:
group_id = -1
service_opts.setOmeroGroup(group_id)
# Paging
if page is not None and page > 0:
params.page((page - 1) * limit, limit)
from_join_clauses = []
where_clause = []
if experimenter_id is not None and experimenter_id != -1:
params.addId(experimenter_id)
where_clause.append("image.details.owner.id = :id")
qs = conn.getQueryService()
extraValues = ""
if load_pixels:
extraValues = """
,
pix.sizeX as sizeX,
pix.sizeY as sizeY,
pix.sizeT as sizeT,
pix.sizeZ as sizeZ
"""
if date:
extraValues += """,
image.details.creationEvent.time as date,
image.acquisitionDate as acqDate
"""
q = """
select new map(image.id as id,
image.archived as archived,
image.name as name,
image.details.owner.id as ownerId,
image as image_details_permissions,
image.fileset.id as filesetId %s)
""" % extraValues
from_join_clauses.append("Image image")
if load_pixels:
# We use 'left outer join', since we still want images if no pixels
from_join_clauses.append("left outer join image.pixels pix")
# If this is a query to get images from a parent dataset
if dataset_id is not None:
params.add("did", rlong(dataset_id))
from_join_clauses.append("join image.datasetLinks dlink")
where_clause.append("dlink.parent.id = :did")
# If this is a query to get images with no parent datasets (orphans)
# At the moment the implementation assumes that a cross-linked
# object is not an orphan. We may need to change that so that a user
# see all the data that belongs to them that is not assigned to a container
# that they own.
elif orphaned:
orphan_where = """
not exists (
select dilink from DatasetImageLink as dilink
where dilink.child = image.id
"""
# This is what is necessary if an orphan means that it has no
# container that belongs to the image owner. This corresponds
# to marshal_orphaned as well because of the child count
# if experimenter_id is not None and experimenter_id != -1:
# orphan_where += ' and dilink.parent.details.owner.id = :id '
orphan_where += ") "
where_clause.append(orphan_where)
# Also discount any images which are part of a screen. No need to
# take owner into account on this because we don't want them in
# orphans either way
where_clause.append("""
not exists (
select ws from WellSample ws
where ws.image.id = image.id
)
""")
# If this is a query to get images in a share
if share_id is not None:
# Get the contents of the blob which contains the images in the share
# Would be nice to do this without the ShareService, preferably as part
# of the single query
image_rids = [
image_rid.getId().val
for image_rid in conn.getShareService().getContents(share_id)
if isinstance(image_rid, omero.model.ImageI)
]
# If there are no images in the share, don't bother querying
if not image_rids:
return images
params.add("iids", wrap([rlong(id) for id in image_rids]))
where_clause.append("image.id in (:iids)")
q += """
%s %s
order by lower(image.name), image.id
""" % (
" from " + " ".join(from_join_clauses),
build_clause(where_clause, "where", "and"),
)
for e in qs.projection(q, params, service_opts):
data = unwrap(e)[0]
kwargs = {}
if date:
kwargs["acqDate"] = data["acqDate"]
kwargs["date"] = data["date"]
# While marshalling the images, determine if there are any
# images mentioned in shares that are not in the results
# because they have been deleted
if share_id is not None and image_rids and data["id"] in image_rids:
image_rids.remove(data["id"])
kwargs["share_id"] = share_id
images.append(_marshal_image_map(conn, data, **kwargs))
# Load thumbnails separately
# We want version of most recent thumbnail (max thumbId) owned by user
if thumb_version and len(images) > 0:
userId = conn.getUserId()
iids = [i["id"] for i in images]
params = omero.sys.ParametersI()
params.addIds(iids)
params.add("thumbOwner", rlong(userId))
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
)
"""
thumbVersions = {}
for t in qs.projection(q, params, service_opts):
iid, tv = unwrap(t)
thumbVersions[iid] = tv
# For all images, set thumb version if we have it...
for i in images:
if i["id"] in thumbVersions:
i["thumbVersion"] = thumbVersions[i["id"]]
# If there were any deleted images in the share, marshal and return
# those
if share_id is not None and image_rids:
for image_rid in image_rids:
images.append(_marshal_image_deleted(conn, image_rid))
return images
def _marshal_screen(conn, row):
"""Given a Screen row (list) marshals it into a dictionary. Order and
type of columns in row is:
* id (rlong)
* name (rstring)
* details.owner.id (rlong)
* details.permissions (dict)
* child_count (rlong)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param row The Screen row to marshal
@type row L{list}
"""
screen_id, name, owner_id, permissions, child_count = row
screen = dict()
screen["id"] = unwrap(screen_id)
screen["name"] = unwrap_to_str(name)
screen["ownerId"] = unwrap(owner_id)
screen["childCount"] = unwrap(child_count)
screen["permsCss"] = parse_permissions_css(permissions, unwrap(owner_id), conn)
return screen
def marshal_screens(conn, group_id=-1, experimenter_id=-1, page=1, limit=settings.PAGE):
"""Marshals screens
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@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}
"""
screens = []
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
# Set the desired group context
if group_id is None:
group_id = -1
service_opts.setOmeroGroup(group_id)
# Paging
if page is not None and page > 0:
params.page((page - 1) * limit, limit)
where_clause = ""
if experimenter_id is not None and experimenter_id != -1:
params.addId(experimenter_id)
where_clause = "where screen.details.owner.id = :id"
qs = conn.getQueryService()
q = """
select new map(screen.id as id,
screen.name as name,
screen.details.owner.id as ownerId,
screen as screen_details_permissions,
(select count(spl.id) from ScreenPlateLink spl
where spl.parent=screen.id) as childCount)
from Screen screen
%s
order by lower(screen.name), screen.id
""" % where_clause
for e in qs.projection(q, params, service_opts):
e = unwrap(e)
e = [
e[0]["id"],
e[0]["name"],
e[0]["ownerId"],
e[0]["screen_details_permissions"],
e[0]["childCount"],
]
screens.append(_marshal_screen(conn, e[0:5]))
return screens
def _marshal_plate(conn, row):
"""Given a Plate row (list) marshals it into a dictionary. Order and
type of columns in row is:
* id (rlong)
* name (rstring)
* details.owner.id (rlong)
* details.permissions (dict)
* child_count (rlong)
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param row The Plate row to marshal
@type row L{list}
"""
plate_id, name, owner_id, permissions, child_count = row
plate = dict()
plate["id"] = unwrap(plate_id)
plate["name"] = unwrap_to_str(name)
plate["ownerId"] = unwrap(owner_id)
plate["childCount"] = unwrap(child_count)
plate["permsCss"] = parse_permissions_css(permissions, unwrap(owner_id), conn)
return plate
def marshal_plates(
conn,
screen_id=None,
orphaned=False,
group_id=-1,
experimenter_id=-1,
page=1,
limit=settings.PAGE,
):
"""Marshals plates
@param conn OMERO gateway.
@type conn L{omero.gateway.BlitzGateway}
@param screen_id The Screen ID to filter by or `None` to
not filter by a specific screen.
defaults to `None`
@type screen_id L{long}
@param orphaned If this is to filter by orphaned data. Overridden
by dataset_id.
defaults to False
@type orphaned 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}
"""
plates = []
params = omero.sys.ParametersI()
service_opts = deepcopy(conn.SERVICE_OPTS)
# Set the desired group context
if group_id is None:
group_id = -1
service_opts.setOmeroGroup(group_id)
# Paging