Exemple #1
0
 def direct(self, x, out=None):
     
     '''Returns E(v)'''        
     
     if out is None:
         
         tmp = []
         for i in range(self.domain_geometry().shape[0]):
             for j in range(x.shape[0]):
                 self.FD.direction = i
                 tmp.append(self.FD.adjoint(x.get_item(j)))
                 
         tmp1 = [tmp[i] for i in self.order_ind]        
                 
         res = [0.5 * sum(x) for x in zip(tmp, tmp1)]   
                 
         return BlockDataContainer(*res) 
 
     else:
         
         ind = 0
         for i in range(self.domain_geometry().shape[0]):
             for j in range(x.shape[0]):
                 self.FD.direction = i
                 self.FD.adjoint(x.get_item(j), out=out[ind])
                 ind+=1                    
         out1 = BlockDataContainer(*[out[i] for i in self.order_ind])          
         out.fill( 0.5 * (out + out1) )
Exemple #2
0
    def test_axpby2(self):
        # test axpby with BlockDataContainer and DataContainer
        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(data1,data3)

        out = cp0 * 0. - 10

        cp0.axpby(3, -2, data1, out)

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

        print("res0", res0.as_array())
        print("res2", res2.as_array())

        print("###############################")

        print("out_0", out.get_item(0).as_array())
        print("out_1", out.get_item(1).as_array())
        self.assertBlockDataContainerEqual(out, res)
Exemple #3
0
    def test_mixedL12Norm(self):
        M, N, K = 2, 3, 5
        ig = ImageGeometry(voxel_num_x=M, voxel_num_y=N)
        u1 = ig.allocate('random_int')
        u2 = ig.allocate('random_int')

        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_int')
        u4 = ig.allocate('random_int')

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

        f_no_scaled.proximal_conjugate(U, 1, out=z3)
        self.assertBlockDataContainerEqual(z3, z1)
Exemple #4
0
    def adjoint(self, x, out=None):
        '''Adjoint operation for the BlockOperator

        BlockOperator may contain both LinearOperator and Operator
        This method exists in BlockOperator as it is not known what type of
        Operator it will contain.

        BlockOperator work on BlockDataContainer, but they will work on DataContainers
        and inherited classes by simple wrapping the input in a BlockDataContainer of shape (1,1)

        Raises: ValueError if the contained Operators are not linear
        '''
        if not self.is_linear():
            raise ValueError('Not all operators in Block are linear.')
        if not isinstance(x, BlockDataContainer):
            x_b = BlockDataContainer(x)
        else:
            x_b = x
        shape = self.get_output_shape(x_b.shape, adjoint=True)
        if out is None:
            res = []
            for col in range(self.shape[1]):
                for row in range(self.shape[0]):
                    if row == 0:
                        prod = self.get_item(row,
                                             col).adjoint(x_b.get_item(row))
                    else:
                        prod += self.get_item(row,
                                              col).adjoint(x_b.get_item(row))
                res.append(prod)
            if self.shape[1] == 1:
                # the output is a single DataContainer, so we can take it out
                return res[0]
            else:
                return BlockDataContainer(*res, shape=shape)
        else:

            for col in range(self.shape[1]):
                for row in range(self.shape[0]):
                    if row == 0:
                        if issubclass(out.__class__, DataContainer) or \
                ( has_sirf and issubclass(out.__class__, SIRFDataContainer) ):
                            self.get_item(row, col).adjoint(x_b.get_item(row),
                                                            out=out)
                        else:
                            op = self.get_item(row, col)
                            self.get_item(row,
                                          col).adjoint(x_b.get_item(row),
                                                       out=out.get_item(col))
                    else:
                        if issubclass(out.__class__, DataContainer) or \
                ( has_sirf and issubclass(out.__class__, SIRFDataContainer) ):
                            out += self.get_item(row, col).adjoint(
                                x_b.get_item(row))
                        else:
                            a = out.get_item(col)
                            a += self.get_item(row, col).adjoint(
                                x_b.get_item(row), )
Exemple #5
0
    def skiptest_BlockDataContainerShape(self):
        print("test block data container")
        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)
Exemple #6
0
    def adjoint(self, x, out=None):
        
        if out is None:
            
            tmp = [None]*self.domain_geometry().shape[0]
            i = 0
            
            for k in range(self.domain_geometry().shape[0]):
                tmp1 = 0
                for j in range(self.domain_geometry().shape[0]):
                    self.FD.direction = j
                    tmp1 += self.FD.direct(x[i])                    
                    i+=1
                tmp[k] = tmp1  
            return BlockDataContainer(*tmp)
            

        else:
            
            tmp = self.domain_geometry().allocate() 
            i = 0
            for k in range(self.domain_geometry().shape[0]):
                tmp1 = 0
                for j in range(self.domain_geometry().shape[0]):
                    self.FD.direction = j
                    self.FD.direct(x[i], out=tmp[j])
                    i+=1
                    tmp1+=tmp[j]
                out[k].fill(tmp1)
Exemple #7
0
    def proximal(self, x, tau, out=None):
        r"""Proximal operator of the BlockFunction at x:
        
            .. math:: \mathrm{prox}_{\tau F}(x) =  (\mathrm{prox}_{\tau f_{i}}(x_{i}))_{i=1}^{m}
            
            Parameter:
            
                x : BlockDataContainer and must have as many rows as self.length            
        """

        if self.length != x.shape[0]:
            raise ValueError(
                'BlockFunction and BlockDataContainer have incompatible size')

        if out is None:

            out = [None] * self.length
            if isinstance(tau, Number):
                for i in range(self.length):
                    out[i] = self.functions[i].proximal(x.get_item(i), tau)
            else:
                for i in range(self.length):
                    out[i] = self.functions[i].proximal(
                        x.get_item(i), tau.get_item(i))

            return BlockDataContainer(*out)

        else:
            if isinstance(tau, Number):
                for i in range(self.length):
                    self.functions[i].proximal(x.get_item(i), tau, out[i])
            else:
                for i in range(self.length):
                    self.functions[i].proximal(x.get_item(i), tau.get_item(i),
                                               out[i])
Exemple #8
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)
Exemple #9
0
    def sum_abs_col(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_col()
                else:
                    prod += self.get_item(row, col).sum_abs_col()
            res.append(prod)

        return BlockDataContainer(*res)
Exemple #10
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)

        print("res0", res0.as_array())
        print("res2", res2.as_array())

        print("###############################")

        print("out_0", out.get_item(0).as_array())
        print("out_1", out.get_item(1).as_array())
        self.assertBlockDataContainerEqual(out, res)
Exemple #11
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)
Exemple #12
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)
Exemple #13
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)
Exemple #14
0
    def allocate(self, value=0, dimension_labels=None, **kwargs):

        max_value = kwargs.get('max_value', 100)
        symmetry = kwargs.get('symmetry', False)
        containers = [
            geom.allocate(value, max_value=max_value)
            for geom in self.geometries
        ]

        if symmetry == True:

            # for 2x2
            # [ ig11, ig12\
            #   ig21, ig22]

            # Row-wise Order

            if len(containers) == 4:
                containers[1] = containers[2]

            # for 3x3
            # [ ig11, ig12, ig13\
            #   ig21, ig22, ig23\
            #   ig31, ig32, ig33]

            elif len(containers) == 9:
                containers[1] = containers[3]
                containers[2] = containers[6]
                containers[5] = containers[7]

            # for 4x4
            # [ ig11, ig12, ig13, ig14\
            #   ig21, ig22, ig23, ig24\
            #   ig31, ig32, ig33, ig34
            #   ig41, ig42, ig43, ig44]

            elif len(containers) == 16:
                containers[1] = containers[4]
                containers[2] = containers[8]
                containers[3] = containers[12]
                containers[6] = containers[9]
                containers[7] = containers[10]
                containers[11] = containers[15]

        return BlockDataContainer(*containers)
Exemple #15
0
    def gradient(self, x, out=None):
        r"""Returns the value of the gradient of the BlockFunction function at x.
        
        .. math:: F'(x) = [f_{1}'(x_{1}), ... , f_{m}'(x_{m})]        
        
        Parameter:
            
            x : BlockDataContainer and must have as many rows as self.length
                
        """

        if self.length != x.shape[0]:
            raise ValueError(
                'BlockFunction and BlockDataContainer have incompatible size')

        out = [None] * self.length
        for i in range(self.length):
            out[i] = self.functions[i].gradient(x.get_item(i))

        return BlockDataContainer(*out)
Exemple #16
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)
        print(cp1.get_item(0).get_item(0).as_array())
        print(cp1.get_item(0).get_item(1).as_array())
        print(cp1.get_item(1).as_array())
        print("###############################")

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

        print(cp2.get_item(0).get_item(0).as_array())
        print(cp2.get_item(0).get_item(1).as_array())
        print(cp2.get_item(1).as_array())

        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)

        # print ("res0", res0.as_array())
        # print ("res2", res2.as_array())

        print("###############################")

        # print ("out_0", out.get_item(0).as_array())
        # print ("out_1", out.get_item(1).as_array())
        self.assertBlockDataContainerEqual(out, res)
Exemple #17
0
    def direct(self, x, out=None):
        '''Direct operation for the BlockOperator

        BlockOperator work on BlockDataContainer, but they will work on DataContainers
        and inherited classes by simple wrapping the input in a BlockDataContainer of shape (1,1)
        '''

        if not isinstance(x, BlockDataContainer):
            x_b = BlockDataContainer(x)
        else:
            x_b = x
        shape = self.get_output_shape(x_b.shape)
        res = []

        if out is None:

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

        else:

            tmp = self.range_geometry().allocate()
            for row in range(self.shape[0]):
                for col in range(self.shape[1]):
                    if col == 0:
                        self.get_item(row, col).direct(x_b.get_item(col),
                                                       out=out.get_item(row))
                    else:
                        a = out.get_item(row)
                        self.get_item(row, col).direct(x_b.get_item(col),
                                                       out=tmp.get_item(row))
                        a += tmp.get_item(row)
Exemple #18
0
    def test_Nested_BlockDataContainer(self):
        print("test_Nested_BlockDataContainer")
        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
        data0 = ig0.allocate(0.)
        data1 = ig1.allocate(1.)

        data2 = ig0.allocate(2.)
        data3 = ig1.allocate(3.)

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

        nbdc = BlockDataContainer(cp0, cp1)
        nbdc2 = nbdc + 2
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(0).as_array()[0][0][0], 2., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(1).as_array()[0][0][0], 3., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(0).as_array()[0][0][0], 4., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(1).as_array()[0][0][0], 5., decimal=5)

        nbdc2 = 2 + nbdc
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(0).as_array()[0][0][0], 2., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(1).as_array()[0][0][0], 3., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(0).as_array()[0][0][0], 4., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(1).as_array()[0][0][0], 5., decimal=5)

        nbdc2 = nbdc * 2
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(0).as_array()[0][0][0], 0., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(1).as_array()[0][0][0], 2., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(0).as_array()[0][0][0], 4., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(1).as_array()[0][0][0], 6., decimal=5)

        nbdc2 = 2 * nbdc
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(0).as_array()[0][0][0], 0., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(1).as_array()[0][0][0], 2., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(0).as_array()[0][0][0], 4., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(1).as_array()[0][0][0], 6., decimal=5)

        nbdc2 = nbdc / 2
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(0).as_array()[0][0][0], 0., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(0).get_item(1).as_array()[0][0][0], .5, decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(0).as_array()[0][0][0], 1., decimal=5)
        numpy.testing.assert_almost_equal(
            nbdc2.get_item(1).get_item(1).as_array()[0][0][0],
            3. / 2,
            decimal=5)

        c5 = nbdc.get_item(0).power(2).sum()
        c5a = nbdc.power(2).sum()
        print("sum", c5a, c5)

        cp0 = BlockDataContainer(data0, data2)
        a = cp0 * data2
        b = data2 * cp0
        self.assertBlockDataContainerEqual(a, b)

        print("test_Nested_BlockDataContainer OK")
Exemple #19
0
# Setup and run the simple CGLS algorithm
x_init = ig.allocate()

cgls1 = CGLS(x_init=x_init, operator=Aop, data=noisy_data)
cgls1.max_iteration = 20
cgls1.update_objective_interval = 5
cgls1.run(20, verbose=True)

# Setup and run the regularised CGLS algorithm  (Tikhonov with Identity)

x_init = ig.allocate()
alpha1 = 50
op1 = Identity(ig)

block_op1 = BlockOperator(Aop, alpha1 * op1, shape=(2, 1))
block_data1 = BlockDataContainer(noisy_data, op1.range_geometry().allocate())

cgls2 = CGLS(x_init=x_init, operator=block_op1, data=block_data1)
cgls2.max_iteration = 200
cgls2.update_objective_interval = 10
cgls2.run(200, verbose=True)

# Setup and run the regularised CGLS algorithm  (Tikhonov with Gradient)

x_init = ig.allocate()
alpha2 = 25
op2 = Gradient(ig)

block_op2 = BlockOperator(Aop, alpha2 * op2, shape=(2, 1))
block_data2 = BlockDataContainer(noisy_data, op2.range_geometry().allocate())
Exemple #20
0
    def test_BlockOperator(self):
        print ("test_BlockOperator")
        
        M, N  = 3, 4
        ig = ImageGeometry(M, N)
        arr = ig.allocate('random_int')  
        
        G = Gradient(ig)
        Id = Identity(ig)
        
        B = BlockOperator(G, Id)
        # Nx1 case
        u = ig.allocate('random_int')
        z1 = B.direct(u)
        
        res = B.range_geometry().allocate()
        #res = z1.copy()
        B.direct(u, out=res)
        
        
        print (type(z1), type(res))
        print (z1.shape)
        print(z1[0][0].as_array())
        print(res[0][0].as_array())   
        self.assertBlockDataContainerEqual(z1, res)
        # for col in range(z1.shape[0]):
        #     a = z1.get_item(col)
        #     b = res.get_item(col)
        #     if isinstance(a, BlockDataContainer):
        #         for col2 in range(a.shape[0]):
        #             self.assertNumpyArrayEqual(
        #                 a.get_item(col2).as_array(), 
        #                 b.get_item(col2).as_array()
        #                 )        
        #     else:
        #         self.assertNumpyArrayEqual(
        #             a.as_array(), 
        #             b.as_array()
        #             )
        z1 = B.range_geometry().allocate(ImageGeometry.RANDOM_INT)

        res1 = B.adjoint(z1)
        res2 = B.domain_geometry().allocate()
        B.adjoint(z1, out=res2)
        
        self.assertNumpyArrayEqual(res1.as_array(), res2.as_array())

        BB = BlockOperator( Id, 2 * Id)
        B = BlockOperator( BB, Id )
        v = B.domain_geometry().allocate()
        B.adjoint(res,out=v)
        vv = B.adjoint(res)
        el1 = B.get_item(0,0).adjoint(z1.get_item(0)) +\
              B.get_item(1,0).adjoint(z1.get_item(1)) 
        print ("el1" , el1.as_array())
        print ("vv" , vv.as_array())
        print ("v" , v.as_array())
        
        self.assertNumpyArrayEqual(v.as_array(),vv.as_array())
        # test adjoint
        print ("############ 2x1 #############")

        BB = BlockOperator( Id, 2 * Id)
        u = ig.allocate(1)
        z1 = BB.direct(u)
        print ("z1 shape {} one\n{} two\n{}".format(z1.shape, 
            z1.get_item(0).as_array(),
            z1.get_item(1).as_array()))
        res = BB.range_geometry().allocate(0)
        BB.direct(u, out=res)
        print ("res shape {} one\n{} two\n{}".format(res.shape, 
            res.get_item(0).as_array(),
            res.get_item(1).as_array()))
        
        
        self.assertNumpyArrayEqual(z1.get_item(0).as_array(),
                                   u.as_array())
        self.assertNumpyArrayEqual(z1.get_item(1).as_array(),
                                   2 * u.as_array())
        self.assertNumpyArrayEqual(res.get_item(0).as_array(),
                                   u.as_array())
        self.assertNumpyArrayEqual(res.get_item(1).as_array(),
                                   2 * u.as_array())

        x1 = BB.adjoint(z1)
        print("adjoint x1\n",x1.as_array())

        res1 = BB.domain_geometry().allocate()
        BB.adjoint(z1, out=res1)
        print("res1\n",res1.as_array())
        self.assertNumpyArrayEqual(x1.as_array(),
                                   res1.as_array())
        
        self.assertNumpyArrayEqual(x1.as_array(),
                                   5 * u.as_array())
        self.assertNumpyArrayEqual(res1.as_array(),
                                   5 * u.as_array())
        #################################################
    
        print ("############ 2x2 #############")
        BB = BlockOperator( Id, 2 * Id, 3 * Id,  Id, shape=(2,2))
        B = BB
        u = ig.allocate(1)
        U = BlockDataContainer(u,u)
        z1 = B.direct(U)


        print ("z1 shape {} one\n{} two\n{}".format(z1.shape, 
            z1.get_item(0).as_array(),
            z1.get_item(1).as_array()))
        self.assertNumpyArrayEqual(z1.get_item(0).as_array(),
                                   3 * u.as_array())
        self.assertNumpyArrayEqual(z1.get_item(1).as_array(),
                                   4 * u.as_array())
        res = B.range_geometry().allocate()
        B.direct(U, out=res)
        self.assertNumpyArrayEqual(res.get_item(0).as_array(),
                                   3 * u.as_array())
        self.assertNumpyArrayEqual(res.get_item(1).as_array(),
                                   4 * u.as_array())
        

        x1 = B.adjoint(z1)
        # this should be [15 u, 10 u]
        el1 = B.get_item(0,0).adjoint(z1.get_item(0)) + B.get_item(1,0).adjoint(z1.get_item(1)) 
        el2 = B.get_item(0,1).adjoint(z1.get_item(0)) + B.get_item(1,1).adjoint(z1.get_item(1)) 

        shape = B.get_output_shape(z1.shape, adjoint=True)
        print ("shape ", shape)
        out = B.domain_geometry().allocate()
        
        for col in range(B.shape[1]):
            for row in range(B.shape[0]):
                if row == 0:
                    el = B.get_item(row,col).adjoint(z1.get_item(row))
                else:
                    el += B.get_item(row,col).adjoint(z1.get_item(row))
            out.get_item(col).fill(el)        

        print ("el1 " , el1.as_array())
        print ("el2 " , el2.as_array())
        print ("out shape {} one\n{} two\n{}".format(out.shape,
            out.get_item(0).as_array(), 
            out.get_item(1).as_array()))
        
        self.assertNumpyArrayEqual(out.get_item(0).as_array(),
                                   15 * u.as_array())
        self.assertNumpyArrayEqual(out.get_item(1).as_array(),
                                   10 * u.as_array())
        
        res2 = B.domain_geometry().allocate()  
        #print (res2, res2.as_array())  
        B.adjoint(z1, out = res2)
        
        #print ("adjoint",x1.as_array(),"\n",res2.as_array())
        self.assertNumpyArrayEqual(
            out.get_item(0).as_array(), 
            res2.get_item(0).as_array()
            )
        self.assertNumpyArrayEqual(
            out.get_item(1).as_array(), 
            res2.get_item(1).as_array()
            )
    
        if True:
            #B1 = BlockOperator(Id, Id, Id, Id, shape=(2,2))
            B1 = BlockOperator(G, Id)
            U = ig.allocate(ImageGeometry.RANDOM_INT)
            #U = BlockDataContainer(u,u)
            RES1 = B1.range_geometry().allocate()
            
            Z1 = B1.direct(U)
            B1.direct(U, out = RES1)
            
            self.assertBlockDataContainerEqual(Z1,RES1)
            
                        
            
            print("U", U.as_array())
            print("Z1", Z1[0][0].as_array())
            print("RES1", RES1[0][0].as_array())
            print("Z1", Z1[0][1].as_array())
            print("RES1", RES1[0][1].as_array())
Exemple #21
0
    def test_BlockDataContainer(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
        data0 = ig0.allocate(0.)
        data1 = ig1.allocate(1.)

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

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

        cp2 = BlockDataContainer(data0 + 1, data2 + 1)
        d = cp2 + data0
        self.assertEqual(d.get_item(0).as_array()[0][0][0], 1)
        try:
            d = cp2 + data1
            self.assertTrue(False)
        except ValueError as ve:
            print(ve)
            self.assertTrue(True)
        d = cp2 - data0
        self.assertEqual(d.get_item(0).as_array()[0][0][0], 1)
        try:
            d = cp2 - data1
            self.assertTrue(False)
        except ValueError as ve:
            print(ve)
            self.assertTrue(True)
        d = cp2 * data2
        self.assertEqual(d.get_item(0).as_array()[0][0][0], 2)
        try:
            d = cp2 * data1
            self.assertTrue(False)
        except ValueError as ve:
            print(ve)
            self.assertTrue(True)

        a = [(el, ot) for el, ot in zip(cp0.containers, cp1.containers)]
        print(a[0][0].shape)
        #cp2 = BlockDataContainer(*a)
        cp2 = cp0.add(cp1)
        self.assertEqual(cp2.get_item(0).as_array()[0][0][0], 2.)
        self.assertEqual(cp2.get_item(1).as_array()[0][0][0], 4.)

        cp2 = cp0 + cp1
        self.assertTrue(cp2.get_item(0).as_array()[0][0][0] == 2.)
        self.assertTrue(cp2.get_item(1).as_array()[0][0][0] == 4.)
        cp2 = cp0 + 1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          1.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          2.,
                                          decimal=5)
        cp2 = cp0 + [1, 2]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          1.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          3.,
                                          decimal=5)
        cp2 += cp1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          +3.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          +6.,
                                          decimal=5)

        cp2 += 1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          +4.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          +7.,
                                          decimal=5)

        cp2 += [-2, -1]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          2.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          6.,
                                          decimal=5)

        cp2 = cp0.subtract(cp1)
        assert (cp2.get_item(0).as_array()[0][0][0] == -2.)
        assert (cp2.get_item(1).as_array()[0][0][0] == -2.)
        cp2 = cp0 - cp1
        assert (cp2.get_item(0).as_array()[0][0][0] == -2.)
        assert (cp2.get_item(1).as_array()[0][0][0] == -2.)

        cp2 = cp0 - 1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          -1.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          0,
                                          decimal=5)
        cp2 = cp0 - [1, 2]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          -1.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          -1.,
                                          decimal=5)

        cp2 -= cp1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          -3.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          -4.,
                                          decimal=5)

        cp2 -= 1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          -4.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          -5.,
                                          decimal=5)

        cp2 -= [-2, -1]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          -2.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          -4.,
                                          decimal=5)

        cp2 = cp0.multiply(cp1)
        assert (cp2.get_item(0).as_array()[0][0][0] == 0.)
        assert (cp2.get_item(1).as_array()[0][0][0] == 3.)
        cp2 = cp0 * cp1
        assert (cp2.get_item(0).as_array()[0][0][0] == 0.)
        assert (cp2.get_item(1).as_array()[0][0][0] == 3.)

        cp2 = cp0 * 2
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          2,
                                          decimal=5)
        cp2 = 2 * cp0
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          2,
                                          decimal=5)
        cp2 = cp0 * [3, 2]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          2.,
                                          decimal=5)
        cp2 = cp0 * numpy.asarray([3, 2])
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          2.,
                                          decimal=5)

        cp2 = [3, 2] * cp0
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          2.,
                                          decimal=5)
        cp2 = numpy.asarray([3, 2]) * cp0
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          2.,
                                          decimal=5)

        try:
            cp2 = [3, 2, 3] * cp0
            #numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0] , 0. , decimal=5)
            #numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0] , 2., decimal = 5)
            self.assertTrue(False)
        except ValueError as ve:
            print(ve)
            self.assertTrue(True)
        cp2 *= cp1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          +6.,
                                          decimal=5)

        cp2 *= 1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          +6.,
                                          decimal=5)

        cp2 *= [-2, -1]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          -6.,
                                          decimal=5)

        try:
            cp2 *= [2, 3, 5]
            self.assertTrue(False)
        except ValueError as ve:
            print(ve)
            self.assertTrue(True)

        cp2 = cp0.divide(cp1)
        assert (cp2.get_item(0).as_array()[0][0][0] == 0.)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          1. / 3.,
                                          decimal=4)
        cp2 = cp0 / cp1
        assert (cp2.get_item(0).as_array()[0][0][0] == 0.)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          1. / 3.,
                                          decimal=4)

        cp2 = cp0 / 2
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          0.5,
                                          decimal=5)
        cp2 = cp0 / [3, 2]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          0.5,
                                          decimal=5)
        cp2 = cp0 / numpy.asarray([3, 2])
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          0.5,
                                          decimal=5)
        cp3 = numpy.asarray([3, 2]) / (cp0 + 1)
        numpy.testing.assert_almost_equal(cp3.get_item(0).as_array()[0][0][0],
                                          3.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp3.get_item(1).as_array()[0][0][0],
                                          1,
                                          decimal=5)

        cp2 += 1
        cp2 /= cp1
        # TODO fix inplace division

        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          1. / 2,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          1.5 / 3.,
                                          decimal=5)

        cp2 /= 1
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.5,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          0.5,
                                          decimal=5)

        cp2 /= [-2, -1]
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          -0.5 / 2.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          -0.5,
                                          decimal=5)
        ####

        cp2 = cp0.power(cp1)
        assert (cp2.get_item(0).as_array()[0][0][0] == 0.)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          1.,
                                          decimal=4)
        cp2 = cp0**cp1
        assert (cp2.get_item(0).as_array()[0][0][0] == 0.)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          1.,
                                          decimal=4)

        cp2 = cp0**2
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=5)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          1.,
                                          decimal=5)

        cp2 = cp0.maximum(cp1)
        assert (cp2.get_item(0).as_array()[0][0][0] == cp1.get_item(
            0).as_array()[0][0][0])
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          cp2.get_item(1).as_array()[0][0][0],
                                          decimal=4)

        cp2 = cp0.abs()
        numpy.testing.assert_almost_equal(cp2.get_item(0).as_array()[0][0][0],
                                          0.,
                                          decimal=4)
        numpy.testing.assert_almost_equal(cp2.get_item(1).as_array()[0][0][0],
                                          1.,
                                          decimal=4)

        cp2 = cp0.subtract(cp1)
        s = cp2.sign()
        numpy.testing.assert_almost_equal(s.get_item(0).as_array()[0][0][0],
                                          -1.,
                                          decimal=4)
        numpy.testing.assert_almost_equal(s.get_item(1).as_array()[0][0][0],
                                          -1.,
                                          decimal=4)

        cp2 = cp0.add(cp1)
        s = cp2.sqrt()
        numpy.testing.assert_almost_equal(s.get_item(0).as_array()[0][0][0],
                                          numpy.sqrt(2),
                                          decimal=4)
        numpy.testing.assert_almost_equal(s.get_item(1).as_array()[0][0][0],
                                          numpy.sqrt(4),
                                          decimal=4)

        s = cp0.sum()
        size = functools.reduce(lambda x, y: x * y, data1.shape, 1)
        print("size", size)
        numpy.testing.assert_almost_equal(s, 0 + size, decimal=4)
        s0 = 1
        s1 = 1
        for i in cp0.get_item(0).shape:
            s0 *= i
        for i in cp0.get_item(1).shape:
            s1 *= i
Exemple #22
0
    dev = 'gpu'
else:
    dev = 'cpu'

Aop = AstraProjectorSimple(ig, ag, dev)
sin = Aop.direct(data)

noisy_data = AcquisitionData(sin.as_array() + np.random.normal(0, 3, ig.shape))

# Setup and run the CGLS algorithm
alpha = 50
Grad = Gradient(ig)

# Form Tikhonov as a Block CGLS structure
op_CGLS = BlockOperator(Aop, alpha * Grad, shape=(2, 1))
block_data = BlockDataContainer(noisy_data, Grad.range_geometry().allocate())

x_init = ig.allocate()
cgls = CGLS(x_init=x_init, operator=op_CGLS, data=block_data)
cgls.max_iteration = 1000
cgls.update_objective_interval = 200
cgls.run(1000, verbose=False)

#Setup and run the PDHG algorithm

# Create BlockOperator
op_PDHG = BlockOperator(Grad, Aop, shape=(2, 1))
# Create functions
f1 = 0.5 * alpha**2 * L2NormSquared()
f2 = 0.5 * L2NormSquared(b=noisy_data)
f = BlockFunction(f1, f2)
Exemple #23
0
    Gy = SparseFiniteDiff(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()

    B.direct(u, out=res)