Esempio n. 1
0
    def process(self, out=None):

        DATA = self.get_input()

        pad = False
        if len(DATA.shape) == 2:
            #for 2D cases
            pad = True
            data_temp = numpy.expand_dims(DATA.as_array(), axis=0)
        else:
            data_temp = DATA.as_array()

        rec_id, arr_out = astra.create_backprojection3d_gpu(
            data_temp, self.proj_geom, self.vol_geom)

        astra.data3d.delete(rec_id)

        if pad is True:
            arr_out = numpy.squeeze(arr_out, axis=0)

        if out is None:
            out = ImageData(arr_out,
                            deep_copy=False,
                            geometry=self.volume_geometry.copy(),
                            suppress_warning=True)
            return out
        else:
            out.fill(arr_out)
Esempio n. 2
0
    def test_FISTA_catch_Lipschitz(self):
        if debug_print:
            print("Test FISTA catch Lipschitz")
        ig = ImageGeometry(127, 139, 149)
        initial = ImageData(geometry=ig)
        initial = ig.allocate()
        b = initial.copy()
        # fill with random numbers
        b.fill(numpy.random.random(initial.shape))
        initial = ig.allocate(ImageGeometry.RANDOM)
        identity = IdentityOperator(ig)

        #### it seems FISTA does not work with Nowm2Sq
        norm2sq = LeastSquares(identity, b)
        if debug_print:
            print('Lipschitz', norm2sq.L)
        # norm2sq.L = None
        #norm2sq.L = 2 * norm2sq.c * identity.norm()**2
        #norm2sq = OperatorCompositionFunction(L2NormSquared(b=b), identity)
        opt = {'tol': 1e-4, 'memopt': False}
        if debug_print:
            print("initial objective", norm2sq(initial))
        try:
            alg = FISTA(initial=initial, f=L1Norm(), g=ZeroFunction())
            self.assertTrue(False)
        except ValueError as ve:
            print(ve)
            self.assertTrue(True)
Esempio n. 3
0
    def skiptest_BlockDataContainerShapeArithmetic(self):
        print ("test block data container")
        ig0 = ImageGeometry(2,3,4)
        ig1 = ImageGeometry(2,3,4)

        data0 = ImageData(geometry=ig0)
        data1 = ImageData(geometry=ig1) + 1

        data2 = ImageData(geometry=ig0) + 2
        data3 = ImageData(geometry=ig1) + 3

        cp0 = BlockDataContainer(data0,data1)
        #cp1 = BlockDataContainer(data2,data3)
        cp1 = cp0 + 1
        self.assertTrue(cp1.shape == cp0.shape)
        cp1 = cp0.T + 1

        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = cp0.T - 1
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = (cp0.T + 1)*2
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = (cp0.T + 1)/2
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = cp0.T.power(2.2)
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = cp0.T.maximum(3)
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = cp0.T.abs()
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = cp0.T.sign()
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = cp0.T.sqrt()
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)

        cp1 = cp0.T.conjugate()
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp1.shape == transpose_shape)
Esempio n. 4
0
    def create_simple_ImageData(self):
        N = 64
        ig = ImageGeometry(voxel_num_x=N, voxel_num_y=N)
        Phantom = ImageData(geometry=ig)

        x = Phantom.as_array()

        x[int(round(N/4)):int(round(3*N/4)),
          int(round(N/4)):int(round(3*N/4))] = 0.5
        x[int(round(N/8)):int(round(7*N/8)),
          int(round(3*N/8)):int(round(5*N/8))] = 1

        return (ig, Phantom)
Esempio n. 5
0
    def skiptest_BlockDataContainerShape(self):
        ig0 = ImageGeometry(12, 42, 55, 32)
        ig1 = ImageGeometry(12, 42, 55, 32)

        data0 = ImageData(geometry=ig0)
        data1 = ImageData(geometry=ig1) + 1

        data2 = ImageData(geometry=ig0) + 2
        data3 = ImageData(geometry=ig1) + 3

        cp0 = BlockDataContainer(data0, data1)
        cp1 = BlockDataContainer(data2, data3)
        transpose_shape = (cp0.shape[1], cp0.shape[0])
        self.assertTrue(cp0.T.shape == transpose_shape)
Esempio n. 6
0
    def adjoint(self, x, out=None):

        if self.tigre_geom.is2D:
            data_temp = np.expand_dims(x.as_array(),axis=1)
            arr_out = Atb.Atb(data_temp, self.tigre_geom, self.tigre_angles, krylov=self.method['adjoint'])
            arr_out = np.squeeze(arr_out, axis=0)
        else:
            arr_out = Atb.Atb(x.as_array(), self.tigre_geom, self.tigre_angles, krylov=self.method['adjoint'])

        if out is None:
            out = ImageData(arr_out, deep_copy=False, geometry=self._domain_geometry.copy(), suppress_warning=True)
            return out
        else:
            out.fill(arr_out)
Esempio n. 7
0
    def read(self):

        if self._geometry is None:
            self.get_geometry()

        with h5py.File(self.file_name, 'r') as dfile:

            ds_data = dfile['entry1/tomo_entry/data/data']
            data = np.array(ds_data, dtype=np.float32)

            # handle old files?
            if self.is_old_file_version():
                if isinstance(self._geometry, AcquisitionGeometry):
                    return AcquisitionData(data,
                                           True,
                                           geometry=self._geometry,
                                           suppress_warning=True)
                elif isinstance(self._geometry, ImageGeometry):
                    return ImageData(data,
                                     True,
                                     geometry=self._geometry,
                                     suppress_warning=True)
                else:
                    raise TypeError("Unsupported geometry. Expected ImageGeometry or AcquisitionGeometry, got {}"\
                        .format(type(self._geometry)))

            output = self._geometry.allocate(None)
            output.fill(data)
            return output
    def process(self, out=None):

        DATA = self.get_input()
        data_temp = DATA.as_array()

        rec_id, arr_out = astra.create_backprojection(data_temp, self.proj_id)
        astra.data2d.delete(rec_id)

        if out is None:
            out = ImageData(arr_out,
                            deep_copy=False,
                            geometry=self.volume_geometry.copy(),
                            suppress_warning=True)
            return out
        else:
            out.fill(arr_out)
    def sum_abs_col(self):

        res = np.array(
            np.reshape(
                abs(self.matrix()).sum(axis=1),
                self.domain_geometry().shape, 'F'))
        #res[res==0]=0
        return ImageData(res)
Esempio n. 10
0
 def _return_appropriate_data(self, data, geometry):
     if isinstance (geometry, ImageGeometry):
         return ImageData(data, deep=True, geometry=geometry.copy(), suppress_warning=True)
     elif isinstance (geometry, AcquisitionGeometry):
         return AcquisitionData(data, deep=True, geometry=geometry.copy(), suppress_warning=True)
     else:
         raise TypeError("Unsupported Geometry type. Expected ImageGeometry or AcquisitionGeometry, got {}"\
             .format(type(geometry)))
Esempio n. 11
0
    def process(self, out=None):

        if self.tigre_geom.is2D:
            data_temp = np.expand_dims(self.get_input().as_array(), axis=1)
            arr_out = fdk(data_temp, self.tigre_geom, self.tigre_angles)
            arr_out = np.squeeze(arr_out, axis=0)
        else:
            arr_out = fdk(self.get_input().as_array(), self.tigre_geom,
                          self.tigre_angles)

        if out is None:
            out = ImageData(arr_out,
                            deep_copy=False,
                            geometry=self.volume_geometry.copy(),
                            suppress_warning=True)
            return out
        else:
            out.fill(arr_out)
Esempio n. 12
0
    def process(self, out=None):

        # Get DATA
        DATA = self.get_input()

        pad = False
        if len(DATA.shape) == 2:
            #for 2D cases
            pad = True
            data_temp = numpy.expand_dims(DATA.as_array(), axis=0)
        else:
            data_temp = DATA.as_array()

        rec_id = astra.data3d.create('-vol', self.vol_geom_astra)
        sinogram_id = astra.data3d.create('-sino', self.proj_geom_astra,
                                          data_temp)
        cfg = astra.astra_dict('FDK_CUDA')
        cfg['ReconstructionDataId'] = rec_id
        cfg['ProjectionDataId'] = sinogram_id
        alg_id = astra.algorithm.create(cfg)

        astra.algorithm.run(alg_id)
        arr_out = astra.data3d.get(rec_id)

        astra.data3d.delete(rec_id)
        astra.data3d.delete(sinogram_id)
        astra.algorithm.delete(alg_id)

        if pad == True:
            arr_out = numpy.squeeze(arr_out, axis=0)

        if out is None:
            out = ImageData(arr_out,
                            deep_copy=False,
                            geometry=self.volume_geometry.copy(),
                            suppress_warning=True)
            return out
        else:
            out.fill(arr_out)
    def adjoint(self, x, out=None):

        data = x.as_array()

        #if single angle projection add the dimension in for TIGRE
        if x.dimension_labels[0] != AcquisitionGeometry.ANGLE:
            data = np.expand_dims(data, axis=0)

        if self.tigre_geom.is2D:
            data = np.expand_dims(data, axis=1)
            arr_out = self.__call_Atb(data)
            arr_out = np.squeeze(arr_out, axis=0)
        else:
            arr_out = self.__call_Atb(data)

        if out is None:
            out = ImageData(arr_out,
                            deep_copy=False,
                            geometry=self._domain_geometry.copy(),
                            suppress_warning=True)
            return out
        else:
            out.fill(arr_out)
Esempio n. 14
0
    def sum_abs_row(self):

        res = []
        for row in range(self.shape[0]):
            for col in range(self.shape[1]):
                if col == 0:
                    prod = self.get_item(row, col).sum_abs_row()
                else:
                    prod += self.get_item(row, col).sum_abs_row()
            res.append(prod)

        if self.shape[1] == 1:
            tmp = sum(res)
            return ImageData(tmp)
        else:

            return BlockDataContainer(*res)
Esempio n. 15
0
 def test_ImageGeometry_allocate(self):
     vgeometry = ImageGeometry(voxel_num_x=4, voxel_num_y=3, channels=2)
     image = vgeometry.allocate()
     self.assertEqual(0,image.as_array()[0][0][0])
     image = vgeometry.allocate(1)
     self.assertEqual(1,image.as_array()[0][0][0])
     default_order = ['channel' , 'horizontal_y' , 'horizontal_x']
     self.assertEqual(default_order[0], image.dimension_labels[0])
     self.assertEqual(default_order[1], image.dimension_labels[1])
     self.assertEqual(default_order[2], image.dimension_labels[2])
     order = [ 'horizontal_x' , 'horizontal_y', 'channel' ]
     image = vgeometry.allocate(0,dimension_labels=order)
     self.assertEqual(order[0], image.dimension_labels[0])
     self.assertEqual(order[1], image.dimension_labels[1])
     self.assertEqual(order[2], image.dimension_labels[2])
     
     ig = ImageGeometry(2,3,2)
     try:
         z = ImageData(numpy.random.randint(10, size=(2,3)), geometry=ig)
         self.assertTrue(False)
     except ValueError as ve:
         print (ve)
         self.assertTrue(True)
Esempio n. 16
0
def get_ImageData(num_model, geometry):
    '''Returns an ImageData relative to geometry with the model num_model from tomophantom
    
    :param num_model: model number
    :type num_model: int
    :param geometry: geometrical info that describes the phantom
    :type geometry: ImageGeometry
    Example usage:
    
    .. code-block:: python
      
      ndim = 2
      N=128
      angles = np.linspace(0, 360, 50, True, dtype=np.float32)
      offset = 0.4
      channels = 3
        
      if ndim == 2:
          ag = AcquisitionGeometry.create_Cone2D((offset,-100), (offset,100))
          ag.set_panel(N)
            
      else:
          ag = AcquisitionGeometry.create_Cone3D((offset,-100, 0), (offset,100,0))
          ag.set_panel((N,N-2))
        
      ag.set_channels(channels)
      ag.set_angles(angles, angle_unit=AcquisitionGeometry.DEGREE)
        
        
      ig = ag.get_ImageGeometry()
      num_model = 1
      phantom = TomoPhantom.get_ImageData(num_model=num_model, geometry=ig)

    
    '''
    ig = geometry.copy()
    ig.set_labels(DataOrder.TOMOPHANTOM_IG_LABELS)
    num_dims = len(ig.dimension_labels)
    
    if ImageGeometry.CHANNEL in ig.dimension_labels:
        if not is_model_temporal(num_model):
            raise ValueError('Selected model {} is not a temporal model, please change your selection'.format(num_model))
        if num_dims == 4:
            # 3D+time for tomophantom
            # output dimensions channel and then spatial, 
            # e.g. [ 'channel', 'vertical', 'horizontal_y', 'horizontal_x' ]
            num_model = num_model
            shape = tuple(ig.shape[1:])
            phantom_arr = TomoP3D.ModelTemporal(num_model, shape, path_library3D)
        elif num_dims == 3:
            # 2D+time for tomophantom
            # output dimensions channel and then spatial, 
            # e.g. [ 'channel', 'horizontal_y', 'horizontal_x' ]
            N = ig.shape[1]
            num_model = num_model
            phantom_arr = TomoP2D.ModelTemporal(num_model, ig.shape[1], path_library2D)
        else:
            raise ValueError('Wrong ImageGeometry')
        if ig.channels != phantom_arr.shape[0]:
            raise ValueError('The required model {} has {} channels. The ImageGeometry you passed has {}. Please update your ImageGeometry.'\
                .format(num_model, ig.channels, phantom_arr.shape[0]))
    else:
        if num_dims == 3:
            # 3D
            num_model = num_model
            phantom_arr = TomoP3D.Model(num_model, ig.shape, path_library3D)
        elif num_dims == 2:
            # 2D
            if ig.shape[0] != ig.shape[1]:
                raise ValueError('Can only handle square ImageData, got shape'.format(ig.shape))
            N = ig.shape[0]
            num_model = num_model
            phantom_arr = TomoP2D.Model(num_model, N, path_library2D)
        else:
            raise ValueError('Wrong ImageGeometry')

    
    im_data = ImageData(phantom_arr, geometry=ig, suppress_warning=True)
    im_data.reorder(list(geometry.dimension_labels))
    return im_data
Esempio n. 17
0
    def test_BlockDataContainer_fill(self):
        print ("test block data container")
        ig0 = ImageGeometry(2,3,4)
        ig1 = ImageGeometry(2,3,5)
        
        data0 = ImageData(geometry=ig0)
        data1 = ImageData(geometry=ig1) + 1
        
        data2 = ImageData(geometry=ig0) + 2
        data3 = ImageData(geometry=ig1) + 3
        
        cp0 = BlockDataContainer(data0,data1)
        #cp1 = BlockDataContainer(data2,data3)

        cp2 = BlockDataContainer(data0+1, data1+1)

        data0.fill(data2)
        self.assertNumpyArrayEqual(data0.as_array(), data2.as_array())
        data0 = ImageData(geometry=ig0)

        for el,ot in zip(cp0, cp2):
            print (el.shape, ot.shape)
        cp0.fill(cp2)
        self.assertBlockDataContainerEqual(cp0, cp2)
Esempio n. 18
0
dist1 = ((x - circle1[1])**2 + (y - circle1[2])**2)**0.5

circle2 = [5, 80, 0]  #r,x,y
dist2 = ((x - circle2[1])**2 + (y - circle2[2])**2)**0.5

circle3 = [25, 0, 80]  #r,x,y
dist3 = ((x - circle3[1])**2 + (y - circle3[2])**2)**0.5

mask1 = (dist1 - circle1[0]).clip(0, 1)
mask2 = (dist2 - circle2[0]).clip(0, 1)
mask3 = (dist3 - circle3[0]).clip(0, 1)
phantomarr = 1 - np.logical_and(np.logical_and(mask1, mask2), mask3)
print(phantomarr.shape)

phantom = ImageData(phantomarr,
                    deep_copy=False,
                    geometry=ig,
                    suppress_warning=True)
# show2D(phantom)

#%%
from cil.io import NEXUSDataReader

reader = NEXUSDataReader()
reader.set_up(file_name='phantom.nxs')
data = reader.read()


def BP(data, ig):
    '''Backward projection for 2D parallel beam'''
    spread = ig.allocate(0)
    spreadarr = spread.as_array()
Esempio n. 19
0
    Gx = SparseFiniteDifferenceOperator(ig, direction=1, bnd_cond='Neumann')
    Gy = SparseFiniteDifferenceOperator(ig, direction=0, bnd_cond='Neumann')

    d1 = abs(Gx.matrix()).toarray().sum(axis=0)
    d2 = abs(Gy.matrix()).toarray().sum(axis=0)
    d3 = abs(Id.matrix()).toarray().sum(axis=0)

    d_res = numpy.reshape(d1 + d2 + d3, ig.shape, 'F')

    print(d_res)
    #
    z1 = abs(Gx.matrix()).toarray().sum(axis=1)
    z2 = abs(Gy.matrix()).toarray().sum(axis=1)
    z3 = abs(Id.matrix()).toarray().sum(axis=1)
    #
    z_res = BlockDataContainer(BlockDataContainer(ImageData(numpy.reshape(z2, ig.shape, 'F')),\
                                                  ImageData(numpy.reshape(z1, ig.shape, 'F'))),\
                                                  ImageData(numpy.reshape(z3, ig.shape, 'F')))
    #
    ttt = B.sum_abs_col()
    #
    #TODO this is not working
    #    numpy.testing.assert_array_almost_equal(z_res[0][0].as_array(), ttt[0][0].as_array(), decimal=4)
    #    numpy.testing.assert_array_almost_equal(z_res[0][1].as_array(), ttt[0][1].as_array(), decimal=4)
    #    numpy.testing.assert_array_almost_equal(z_res[1].as_array(), ttt[1].as_array(), decimal=4)

    u = ig.allocate('random_int')

    z1 = B.direct(u)
    res = B.range_geometry().allocate()
Esempio n. 20
0
    def test_BlockDataContainer_fill(self):

        ig0 = ImageGeometry(2, 3, 4)
        ig1 = ImageGeometry(2, 3, 5)

        data0 = ImageData(geometry=ig0)
        data1 = ImageData(geometry=ig1) + 1

        data2 = ImageData(geometry=ig0) + 2
        data3 = ImageData(geometry=ig1) + 3

        cp0 = BlockDataContainer(data0, data1)
        #cp1 = BlockDataContainer(data2,data3)

        cp2 = BlockDataContainer(data0 + 1, data1 + 1)

        data0.fill(data2)
        self.assertNumpyArrayEqual(data0.as_array(), data2.as_array())
        data0 = ImageData(geometry=ig0)

        cp0.fill(cp2)
        self.assertBlockDataContainerEqual(cp0, cp2)