tomobar 2024.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tomobar/__init__.py ADDED
File without changes
File without changes
@@ -0,0 +1,579 @@
1
+ """The series of classes for wrapping of ASTRA toolbox to perform projection/backprojection
2
+ and reconstruction of of 2D/3D parallel beam data.
3
+
4
+ GPLv3 license (defined by ASTRA toolbox)
5
+ """
6
+
7
+ import numpy as np
8
+ from typing import Union
9
+ from tomobar.supp.funcs import _vec_geom_init2D, _vec_geom_init3D
10
+ from astra.experimental import direct_BP3D, direct_FP3D
11
+
12
+ try:
13
+ import cupy as xp
14
+
15
+ try:
16
+ xp.cuda.Device(0).compute_capability
17
+ except xp.cuda.runtime.CUDARuntimeError:
18
+ import numpy as xp
19
+
20
+ print("CuPy is installed but the GPU device is inaccessible")
21
+ except ImportError:
22
+ import numpy as xp
23
+
24
+ print("CuPy is not installed")
25
+
26
+ try:
27
+ import astra
28
+ except ImportError:
29
+ print("____! Astra-toolbox package is missing, please install !____")
30
+
31
+
32
+ ###########Base class############
33
+ class AstraBase:
34
+ """The base class for projection/backprojection operations and various reconstruction algorithms using ASTRA toolbox wrappers.
35
+
36
+ Args:
37
+ detectors_x (int): Horizontal detector dimension in pixel units.
38
+ angles_vec (np.ndarray): A vector of projection angles in radians.
39
+ centre_of_rotation (float, np.ndarray): The Centre of Rotation (CoR) scalar or a vector of CoRs for each angle.
40
+ recon_size (int): Reconstructed object size (a slice).
41
+ processing_arch (str): 'cpu' or 'gpu' - based processing.
42
+ device_index (int, optional): An integer for the GPU device, -1 for CPU computing and >0 for the GPU device.
43
+ ordsub_number (int): The number of ordered-subsets for iterative reconstruction.
44
+ detectors_y (int): Vertical detector dimension in pixel units (3D case).
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ detectors_x,
50
+ angles_vec,
51
+ centre_of_rotation,
52
+ recon_size,
53
+ processing_arch,
54
+ device_index,
55
+ ordsub_number,
56
+ detectors_y,
57
+ ):
58
+ self.detectors_x = detectors_x
59
+ self.angles_vec = angles_vec
60
+ self.centre_of_rotation = centre_of_rotation
61
+ self.recon_size = recon_size
62
+ self.processing_arch = processing_arch
63
+ self.device_index = device_index
64
+ self.ordsub_number = ordsub_number
65
+ self.detectors_y = detectors_y
66
+
67
+ @property
68
+ def detectors_x(self) -> int:
69
+ return self._detectors_x
70
+
71
+ @detectors_x.setter
72
+ def detectors_x(self, detectors_x_val):
73
+ if detectors_x_val <= 0:
74
+ raise ValueError(
75
+ "The size of the horizontal detector cannot be negative or zero"
76
+ )
77
+ self._detectors_x = detectors_x_val
78
+
79
+ @property
80
+ def angles_vec(self) -> np.ndarray:
81
+ return self._angles_vec
82
+
83
+ @angles_vec.setter
84
+ def angles_vec(self, angles_vec_val):
85
+ if len(angles_vec_val) == 0:
86
+ raise ValueError("The length of angles array cannot be zero")
87
+ if np.ndim(angles_vec_val) >= 2:
88
+ raise ValueError("The array of angles must be 1D")
89
+ self._angles_vec = angles_vec_val
90
+
91
+ @property
92
+ def centre_of_rotation(self) -> Union[float, np.ndarray]:
93
+ return self._centre_of_rotation
94
+
95
+ @centre_of_rotation.setter
96
+ def centre_of_rotation(self, centre_of_rotation_val):
97
+ if np.ndim(centre_of_rotation_val) == 1 and len(centre_of_rotation_val) != len(
98
+ self.angles_vec
99
+ ):
100
+ raise ValueError(
101
+ "The CoR must be a scalar or a 1D array of the SAME size as angles"
102
+ )
103
+ if centre_of_rotation_val is None:
104
+ centre_of_rotation_val = 0.0
105
+ self._centre_of_rotation = centre_of_rotation_val
106
+
107
+ @property
108
+ def recon_size(self) -> int:
109
+ return self._recon_size
110
+
111
+ @recon_size.setter
112
+ def recon_size(self, recon_size_val):
113
+ if isinstance(recon_size_val, tuple):
114
+ raise ValueError(
115
+ "Reconstruction is currently available for square or cubic objects only, please provide a scalar"
116
+ )
117
+ if recon_size_val <= 0:
118
+ raise ValueError("The size of the reconstruction object cannot be zero")
119
+ self._recon_size = recon_size_val
120
+
121
+ @property
122
+ def processing_arch(self) -> str:
123
+ return self._processing_arch
124
+
125
+ @processing_arch.setter
126
+ def processing_arch(self, processing_arch_val):
127
+ if processing_arch_val != "cpu" and processing_arch_val != "gpu":
128
+ raise ValueError(
129
+ "Please choose the processing architecture to be either 'cpu' or 'gpu'"
130
+ )
131
+ if processing_arch_val == "cpu" and self.centre_of_rotation != 0:
132
+ raise ValueError(
133
+ "Correction for the CoR with the vector geometry is implemented on the GPU only"
134
+ )
135
+ self._processing_arch = processing_arch_val
136
+
137
+ @property
138
+ def device_index(self) -> int:
139
+ return self._device_index
140
+
141
+ @device_index.setter
142
+ def device_index(self, device_index_val):
143
+ if device_index_val <= -2:
144
+ raise ValueError("The GPU device index can be only -1, 0 and larger than 0")
145
+ if self.processing_arch == "cpu":
146
+ self._device_index = -1
147
+ else:
148
+ self._device_index = device_index_val
149
+ astra.set_gpu_index = device_index_val
150
+
151
+ @property
152
+ def ordsub_number(self) -> int:
153
+ return self._ordsub_number
154
+
155
+ @ordsub_number.setter
156
+ def ordsub_number(self, ordsub_number_val):
157
+ if ordsub_number_val is None:
158
+ ordsub_number_val = 1
159
+ if ordsub_number_val <= 0:
160
+ raise ValueError("The number of ordered subsets cannot be negative or zero")
161
+ self._ordsub_number = ordsub_number_val
162
+
163
+ @property
164
+ def detectors_y(self) -> int:
165
+ return self._detectors_y
166
+
167
+ @detectors_y.setter
168
+ def detectors_y(self, detectors_y_val):
169
+ if detectors_y_val is not None:
170
+ if detectors_y_val <= 0:
171
+ raise ValueError(
172
+ "The size of the vertical detector cannot be negative or zero"
173
+ )
174
+ self._detectors_y = detectors_y_val
175
+
176
+ def _setOS_indices(self):
177
+ angles_tot = np.size(self.angles_vec) # total number of angles
178
+ self.NumbProjBins = (int)(
179
+ np.ceil(float(angles_tot) / float(self.ordsub_number))
180
+ ) # get the number of projections per bin (subset)
181
+ self.newInd_Vec = np.zeros(
182
+ [self.ordsub_number, self.NumbProjBins], dtype="int"
183
+ ) # 2D array of OS-sorted indeces
184
+ for sub_ind in range(self.ordsub_number):
185
+ ind_sel = 0
186
+ for proj_ind in range(self.NumbProjBins):
187
+ indexS = ind_sel + sub_ind
188
+ if indexS < angles_tot:
189
+ self.newInd_Vec[sub_ind, proj_ind] = indexS
190
+ ind_sel += self.ordsub_number
191
+
192
+ def _set_vol2d_geometry(self):
193
+ """set the reconstruction (vol_geom)"""
194
+ self.vol_geom = astra.create_vol_geom(self.recon_size, self.recon_size)
195
+
196
+ def _set_vol3d_geometry(self):
197
+ """set the reconstruction (vol_geom)"""
198
+ if isinstance(self.recon_size, tuple):
199
+ Y, X, Z = [int(i) for i in self.recon_size]
200
+ else:
201
+ Y = X = self.recon_size
202
+ Z = self.detectors_y
203
+ self.vol_geom = astra.create_vol_geom(Y, X, Z)
204
+
205
+ def _set_cpu_projection2d_parallel_geometry(self):
206
+ """the classical 2D projection geometry (cpu)"""
207
+ self.proj_geom = astra.create_proj_geom(
208
+ "parallel", 1.0, self.detectors_x, self.angles_vec
209
+ )
210
+ self.proj_id = astra.create_projector("line", self.proj_geom, self.vol_geom)
211
+ # optomo operator is used for ADMM algorithm only
212
+ self.A_optomo = astra.OpTomo(self.proj_id)
213
+
214
+ def _set_gpu_projection2d_parallel_geometry(self):
215
+ """the classical projection geometry (gpu)"""
216
+ vectors = _vec_geom_init2D(self.angles_vec, self.centre_of_rotation)
217
+ self.proj_geom = astra.create_proj_geom(
218
+ "parallel_vec", self.detectors_x, vectors
219
+ )
220
+ self.proj_id = astra.create_projector(
221
+ "cuda", self.proj_geom, self.vol_geom
222
+ ) # for GPU
223
+ # optomo operator is used for ADMM algorithm only
224
+ self.A_optomo = astra.OpTomo(self.proj_id)
225
+
226
+ def _set_gpu_projection3d_parallel_geometry(self):
227
+ """the classical 3D projection geometry (cpu)"""
228
+ vectors = _vec_geom_init3D(self.angles_vec, 1.0, 1.0, self.centre_of_rotation)
229
+ self.proj_geom = astra.create_proj_geom(
230
+ "parallel3d_vec", self.detectors_y, self.detectors_x, vectors
231
+ )
232
+ # optomo operator is used for ADMM algorithm only
233
+ self.proj_id = astra.create_projector(
234
+ "cuda3d", self.proj_geom, self.vol_geom
235
+ ) # for GPU
236
+ self.A_optomo = astra.OpTomo(self.proj_id)
237
+
238
+ def _set_projection2d_OS_parallel_geometry(self):
239
+ """organising 2d OS projection geometry CPU/GPU"""
240
+ self.proj_geom_OS = {}
241
+ self.proj_id_OS = {}
242
+ for sub_ind in range(self.ordsub_number):
243
+ self.indVec = self.newInd_Vec[sub_ind, :] # OS-specific indices
244
+ if self.indVec[self.NumbProjBins - 1] == 0:
245
+ self.indVec = self.indVec[:-1] # shrink vector size
246
+ anglesOS = self.angles_vec[self.indVec] # OS-specific angles
247
+
248
+ if np.ndim(self.centre_of_rotation) == 0:
249
+ # centre_of_rotation is a _scalar_
250
+ vectorsOS = _vec_geom_init2D(anglesOS, self.centre_of_rotation)
251
+ else:
252
+ # centre_of_rotation is a _vector_
253
+ vectorsOS = _vec_geom_init2D(
254
+ anglesOS, self.centre_of_rotation[self.indVec]
255
+ )
256
+ self.proj_geom_OS[sub_ind] = astra.create_proj_geom(
257
+ "parallel_vec", self.detectors_x, vectorsOS
258
+ )
259
+ if self.processing_arch == "cpu":
260
+ self.proj_id_OS[sub_ind] = astra.create_projector(
261
+ "line", self.proj_geom_OS[sub_ind], self.vol_geom
262
+ ) # for CPU
263
+ else:
264
+ self.proj_id_OS[sub_ind] = astra.create_projector(
265
+ "cuda", self.proj_geom_OS[sub_ind], self.vol_geom
266
+ ) # for GPU
267
+
268
+ def _set_projection3d_OS_parallel_geometry(self):
269
+ """organising 3d OS projection geometry CPU/GPU"""
270
+ self.proj_geom_OS = {}
271
+ for sub_ind in range(self.ordsub_number):
272
+ self.indVec = self.newInd_Vec[sub_ind, :]
273
+ if self.indVec[self.NumbProjBins - 1] == 0:
274
+ self.indVec = self.indVec[:-1] # shrink vector size
275
+ anglesOS = self.angles_vec[self.indVec] # OS-specific angles
276
+
277
+ if np.ndim(self.centre_of_rotation) == 0: # CenterRotOffset is a _scalar_
278
+ vectors = _vec_geom_init3D(anglesOS, 1.0, 1.0, self.centre_of_rotation)
279
+ else: # CenterRotOffset is a _vector_
280
+ vectors = _vec_geom_init3D(
281
+ anglesOS, 1.0, 1.0, self.centre_of_rotation[self.indVec]
282
+ )
283
+ self.proj_geom_OS[sub_ind] = astra.create_proj_geom(
284
+ "parallel3d_vec", self.detectors_y, self.detectors_x, vectors
285
+ )
286
+ return self.proj_geom_OS
287
+
288
+ def _runAstraBackproj2D(
289
+ self,
290
+ sinogram: np.ndarray,
291
+ method: str,
292
+ iterations: int,
293
+ os_index: Union[int, None],
294
+ ) -> np.ndarray:
295
+ """2D ASTRA-based back-projector
296
+
297
+ Args:
298
+ sinogram (np.ndarray): a sinogram to backproject
299
+ method (str): A method to choose from the ASTRA's provided ones.
300
+ iterations (int): The number of iterations for iterative methods.
301
+ os_index (Union[int, None]): The number of ordered subsets.
302
+
303
+ Returns:
304
+ np.ndarray: The reconstructed 2D image.
305
+ """
306
+ if self.ordsub_number != 1 and os_index is not None:
307
+ # ordered-subsets
308
+ sinogram_id = astra.data2d.create(
309
+ "-sino", self.proj_geom_OS[os_index], sinogram
310
+ )
311
+ else:
312
+ # traditional geometry
313
+ sinogram_id = astra.data2d.create("-sino", self.proj_geom, sinogram)
314
+
315
+ # Create a data object for the reconstruction
316
+ rec_id = astra.data2d.create("-vol", self.vol_geom)
317
+
318
+ # Create algorithm object
319
+ cfg = astra.astra_dict(method)
320
+ if self.processing_arch == "cpu":
321
+ if self.ordsub_number != 1:
322
+ cfg["ProjectorId"] = self.proj_id_OS[os_index]
323
+ else:
324
+ cfg["ProjectorId"] = self.proj_id
325
+ else:
326
+ cfg["option"] = {"GPUindex": self.device_index}
327
+ cfg["ReconstructionDataId"] = rec_id
328
+ cfg["ProjectionDataId"] = sinogram_id
329
+ if method == "FBP" or method == "FBP_CUDA":
330
+ cfg["FilterType"] = "Ram-Lak"
331
+
332
+ # Create the algorithm object from the configuration structure
333
+ alg_id = astra.algorithm.create(cfg)
334
+ astra.algorithm.run(alg_id, iterations)
335
+
336
+ # Get the result
337
+ recon_slice = astra.data2d.get(rec_id)
338
+
339
+ astra.algorithm.delete(alg_id)
340
+ astra.data2d.delete(rec_id)
341
+ astra.data2d.delete(sinogram_id)
342
+ if self.ordsub_number != 1:
343
+ astra.data2d.delete(self.proj_id_OS)
344
+ else:
345
+ astra.data2d.delete(self.proj_id)
346
+ return recon_slice
347
+
348
+ def _runAstraProj2D(
349
+ self, image: np.ndarray, os_index: Union[int, None], method: str
350
+ ) -> np.ndarray:
351
+ """2D Forward projector for ASTRA parallel-beam
352
+
353
+ Args:
354
+ image (np.ndarray): Object to perform forward projection on.
355
+ os_index (Union[int, None]): The number of ordered subsets.
356
+ method (str): A method to choose from ASTRA's provided ones.
357
+
358
+ Returns:
359
+ np.ndarray: projected 2d data (sinogram)
360
+ """
361
+ if isinstance(image, np.ndarray):
362
+ rec_id = astra.data2d.link("-vol", self.vol_geom, image)
363
+ else:
364
+ rec_id = image
365
+ if self.ordsub_number != 1 and os_index is not None:
366
+ # ordered-subsets
367
+ sinogram_id = astra.data2d.create("-sino", self.proj_geom_OS[os_index], 0)
368
+ else:
369
+ # traditional full data parallel beam projection geometry
370
+ sinogram_id = astra.data2d.create("-sino", self.proj_geom, 0)
371
+
372
+ # Create algorithm object
373
+ cfg = astra.astra_dict(method)
374
+ if self.processing_arch == "cpu":
375
+ if self.ordsub_number != 1:
376
+ cfg["ProjectorId"] = self.proj_id_OS[os_index]
377
+ else:
378
+ cfg["ProjectorId"] = self.proj_id
379
+ else:
380
+ cfg["option"] = {"GPUindex": self.device_index}
381
+ cfg["VolumeDataId"] = rec_id
382
+ cfg["ProjectionDataId"] = sinogram_id
383
+
384
+ # Create the algorithm object from the configuration structure
385
+ alg_id = astra.algorithm.create(cfg)
386
+ astra.algorithm.run(alg_id)
387
+
388
+ # Get the result
389
+ sinogram = astra.data2d.get(sinogram_id)
390
+
391
+ astra.algorithm.delete(alg_id)
392
+ astra.data2d.delete(rec_id)
393
+ if self.ordsub_number != 1:
394
+ astra.data2d.delete(self.proj_id_OS)
395
+ else:
396
+ astra.data2d.delete(self.proj_id)
397
+ astra.data2d.delete(sinogram_id)
398
+ return sinogram
399
+
400
+ def runAstraBackproj3D(
401
+ self,
402
+ proj_data: np.ndarray,
403
+ method: str,
404
+ iterations: int,
405
+ os_index: Union[int, None],
406
+ ) -> np.ndarray:
407
+ """ "3D ASTRA-based back-projector for parallel beam
408
+
409
+ Args:
410
+ proj_data (np.ndarray): 3D projection data
411
+ method (str): A method to choose from ASTRA's provided ones.
412
+ iterations (int): The number of iterations for iterative methods.
413
+ os_index (Union[int, None]): The number of ordered subsets.
414
+
415
+ Returns:
416
+ np.ndarray: The reconstructed 3D volume.
417
+ """
418
+ # set ASTRA configuration for 3D reconstructor
419
+ if self.ordsub_number != 1 and os_index is not None:
420
+ # ordered-subsets
421
+ proj_id = astra.data3d.create(
422
+ "-sino", self.proj_geom_OS[os_index], proj_data
423
+ )
424
+ else:
425
+ # traditional full data parallel beam projection geometry
426
+ proj_id = astra.data3d.create("-sino", self.proj_geom, proj_data)
427
+
428
+ # Create a data object for the reconstruction
429
+ rec_id = astra.data3d.create("-vol", self.vol_geom)
430
+
431
+ # Create algorithm object
432
+ cfg = astra.astra_dict(method)
433
+ cfg["option"] = {"GPUindex": self.device_index}
434
+ cfg["ReconstructionDataId"] = rec_id
435
+ cfg["ProjectionDataId"] = proj_id
436
+
437
+ # Create the algorithm object from the configuration structure
438
+ alg_id = astra.algorithm.create(cfg)
439
+ astra.algorithm.run(alg_id, iterations)
440
+
441
+ # Get the result
442
+ recon_volume = astra.data3d.get(rec_id)
443
+
444
+ astra.algorithm.delete(alg_id)
445
+ astra.data3d.delete(rec_id)
446
+ astra.data3d.delete(proj_id)
447
+ return recon_volume
448
+
449
+ def runAstraProj3D(
450
+ self, volume_data: np.ndarray, os_index: Union[int, None]
451
+ ) -> np.ndarray:
452
+ """3D ASTRA-based projector for parallel beam
453
+
454
+ Args:
455
+ volume_data (np.ndarray): 3D object to project
456
+ os_index (Union[int, None]): The number of ordered subsets.
457
+
458
+ Returns:
459
+ np.ndarray: 3D projection data
460
+ """
461
+ # set ASTRA configuration for 3D projector
462
+ if isinstance(volume_data, np.ndarray):
463
+ volume_id = astra.data3d.link("-vol", self.vol_geom, volume_data)
464
+ else:
465
+ volume_id = volume_data
466
+ if self.ordsub_number != 1 and os_index is not None:
467
+ # ordered-subsets
468
+ proj_id = astra.data3d.create("-sino", self.proj_geom_OS[os_index], 0)
469
+ else:
470
+ # traditional full data parallel beam projection geometry
471
+ proj_id = astra.data3d.create("-sino", self.proj_geom, 0)
472
+
473
+ # Create algorithm object
474
+ algString = "FP3D_CUDA"
475
+ cfg = astra.astra_dict(algString)
476
+ cfg["option"] = {"GPUindex": self.device_index}
477
+ cfg["VolumeDataId"] = volume_id
478
+ cfg["ProjectionDataId"] = proj_id
479
+
480
+ # Create the algorithm object from the configuration structure
481
+ alg_id = astra.algorithm.create(cfg)
482
+ astra.algorithm.run(alg_id)
483
+
484
+ # Get the result
485
+ proj_volume = astra.data3d.get(proj_id)
486
+
487
+ astra.algorithm.delete(alg_id)
488
+ astra.data3d.delete(volume_id)
489
+ astra.data3d.delete(proj_id)
490
+ return proj_volume
491
+
492
+ def runAstraBackproj3DCuPy(
493
+ self, proj_data: xp.ndarray, method: str, os_index: Union[int, None]
494
+ ) -> xp.ndarray:
495
+ """3d back-projection using ASTRA's GPULink functionality for CuPy arrays
496
+
497
+ Args:
498
+ proj_data (xp.ndarray): 3d projection data as a CuPy array
499
+ method (str): Only BP is available so far.
500
+ os_index (Union[int, None]): The number of ordered subsets.
501
+
502
+ Returns:
503
+ xp.ndarray: A CuPy array containing back-projected volume.
504
+ """
505
+ # set ASTRA configuration for 3D reconstructor using CuPy arrays
506
+ proj_link = astra.data3d.GPULink(
507
+ proj_data.data.ptr, *proj_data.shape[::-1], 4 * proj_data.shape[2]
508
+ )
509
+ if self.ordsub_number != 1 and os_index is not None:
510
+ # ordered-subsets
511
+ projector_id = astra.create_projector(
512
+ "cuda3d", self.proj_geom_OS[os_index], self.vol_geom
513
+ )
514
+ else:
515
+ # traditional full data parallel beam projection geometry
516
+ projector_id = astra.create_projector(
517
+ "cuda3d", self.proj_geom, self.vol_geom
518
+ )
519
+ # create a CuPy array with ASTRA link to it
520
+ recon_volume = xp.empty(astra.geom_size(self.vol_geom), dtype=xp.float32)
521
+
522
+ rec_link = astra.data3d.GPULink(
523
+ recon_volume.data.ptr, *recon_volume.shape[::-1], 4 * recon_volume.shape[2]
524
+ )
525
+
526
+ # run backprojection
527
+ direct_BP3D(projector_id, rec_link, proj_link)
528
+
529
+ astra.data3d.delete(projector_id)
530
+ del proj_data, proj_link, rec_link
531
+ return recon_volume
532
+
533
+ def runAstraProj3DCuPy(
534
+ self, volume_data: xp.ndarray, os_index: Union[int, None]
535
+ ) -> xp.ndarray:
536
+ """3d forward projector using ASTRA's GPULink functionality for CuPy arrays
537
+
538
+ Args:
539
+ volume_data (xp.ndarray): the input 3d volume as a CuPy array
540
+ os_index (Union[int, None]): The number of ordered subsets.
541
+
542
+ Returns:
543
+ xp.ndarray: projected volume array as a cupy array
544
+ """
545
+ # Enable GPUlink to the volume
546
+ volume_link = astra.data3d.GPULink(
547
+ volume_data.data.ptr, *volume_data.shape[::-1], 4 * volume_data.shape[2]
548
+ )
549
+ volume_id = astra.data3d.link("-vol", self.vol_geom, volume_link)
550
+
551
+ if self.ordsub_number != 1:
552
+ # ordered-subsets approach
553
+ proj_volume = xp.empty(
554
+ astra.geom_size(self.proj_geom_OS[os_index]), dtype=xp.float32
555
+ )
556
+ gpu_link_sino = astra.data3d.GPULink(
557
+ proj_volume.data.ptr, *proj_volume.shape[::-1], 4 * proj_volume.shape[2]
558
+ )
559
+ projector_id = astra.create_projector(
560
+ "cuda3d", self.proj_geom_OS[os_index], self.vol_geom
561
+ )
562
+ else:
563
+ # traditional full data parallel beam projection geometry
564
+ # Enabling GPUlink to the created empty CuPy array
565
+ proj_volume = xp.empty(astra.geom_size(self.proj_geom), dtype=xp.float32)
566
+ gpu_link_sino = astra.data3d.GPULink(
567
+ proj_volume.data.ptr, *proj_volume.shape[::-1], 4 * proj_volume.shape[2]
568
+ )
569
+ projector_id = astra.create_projector(
570
+ "cuda3d", self.proj_geom, self.vol_geom
571
+ )
572
+
573
+ # Perform forward projection
574
+ direct_FP3D(projector_id, volume_link, gpu_link_sino)
575
+
576
+ astra.data3d.delete(volume_id)
577
+ astra.data3d.delete(projector_id)
578
+ del volume_data, volume_link, gpu_link_sino
579
+ return proj_volume
@@ -0,0 +1,102 @@
1
+ from tomobar.astra_wrappers.astra_base import AstraBase
2
+
3
+ import numpy as np
4
+
5
+
6
+ ###########Child class############
7
+ class AstraTools2D(AstraBase):
8
+ """2D parallel beam projection/backprojection child class.
9
+
10
+ Args:
11
+ AstraBase (class): the base class.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ detectors_x,
17
+ angles_vec,
18
+ centre_of_rotation,
19
+ recon_size,
20
+ processing_arch,
21
+ device_index,
22
+ ordsub_number=1,
23
+ verbosity=False,
24
+ ):
25
+ super().__init__(
26
+ detectors_x,
27
+ angles_vec,
28
+ centre_of_rotation,
29
+ recon_size,
30
+ processing_arch,
31
+ device_index,
32
+ ordsub_number,
33
+ detectors_y=None,
34
+ )
35
+
36
+ if verbosity:
37
+ print("The shape of the input data has been established...")
38
+ super()._set_vol2d_geometry()
39
+ if verbosity:
40
+ print("2D volume geometry initialised...")
41
+ if ordsub_number == 1 or ordsub_number is None:
42
+ if processing_arch == "cpu":
43
+ super()._set_cpu_projection2d_parallel_geometry()
44
+ else:
45
+ super()._set_gpu_projection2d_parallel_geometry()
46
+ if verbosity:
47
+ print(
48
+ "2D <{}> classical parallel-beam projection geometry initialised...".format(
49
+ processing_arch
50
+ )
51
+ )
52
+ else:
53
+ super()._setOS_indices()
54
+ super()._set_projection2d_OS_parallel_geometry()
55
+ if verbosity:
56
+ print(
57
+ "2D <{}> ordered-subsets parallel-beam projection geometry initialised...".format(
58
+ processing_arch
59
+ )
60
+ )
61
+
62
+ def _forwproj(self, image: np.ndarray) -> np.ndarray:
63
+ astra_method = "FP_CUDA" # 2d forward projection
64
+ if self.processing_arch == "cpu":
65
+ astra_method = "FP"
66
+ return super()._runAstraProj2D(image, None, astra_method)
67
+
68
+ def _forwprojOS(self, image: np.ndarray, os_index: int) -> np.ndarray:
69
+ astra_method = "FP_CUDA" # 2d forward projection
70
+ if self.processing_arch == "cpu":
71
+ astra_method = "FP"
72
+ return super()._runAstraProj2D(image, os_index, astra_method)
73
+
74
+ def _backproj(self, sinogram: np.ndarray) -> np.ndarray:
75
+ astra_method = "BP_CUDA" # 2D back projection
76
+ if self.processing_arch == "cpu":
77
+ astra_method = "BP"
78
+ return super()._runAstraBackproj2D(sinogram, astra_method, 1, None)
79
+
80
+ def _backprojOS(self, sinogram: np.ndarray, os_index: int) -> np.ndarray:
81
+ astra_method = "BP_CUDA" # 2D back projection
82
+ if self.processing_arch == "cpu":
83
+ astra_method = "BP"
84
+ return super()._runAstraBackproj2D(sinogram, astra_method, 1, os_index)
85
+
86
+ def _fbp(self, sinogram: np.ndarray) -> np.ndarray:
87
+ astra_method = "FBP_CUDA" # 2D FBP reconstruction
88
+ if self.processing_arch == "cpu":
89
+ astra_method = "FBP"
90
+ return super()._runAstraBackproj2D(sinogram, astra_method, 1, None)
91
+
92
+ def _sirt(self, sinogram: np.ndarray, iterations: int) -> np.ndarray:
93
+ astra_method = "SIRT_CUDA" # perform 2D SIRT reconstruction
94
+ if self.processing_arch == "cpu":
95
+ astra_method = "SIRT"
96
+ return super()._runAstraBackproj2D(sinogram, astra_method, iterations, None)
97
+
98
+ def _cgls(self, sinogram: np.ndarray, iterations: int) -> np.ndarray:
99
+ astra_method = "CGLS_CUDA" # perform 2D CGLS reconstruction
100
+ if self.processing_arch == "cpu":
101
+ astra_method = "CGLS"
102
+ return super()._runAstraBackproj2D(sinogram, astra_method, iterations, None)