예제 #1
0
    def test_BlockGeometry_allocate_dtype(self):
        ig1 = ImageGeometry(3,3)
        ig2 = ImageGeometry(3,3, dtype=numpy.int16)
        bg = BlockGeometry(ig1,ig2)

        # print("The default dtype of the BlockImageGeometry is {}".format(bg.dtype))   
        self.assertEqual(bg.dtype, (numpy.float32, numpy.int16))
예제 #2
0
    def test_ScaledBlockOperatorSingleScalar(self):
        ig = [ ImageGeometry(10,20,30) , \
               ImageGeometry(10,20,30) , \
               ImageGeometry(10,20,30) ]
        x = [g.allocate() for g in ig]
        ops = [IdentityOperator(g) for g in ig]

        val = 1
        # test limit as non Scaled
        scalar = 1
        k = BlockOperator(*ops)
        K = scalar * k
        X = BlockDataContainer(*x) + val

        Y = K.T.direct(X)
        self.assertTrue(Y.shape == (1, 1))
        zero = numpy.zeros(X.get_item(0).shape)
        xx = numpy.asarray([val for _ in x])
        numpy.testing.assert_array_equal(
            Y.get_item(0).as_array(), ((scalar * xx).sum() + zero))

        scalar = 0.5
        k = BlockOperator(*ops)
        K = scalar * k
        X = BlockDataContainer(*x) + 1

        Y = K.T.direct(X)
        self.assertTrue(Y.shape == (1, 1))
        zero = numpy.zeros(X.get_item(0).shape)
        numpy.testing.assert_array_equal(
            Y.get_item(0).as_array(), scalar * (len(x) + zero))
예제 #3
0
    def test_ImageDataSubset(self):
        new_order = ['horizontal_x', 'channel', 'horizontal_y']


        vgeometry = ImageGeometry(voxel_num_x=4, voxel_num_y=3, channels=2, dimension_labels=new_order)
        # expected dimension_labels
        
        self.assertListEqual(new_order,
                              list(vgeometry.dimension_labels))
        vol = vgeometry.allocate()

        # test reshape
        new_order = ['channel', 'horizontal_y','horizontal_x']
        vol.reorder(new_order)

        self.assertListEqual(new_order, list(vol.geometry.dimension_labels))

        ss1 = vol.get_slice(horizontal_x = 0)
        self.assertListEqual(['channel', 'horizontal_y'], list(ss1.geometry.dimension_labels))

        vg = ImageGeometry(3,4,5,channels=2)
        self.assertListEqual([ImageGeometry.CHANNEL, ImageGeometry.VERTICAL,
                ImageGeometry.HORIZONTAL_Y, ImageGeometry.HORIZONTAL_X],
                              list(vg.dimension_labels))
        ss2 = vg.allocate()
        ss3 = vol.get_slice(channel=0)
        self.assertListEqual([ImageGeometry.HORIZONTAL_Y, ImageGeometry.HORIZONTAL_X], list(ss3.geometry.dimension_labels))
예제 #4
0
    def test_ScaledBlockOperatorScalarList(self):
        ig = [ ImageGeometry(2,3) , \
               #ImageGeometry(10,20,30) , \
               ImageGeometry(2,3    ) ]
        x = [g.allocate() for g in ig]
        ops = [IdentityOperator(g) for g in ig]

        # test limit as non Scaled
        scalar = numpy.asarray([1 for _ in x])
        k = BlockOperator(*ops)
        K = scalar * k
        val = 1
        X = BlockDataContainer(*x) + val

        Y = K.T.direct(X)
        self.assertTrue(Y.shape == (1, 1))
        zero = numpy.zeros(X.get_item(0).shape)
        xx = numpy.asarray([val for _ in x])
        numpy.testing.assert_array_equal(
            Y.get_item(0).as_array(), (scalar * xx).sum() + zero)

        scalar = numpy.asarray([i + 1 for i, el in enumerate(x)])
        #scalar = numpy.asarray([6,0])
        k = BlockOperator(*ops)
        K = scalar * k
        X = BlockDataContainer(*x) + val
        Y = K.T.direct(X)
        self.assertTrue(Y.shape == (1, 1))
        zero = numpy.zeros(X.get_item(0).shape)
        xx = numpy.asarray([val for _ in x])

        numpy.testing.assert_array_equal(
            Y.get_item(0).as_array(), (scalar * xx).sum() + zero)
예제 #5
0
    def test_axpby_ab_blockdc(self):
        # test axpby between BlockDataContainers, with a and b as a blockdatacontainer

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

        data0 = ig0.allocate(-1)
        data2 = ig0.allocate(1)

        data1 = ig0.allocate(2)
        data3 = ig0.allocate(3)

        a1 = ig0.allocate(3)
        a2 = ig0.allocate(2)

        b1 = ig0.allocate(-2)
        b2 = ig0.allocate(-3)

        cp0 = BlockDataContainer(data0, data2)
        cp1 = BlockDataContainer(data1, data3)
        a = BlockDataContainer(a1, a2)
        b = BlockDataContainer(b1, b2)

        out = cp0 * 0. - 10

        cp0.axpby(a, b, cp1, out, num_threads=4)

        # operation should be [  3 * -1 + (-2) * 2 , 2 * 1 + (-3) * 3 ]
        # output should be [ -7 , -7 ]
        res0 = ig0.allocate(-7)
        res2 = ig0.allocate(-7)
        res = BlockDataContainer(res0, res2)

        self.assertBlockDataContainerEqual(out, res)
예제 #6
0
    def test_axpby4(self):
        # test axpby with nested BlockDataContainer
        ig0 = ImageGeometry(2, 3, 4)
        ig1 = ImageGeometry(2, 3, 5)

        data0 = ig0.allocate(-1)
        data2 = ig0.allocate(1)

        # data1 = ig0.allocate(2)
        data3 = ig1.allocate(3)

        cp0 = BlockDataContainer(data0, data2)
        cp1 = BlockDataContainer(cp0 * 0. + [2, -2], data3)

        out = cp1 * 0.
        cp2 = out + [1, 3]

        cp2.axpby(3, -2, cp1, out, num_threads=4)

        # output should be [ [ -1 , 7 ] , 3]
        res0 = ig0.allocate(-1)
        res2 = ig0.allocate(7)
        res3 = ig1.allocate(3)
        res = BlockDataContainer(BlockDataContainer(res0, res2), res3)

        self.assertBlockDataContainerEqual(out, res)
    def test_ChannelwiseOperator(self):
        print("test_ChannelwiseOperator")

        M = 3
        channels = 4
        ig = ImageGeometry(M, M, channels=channels)
        igs = ImageGeometry(M, M)
        x = ig.allocate('random', seed=100)
        diag = igs.allocate('random', seed=101)

        D = DiagonalOperator(diag)
        C = ChannelwiseOperator(D, channels)

        y = C.direct(x)

        y2 = ig.allocate()
        C.direct(x, y2)

        for c in range(channels):
            numpy.testing.assert_array_equal(y.subset(channel=2).as_array(), \
                                             (diag*x.subset(channel=2)).as_array())
            numpy.testing.assert_array_equal(y2.subset(channel=2).as_array(), \
                                             (diag*x.subset(channel=2)).as_array())

        z = C.adjoint(y)

        z2 = ig.allocate()
        C.adjoint(y, z2)

        for c in range(channels):
            numpy.testing.assert_array_equal(z.subset(channel=2).as_array(), \
                                             (diag*(diag*x.subset(channel=2))).as_array())
            numpy.testing.assert_array_equal(z2.subset(channel=2).as_array(), \
                                             (diag*(diag*x.subset(channel=2))).as_array())
예제 #8
0
    def test_axpby(self):
        # test axpby between BlockDataContainers
        ig0 = ImageGeometry(2, 3, 4)
        ig1 = ImageGeometry(2, 3, 5)

        data0 = ig0.allocate(-1)
        data2 = ig0.allocate(1)

        data1 = ig0.allocate(2)
        data3 = ig0.allocate(3)

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

        out = cp0 * 0. - 10

        cp0.axpby(3, -2, cp1, out, num_threads=4)

        # operation should be [  3 * -1 + (-2) * 2 , 3 * 1 + (-2) * 3 ]
        # output should be [ -7 , -3 ]
        res0 = ig0.allocate(-7)
        res2 = ig0.allocate(-3)
        res = BlockDataContainer(res0, res2)

        self.assertBlockDataContainerEqual(out, res)
    def test_get_ImageGeometry(self):

        AG = AcquisitionGeometry.create_Parallel2D()\
            .set_panel(num_pixels=[512,1],pixel_size=[0.1,0.1])      
        IG = AG.get_ImageGeometry()
        IG_gold = ImageGeometry(512,512,0,0.1,0.1,1,0,0,0,1)
        self.assertEqual(IG, IG_gold)

        AG = AcquisitionGeometry.create_Parallel3D()\
            .set_panel(num_pixels=[512,3],pixel_size=[0.1,0.2])
        IG = AG.get_ImageGeometry()
        IG_gold = ImageGeometry(512,512,3,0.1,0.1,0.2,0,0,0,1)
        self.assertEqual(IG, IG_gold)

        AG = AcquisitionGeometry.create_Cone2D(source_position=[0,-500], detector_position=[0.,500.])\
            .set_panel(num_pixels=[512,1],pixel_size=[0.1,0.2])
        IG = AG.get_ImageGeometry()
        IG_gold = ImageGeometry(512,512,0,0.05,0.05,1,0,0,0,1)
        self.assertEqual(IG, IG_gold)

        AG = AcquisitionGeometry.create_Cone3D(source_position=[0,-500,0], detector_position=[0.,500.,0])\
            .set_panel(num_pixels=[512,3],pixel_size=[0.1,0.2])
        IG = AG.get_ImageGeometry()
        IG_gold = ImageGeometry(512,512,3,0.05,0.05,0.1,0,0,0,1)
        self.assertEqual(IG, IG_gold)

        AG = AcquisitionGeometry.create_Cone3D(source_position=[0,-500,0], detector_position=[0.,500.,0])\
            .set_panel(num_pixels=[512,3],pixel_size=[0.1,0.2])
        IG = AG.get_ImageGeometry(resolution=0.5)
        IG_gold = ImageGeometry(256,256,2,0.025,0.025,0.05,0,0,0,1)
        self.assertEqual(IG, IG_gold)
예제 #10
0
    def test_ImageData(self):
        # create ImageData from geometry
        vgeometry = ImageGeometry(voxel_num_x=4, voxel_num_y=3, channels=2)
        #vol = ImageData(geometry=vgeometry)
        vol = vgeometry.allocate()
        self.assertEqual(vol.shape, (2, 3, 4))

        vol1 = vol + 1
        self.assertNumpyArrayEqual(vol1.as_array(), numpy.ones(vol.shape))

        vol1 = vol - 1
        self.assertNumpyArrayEqual(vol1.as_array(), -numpy.ones(vol.shape))

        vol1 = 2 * (vol + 1)
        self.assertNumpyArrayEqual(vol1.as_array(), 2 * numpy.ones(vol.shape))

        vol1 = (vol + 1) / 2
        self.assertNumpyArrayEqual(vol1.as_array(), numpy.ones(vol.shape) / 2)

        vol1 = vol + 1
        self.assertEqual(vol1.sum(), 2*3*4)
        vol1 = (vol + 2) ** 2
        self.assertNumpyArrayEqual(vol1.as_array(), numpy.ones(vol.shape) * 4)

        self.assertEqual(vol.number_of_dimensions, 3)
        
        ig2 = ImageGeometry (voxel_num_x=2,voxel_num_y=3,voxel_num_z=4, 
                     dimension_labels=[ImageGeometry.HORIZONTAL_X, ImageGeometry.HORIZONTAL_Y,
                 ImageGeometry.VERTICAL])
        data = ig2.allocate()
        self.assertNumpyArrayEqual(numpy.asarray(data.shape), numpy.asarray(ig2.shape))
        self.assertNumpyArrayEqual(numpy.asarray(data.shape), data.as_array().shape)
예제 #11
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)
 def setUp(self):
     N, M = 20, 30
     K = 20
     C = 20
     self.decimal = 1
     self.iterations = 50
     ###########################################################################
     # 2D geometry no channels
     self.ig = ImageGeometry(N, M)
     self.ig2 = ImageGeometry(N, M, channels=C)
     self.ig3 = ImageGeometry(N, M, K)
예제 #13
0
    def test_read_as_ImageData_Exceptions(self):
        igs = [ImageGeometry(10, 11, 12, channels=5)]
        igs.append(ImageGeometry(12, 32))
        reader = TIFFStackReader(file_name=self.data_dir)

        for geom in igs:
            try:
                img = reader.read_as_ImageData(geom)
                assert False
            except ValueError as ve:
                print(ve)
                assert True
예제 #14
0
    def setUp(self):
        ig0 = ImageGeometry(2, 3, 4)
        ig1 = ImageGeometry(2, 3, 5)

        data0 = ig0.allocate(-1)
        data2 = ig1.allocate(1)

        # data1 = ig0.allocate(2)
        # data3 = ig1.allocate(3)

        cp0 = BlockDataContainer(data0, data2)
        self.ig0 = ig0
        self.ig1 = ig1
        self.cp0 = cp0
예제 #15
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)
예제 #16
0
    def test_NestedBlockDataContainer(self):
        ig0 = ImageGeometry(2,3,4)
        ig1 = ImageGeometry(2,3,5)
        
        data0 = ig0.allocate(0)
        data2 = ig0.allocate(1)
        
        cp0 = BlockDataContainer(data0,data2)
        #cp1 = BlockDataContainer(data2,data3)

        nested = BlockDataContainer(cp0, data2, data2)
        out = BlockDataContainer(BlockDataContainer(data0 , data0), data0, data0)
        nested.divide(data2,out=out)
        self.assertBlockDataContainerEqual(out, nested)
예제 #17
0
    def test_GD(self):
        print("Test GD")
        ig = ImageGeometry(12, 13, 14)
        initial = ig.allocate()
        # b = initial.copy()
        # fill with random numbers
        # b.fill(numpy.random.random(initial.shape))
        b = ig.allocate('random')
        identity = IdentityOperator(ig)

        norm2sq = LeastSquares(identity, b)
        rate = norm2sq.L / 3.

        alg = GD(initial=initial,
                 objective_function=norm2sq,
                 rate=rate,
                 atol=1e-9,
                 rtol=1e-6)
        alg.max_iteration = 1000
        alg.run(verbose=0)
        self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())
        alg = GD(initial=initial,
                 objective_function=norm2sq,
                 rate=rate,
                 max_iteration=20,
                 update_objective_interval=2,
                 atol=1e-9,
                 rtol=1e-6)
        alg.max_iteration = 20
        self.assertTrue(alg.max_iteration == 20)
        self.assertTrue(alg.update_objective_interval == 2)
        alg.run(20, verbose=0)
        self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())
예제 #18
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)
예제 #19
0
    def test_FISTA_Norm2Sq(self):
        print("Test FISTA Norm2Sq")
        ig = ImageGeometry(127, 139, 149)
        b = ig.allocate(ImageGeometry.RANDOM)
        # fill with random numbers
        initial = ig.allocate(ImageGeometry.RANDOM)
        identity = IdentityOperator(ig)

        #### it seems FISTA does not work with Nowm2Sq
        norm2sq = LeastSquares(identity, b)
        #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))
        alg = FISTA(initial=initial, f=norm2sq, g=ZeroFunction())
        alg.max_iteration = 2
        alg.run(20, verbose=0)
        self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())

        alg = FISTA(initial=initial,
                    f=norm2sq,
                    g=ZeroFunction(),
                    max_iteration=2,
                    update_objective_interval=3)
        self.assertTrue(alg.max_iteration == 2)
        self.assertTrue(alg.update_objective_interval == 3)

        alg.run(20, verbose=0)
        self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())
예제 #20
0
    def test_CGLS(self):
        print("Test CGLS")
        #ig = ImageGeometry(124,153,154)
        ig = ImageGeometry(10, 2)
        numpy.random.seed(2)
        initial = ig.allocate(0.)
        b = ig.allocate('random')
        # b = initial.copy()
        # fill with random numbers
        # b.fill(numpy.random.random(initial.shape))
        # b = ig.allocate()
        # bdata = numpy.reshape(numpy.asarray([i for i in range(20)]), (2,10))
        # b.fill(bdata)
        identity = IdentityOperator(ig)

        alg = CGLS(initial=initial, operator=identity, data=b)
        alg.max_iteration = 200
        alg.run(20, verbose=0)
        self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())

        alg = CGLS(initial=initial,
                   operator=identity,
                   data=b,
                   max_iteration=200,
                   update_objective_interval=2)
        self.assertTrue(alg.max_iteration == 200)
        self.assertTrue(alg.update_objective_interval == 2)
        alg.run(20, verbose=0)
        self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())
예제 #21
0
    def setUp(self):
        ig = ImageGeometry(2, 3, 2)
        data = ig.allocate(1, dtype=np.float32)
        noisy_data = data + 1

        # TV regularisation parameter
        self.alpha = 1

        self.fidelities = [
            0.5 * L2NormSquared(b=noisy_data),
            L1Norm(b=noisy_data),
            KullbackLeibler(b=noisy_data, use_numba=False)
        ]

        F = self.alpha * MixedL21Norm()
        K = GradientOperator(ig)

        # Compute operator Norm
        normK = K.norm()

        # Primal & dual stepsizes
        self.sigma = 1. / normK
        self.tau = 1. / normK
        self.F = F
        self.K = K
예제 #22
0
def test_ConstantFunction(self):      
        
        M, N, K = 3,4,5
        ig = ImageGeometry(M, N, K)
        
        tmp = ig.allocate('random_int')
        
        constant = 10
        f = ConstantFunction(constant)
        
        # check call
        res1 = f(tmp)
        self.assertAlmostEqual(res1, constant)
        
        # check gradient with and without out
        res1 = f.gradient(tmp)
        out = ig.allocate()
        self.assertNumpyArrayAlmostEqual(res1.as_array(), out)
        
        out1 = ig.allocate()
        f.gradient(tmp, out=out1)
        self.assertNumpyArrayAlmostEqual(res1.as_array(), out1)
        
        # check convex conjugate        
        res1 = f.convex_conjugate(tmp)
        res2 = tmp.maximum(0).sum()
        self.assertNumpyArrayAlmostEqual(res1.as_array(), res2.as_array())
        
        # check proximal 
        tau = 0.4
        res1 = f.proximal(tmp, tau)
        self.assertNumpyArrayAlmostEqual(res1.as_array(), tmp.as_array()) 
예제 #23
0
    def test_L1Norm_2D(self):
        model = 12 # select a model number from the library
        N = 400 # set dimension of the phantom
        path = os.path.dirname(tomophantom.__file__)
        path_library2D = os.path.join(path, "Phantom2DLibrary.dat")

        phantom_2D = TomoP2D.Model(model, N, path_library2D)    
        # data = ImageData(phantom_2D)
        ig = ImageGeometry(voxel_num_x=N, voxel_num_y=N)
        data = ig.allocate(None)
        data.fill(phantom_2D)

        # Create acquisition data and geometry
        detectors = N
        angles = np.linspace(0, 180, 120, dtype=np.float32)

        ag = AcquisitionGeometry.create_Parallel2D()\
            .set_angles(angles, angle_unit=AcquisitionGeometry.DEGREE)\
            .set_panel(detectors)
        sin = ag.allocate(None)
        sino = TomoP2D.ModelSino(model, detectors, detectors, angles, path_library2D)
        sin.fill(sino)
        sin_stripe = sin.copy()
        #        sin_stripe = sin
        tmp = sin_stripe.as_array()
        tmp[:,::27]=tmp[:,::28]
        sin_stripe.fill(tmp)

        ring_recon = RingRemover(20, "db15", 21, info = True)(sin_stripe)

        error = (ring_recon - sin).abs().as_array().mean()
        print ("L1Norm ", error)
        np.testing.assert_almost_equal(error, 83.20592, 4)
예제 #24
0
    def test_sapyb_datacontainer_scalar_f(self):
        #mix: a scalar and b DataContainer and a DataContainer and b scalar
        ig = ImageGeometry(10,10)                                               
        d1 = ig.allocate(1., dtype=numpy.complex64)                                                     
        d2 = ig.allocate(2.,dtype=numpy.complex64)   
        a = 2.+2j                                                
        b = ig.allocate(-1.-1j, dtype=numpy.complex64)         


        out = ig.allocate(-1,dtype=numpy.complex64)
        # equals to (2+2j)*[1] + -(1+j)*[2] = 0
        
        out = d1.sapyb(a,d2,b)
        res = ig.allocate(0, dtype=numpy.complex64)
        numpy.testing.assert_array_equal(res.as_array(), out.as_array())

        out.fill(-1)
        d1.sapyb(a,d2,b, out)
        numpy.testing.assert_array_equal(res.as_array(), out.as_array())

        out = d2.sapyb(b,d1,a)
        res = ig.allocate(0, dtype=numpy.complex64)
        numpy.testing.assert_array_equal(res.as_array(), out.as_array())

        out.fill(-1)
        d2.sapyb(b,d1,a, out)
        numpy.testing.assert_array_equal(res.as_array(), out.as_array())
    def setUp(self, *args, **kwargs):

        M, N, K = 3, 4, 5
        self.ig = ImageGeometry(M, N, K)

        self.x = self.ig.allocate('random', seed=1)
        self.b = self.ig.allocate('random', seed=2)
        self.eta = self.ig.allocate(0.1)

        self.operator = IdentityOperator(self.ig)

        scalar = 0.25
        self.f1 = L2NormSquared()
        self.f2 = L1Norm()
        self.f3 = scalar * L2NormSquared()
        self.f4 = scalar * L1Norm()
        self.f5 = scalar * L2NormSquared(b=self.b)
        self.f6 = scalar * L1Norm(b=self.b)
        self.f7 = ZeroFunction()
        self.f8 = 5 * ConstantFunction(10)
        self.f9 = LeastSquares(self.operator, self.b, c=scalar)
        self.f10 = 0.5 * KullbackLeibler(b=self.b, eta=self.eta)
        self.f11 = KullbackLeibler(b=self.b, eta=self.eta)
        self.f12 = 10

        self.list1 = [self.f1, self.f2, self.f3, self.f4, self.f5, \
                    self.f6, self.f7, self.f8, self.f9, self.f10, self.f11, self.f12]
예제 #26
0
    def test_Function(self):

        numpy.random.seed(10)
        N = 3
        ig = ImageGeometry(N, N)
        ag = ig
        op1 = GradientOperator(ig)
        op2 = IdentityOperator(ig, ag)

        # Form Composite Operator
        operator = BlockOperator(op1, op2, shape=(2, 1))

        # Create functions
        noisy_data = ag.allocate(ImageGeometry.RANDOM)

        d = ag.allocate(ImageGeometry.RANDOM)
        alpha = 0.5
        # scaled function
        g = alpha * L2NormSquared(b=noisy_data)

        # Compare call of g
        a2 = alpha * (d - noisy_data).power(2).sum()
        #print(a2, g(d))
        self.assertEqual(a2, g(d))

        # Compare convex conjugate of g
        a3 = 0.5 * d.squared_norm() + d.dot(noisy_data)
        self.assertAlmostEqual(a3, g.convex_conjugate(d), places=7)
예제 #27
0
    def test_mixedL12Norm(self):
        numpy.random.seed(1)
        M, N, K = 2, 3, 5
        ig = ImageGeometry(voxel_num_x=M, voxel_num_y=N)
        u1 = ig.allocate('random')
        u2 = ig.allocate('random')

        U = BlockDataContainer(u1, u2, shape=(2, 1))

        # Define no scale and scaled
        f_no_scaled = MixedL21Norm()
        f_scaled = 1 * MixedL21Norm()

        # call

        a1 = f_no_scaled(U)
        a2 = f_scaled(U)
        self.assertNumpyArrayAlmostEqual(a1, a2)

        tmp = [el**2 for el in U.containers]
        self.assertBlockDataContainerEqual(BlockDataContainer(*tmp),
                                           U.power(2))

        z1 = f_no_scaled.proximal_conjugate(U, 1)
        u3 = ig.allocate('random')
        u4 = ig.allocate('random')

        z3 = BlockDataContainer(u3, u4, shape=(2, 1))

        f_no_scaled.proximal_conjugate(U, 1, out=z3)
        self.assertBlockDataContainerAlmostEqual(z3, z1, decimal=5)
예제 #28
0
    def test_sapyb_datacontainer_c(self):
        #a vec, b vec
        ig = ImageGeometry(10,10)                                               
        d1 = ig.allocate(dtype=numpy.complex64)                                                     
        d2 = ig.allocate(dtype=numpy.complex64)   
        a = ig.allocate(dtype=numpy.complex64)                                                  
        b = ig.allocate(dtype=numpy.complex64)         

        arr = numpy.empty(ig.shape, dtype=numpy.complex64)
        arr.real = numpy.asarray(numpy.arange(1,101).reshape(10,10), dtype=numpy.float32)
        arr.imag = numpy.asarray(numpy.arange(1,101).reshape(10,10), dtype=numpy.float32)

        d1.fill(arr)

        arr.imag = -1* arr.imag
        d2.fill(arr)

        a.fill(d2.as_array())                                                  
        b.fill(d1.as_array())   

        out = ig.allocate(-1,dtype=numpy.complex64)
        # equals to d1^ * d1 + d2^*d2 = d1**2 + d2**2 = 2* arr.norm = 2 * (arr.real **2 + arr.imag **2)
        out = d1.sapyb(a,d2,b)
        res = 2* (arr.real * arr.real + arr.imag * arr.imag)
        numpy.testing.assert_array_equal(res, out.as_array())

        out.fill(0)
        d1.sapyb(a,d2,b, out)
        numpy.testing.assert_array_equal(res, out.as_array())
예제 #29
0
    def test_Norm(self):
        print("test_BlockOperator")
        ##
        numpy.random.seed(1)
        N, M = 200, 300

        ig = ImageGeometry(N, M)
        G = GradientOperator(ig)
        t0 = timer()
        norm = G.norm()
        t1 = timer()
        norm2 = G.norm()
        t2 = timer()
        norm3 = G.norm(force=True)
        t3 = timer()
        print("Norm dT1 {} dT2 {} dT3 {}".format(t1 - t0, t2 - t1, t3 - t2))
        self.assertLess(t2 - t1, t1 - t0)
        self.assertLess(t2 - t1, t3 - t2)

        numpy.random.seed(1)
        t4 = timer()
        norm4 = G.norm(iterations=50, force=True)
        t5 = timer()
        self.assertLess(t2 - t1, t5 - t4)

        numpy.random.seed(1)
        t4 = timer()
        norm5 = G.norm(x_init=ig.allocate('random'), iterations=50, force=True)
        t5 = timer()
        self.assertLess(t2 - t1, t5 - t4)
        for n in [norm, norm2, norm3, norm4, norm5]:
            print("norm {}", format(n))
    def test_PDHG_strongly_convex_gamma_g(self):

        ig = ImageGeometry(3,3)
        data = ig.allocate('random')

        f = L2NormSquared(b=data)
        g = L2NormSquared()
        operator = IdentityOperator(ig)

        # sigma, tau 
        sigma = 1.0
        tau  = 1.0        

        pdhg = PDHG(f=f, g=g, operator=operator, sigma = sigma, tau=tau,
                    max_iteration=5, gamma_g=0.5)
        pdhg.run(1, verbose=0)
        self.assertAlmostEquals(pdhg.theta, 1.0/ np.sqrt(1 + 2 * pdhg.gamma_g * tau))
        self.assertAlmostEquals(pdhg.tau, tau * pdhg.theta)
        self.assertAlmostEquals(pdhg.sigma, sigma / pdhg.theta)
        pdhg.run(4, verbose=0)
        self.assertNotEqual(pdhg.sigma, sigma)
        self.assertNotEqual(pdhg.tau, tau)  

        # check negative strongly convex constant
        with self.assertRaises(ValueError):
            pdhg = PDHG(f=f, g=g, operator=operator, sigma = sigma, tau=tau,
                    max_iteration=5, gamma_g=-0.5)  
        

        # check strongly convex constant not a number
        with self.assertRaises(ValueError):
            pdhg = PDHG(f=f, g=g, operator=operator, sigma = sigma, tau=tau,
                    max_iteration=5, gamma_g="-0.5")