-
Notifications
You must be signed in to change notification settings - Fork 12
/
ndwsrest.py
2276 lines (1754 loc) · 81.3 KB
/
ndwsrest.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
# Copyright 2014 NeuroData (http://neurodata.io)
#
#Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#RBTODO --- refactor other fields like ROI children
# e.g. Node children, Skeleton nodes, other TODOs in file
import tempfile
import numpy as np
import zlib
import h5py
import os
from io import BytesIO
import csv
import re
import json
import blosc
from PIL import Image
import MySQLdb
import itertools
from contextlib import closing
#from libtiff import TIFF
from operator import sub, add
#from libtiff import TIFFfile, TIFFimage
import webservices.restargs as restargs
from ndlib.ndtype import *
from spdb.spatialdb import SpatialDB
from ndproj.ndprojdb import NDProjectsDB
from ndproj.ndchannel import NDChannel
from ndproj.ndproject import NDProject
from ndramon import h5ann
from ndramon.annotation import *
from ndramon.ramondb import RamonDB
from ndproj import h5projinfo
from ndproj import jsonprojinfo
from . import mcfc
from ndlib.ndctypelib import filter_ctype_OMP
from spdb.ndcube.timecube8 import TimeCube8
import webservices.ndwsskel
from webservices.ndwsnifti import ingestNIFTI, queryNIFTI
from ndlib.windowcutout import windowCutout
from ndlib.ndtype import TIMESERIES_CHANNELS, ANNOTATION_CHANNELS, NOT_PROPAGATED, UNDER_PROPAGATION, PROPAGATED, ND_dtypetonp, DTYPE_uint8, DTYPE_uint16, DTYPE_uint32, READONLY_TRUE, READONLY_FALSE
from webservices.ndwserror import NDWSError, IncorrectSyntaxError
import logging
logger = logging.getLogger("neurodata")
#RBTODO check all the zoom in zoom out and write unittests.
def cutout (imageargs, ch, proj, db):
"""Build and Return a cube of data for the specified dimensions. This method is called by all of the more basic services to build the data. They then format and refine the output. """
# Perform argument processing
try:
args = restargs.BrainRestArgs ()
args.cutoutArgs(imageargs, proj.datasetcfg)
except restargs.RESTArgsError as e:
logger.error("REST Arguments {} failed: {}".format(imageargs,e))
raise NDWSError(str(e))
# Extract the relevant values
corner = args.getCorner()
dim = args.getDim()
resolution = args.getResolution()
filterlist = args.getFilter()
zscaling = args.getZScaling()
timerange = args.getTimeRange()
windowrange = args.getWindowRange()
# Perform the cutout
# support for 3-d cutouts
if timerange == None:
cube = db.cutout(ch, corner, dim, resolution, timerange=ch.default_time_range, zscaling=zscaling)
else:
cube = db.cutout(ch, corner, dim, resolution, timerange=timerange, zscaling=zscaling)
filterCube(ch, cube, filterlist)
if timerange==None:
# convert 4-d to 3-d here for now
cube.data = cube.data.reshape(cube.data.shape[1:])
# window range on cutout only when specified by argument -- no defaults for now
if windowrange!= None:
if ch.channel_datatype == 'float32':
windowrange = [float(x) for x in windowrange]
else:
windowrange = [int(x) for x in windowrange]
cbnew = TimeCube8 ( )
cbnew.data = window(cube.data, ch, window_range=windowrange)
return cbnew
else:
return cube
def filterCube(ch, cube, filterlist=None):
"""Call Filter on a cube"""
if ch.channel_type in ANNOTATION_CHANNELS and filterlist is not None:
cube.data = filter_ctype_OMP ( cube.data, filterlist )
elif filterlist is not None and ch.channel_type not in ANNOTATION_CHANNELS:
logger.error("Filter only possible for Annotation Channels")
raise NDWSError("Filter only possible for Annotation Channels")
def channelIterCutout(channels, imageargs, proj, db):
"""Create a numpy datacube array using data from the given channels."""
try:
# extract the first channel
channel_list = channels.split(',')
ch = proj.getChannelObj(channel_list[0])
# call cutout for first channel
channel_data = cutout( imageargs, ch, proj, db ).data
cubedata = np.zeros ( (len(channel_list),)+channel_data.shape[:], dtype=channel_data.dtype )
cubedata[0,:] = cutout(imageargs, ch, proj, db).data
# iterate from second to nth channel
for idx,channel_name in enumerate(channel_list[1:]):
if channel_name == '0':
continue
else:
ch = proj.getChannelObj(channel_name)
if ND_dtypetonp[ch.channel_datatype] == cubedata.dtype:
cubedata[idx+1,:] = cutout(imageargs, ch, proj, db).data
else:
logger.error("The cutout {} can only contain cutouts of one single Channel Type.".format())
raise NDWSError("The cutout {} can only contain cutouts of one single Channel Type.".format())
return cubedata
except Exception as e:
logger.error("{}".format(e))
raise NDWSError("{}".format(e))
def numpyZip ( chanargs, proj, db ):
"""Return a web readable Numpy Pickle zipped"""
try:
# argument of format channel/service/imageargs
m = re.match("([\w+,]+)/(\w+)/([\w\.,/-]+)$", chanargs)
[channels, service, imageargs] = [i for i in m.groups()]
except Exception as e:
logger.error("Arguments not in the correct format {}. {}".format(chanargs, e))
raise NDWSError("Arguments not in the correct format {}. {}".format(chanargs, e))
try:
cubedata = channelIterCutout(channels, imageargs, proj, db)
# Create the compressed cube
fileobj = BytesIO()
np.save ( fileobj, cubedata )
cdz = zlib.compress (fileobj.getvalue())
# Package the object as a Web readable file handle
fileobj = BytesIO(cdz)
fileobj.seek(0)
return fileobj.read()
except Exception as e:
logger.error("{}".format(e))
raise NDWSError("{}".format(e))
def RAW ( chanargs, proj, db ):
"""Return a web readable raw binary representation (knossos format).
It's a simple binary representation with the multidimensional array being
converted into a byte array in C-style iteration over the matrix."""
try:
# argument of format channel/service/imageargs
m = re.match("([\w+,]+)/(\w+)/([\w+,/-]+)$", chanargs)
[channels, service, imageargs] = [i for i in m.groups()]
except Exception as e:
logger.error("Arguments not in the correct format {}. {}".format(chanargs, e))
raise NDWSError("Arguments not in the correct format {}. {}".format(chanargs, e))
try:
cubedata = channelIterCutout(channels, imageargs, proj, db)
binary_representation = cubedata.tobytes("C")
return binary_representation
except Exception as e:
logger.error("{}".format(e))
raise NDWSError("{}".format(e))
def JPEG ( chanargs, proj, db ):
"""Return a web readable JPEG File"""
try:
# argument of format channel/service/imageargs
m = re.match("([\w+,]+)/(\w+)/([\w+,/-]+)$", chanargs)
[channels, service, imageargs] = [i for i in m.groups()]
except Exception as e:
logger.error("Arguments not in the correct format {}. {}".format(chanargs, e))
raise NDWSError("Arguments not in the correct format {}. {}".format(chanargs, e))
try:
ch = proj.getChannelObj(channels.split(',')[0])
cubedata = channelIterCutout(channels, imageargs, proj, db)
xdim, ydim, zdim = cubedata[0,:,:,:].shape[::-1]
#cubedata = np.swapaxes(cubedata[0,:,:,:], 0,2).reshape(xdim*zdim, ydim)
cubedata = cubedata[0,:,:,:].reshape(ydim*zdim, xdim)
if ch.channel_datatype in DTYPE_uint16:
img = Image.fromarray(cubedata, mode='I;16')
img = img.point(lambda i:i*(1./256)).convert('L')
elif ch.channel_datatype in DTYPE_uint32:
img = Image.fromarray(cubedata, mode='RGBA')
else:
img = Image.fromarray(cubedata)
fileobj = BytesIO()
img.save ( fileobj, "JPEG" )
fileobj.seek(0)
return fileobj.read()
except Exception as e:
logger.error("{}".format(e))
raise NDWSError("{}".format(e))
def BLOSC ( chanargs, proj, db ):
"""Return a web readable blosc file"""
try:
# argument of format channel/service/imageargs
m = re.match("([\w+,]+)/(\w+)/([\w+,/-]+)$", chanargs)
[channels, service, imageargs] = [i for i in m.groups()]
except Exception as e:
logger.error("Arguments not in the correct format {}. {}".format(chanargs, e))
raise NDWSError("Arguments not in the correct format {}. {}".format(chanargs, e))
try:
cubedata = channelIterCutout(channels, imageargs, proj, db)
# Create the compressed cube
return blosc.pack_array(cubedata)
except Exception as e:
logger.error("{}".format(e))
raise NDWSError("{}".format(e))
def binZip ( chanargs, proj, db ):
"""Return a web readable Numpy Pickle zipped"""
try:
# argument of format channel/service/imageargs
m = re.match("([\w+,]+)/(\w+)/([\w+,/-]+)$", chanargs)
[channels, service, imageargs] = [i for i in m.groups()]
except Exception as e:
logger.error("Arguments not in the correct format {}. {}".format(chanargs, e))
raise NDWSError("Arguments not in the correct format {}. {}".format(chanargs, e))
try:
cubedata = channelIterCutout(channels, imageargs, proj, db)
# Create the compressed cube
cdz = zlib.compress (cubedata.tostring())
# Package the object as a Web readable file handle
fileobj = BytesIO(cdz)
fileobj.seek(0)
return fileobj.read()
except Exception as e:
logger.error("{}".format(e))
raise NDWSError("{}".format(e))
def HDF5(chanargs, proj, db):
"""Return a web readable HDF5 file"""
# Create an in-memory HDF5 file
tmpfile = tempfile.NamedTemporaryFile()
fh5out = h5py.File(tmpfile.name, driver='core', backing_store=True)
try:
# argument of format channel/service/imageargs
m = re.match("([\w+,]+)/(\w+)/([\w+,/-]+)$", chanargs)
[channels, service, imageargs] = [i for i in m.groups()]
except Exception as e:
logger.error("Arguments not in the correct format {}. {}".format(chanargs, e))
raise IncorrectSyntaxError("Arguments not in the correct format {}. {}".format(chanargs, e))
try:
for channel_name in channels.split(','):
ch = proj.getChannelObj(channel_name)
cube = cutout(imageargs, ch, proj, db)
changrp = fh5out.create_group( "{}".format(channel_name) )
changrp.create_dataset("CUTOUT", tuple(cube.data.shape), cube.data.dtype, compression='gzip', data=cube.data.reshape(cube.data.shape))
changrp.create_dataset("CHANNELTYPE", (1,), dtype=h5py.special_dtype(vlen=str), data=ch.channel_type)
changrp.create_dataset("DATATYPE", (1,), dtype=h5py.special_dtype(vlen=str), data=ch.channel_datatype)
fh5out.close()
tmpfile.seek(0)
return tmpfile.read()
except Exception as e:
fh5out.close()
tmpfile.close()
logger.error("{}".format(e))
raise NDWSError("{}".format(e))
def postTiff3d ( channel, postargs, proj, db, postdata ):
"""Upload a tiff to the database"""
# get the channel
ch = proj.getChannelObj(channel)
if ch.channel_datatype in DTYPE_uint8:
datatype=np.uint8
elif ch.channel_datatype in DTYPE_uint16:
datatype=np.uint16
elif ch.channel_datatype in DTYPE_uint32:
datatype=np.uint32
else:
logger.error("Unsupported data type for TIFF3d post. {}".format(ch.channel_datatype))
raise NDWSError ("Unsupported data type for TIFF3d post. {}".format(ch.channel_datatype))
# parse the args
resstr, xoffstr, yoffstr, zoffstr, rest = postargs.split('/',4)
resolution = int(resstr)
projoffset = proj.datasetcfg.get_offset(resolution)
xoff = int(xoffstr)-projoffset[0]
yoff = int(yoffstr)-projoffset[1]
zoff = int(zoffstr)-projoffset[2]
# RBTODO check that the offsets are legal
# read the tiff data into a cuboid
with closing (tempfile.NamedTemporaryFile()) as tmpfile:
tmpfile.write( postdata )
tmpfile.seek(0)
# RBTODO move to libtiff
assert(0)
# tif = TIFF.open(tmpfile.name)
# get tiff metadata
image_width = tif.GetField("ImageWidth")
image_length = tif.GetField("ImageLength")
# get a z batch -- how many slices per cube
zbatch = proj.datasetcfg.get_cubedim(resolution)[0]
dircount = 0
dataar = None
# read each one at a time
for image in tif.iter_images():
# allocate a batch every cubesize
if dircount % zbatch == 0:
dataarray = np.zeros((zbatch, image_length, image_width), dtype=datatype)
dataarray[dircount%zbatch,:,:] = image
dircount += 1
# if we have a full batch go ahead and ingest
if dircount % zbatch == 0:
corner = ( xoff, yoff, zoff+dircount-zbatch )
db.writeCuboid (ch, corner, resolution, dataarray)
# ingest any remaining data
corner = ( xoff, yoff, zoff+dircount-(dircount%zbatch) )
db.writeCuboid (ch, corner, resolution, dataarray[0:(dircount%zbatch),:,:])
def timeDiff ( chanargs, proj, db):
"""Return a 3d delta in time"""
try:
# argument of format channel/service/imageargs
m = re.match("([\w+,]+)/(\w+)/([\w+,/-]+)$", chanargs)
[channels, service, imageargs] = [i for i in m.groups()]
except Exception as e:
logger.error("Arguments not in the correct format {}. {}".format(chanargs, e))
raise NDWSError("Arguments not in the correct format {}. {}".format(chanargs, e))
try:
channel_list = channels.split(',')
ch = proj.getChannelObj(channel_list[0])
channel_data = cutout( imageargs, ch, proj, db ).data
channel_data = np.negative(np.diff(np.float32(channel_data), axis=0))
cubedata = np.zeros((len(channel_list),)+channel_data.shape, dtype=np.float32)
cubedata[0,:] = channel_data
# if one channel convert 3-d to 4-d array
for idx,channel_name in enumerate(channel_list[1:]):
if channel_name == '0':
continue
else:
ch = proj.getChannelObj(channel_name)
if ND_dtypetonp[ch.channel_datatype] == cubedata.dtype:
cubedata[idx+1,:] = np.diff(cutout(imageargs, ch, proj, db).data, axis=0)
else:
raise NDWSError("The npz cutout can only contain cutouts of one single Channel Type.")
# Create the compressed cube
return blosc.pack_array(cubedata)
except Exception as e:
raise NDWSError("{}".format(e))
def tiff3d ( chanargs, proj, db ):
"""Return a 3d tiff file"""
[channels, service, imageargs] = chanargs.split('/', 2)
# create a temporary tif file
tmpfile = tempfile.NamedTemporaryFile()
assert 0 # RBTODO new TIFF
# tif = TIFF.open(tmpfile.name, mode='w')
try:
for channel_name in channels.split(','):
ch = proj.getChannelObj(channel_name)
cube = cutout ( imageargs, ch, proj, db )
FilterCube ( imageargs, cube )
# RB -- I think this is a cutout format. So, let's not recolor.
# # if it's annotations, recolor
# if ch.channel_type in ndprojdb.ANNOTATION_CHANNELS:
#
# imagemap = np.zeros ( (cube.data.shape[0]*cube.data.shape[1], cube.data.shape[2]), dtype=np.uint32 )
#
# # turn it into a 2-d array for recolor -- maybe make a 3-d recolor
# recolor_cube = recolor_ctype( cube.data.reshape((cube.data.shape[0]*cube.data.shape[1], cube.data.shape[2])), imagemap )
#
# # turn it back into a 4-d array RGBA
# recolor_cube = recolor_cube.view(dtype=np.uint8).reshape((cube.data.shape[0],cube.data.shape[1],cube.data.shape[2], 4 ))
#
# for i in range(recolor_cube.shape[0]):
# tif.write_image(recolor_cube[i,:,:,0:3], write_rgb=True)
#
# else:
tif.write_image(cube.data)
except:
tif.close()
tmpfile.close()
raise
tif.close()
tmpfile.seek(0)
return tmpfile.read()
def FilterCube ( imageargs, cb ):
""" Return a cube with the filtered ids """
# Filter Function - used to filter
result = re.search ("filter/([\d/,]+)/",imageargs)
if result != None:
filterlist = np.array ( result.group(1).split(','), dtype=np.uint32 )
cb.data = filter_ctype_OMP ( cb.data, filterlist )
def window(data, ch, window_range=None ):
"""Performs a window transformation on the cutout area
window always returns 8-bit data.
Careful how you use it. load target data into timeseriescube8.
"""
if window_range is None:
window_range = ch.window_range
[startwindow, endwindow] = window_range
# KL TODO window with signed channels -a to +b
if (startwindow == endwindow == 0):
return np.uint8(data)
elif endwindow!=0:
data = windowCutout (data, window_range)
return np.uint8(data)
return data
def imgSlice(webargs, proj, db):
"""Return the cube object for any plane xy, yz, xz"""
try:
# argument of format channel/service/resolution/cutoutargs
# cutoutargs can be window|filter/value,value/
m = re.match("(\w+)/(xy|yz|xz)/(\d+)/([\d+,/]+)?(.*)?$", webargs)
[channel, service, resolution, imageargs] = [i for i in m.groups()[:-1]]
imageargs = resolution + '/' + imageargs
extra_args = m.groups()[-1]
except Exception as e:
logger.error("Incorrect arguments for imgSlice {}. {}".format(webargs, e))
raise NDWSError("Incorrect arguments for imgSlice {}. {}".format(webargs, e))
try:
# Rewrite the imageargs to be a cutout
if service == 'xy':
m = re.match("(\d+/\d+,\d+/\d+,\d+/)(\d+)/(\d+)?[/]?$", imageargs)
if m.group(3) is None:
cutoutargs = '{}{},{}/'.format(m.group(1), m.group(2), int(m.group(2))+1)
else:
cutoutargs = '{}{},{}/{},{}/'.format(m.group(1), m.group(2), int(m.group(2))+1, m.group(3), int(m.group(3))+1)
elif service == 'xz':
m = re.match("(\d+/\d+,\d+/)(\d+)(/\d+,\d+)/(\d+)?[/]?", imageargs)
if m.group(4) is None:
cutoutargs = '{}{},{}{}/'.format(m.group(1), m.group(2), int(m.group(2))+1, m.group(3))
else:
cutoutargs = '{}{},{}{}/{},{}/'.format(m.group(1), m.group(2), int(m.group(2))+1, m.group(3), m.group(4), int(m.group(4))+1)
elif service == 'yz':
m = re.match("(\d+/)(\d+)(/\d+,\d+/\d+,\d+)/(\d+)?[/]?", imageargs)
if m.group(4) is None:
cutoutargs = '{}{},{}{}/'.format(m.group(1), m.group(2), int(m.group(2))+1, m.group(3))
else:
cutoutargs = '{}{},{}{}/{},{}/'.format(m.group(1), m.group(2), int(m.group(2))+1, m.group(3), m.group(4), int(m.group(4))+1)
else:
raise "No such image plane {}".format(service)
except Exception as e:
logger.error ("Illegal image arguments={}. Error={}".format(imageargs,e))
raise NDWSError ("Illegal image arguments={}. Error={}".format(imageargs,e))
cutoutargs = cutoutargs + extra_args
# Perform the cutout
ch = proj.getChannelObj(channel)
cb = cutout(cutoutargs, ch, proj, db)
# perform default window if not specified
if not re.search("window", extra_args) and (cb.data.dtype == np.uint16 or cb.data.dtype == np.float32):
cbnew = TimeCube8 ( )
cbnew.data = window ( cb.data, ch )
return cbnew
elif cb.data.dtype == np.uint8:
return cb
else:
return cb
def imgPNG (proj, webargs, cb):
"""Return a png object for any plane"""
try:
# argument of format channel/service/resolution/cutoutargs
# cutoutargs can be window|filter/value,value/
m = re.match("(\w+)/(xy|yz|xz)/(\d+)/([\d+,/]+)(.*)?$", webargs)
[channel, service, resolution, imageargs] = [i for i in m.groups()[:-1]]
except Exception as e:
logger.error("Incorrect arguments for imgSlice {}. {}".format(webargs, e))
raise NDWSError("Incorrect arguments for imgSlice {}. {}".format(webargs, e))
# window argument
result = re.search (r"/window/([\d\.]+),([\d\.]+)/", webargs)
if result != None:
window = [str(i) for i in result.groups()]
else:
window = None
if service == 'xy':
img = cb.xyImage(window=window)
elif service == 'yz':
img = cb.yzImage(proj.datasetcfg.scale[int(resolution)][service])
elif service == 'xz':
img = cb.xzImage(proj.datasetcfg.scale[int(resolution)][service])
fileobj = BytesIO( )
img.save ( fileobj, "PNG" )
fileobj.seek(0)
return fileobj.read()
#
# Read individual annotation image slices xy, xz, yz
#
def imgAnno ( service, chanargs, proj, db, rdb ):
"""Return a plane fileobj.read() for a single objects"""
[channel, service, annoidstr, imageargs] = chanargs.split('/', 3)
ch = NDChannel.fromName(proj, channel)
annoids = [int(x) for x in annoidstr.split(',')]
# retrieve the annotation
if len(annoids) == 1:
anno = rdb.getAnnotation ( ch, annoids[0] )
if anno == None:
logger.error("No annotation found at identifier = {}".format(annoids[0]))
raise NDWSError ("No annotation found at identifier = {}".format(annoids[0]))
else:
iscompound = True if anno.__class__ in [AnnNeuron] else False;
else:
iscompound = False
try:
# Rewrite the imageargs to be a cutout
if service == 'xy':
m = re.match("(\d+/\d+,\d+/\d+,\d+/)(\d+)/", imageargs)
cutoutargs = '{}{},{}/'.format(m.group(1),m.group(2),int(m.group(2))+1)
elif service == 'xz':
m = re.match("(\d+/\d+,\d+/)(\d+)(/\d+,\d+)/", imageargs)
cutoutargs = '{}{},{}{}/'.format(m.group(1),m.group(2),int(m.group(2))+1,m.group(3))
elif service == 'yz':
m = re.compile("(\d+/)(\d+)(/\d+,\d+/\d+,\d+)/", imageargs)
cutoutargs = '{}{},{}{}/'.format(m.group(1),m.group(2),int(m.group(2))+1,m.group(3))
else:
raise "No such image plane {}".format(service)
except Exception as e:
logger.error ("Illegal image arguments={}. Error={}".format(imageargs,e))
raise NDWSError ("Illegal image arguments={}. Error={}".format(imageargs,e))
# Perform argument processing
try:
args = restargs.BrainRestArgs ();
args.cutoutArgs ( cutoutargs, proj.datasetcfg )
except restargs.RESTArgsError as e:
logger.error("REST Arguments %s failed: {}".format(chanargs,e))
raise NDWSError(e.value)
# Extract the relevant values
corner = args.getCorner()
dim = args.getDim()
resolution = args.getResolution()
# determine if it is a compound type (NEURON) and get the list of relevant segments
if iscompound:
# remap the ids for a neuron
dataids = rdb.getSegments ( ch, annoids[0] )
cb = db.annoCutout ( ch, dataids, timestamp, resolution, corner, dim, annoids[0] )
else:
# no remap when not a neuron
dataids = annoids
cb = db.annoCutout ( ch, dataids, timestamp, resolution, corner, dim, None)
# reshape to 2-d
if service == 'xy':
img = cb.xyImage ( )
elif service == 'xz':
img = cb.xzImage ( proj.datasetcfg.zscale[resolution] )
elif service == 'yz':
img = cb.yzImage ( proj.datasetcfg.zscale[resolution] )
fileobj = BytesIO( )
img.save ( fileobj, "PNG" )
fileobj.seek(0)
return fileobj.read()
def annId ( chanargs, proj, db ):
"""Return the annotation identifier of a voxel"""
# RBTODO timestamp should be in args 0 for now.
timestamp = 0
[channel, service, imageargs] = chanargs.split('/',2)
ch = NDChannel.fromName(proj, channel)
# Perform argument processing
(resolution, voxel) = restargs.voxel(imageargs, proj.datasetcfg)
# Get the identifier
return db.getVoxel(ch, timestamp, resolution, voxel)
def listIds ( chanargs, proj, db ):
"""Return the list of annotation identifiers in a region"""
[channel, service, imageargs] = chanargs.split('/', 2)
ch = NDChannel.fromName(proj,channel)
# Perform argument processing
try:
args = restargs.BrainRestArgs ();
args.cutoutArgs ( imageargs, proj.datasetcfg )
except restargs.RESTArgsError as e:
logger.error("REST Arguments {} failed: {}".format(imageargs,e))
raise NDWSError("REST Arguments {} failed: {}".format(imageargs,e))
# Extract the relevant values
corner = args.getCorner()
dim = args.getDim()
resolution = args.getResolution()
cb = db.cutout ( ch, corner, dim, resolution )
ids = np.unique(cb.data)
idstr=''.join([repr(id)+', ' for id in ids])
idstr1 = idstr.lstrip('0,')
return idstr1.rstrip(', ')
def selectService ( service, webargs, proj, db ):
"""Select the service and pass on the arguments to the appropiate function."""
if service in ['xy','yz','xz']:
return imgPNG(proj, webargs, imgSlice (webargs, proj, db))
elif service == 'hdf5':
return HDF5 ( webargs, proj, db )
elif service == 'tiff':
return tiff3d ( webargs, proj, db )
elif service in ['npz']:
return numpyZip ( webargs, proj, db )
elif service in ['blosc']:
return BLOSC ( webargs, proj, db )
elif service in ['raw']:
return RAW ( webargs, proj, db )
elif service in ['jpeg']:
return JPEG ( webargs, proj, db )
elif service in ['zip']:
return binZip ( webargs, proj, db )
elif service == 'id':
return annId ( webargs, proj, db )
elif service == 'ids':
return listIds ( webargs, proj, db )
elif service == 'diff':
return timeDiff ( webargs, proj, db )
elif service in ['xzanno', 'yzanno', 'xyanno']:
return imgAnno ( service.strip('anno'), webargs, proj, db )
else:
logger.error("An illegal Web GET service was requested {}. Args {}".format(service, webargs))
raise NDWSError("An illegal Web GET service was requested {}. Args {}".format(service, webargs))
def selectPost ( webargs, proj, db, postdata ):
"""Identify the service and pass on the arguments to the appropiate service."""
[channel, service, postargs] = webargs.split('/', 2)
# Create a list of channels from the comma separated argument
channel_list = channel.split(',')
# Retry in case the databse is busy
tries = 0
done = False
# Process the arguments
try:
args = restargs.BrainRestArgs ();
args.cutoutArgs ( postargs, proj.datasetcfg )
except restargs.RESTArgsError as e:
logger.error( "REST Arguments {} failed: {}".format(postargs,e) )
raise NDWSError(e)
corner = args.getCorner()
dimension = args.getDim()
resolution = args.getResolution()
timerange = args.getTimeRange()
conflictopt = restargs.conflictOption ( "" )
while not done and tries < 5:
try:
# if it's a 3d tiff treat differently. No cutout args.
if service == 'tiff':
return postTiff3d ( channel, postargs, proj, db, postdata )
elif service == 'blaze':
for channel_name in channel_list:
ch = proj.getChannelObj(channel_name)
db.writeBlazeCuboid(ch, corner, resolution, postdata, timerange=timerange)
elif service == 'hdf5':
# Get the HDF5 file.
with closing (tempfile.NamedTemporaryFile ( )) as tmpfile:
tmpfile.write ( postdata )
tmpfile.seek(0)
h5f = h5py.File ( tmpfile.name, driver='core', backing_store=False )
for channel_name in channel_list:
ch = proj.getChannelObj(channel_name)
chgrp = h5f.get(ch.channel_name)
voxarray = chgrp['CUTOUT'].value
h5_datatype = h5f.get(ch.channel_name)['DATATYPE'].value[0]
h5_channeltype = h5f.get(ch.channel_name)['CHANNELTYPE'].value[0]
# Checking the datatype of the voxarray
if voxarray.dtype != ND_dtypetonp[ch.channel_datatype]:
logger.error("Channel datatype {} in the HDF5 file does not match with the {} in the database.".format(h5_datatype, ch.channel_datatype))
raise NDWSError("Channel datatype {} in the HDF5 file does not match with the {} in the database.".format(h5_datatype, ch.channel_datatype))
# Don't write to readonly channels
if ch.readonly == READONLY_TRUE:
logger.error("Attempt to write to read only channel {} in project. Web Args:{}".format(ch.channel_name, proj.project_name, webargs))
raise NDWSError("Attempt to write to read only channel {} in project. Web Args: {}".format(ch.channel_name, proj.project_name, webargs))
# reshape the data to 4d if no timerange
if timerange == None:
voxarray = voxarray.reshape((1,voxarray.shape[0],voxarray.shape[1],voxarray.shape[2]))
efftimerange = ch.default_time_range
else:
efftimerange = timerange
# checking if the dimension for x,y,z,t(optional) are correct
# this is different then the one for blosc/numpy because channels are packed separately
if voxarray.shape[::-1] != tuple(dimension + [efftimerange[1]-efftimerange[0]]):
logger.error("The data has mismatched dimensions {} compared to the arguments {}".format(voxarray.shape[1:], dimension))
raise NDWSError("The data has mismatched dimensions {} compared to the arguments {}".format(voxarray.shape[1:], dimension))
if ch.channel_type in ANNOTATION_CHANNELS:
db.annotateDense ( ch, efftimerange[0], corner, resolution, voxarray, conflictopt)
else:
db.writeCuboid (ch, corner, resolution, voxarray, timerange=efftimerange)
h5f.flush()
h5f.close()
# other services take cutout args
elif service in ['npz', 'blosc']:
# get the data out of the compressed blob
if service == 'npz':
rawdata = zlib.decompress ( postdata )
fileobj = BytesIO( rawdata )
voxarray = np.load ( fileobj )
elif service == 'blosc':
voxarray = blosc.unpack_array(postdata)
if voxarray.shape[0] != len(channel_list):
logger.error("The data has some missing channels")
raise NDWSError("The data has some missing channels")
# checking if the dimension for x,y,z,t(optional) are correct
# reshape the data to 4d if no timerange
if timerange==None:
voxarray = voxarray.reshape((voxarray.shape[0],1,voxarray.shape[1],voxarray.shape[2],voxarray.shape[3]))
efftimerange=[0,1]
else:
efftimerange=timerange
if voxarray.shape[1:][::-1] != tuple(dimension + [efftimerange[1]-efftimerange[0]]):
logger.error("The data has mismatched dimensions {} compared to the arguments {}".format(voxarray.shape[1:], dimension))
raise NDWSError("The data has mismatched dimensions {} compared to the arguments {}".format(voxarray.shape[1:], dimension))
for idx, channel_name in enumerate(channel_list):
ch = proj.getChannelObj(channel_name)
# Don't write to readonly channels
if ch.readonly == READONLY_TRUE:
logger.error("Attempt to write to read only channel {} in project. Web Args:{}".format(ch.channel_name, proj.project_name, webargs))
raise NDWSError("Attempt to write to read only channel {} in project. Web Args: {}".format(ch.channel_name, proj.project_name, webargs))
if not voxarray.dtype == ND_dtypetonp[ch.channel_datatype]:
logger.error("Wrong datatype in POST")
raise NDWSError("Wrong datatype in POST")
if ch.channel_type in ANNOTATION_CHANNELS:
db.annotateDense(ch, efftimerange[0], corner, resolution, voxarray[idx,:], conflictopt )
else:
db.writeCuboid(ch, corner, resolution, voxarray[idx,:], efftimerange)
else:
logger.error("An illegal Web POST service was requested: {}. Args {}".format(service, webargs))
raise NDWSError("An illegal Web POST service was requested: {}. Args {}".format(service, webargs))
done = True
# rollback if you catch an error
except MySQLdb.OperationalError as e:
logger.warning("Transaction did not complete. {}".format(e))
tries += 1
continue
except MySQLdb.Error as e:
logger.error("POST transaction rollback. {}".format(e))
raise NDWSError("POST transaction rollback. {}".format(e))
except Exception as e:
logger.exception("POST transaction rollback. {}".format(e))
raise NDWSError("POST transaction rollback. {}".format(e))
def getCutout ( webargs ):
"""Interface to the cutout service for annotations.Load the annotation project and invoke the appropriate dataset."""
#[ token, sym, rangeargs ] = webargs.partition ('/')
[token, webargs] = webargs.split('/', 1)
[channel, service, chanargs] = webargs.split('/', 2)
# get the project
proj = NDProject.fromTokenName(token)
# and the database and then call the db function
with closing (SpatialDB(proj)) as db:
return selectService ( service, webargs, proj, db )
def putCutout ( webargs, postdata ):
"""Interface to the write cutout data. Load the annotation project and invoke the appropriate dataset"""
[ token, rangeargs ] = webargs.split('/',1)
# get the project
proj = NDProject.fromTokenName(token)
# and the database and then call the db function
with closing (SpatialDB(proj)) as db:
return selectPost ( rangeargs, proj, db, postdata )
################# RAMON interfaces #######################
"""An enumeration for options processing in getAnnotation"""
AR_NODATA = 0
AR_VOXELS = 1
AR_CUTOUT = 2
AR_TIGHTCUTOUT = 3
AR_BOUNDINGBOX = 4
AR_CUBOIDS = 5
def getAnnoDictById ( ch, annoid, proj, rdb ):
"""Retrieve the annotation and return it as a Python dictionary"""
# retrieve the annotation
anno = rdb.getAnnotation ( ch, annoid )
if anno == None:
logger.error("No annotation found at identifier = %s" % (annoid))
raise NDWSError ("No annotation found at identifier = %s" % (annoid))
# the json interface returns anno_id -> dictionary containing annotation info
tmpdict = {
annoid: anno.toDict()
}
# return dictionary
return tmpdict
def getAnnoById ( ch, annoid, h5f, proj, rdb, db, dataoption, timestamp, resolution=None, corner=None, dim=None ):
"""Retrieve the annotation and put it in the HDF5 file."""
# retrieve the annotation
anno = rdb.getAnnotation ( ch, annoid )
if anno == None:
logger.error("No annotation found at identifier = %s" % (annoid))
raise NDWSError ("No annotation found at identifier = %s" % (annoid))
# create the HDF5 object
h5anno = h5ann.AnnotationtoH5 ( anno, h5f )
# only return data for annotation types that have data
if anno.__class__ in [AnnSeed] and dataoption != AR_NODATA:
logger.error("No data associated with annotation type %s" % ( anno.__class__))
raise NDWSError ("No data associated with annotation type %s" % ( anno.__class__))
# determine if it is a compound type (NEURON) and get the list of relevant segments
if anno.__class__ in [AnnNeuron] and dataoption != AR_NODATA:
dataids = rdb.getSegments ( ch, annoid )
else:
dataids = [anno.annid]
# get the voxel data if requested
if dataoption == AR_VOXELS:
# RBTODO Need to make voxels zoom
allvoxels = []
# add voxels for all of the ids
for dataid in dataids:
voxlist = db.getLocations(ch, dataid, timestamp, resolution )
if len(voxlist) != 0:
allvoxels = allvoxels + voxlist
allvoxels = [ el for el in set ( [ tuple(t) for t in allvoxels ] ) ]
h5anno.addVoxels ( resolution, allvoxels )
# support list of IDs to filter cutout
elif dataoption == AR_CUTOUT:
# cutout the data with the and remap for neurons.
if anno.__class__ in [AnnNeuron] and dataoption != AR_NODATA:
cb = db.annoCutout(ch, dataids, timestamp, resolution, corner, dim, annoid )
else:
# don't need to remap single annotations
cb = db.annoCutout(ch, dataids, timestamp, resolution, corner, dim, None )
# again an abstraction problem with corner. return the corner to cutout arguments space
offset = proj.datasetcfg.get_offset(resolution)
retcorner = [corner[0]+offset[0], corner[1]+offset[1], corner[2]+offset[2]]
h5anno.addCutout ( resolution, retcorner, cb.data.reshape(cb.data.shape[1:]))
elif dataoption == AR_TIGHTCUTOUT: