forked from SBC-Utrecht/PyTom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpuStructures.py
More file actions
executable file
·1701 lines (1353 loc) · 74.2 KB
/
gpuStructures.py
File metadata and controls
executable file
·1701 lines (1353 loc) · 74.2 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
import threading
import importlib
import cupy as cp
from pytom.agnostic.io import read, write
from pytom.gpu.initialize import device, xp
class TemplateMatchingPlan():
def __init__(self, volume, template, mask, wedge, get_fft_plan, deviceid):
import pytom.voltools as vt
self.volume = cp.asarray(volume, dtype=cp.float32, order='C')
self.mask = cp.asarray(mask, dtype=cp.float32, order='C')
self.mask_texture = vt.StaticVolume(self.mask, interpolation='linear', device=f'gpu:{deviceid}')
self.maskPadded = cp.zeros_like(self.volume).astype(cp.float32)
self.template = cp.asarray(template, dtype=cp.float32, order='C')
self.template_texture = vt.StaticVolume(self.template, interpolation='filt_bspline', device=f'gpu:{deviceid}')
self.templatePadded = cp.zeros_like(self.volume)
# wedge for the template
self.wedge = cp.asarray(wedge, order='C', dtype=cp.float32)
# initialize result volumes
self.ccc_map = cp.zeros_like(self.volume)
self.scores = cp.ones_like(self.volume)*-1000
self.angles = cp.ones_like(self.volume)*-1000
# weight of the mask
self.p = self.mask.sum()
# assign fft plan
self.volume_fft2 = cp.fft.fftn(self.volume)
self.fftplan = get_fft_plan(self.volume.astype(cp.complex64))
cp.cuda.stream.get_current_stream().synchronize()
class TemplateMatchingGPU(threading.Thread):
def __init__(self, jobid, deviceid, input):
threading.Thread.__init__(self)
cp.cuda.Device(deviceid).use()
from cupy import sqrt, float32
from cupy.fft import fftshift, rfftn, irfftn, ifftn, fftn
from cupyx.scipy.ndimage import map_coordinates
try:
from cupyx.scipy.fftpack.fft import get_fft_plan
from cupyx.scipy.fftpack.fft import fftn as fftnP
from cupyx.scipy.fftpack.fft import ifftn as ifftnP
except ModuleNotFoundError: # TODO go to 'from cupyx.scipy.fftpack import ...' once fully moved to cupy > 8.3
from cupyx.scipy.fftpack import get_fft_plan
from cupyx.scipy.fftpack import fftn as fftnP
from cupyx.scipy.fftpack import ifftn as ifftnP
self.fftnP = fftnP
self.ifftnP = ifftnP
self.map_coordinates = map_coordinates
self.Device = cp.cuda.Device
self.jobid = jobid
self.deviceid = deviceid
self.active = True
self.completed = False
self.input = input
self.mask_is_spherical = input[5] # whether mask is spherical
self.angle_list = input[4]
self.fftn = fftn
self.ifftn = ifftn
self.fftshift = fftshift
self.rfftn = rfftn
self.irfftn = irfftn
self.sqrt = sqrt
self.float32 = float32
self.update_scores_angles = cp.RawKernel(r"""
extern "C" __global__ void update_scores_angles(float *scores, float *angles, float *ccc_map, float angleId, int num_elements, int dimx)
{
const int idx = (threadIdx.x + blockIdx.x*dimx)*dimx;
for (int i=0; i < dimx; i++) {
if (idx +i < num_elements){
if (scores[idx+i] < ccc_map[idx+i]) {
scores[idx+i] = ccc_map[idx+i];
angles[idx+i] = angleId;
}
}
}
__syncthreads();
}
""", 'update_scores_angles')
self.updateResFromIdx = cp.ElementwiseKernel(
'float32 scores, float32 angles, float32 ccc_map, float32 angleId',
'float32 out, float32 out2',
'if (scores < ccc_map) {out = ccc_map; out2 = angleId;}',
'updateResFromIdx')
self.plan = TemplateMatchingPlan(input[0], input[1], input[2], input[3],
get_fft_plan, deviceid)
print("Initialized job_{:03d} on device {:d}".format(self.jobid, self.deviceid))
def run(self):
print("RUN")
self.Device(self.deviceid).use()
self.template_matching_gpu()
self.completed = True
self.active = False
def template_matching_gpu(self):
sx, sy, sz = self.plan.template.shape
SX, SY, SZ = self.plan.templatePadded.shape
CX, CY, CZ = SX // 2, SY // 2, SZ // 2
cx, cy, cz = sx // 2, sy // 2, sz // 2
mx, my, mz = sx % 2, sy % 2, sz % 2
# rotation center needs to be set, voltools uses (s - 1) / 2 by default, but pytom_volume s // 2 + s % 2
rotation_center = (cx + mx, cy + my, cz + mz)
if self.mask_is_spherical: # then we only need to calculate std volume once
self.plan.maskPadded[CX - cx:CX + cx + mx, CY - cy:CY + cy + my, CZ - cz:CZ + cz + mz] = \
self.plan.mask
std_v = self.calc_std_v(self.plan.volume, self.plan.maskPadded, self.plan.p)
for angleId, angles in enumerate(self.angle_list):
if not self.mask_is_spherical:
self.plan.mask_texture.transform(rotation=(angles[0], angles[2], angles[1]), rotation_order='rzxz',
output=self.plan.mask, center=rotation_center)
self.plan.maskPadded[CX - cx:CX + cx + mx, CY - cy:CY + cy + my, CZ - cz:CZ + cz + mz] = \
self.plan.mask
# std volume needs to be recalculated for every rotation of the mask, expensive step
std_v = self.calc_std_v(self.plan.volume, self.plan.maskPadded, self.plan.p)
# Rotate template
self.plan.template_texture.transform(rotation=(angles[0], angles[2], angles[1]), rotation_order='rzxz',
output=self.plan.template, center=rotation_center)
# Add wedge to the template after rotating
self.plan.template = self.irfftn(self.rfftn(self.plan.template) * self.plan.wedge,
s=self.plan.template.shape).real
# Normalize template
meanT = self.meanUnderMask(self.plan.template, self.plan.mask, p=self.plan.p)
stdT = self.stdUnderMask(self.plan.template, self.plan.mask, meanT, p=self.plan.p)
self.plan.template = ((self.plan.template - meanT) / stdT) * self.plan.mask
# Paste in center
self.plan.templatePadded[CX-cx:CX+cx+mx, CY-cy:CY+cy+my, CZ-cz:CZ+cz+mz] = self.plan.template
# Cross-correlate and normalize by std_v
self.plan.ccc_map = self.normalized_cross_correlation(self.plan.volume_fft2, self.plan.templatePadded,
std_v, self.plan.p, fft_plan=self.plan.fftplan)
# Update the scores and angles
self.updateResFromIdx(self.plan.scores, self.plan.angles, self.plan.ccc_map,
angleId, self.plan.scores, self.plan.angles)
def is_alive(self):
"""
whether process is running
"""
return self.active
def calc_std_v(self, volume, padded_mask, p):
"""
std convolution of volume and mask
"""
std_v = self.meanVolUnderMask2(volume**2, padded_mask, p) - self.meanVolUnderMask2(volume, padded_mask, p)**2
std_v[std_v <= self.float32(1e-09)] = 1
return self.sqrt(std_v)
def meanVolUnderMask2(self, volume, mask, p):
"""
mean convolution of volume and mask
"""
return (self.fftshift(self.ifftn(self.fftn(volume) * self.fftn(mask).conj())) / p).real
def meanUnderMask(self, volume, mask, p):
"""
mean value of the template under the mask
"""
return (volume * mask).sum() / p
def stdUnderMask(self, volume, mask, mean, p):
"""
standard deviation of the template under the mask
"""
return self.sqrt(self.meanUnderMask(volume**2, mask, p) - mean**2)
def normalized_cross_correlation(self, volume_fft, template, norm, p, fft_plan=None):
"""
fast local correlation function between volume and template, norm is the standard deviation at each point in
the volume in the masked area
"""
return self.fftshift(self.ifftnP(volume_fft * self.fftnP(template, plan=fft_plan).conj(),
plan=fft_plan)).real / (p * norm)
class GLocalAlignmentPlan():
def __init__(self, particle, reference, mask, wedge, maskIsSphere=True, cp=xp, device='cpu',
interpolation='linear', taper=0, binning=1, max_shift=None):
id = int(device.split(":")[1])
cp.cuda.Device(id).use()
self.cp = cp
self.device = device
from pytom.voltools import StaticVolume
from pytom.agnostic.tools import taper_edges
from pytom.agnostic.transform import fourier_reduced2full
from pytom.agnostic.io import read_size, write
from pytom.agnostic.transform import resize
from pytom.gpu.kernels import argmax_text, meanStdv_text
try:
from cupyx.scipy.fftpack.fft import get_fft_plan
from cupyx.scipy.fftpack.fft import fftn as fftnP
from cupyx.scipy.fftpack.fft import ifftn as ifftnP
except ModuleNotFoundError: # TODO go to 'from cupyx.scipy.fftpack import ...' once fully moved to cupy > 8.3
from cupyx.scipy.fftpack import get_fft_plan
from cupyx.scipy.fftpack import fftn as fftnP
from cupyx.scipy.fftpack import ifftn as ifftnP
# particle shape and binned shape
assert isinstance(binning, int) and binning >= 1, "invalid binning type for glocal plan"
self.binning = binning
shape = read_size(particle.getFilename())
self.shape = tuple(cp.asnumpy((cp.around(cp.array(shape) * (1 / self.binning), 0)).astype(cp.int))) if \
self.binning > 1 else shape
# Allocate volume and volume_fft
self.volume = cp.zeros(self.shape, dtype=cp.float32)
self.volume_fft = cp.zeros_like(self.volume, dtype=cp.complex64)
# Allocate planned-fftn-related functions and structure
self.ifftnP = ifftnP
self.fftnP = fftnP
self.fftplan = get_fft_plan(self.volume.astype(cp.complex64))
# Allocate mask-related objects
mask = mask.getVolume().get()
self.mask = resize(cp.array(mask, dtype=cp.float32), 1 / self.binning)
self.rotatedMask = self.mask.copy()
self.maskTex = StaticVolume(self.mask, device=device, interpolation=interpolation)
self.mask_fft = self.fftnP(self.rotatedMask.astype(cp.complex64),plan=self.fftplan)
self.p = self.rotatedMask.sum()
# Allocate wedge-related objects
self.wedge = wedge
if wedge._type != 'Wedge3dCTF':
self.wedge_angles = wedge.getWedgeAngle()
else:
self.wedge_angles = None
wedgePart = wedge.returnWedgeVolume(*self.volume.shape, humanUnderstandable=True).get()
self.rotatedWedge = cp.array(wedgePart, dtype=cp.float32)
self.wedgePart = cp.fft.fftshift(wedgePart).astype(cp.float32)
self.wedgeTex = StaticVolume(self.rotatedWedge.copy(), device=self.device, interpolation=interpolation)
del wedgePart
# Allocate reference related objects
reference = resize(cp.array((reference.getVolume()).get(), dtype=cp.float32),
1 / self.binning) * self.mask
self.referenceTex = StaticVolume(reference, device=device, interpolation=interpolation)
self.rotatedRef = reference.copy()
self.simulatedVolume = cp.zeros_like(self.volume, dtype=cp.float32)
del reference
# Allocate taper-related arrays
dummy, taperMask = taper_edges(self.volume, self.volume.shape[0]/10)
self.taperMask = cp.array(taperMask.get(), dtype=cp.float32)
self.masked_taper = self.rotatedMask * self.taperMask
del dummy, taperMask
# Allocate required volumes
self.std_v = cp.zeros_like(self.volume, dtype=cp.float32)
self.ccc_map = cp.zeros_like(self.volume, dtype=cp.float32)
self.sumParticles = cp.zeros_like(self.volume, dtype=cp.float32)
self.sumWeights = cp.zeros_like(self.wedgePart[:,:,:self.volume.shape[2]//2+1], dtype=cp.float32)
# Allocate arrays used for normalisation of reference
self.num_threads = 1024
self.nblocks = int(self.cp.ceil(self.simulatedVolume.size / self.num_threads / 2))
self.fast_sum_mean = self.cp.zeros((4 * self.nblocks * 2), dtype=self.cp.float32)
self.fast_sum_stdv = self.cp.zeros((4 * self.nblocks * 2), dtype=self.cp.float32)
# Allocate arrays used in subPixelMas3D
self.subvolume_size = 8 # default 8 is enough for spline interpolation
self.subvolume_start = self.subvolume_size // 2
# the border should always be larger than the subvolume to be cropped, makes sure we can interpolate
if max_shift is None:
self.ignore_border = self.subvolume_start + 1
else:
self.ignore_border = max(min(self.shape) // 2 - max_shift, self.subvolume_start + 1)
self.scale_ratio = 1. / 10. # same as cpu scaling
self.zoom_cube_size = self.subvolume_size * 10
self.zoomed = self.cp.zeros((self.zoom_cube_size, ) * 3, dtype=self.cp.float32)
self.temp_sub = self.cp.zeros_like(self.zoomed, dtype=self.cp.float32)
# previous subpixel values
# b = max(0, int(self.volume.shape[0] // 2 - 4 / 0.1))
# zx, zy, zz = self.volume.shape
# croppedForZoom = self.volume[b:zx - b, b:zy - b, b:zz - b]
# nblocks = int(self.cp.ceil(croppedForZoom.size / 1024 / 2))
# self.zoomed = self.cp.zeros_like(croppedForZoom, dtype=cp.float32)
# self.fast_sum = self.cp.zeros((nblocks), dtype=cp.float32)
# self.max_id = self.cp.zeros((nblocks), dtype=cp.int32)
# del croppedForZoom
# Kernels
self.normalize = cp.ElementwiseKernel('T ref, T mask, raw T mean, raw T std_v ', 'T z', 'z = ((ref - mean[i*0]) / std_v[i*0]) * mask', 'norm2')
self.sumMeanStdv = cp.RawKernel(meanStdv_text, 'sumMeanStdv')
self.argmax = self.cp.RawKernel(argmax_text, 'argmax')
print(f'init completed on: {device}')
def clean(self):
del self.masked_taper
del self.fftplan
del self.ifftnP
del self.fftnP
del self.cp
del self.std_v
del self.ccc_map
del self.volume_fft
del self.volume
del self.wedge
del self.wedgePart
del self.wedgeTex
del self.rotatedWedge
del self.wedge_angles
del self.referenceTex
del self.rotatedRef
del self.simulatedVolume
del self.mask
del self.maskTex
del self.rotatedMask
del self.mask_fft
del self.normalize
del self.sumMeanStdv
del self.argmax
# del self.max_id
# del self.fast_sum
del self.zoomed
del self.temp_sub
del self.fast_sum_mean
del self.fast_sum_stdv
del self.nblocks
del self.num_threads
def normalizeVolume(self):
self.fast_sum_stdv *= 0
self.fast_sum_mean *= 0
self.sumMeanStdv((self.nblocks, 1,), (self.num_threads, 1, 1), (self.simulatedVolume, self.mask, self.fast_sum_mean, self.fast_sum_stdv, self.simulatedVolume.size),
shared_mem=8 * self.num_threads)
meanT = self.fast_sum_mean.sum() / self.p
stdT = self.cp.sqrt(self.fast_sum_stdv.sum()/self.p - meanT*meanT)
self.simulatedVolume = ((self.simulatedVolume - meanT)/stdT) * self.mask
def cross_correlation(self):
self.simulatedVolume = self.fftnP(self.simulatedVolume.astype(self.cp.complex64), plan=self.fftplan)
self.ccc_map = ( self.cp.fft.ifftshift(self.ifftnP(self.volume_fft * self.simulatedVolume.conj(), plan=self.fftplan))).real
self.ccc_map *= self.std_v
def wedgeRotatedRef(self):
self.simulatedVolume = self.ifftnP(self.fftnP(self.rotatedRef.astype(self.cp.complex64), plan=self.fftplan) * self.wedgePart,
plan=self.fftplan).real.astype(self.cp.float32) * self.masked_taper
def wedgeParticle(self):
self.volume_fft = self.fftnP(self.volume.astype(self.cp.complex64),plan=self.fftplan) * self.wedgePart
self.volume_fft = self.volume_fft.astype(self.cp.complex64)
def subPixelMaxSpline(self):
"""
@param ignore_border: number of pixels to ignore for the border
@type ignore_border: int
@param k: number of types the cropped volume is upsampled
@type k: int
@return: interpolated correlation value and shift
@rtype: list of peak value and shifts
"""
from pytom.agnostic.tools import paste_in_center
from pytom.voltools import transform
# needs these value to run
# self.ignore_border ; number of pixel to ignore for border, cannot be less than subvolume size
# self.subvolume_size ; size of subvolume
# self.subvolume_start ; center of subvolume self.subvolume_size // 2
# self.scale_ratio ; ratio to scale should be integer
# self.zoom_cube_size ; sube size of zoom is self.subvolume_size * self.scale_ratio
# self.zoomed ; zoomed allocated box of shape (zoom_cube_size,) * 3
# crop volume with the border
ox, oy, oz = self.ccc_map.shape
cropped_volume = self.ccc_map[self.ignore_border:ox - self.ignore_border,
self.ignore_border:oy - self.ignore_border,
self.ignore_border:oz - self.ignore_border].astype(self.cp.float32)
# get coordinates, but correct for cropping of the border
peak = [s + self.ignore_border for s in self.cp.unravel_index(cropped_volume.argmax(), cropped_volume.shape)]
subvolume = self.ccc_map[peak[0] - self.subvolume_start: peak[0] - self.subvolume_start + self.subvolume_size,
peak[1] - self.subvolume_start: peak[1] - self.subvolume_start + self.subvolume_size,
peak[2] - self.subvolume_start: peak[2] - self.subvolume_start + self.subvolume_size]
# scale the subvolume to the allocated zoomed subvolume
self.temp_sub *= 0
self.zoomed *= 0
self.temp_sub = paste_in_center(subvolume, self.temp_sub)
transform(self.temp_sub, scale=(self.scale_ratio, self.scale_ratio, self.scale_ratio),
interpolation='bspline', output=self.zoomed, device=self.device,
center=tuple([s // 2 for s in self.zoomed.shape]))
# get the argmax and max
zoom_peak = self.cp.unravel_index(self.zoomed.argmax(), self.zoomed.shape)
peak_value = self.zoomed[zoom_peak[0], zoom_peak[1], zoom_peak[2]]
# get the interpolated peak
interpolated_peak = [interp * self.scale_ratio -
self.subvolume_start + orig for orig, interp in zip(peak, zoom_peak)]
# get the shift
peak_shift = [ip - s // 2 for ip, s in zip(interpolated_peak, self.ccc_map.shape)]
# get the shift without binning
peak_shift = [ip*self.binning for ip in peak_shift]
# compared to cpu there is always a shift of 2 here... likely goes wrong before this function
# print([ip - s // 2 for ip, s in zip(peak, self.ccc_map.shape)])
# print(peak_shift)
# return as list
return peak_value, peak_shift
def max_index(self, volume, num_threads=1024):
nblocks = int(self.cp.ceil(volume.size / num_threads / 2))
fast_sum = -1000000 * self.cp.ones((nblocks), dtype=self.cp.float32)
max_id = self.cp.zeros((nblocks), dtype=self.cp.int32)
self.argmax((nblocks, 1,), (num_threads, 1, 1), (volume, fast_sum, max_id, volume.size),
shared_mem=16 * num_threads)
mm = min(max_id[fast_sum.argmax()], volume.size - 1)
indices = self.cp.unravel_index(mm, volume.shape)
return indices
def calc_std_v(self):
meanV = (self.cp.fft.fftshift(self.ifftnP(self.volume_fft * self.cp.conj(self.mask_fft), plan=self.fftplan))/self.p).real
self.std_v = 1 / (self.stdVolUnderMaskPlanned(self.volume, meanV) * self.p)
del meanV
def meanVolUnderMaskPlanned(self, volume):
"""
meanUnderMask: calculate the mean volume under the given mask (Both should have the same size)
@param volume: input volume
@type volume: L{numpy.ndarray} L{cupy.ndarray}
@param mask: mask
@type mask: L{numpy.ndarray} L{cupy.ndarray}
@return: the calculated mean volume under mask
@rtype: L{numpy.ndarray} L{cupy.ndarray}
@author: Gijs van der Schot
"""
volume_fft = self.fftnP(volume.astype(self.cp.complex64), plan=self.fftplan)
mask_fft = self.fftnP(self.rotatedMask.astype(self.cp.complex64), plan=self.fftplan)
res = self.cp.fft.fftshift(self.ifftnP(volume_fft * self.cp.conj(mask_fft), plan=self.fftplan)) / self.p
return res.real
def stdVolUnderMaskPlanned(self, volume, meanV):
"""
stdUnderMask: calculate the std volume under the given mask
@param volume: input volume
@type volume: L{numpy.ndarray} L{cupy.ndarray}
@param mask: mask
@type mask: L{numpy.ndarray} L{cupy.ndarray}
@param p: non zero value numbers in the mask
@type p: L{int}
@param meanV: mean volume under mask, which should already been caculated
@type meanV: L{numpy.ndarray} L{cupy.ndarray}
@return: the calculated std volume under mask
@rtype: L{numpy.ndarray} L{cupy.ndarray}
@author: GvdS
"""
meanV2 = meanV * meanV
vol2 = volume * volume
var = self.meanVolUnderMaskPlanned(vol2) - meanV2
var[var < 1E-09] = 1
return self.cp.sqrt(var)
def addParticleAndWedgeToSum(self, particle, bestPeak, centerCoordinates, rotation_order='rzxz'):
from pytom.voltools import transform
bestRotation = [-1 * bestPeak.getRotation()[1], -1 * bestPeak.getRotation()[2], -1 * bestPeak.getRotation()[0]]
bestShift = list((self.cp.array(bestPeak.getShift().toVector()) * -1).get())
# Add rotated particle to sum
self.rotatedRef *= 0
transform(particle, rotation=bestRotation, translation=bestShift, output=self.rotatedRef,
rotation_order=rotation_order, device=self.device, interpolation='filt_bspline')
self.sumParticles += self.rotatedRef
# Add rotated wedge to sum
self.rotatedWedge *= 0
self.wedgeTex.transform(rotation=bestRotation, center=centerCoordinates, rotation_order=rotation_order,
output=self.rotatedWedge)
self.sumWeights += self.cp.fft.fftshift(self.rotatedWedge)[:,:,:self.rotatedWedge.shape[2]//2+1]
def updateWedge(self, wedge, interpolation='filt_bspline'):
from pytom.voltools import StaticVolume
if wedge._type == 'Wedge3dCTF':
self.wedge_angles = None
self.wedge = wedge
wedgePart = wedge.returnWedgeVolume(*self.volume.shape, humanUnderstandable=True).astype(
self.cp.float32).get()
self.rotatedWedge = self.cp.array(wedgePart, dtype=self.cp.float32)
self.wedgePart = self.cp.fft.fftshift(wedgePart)
self.wedgeTex = StaticVolume(self.rotatedWedge.copy(), device=self.device, interpolation=interpolation)
else:
wedge_angles = wedge.getWedgeAngle()
if type(wedge_angles) == float: wedge_angles = [wedge_angles, wedge_angles]
if type(self.wedge_angles) == float: self.wedge_angles = [self.wedge_angles, self.wedge_angles]
if wedge_angles[0] == self.wedge_angles[0] and wedge_angles[1] == self.wedge_angles[1]:
return
else:
self.wedge_angles = wedge_angles
self.wedge = wedge
wedgePart = wedge.returnWedgeVolume(*self.volume.shape,
humanUnderstandable=True).astype(self.cp.float32).get()
self.rotatedWedge = self.cp.array(wedgePart, dtype=self.cp.float32)
self.wedgePart = self.cp.fft.fftshift(wedgePart)
self.wedgeTex = StaticVolume(self.rotatedWedge.copy(), device=self.device,
interpolation=interpolation)
def rotate3d(data, phi=0, psi=0, the=0, center=None, order=1, output=None):
"""Rotate a 3D data using ZXZ convention (phi: z1, the: x, psi: z2).
@param data: data to be rotated.
@param phi: 1st rotate around Z axis, in degree.
@param psi: 3rd rotate around Z axis, in degree.
@param the: 2nd rotate around X axis, in degree.
@param center: rotation center.
@return: the data after rotation.
"""
from cupyx.scipy.ndimage import map_coordinates
import cupy as cp
# Figure out the rotation center
if center is None:
cx = data.shape[0] / 2
cy = data.shape[1] / 2
cz = data.shape[2] / 2
else:
assert len(center) == 3
(cx, cy, cz) = center
# Transfer the angle to Euclidean
phi = -float(phi) * cp.pi / 180.0
the = -float(the) * cp.pi / 180.0
psi = -float(psi) * cp.pi / 180.0
sin_alpha = cp.sin(phi)
cos_alpha = cp.cos(phi)
sin_beta = cp.sin(the)
cos_beta = cp.cos(the)
sin_gamma = cp.sin(psi)
cos_gamma = cp.cos(psi)
# Calculate inverse rotation matrix
Inv_R = cp.zeros((3, 3), dtype=cp.float32)
Inv_R[0][0] = cos_alpha * cos_gamma - cos_beta * sin_alpha * sin_gamma
Inv_R[0][1] = -cos_alpha * sin_gamma - cos_beta * sin_alpha * cos_gamma
Inv_R[0][2] = sin_beta * sin_alpha
Inv_R[1][0] = sin_alpha * cos_gamma + cos_beta * cos_alpha * sin_gamma
Inv_R[1][1] = -sin_alpha * sin_gamma + cos_beta * cos_alpha * cos_gamma
Inv_R[1][2] = -sin_beta * cos_alpha
Inv_R[2][0] = sin_beta * sin_gamma
Inv_R[2][1] = sin_beta * cos_gamma
Inv_R[2][2] = cos_beta
grid = cp.mgrid[-cx:data.shape[0]-cx, -cy:data.shape[1]-cy, -cz:data.shape[2]-cz]
temp = grid.reshape((3, grid.size // 3))
temp = cp.dot(Inv_R, temp)
grid = cp.reshape(temp, grid.shape)
grid[0] += cx
grid[1] += cy
grid[2] += cz
dataout = cp.zeros_like(data)
# Interpolation
dataout = map_coordinates(data, grid.reshape(len(grid), -1), order=order).reshape(grid.shape[1:])
return dataout
class GLocalAlignmentGPU(threading.Thread):
def __init__(self, jobid, deviceid, input):
threading.Thread.__init__(self)
import numpy as np
from pytom.agnostic.tools import paste_in_center
from pytom.agnostic.transform import rotate3d
from pytom_volume import rotateSpline as rotate
import cupy as cp
cp.cuda.Device(deviceid).use()
from cupy import sqrt, float32
from cupy.fft import fftshift, rfftn, irfftn, ifftn, fftn
import pytom.voltools as vt
from pytom.agnostic.io import write
from cupyx.scipy.ndimage import map_coordinates
try:
from cupyx.scipy.fftpack.fft import get_fft_plan
from cupyx.scipy.fftpack.fft import fftn as fftnP
from cupyx.scipy.fftpack.fft import ifftn as ifftnP
except ModuleNotFoundError: # TODO go to 'from cupyx.scipy.fftpack import ...' once fully moved to cupy > 8.3
from cupyx.scipy.fftpack import get_fft_plan
from cupyx.scipy.fftpack import fftn as fftnP
from cupyx.scipy.fftpack import ifftn as ifftnP
self.fftnP = fftnP
self.ifftnP = ifftnP
self.cp = cp
self.map_coordinates = map_coordinates
self.Device = cp.cuda.Device
self.jobid = jobid
self.deviceid = deviceid
self.active = True
self.input = input
self.fftn = fftn
self.ifftn = ifftn
self.fftshift = fftshift
self.rfftn = rfftn
self.irfftn = irfftn
self.sqrt = sqrt
self.float32 = float32
self.update_scores_angles = cp.RawKernel(r"""
extern "C" __global__ void update_scores_angles(float *scores, float *angles, float *ccc_map, float angleId, int num_elements, int dimx)
{
const int idx = (threadIdx.x + blockIdx.x*dimx)*dimx;
for (int i=0; i < dimx; i++) {
if (idx +i < num_elements){
if (scores[idx+i] < ccc_map[idx+i]) {
scores[idx+i] = ccc_map[idx+i];
angles[idx+i] = angleId;
}
}
}
__syncthreads();
}
""", 'update_scores_angles')
self.updateResFromIdx = cp.ElementwiseKernel(
'float32 scores, float32 angles, float32 ccc_map, float32 angleId',
'float32 out, float32 out2',
'if (scores < ccc_map) {out = ccc_map; out2 = angleId;}',
'updateResFromIdx')
self.plan = TemplateMatchingPlan(input[0], input[1], input[2], input[3], cp, vt, self.calc_std_v, self.pad, get_fft_plan, deviceid)
print("Initialized job_{:03d} on device {:d}".format(self.jobid, self.deviceid))
def run(self):
print("RUN")
if 1:
self.glocal_alignment_gpu(self.input[4], self.input[5])
self.completed = True
else:
self.completed = False
self.active = False
def glocal_alignment_gpu(self, angle_list, dims, isSphere=True, verbose=True):
self.Device(self.deviceid).use()
import pytom.voltools as vt
from pytom.agnostic.io import write
sx, sy, sz = self.plan.template.shape
cx, cy, cz = sx // 2, sy // 2, sz // 2
mx, my, mz = sx % 2, sy % 2, sz % 2
for angleId, angles in enumerate(angle_list):
# Rotate
#self.plan.template = self.rotate3d(self.plan.templateOrig, phi=phi,the=the,psi=psi)
self.plan.texture.transform(rotation=(angles[0], angles[2], angles[1]), rotation_order='rzxz', output=self.plan.template)
# Add wedge
#print(self.rfftn(self.plan.template).shape)
self.plan.template = self.irfftn(self.rfftn(self.plan.template) * self.plan.wedge)
# Normalize template
meanT = self.meanUnderMask(self.plan.template, self.plan.mask, p=self.plan.p)
stdT = self.stdUnderMask(self.plan.template, self.plan.mask, meanT, p=self.plan.p)
self.plan.template = ((self.plan.template - meanT) / stdT) * self.plan.mask
# write('template_gpu.em', self.plan.templatePadded)
# Cross-correlate and normalize by std_v
self.plan.ccc_map = self.normalized_cross_correlation(self.plan.volume_fft2, self.plan.template, self.plan.std_v, self.plan.p, plan=self.plan.fftplan)
# Update the scores and angles
self.updateResFromIdx(self.plan.scores, self.plan.angles, self.plan.ccc_map, angleId, self.plan.scores, self.plan.angles)
#self.cp.cuda.stream.get_current_stream().synchronize()
def is_alive(self):
return self.active
def calc_std_v(self, plan):
std_v = self.meanVolUnderMask2(plan.volume**2, plan) - self.meanVolUnderMask2(plan.volume, plan)**2
std_v[std_v < self.float32(1e-09)] = 1
plan.std_v = self.sqrt(std_v)
def meanVolUnderMask2(self, volume, plan):
res = self.fftshift(self.ifftn(self.fftn(volume) * self.fftn(plan.maskPadded).conj())) / plan.mask.sum()
return res.real
def meanUnderMask(self,volume, mask=None, p=1, gpu=False):
"""
meanValueUnderMask: Determines the mean value under a mask
@param volume: The volume
@type volume: L{pytom_volume.vol}
@param mask: The mask
@type mask: L{pytom_volume.vol}
@param p: precomputed number of voxels in mask
@type p: float
@return: A value (scalar)
@rtype: single
@change: support None as mask, FF 08.07.2014
"""
return (volume * mask).sum() / p
def stdUnderMask(self, volume, mask, meanValue, p=None, gpu=False):
"""
stdValueUnderMask: Determines the std value under a mask
@param volume: input volume
@type volume: L{pytom_volume.vol}
@param mask: mask
@type mask: L{pytom_volume.vol}
@param p: non zero value numbers in the mask
@type p: L{float} or L{int}
@return: A value
@rtype: L{float}
@change: support None as mask, FF 08.07.2014
"""
return self.sqrt(self.meanUnderMask(volume**2, mask, p=p) - meanValue**2)
def normalized_cross_correlation(self, volume_fft, template, norm, p=1, plan=None):
return self.cp.real(self.fftshift(self.ifftnP(volume_fft * self.cp.conj(self.fftnP(template, plan=plan)), plan=plan)) / (p * norm))
#print(volume_fft.shape)
print('cc')
cc = self.cp.conj(self.cp.fft.fftn(template))
print('ccc')
aa = self.cp.fft.fftn(template)
res = self.cp.abs(self.cp.fft.fftshift(self.cp.fft.ifftn(aa * cc )) )
#res = self.cp.abs(self.cp.fft.fftshift(self.cp.fft.ifftn(volume_fft * xp.fft.fftn(template).conj() )) / (p * norm))
return res
def pad(self, volume, out, sPad, sOrg):
SX, SY, SZ = sPad
sx, sy, sz = sOrg
print(sPad, sOrg)
out[SX // 2 - sx // 2:SX // 2 + sx // 2 + sx % 2, SY // 2 - sy // 2:SY // 2 + sy // 2 + sy % 2,
SZ // 2 - sz // 2:SZ // 2 + sz // 2 + sz % 2] = volume
def rotate3d(self, data, phi=0, psi=0, the=0, center=None, order=1, output=None):
"""Rotate a 3D data using ZXZ convention (phi: z1, the: x, psi: z2).
@param data: data to be rotated.
@param phi: 1st rotate around Z axis, in degree.
@param psi: 3rd rotate around Z axis, in degree.
@param the: 2nd rotate around X axis, in degree.
@param center: rotation center.
@return: the data after rotation.
"""
# Figure out the rotation center
if center is None:
cx = data.shape[0] / 2
cy = data.shape[1] / 2
cz = data.shape[2] / 2
else:
assert len(center) == 3
(cx, cy, cz) = center
# Transfer the angle to Euclidean
phi = -float(phi) * self.cp.pi / 180.0
the = -float(the) * self.cp.pi / 180.0
psi = -float(psi) * self.cp.pi / 180.0
sin_alpha = self.cp.sin(phi)
cos_alpha = self.cp.cos(phi)
sin_beta = self.cp.sin(the)
cos_beta = self.cp.cos(the)
sin_gamma = self.cp.sin(psi)
cos_gamma = self.cp.cos(psi)
# Calculate inverse rotation matrix
Inv_R = self.cp.zeros((3, 3), dtype=self.cp.float32)
Inv_R[0][0] = cos_alpha * cos_gamma - cos_beta * sin_alpha * sin_gamma
Inv_R[0][1] = -cos_alpha * sin_gamma - cos_beta * sin_alpha * cos_gamma
Inv_R[0][2] = sin_beta * sin_alpha
Inv_R[1][0] = sin_alpha * cos_gamma + cos_beta * cos_alpha * sin_gamma
Inv_R[1][1] = -sin_alpha * sin_gamma + cos_beta * cos_alpha * cos_gamma
Inv_R[1][2] = -sin_beta * cos_alpha
Inv_R[2][0] = sin_beta * sin_gamma
Inv_R[2][1] = sin_beta * cos_gamma
Inv_R[2][2] = cos_beta
grid = self.cp.mgrid[-cx:data.shape[0]-cx, -cy:data.shape[1]-cy, -cz:data.shape[2]-cz]
temp = grid.reshape((3, grid.size // 3))
temp = self.cp.dot(Inv_R, temp)
grid = self.cp.reshape(temp, grid.shape)
grid[0] += cx
grid[1] += cy
grid[2] += cz
# Interpolation
#self.map_coordinates(data, grid, output=output)
return self.map_coordinates(data, grid.reshape(len(grid), -1), order=order).reshape(grid.shape[1:])
class CCCPlan():
def __init__(self, particleList, maskname, freq, cp=xp, device='cpu', interpolation='filt_bspline',
max_num_part=65, profile=True, binning=1):
id = int(device.split(":")[1])
cp.cuda.Device(id).use()
self.cp = cp
self.device = device
print(f'start init on: {device}')
from pytom.voltools import transform, StaticVolume
from pytom.agnostic.tools import taper_edges
from pytom.agnostic.transform import fourier_reduced2full, resize
from pytom.agnostic.io import read_size, read, write
from pytom.agnostic.tools import create_sphere
try:
from cupyx.scipy.fftpack.fft import get_fft_plan
from cupyx.scipy.fftpack.fft import fftn as fftnP
from cupyx.scipy.fftpack.fft import ifftn as ifftnP
except ModuleNotFoundError: # TODO go to 'from cupyx.scipy.fftpack import ...' once fully moved to cupy > 8.3
from cupyx.scipy.fftpack import get_fft_plan
from cupyx.scipy.fftpack import fftn as fftnP
from cupyx.scipy.fftpack import ifftn as ifftnP
maskFull = read(maskname)
if binning != 1:
mask = resize(maskFull, 1. / binning)[0] # This is not a good idea
mask = maskFull[::binning, ::binning, ::binning]
else:
mask = maskFull
wedgeVol = particleList[0].getWedge().convert2numpy().getWedgeObject().returnWedgeVolume(*mask.shape)
wedge = fourier_reduced2full(wedgeVol, isodd=mask.shape[-1] % 2)
lpf = xp.fft.fftshift(create_sphere(mask.shape, freq))
print(mask.shape)
self.volume = cp.zeros(mask.shape, dtype=cp.float32)
self.vg = cp.zeros_like(self.volume, dtype=cp.float32)
self.vf = cp.zeros_like(self.volume, dtype=cp.float32)
self.binning = binning
self.max_particles_on_card = max_num_part
self.particleList = particleList
self.formatting = ['', ] * self.max_particles_on_card * 2
# General functions
self.transform = transform
self.ifftnP = ifftnP
self.fftnP = fftnP
self.fftplan = get_fft_plan(self.volume.astype(cp.complex64))
self.ifftplan = get_fft_plan(self.volume.astype(cp.complex64))
self.fftplan2 = get_fft_plan(maskFull.astype(cp.complex64))
self.ifftplan2 = get_fft_plan(self.volume.astype(cp.complex64))
self.read = read
self.write = write
self.xp = cp
self.profile = profile
self.stream = cp.cuda.Stream.null
self.staticVolume = StaticVolume
self.device = device
self.interpolation = interpolation
self.read_time = 0
# Mask info
self.mask = self.cp.array(mask, dtype=xp.float32)
self.p = mask.sum()
# Wedge
self.wedge = StaticVolume(cp.fft.fftshift(wedge), device=device, interpolation=interpolation)
self.wedgeZero = self.cp.array(wedge, dtype=self.cp.float32)
self.rot_wf = self.cp.zeros_like(self.volume)
self.rot_wg = self.cp.zeros_like(self.volume)
self.cwf, self.cwg = [-9999, -9999, -9999], [-9999, -9999, -9999]
# Low Pass Filter
self.lpf = self.cp.array(lpf, dtype=self.cp.float32)
# Allocate arrays used for normalisation of reference
self.num_threads = 1024
rr = 1
self.nblocks = int(self.cp.ceil(self.volume.size / self.num_threads / 2))
self.fast_sum_mean = self.cp.zeros((self.nblocks * rr), dtype=self.cp.float32)
self.fast_sum_stdv = self.cp.zeros((self.nblocks * rr), dtype=self.cp.float32)
# Kernels
self.normalize = cp.RawKernel(r'''
extern "C" __global__
void normalize( float* volume, const float* mask, float mean, float std_v, int n ){
int tid = blockDim.x * blockIdx.x + threadIdx.x;
if (tid < n) { volume[tid] = ((volume[tid] - mean)/ std_v) * mask[tid];}
}
''', 'normalize')
self.sumMeanStdv = cp.RawKernel(r'''
__device__ void warpReduce(volatile float* sdata, volatile float* stdv, int tid, int blockSize) {
if (blockSize >= 64) {sdata[tid] += sdata[tid + 32]; stdv[tid] += stdv[tid+32];}
if (blockSize >= 32) {sdata[tid] += sdata[tid + 16]; stdv[tid] += stdv[tid+16];}
if (blockSize >= 16) {sdata[tid] += sdata[tid + 8]; stdv[tid] += stdv[tid+ 8];}
if (blockSize >= 8) {sdata[tid] += sdata[tid + 4]; stdv[tid] += stdv[tid+ 4];}
if (blockSize >= 4) {sdata[tid] += sdata[tid + 2]; stdv[tid] += stdv[tid+ 2];}
if (blockSize >= 2) {sdata[tid] += sdata[tid + 1]; stdv[tid] += stdv[tid+ 1];} }
extern "C" __global__
void sumMeanStdv(float *g_idata, float *mask, float *g_mean, float * g_stdv, int n) {
__shared__ float mean[1024];
__shared__ float stdv[1024];
int blockSize = blockDim.x;
unsigned int tid = threadIdx.x;
int i = blockIdx.x*(blockSize)*2 + tid;
int gridSize = blockSize*gridDim.x*2;
mean[tid] = 0.;
stdv[tid] = 0.;
while (i < n) {
mean[tid] += g_idata[i] * mask[i] ;
stdv[tid] += g_idata[i] * g_idata[i] * mask[i];
if (i + blockSize < n){
mean[tid] += g_idata[i + blockSize] * mask[i+blockSize];
stdv[tid] += g_idata[i + blockSize] * g_idata[i + blockSize] * mask[i+blockSize];}
i += gridSize;}
__syncthreads();
if (blockSize >= 1024){ if (tid < 512) { mean[tid] += mean[tid + 512]; stdv[tid] += stdv[tid+512];} __syncthreads(); }
if (blockSize >= 512) { if (tid < 256) { mean[tid] += mean[tid + 256]; stdv[tid] += stdv[tid+256];} __syncthreads(); }
if (blockSize >= 256) { if (tid < 128) { mean[tid] += mean[tid + 128]; stdv[tid] += stdv[tid+128];} __syncthreads(); }