Esempio n. 1
0
    def test_FBPD_Norm1_cvx(self):
        if not cvx_not_installable:
            opt = {'memopt': True}
            # Problem data.
            m = 30
            n = 20
            np.random.seed(1)
            Amat = np.random.randn(m, n)
            A = LinearOperatorMatrix(Amat)
            bmat = np.random.randn(m)
            bmat.shape = (bmat.shape[0], 1)

            # A = Identity()
            # Change n to equal to m.

            b = DataContainer(bmat)

            # Regularization parameter
            lam = 10
            opt = {'memopt': True}
            # Create object instances with the test data A and b.
            f = Norm2sq(A, b, c=0.5, memopt=True)
            g0 = ZeroFun()

            # Initial guess
            x_init = DataContainer(np.zeros((n, 1)))

            # Create 1-norm object instance
            g1 = Norm1(lam)

            # Compare to CVXPY

            # Construct the problem.
            x1 = Variable(n)
            objective1 = Minimize(0.5 * sum_squares(Amat * x1 - bmat.T[0]) +
                                  lam * norm(x1, 1))
            prob1 = Problem(objective1)

            # The optimal objective is returned by prob.solve().
            result1 = prob1.solve(verbose=False, solver=SCS, eps=1e-9)

            # The optimal solution for x is stored in x.value and optimal objective value
            # is in result as well as in objective.value
            print(
                "CVXPY least squares plus 1-norm solution and objective value:"
            )
            print(x1.value)
            print(objective1.value)

            # Now try another algorithm FBPD for same problem:
            x_fbpd1, itfbpd1, timingfbpd1, criterfbpd1 = FBPD(
                x_init, Identity(), None, f, g1)
            print(x_fbpd1)
            print(criterfbpd1[-1])

            self.assertNumpyArrayAlmostEqual(numpy.squeeze(x_fbpd1.array),
                                             x1.value, 6)
        else:
            self.assertTrue(cvx_not_installable)
Esempio n. 2
0
    def test_FISTA_cvx(self):
        if not cvx_not_installable:
            # Problem data.
            m = 30
            n = 20
            np.random.seed(1)
            Amat = np.random.randn(m, n)
            A = LinearOperatorMatrix(Amat)
            bmat = np.random.randn(m)
            bmat.shape = (bmat.shape[0], 1)

            # A = Identity()
            # Change n to equal to m.

            b = DataContainer(bmat)

            # Regularization parameter
            lam = 10
            opt = {'memopt': True}
            # Create object instances with the test data A and b.
            f = Norm2sq(A, b, c=0.5, memopt=True)
            g0 = ZeroFun()

            # Initial guess
            x_init = DataContainer(np.zeros((n, 1)))

            f.grad(x_init)

            # Run FISTA for least squares plus zero function.
            x_fista0, it0, timing0, criter0 = FISTA(x_init, f, g0, opt=opt)

            # Print solution and final objective/criterion value for comparison
            print(
                "FISTA least squares plus zero function solution and objective value:"
            )
            print(x_fista0.array)
            print(criter0[-1])

            # Compare to CVXPY

            # Construct the problem.
            x0 = Variable(n)
            objective0 = Minimize(0.5 * sum_squares(Amat * x0 - bmat.T[0]))
            prob0 = Problem(objective0)

            # The optimal objective is returned by prob.solve().
            result0 = prob0.solve(verbose=False, solver=SCS, eps=1e-9)

            # The optimal solution for x is stored in x.value and optimal objective value
            # is in result as well as in objective.value
            print(
                "CVXPY least squares plus zero function solution and objective value:"
            )
            print(x0.value)
            print(objective0.value)
            self.assertNumpyArrayAlmostEqual(numpy.squeeze(x_fista0.array),
                                             x0.value, 6)
        else:
            self.assertTrue(cvx_not_installable)
Esempio n. 3
0
 def create_DataContainer(self, X,Y,Z, value=1):
     steps = [timer()]
     a = value * numpy.ones((X, Y, Z), dtype='float32')
     steps.append(timer())
     t0 = dt(steps)
     #print("a refcount " , sys.getrefcount(a))
     ds = DataContainer(a, False, ['X', 'Y', 'Z'])
     return ds
Esempio n. 4
0
 def prox(self,x,tau):
     pars = {'algorithm' : ROF_TV, \
            'input' : np.asarray(x.as_array(), dtype=np.float32),\
             'regularization_parameter':self.lambdaReg*tau, \
             'number_of_iterations' :self.iterationsTV ,\
             'time_marching_parameter':self.time_marchstep}
     
     out = regularisers.ROF_TV(pars['input'], 
           pars['regularization_parameter'],
           pars['number_of_iterations'],
           pars['time_marching_parameter'], self.device)
     return DataContainer(out)
Esempio n. 5
0
    def binary_multiply(self):
        print("Test binary multiply")
        X, Y, Z = 1024, 512, 512
        X, Y, Z = 256, 512, 512
        steps = [timer()]
        a = numpy.ones((X, Y, Z), dtype='float32')
        steps.append(timer())
        t0 = dt(steps)

        #print("a refcount " , sys.getrefcount(a))
        ds = DataContainer(a, False, ['X', 'Y', 'Z'])
        ds1 = ds.copy()

        steps.append(timer())
        ds.multiply(ds1, out=ds)
        steps.append(timer())
        t1 = dt(steps)
        print("ds.multiply(ds1, out=ds)", dt(steps))
        steps.append(timer())
        ds2 = ds.multiply(ds1)
        steps.append(timer())
        t2 = dt(steps)
        print("ds2 = ds.multiply(ds1)", dt(steps))

        #self.assertLess(t1, t2)

        ds0 = ds
        ds0.multiply(2, out=ds0)
        steps.append(timer())
        print("ds0.multiply(2,out=ds0)", dt(
            steps), 2., ds0.as_array()[0][0][0])
        self.assertEqual(2., ds0.as_array()[0][0][0])

        dt1 = dt(steps)
        ds3 = ds0.multiply(2)
        steps.append(timer())
        print("ds3 = ds0.multiply(2)", dt(steps), 4., ds3.as_array()[0][0][0])
        dt2 = dt(steps)
        #self.assertLess(dt1, dt2)
        self.assertEqual(4., ds3.as_array()[0][0][0])
        self.assertEqual(2., ds.as_array()[0][0][0])
        
        ds.multiply(2.5, out=ds0)
        self.assertEqual(2.5*2., ds0.as_array()[0][0][0])
Esempio n. 6
0
 def test_creation_copy(self):
     shape = (2, 3, 4, 5)
     size = shape[0]
     for i in range(1, len(shape)):
         size = size * shape[i]
     #print("a refcount " , sys.getrefcount(a))
     a = numpy.asarray([i for i in range(size)])
     #print("a refcount " , sys.getrefcount(a))
     a = numpy.reshape(a, shape)
     #print("a refcount " , sys.getrefcount(a))
     ds = DataContainer(a, True, ['X', 'Y', 'Z', 'W'])
     #print("a refcount " , sys.getrefcount(a))
     self.assertEqual(sys.getrefcount(a), 2)
Esempio n. 7
0
 def test_creation_nocopy(self):
     shape = (2, 3, 4, 5)
     size = shape[0]
     for i in range(1, len(shape)):
         size = size * shape[i]
     #print("a refcount " , sys.getrefcount(a))
     a = numpy.asarray([i for i in range(size)])
     #print("a refcount " , sys.getrefcount(a))
     a = numpy.reshape(a, shape)
     #print("a refcount " , sys.getrefcount(a))
     ds = DataContainer(a, False, ['X', 'Y', 'Z', 'W'])
     #print("a refcount " , sys.getrefcount(a))
     self.assertEqual(sys.getrefcount(a), 3)
     self.assertEqual(ds.dimension_labels, {0: 'X', 1: 'Y', 2: 'Z', 3: 'W'})
Esempio n. 8
0
    def binary_subtract(self):
        print("Test binary subtract")
        X, Y, Z = 512, 512, 512
        steps = [timer()]
        a = numpy.ones((X, Y, Z), dtype='float32')
        steps.append(timer())
        t0 = dt(steps)

        #print("a refcount " , sys.getrefcount(a))
        ds = DataContainer(a, False, ['X', 'Y', 'Z'])
        ds1 = ds.copy()

        steps.append(timer())
        ds.subtract(ds1, out=ds)
        steps.append(timer())
        t1 = dt(steps)
        print("ds.subtract(ds1, out=ds)", dt(steps))
        self.assertEqual(0., ds.as_array()[0][0][0])

        steps.append(timer())
        ds2 = ds.subtract(ds1)
        self.assertEqual(-1., ds2.as_array()[0][0][0])

        steps.append(timer())
        t2 = dt(steps)
        print("ds2 = ds.subtract(ds1)", dt(steps))

        self.assertLess(t1, t2)

        del ds1
        ds0 = ds.copy()
        steps.append(timer())
        ds0.subtract(2, out=ds0)
        #ds0.__isub__( 2 )
        steps.append(timer())
        print("ds0.subtract(2,out=ds0)", dt(
            steps), -2., ds0.as_array()[0][0][0])
        self.assertEqual(-2., ds0.as_array()[0][0][0])

        dt1 = dt(steps)
        ds3 = ds0.subtract(2)
        steps.append(timer())
        print("ds3 = ds0.subtract(2)", dt(steps), 0., ds3.as_array()[0][0][0])
        dt2 = dt(steps)
        self.assertLess(dt1, dt2)
        self.assertEqual(-2., ds0.as_array()[0][0][0])
        self.assertEqual(-4., ds3.as_array()[0][0][0])
Esempio n. 9
0
 def test_exp_log(self):
     a0 = numpy.asarray([1 for i in range(2*3*4)])
             
     ds0 = DataContainer(numpy.reshape(a0,(2,3,4)), suppress_warning=True)
     # ds1 = DataContainer(numpy.reshape(a1,(2,3,4)), suppress_warning=True)
     b = ds0.exp().log()
     self.assertNumpyArrayEqual(ds0.as_array(), b.as_array())
     
     self.assertEqual(ds0.exp().as_array()[0][0][0], numpy.exp(1))
     self.assertEqual(ds0.log().as_array()[0][0][0], 0.)
Esempio n. 10
0
 def prox(self,x,tau):
     pars = {'algorithm' : SB_TV, \
            'input' : np.asarray(x.as_array(), dtype=np.float32),\
             'regularization_parameter':self.lambdaReg*tau, \
             'number_of_iterations' :self.iterationsTV ,\
             'tolerance_constant':self.tolerance,\
             'methodTV': self.methodTV ,\
             'printingOut': self.printing}
     
     out = regularisers.SB_TV(pars['input'], 
           pars['regularization_parameter'],
           pars['number_of_iterations'],
           pars['tolerance_constant'], 
           pars['methodTV'],
           pars['printingOut'], self.device)
     return DataContainer(out)
Esempio n. 11
0
    def binary_divide(self):
        print("Test binary divide")
        X, Y, Z = 1024, 512, 512
        X, Y, Z = 256, 512, 512
        steps = [timer()]
        a = numpy.ones((X, Y, Z), dtype='float32')
        steps.append(timer())
        t0 = dt(steps)

        #print("a refcount " , sys.getrefcount(a))
        ds = DataContainer(a, False, ['X', 'Y', 'Z'])
        ds1 = ds.copy()

        t1 = 0 
        t2 = 0
        for i in range(10):
            steps.append(timer())
            ds.divide(ds1, out=ds)
            steps.append(timer())
            t1 += dt(steps)/10.
            print("ds.divide(ds1, out=ds)", dt(steps))
            steps.append(timer())
            ds2 = ds.divide(ds1)
            steps.append(timer())
            t2 += dt(steps)/10.
            print("ds2 = ds.divide(ds1)", dt(steps))

        #self.assertLess(t1, t2)
        self.assertEqual(ds.as_array()[0][0][0], 1.)

        ds0 = ds
        ds0.divide(2, out=ds0)
        steps.append(timer())
        print("ds0.divide(2,out=ds0)", dt(steps), 0.5, ds0.as_array()[0][0][0])
        self.assertEqual(0.5, ds0.as_array()[0][0][0])

        dt1 = dt(steps)
        ds3 = ds0.divide(2)
        steps.append(timer())
        print("ds3 = ds0.divide(2)", dt(steps), 0.25, ds3.as_array()[0][0][0])
        dt2 = dt(steps)
        #self.assertLess(dt1, dt2)
        self.assertEqual(.25, ds3.as_array()[0][0][0])
        self.assertEqual(.5, ds.as_array()[0][0][0])
Esempio n. 12
0
 def test_dot(self):
     a0 = numpy.asarray([i for i in range(2*3*4)])
     a1 = numpy.asarray([2*i for i in range(2*3*4)])
     
             
     ds0 = DataContainer(numpy.reshape(a0,(2,3,4)))
     ds1 = DataContainer(numpy.reshape(a1,(2,3,4)))
     
     numpy.testing.assert_equal(ds0.dot(ds1), a0.dot(a1))
     
     a2 = numpy.asarray([2*i for i in range(2*3*5)])
     ds2 = DataContainer(numpy.reshape(a2,(2,3,5)))
     
     # it should fail if the shape is wrong
     try:
         ds2.dot(ds0)
         self.assertTrue(False)
     except ValueError as ve:
         self.assertTrue(True)
 def process(self):
     
     data = self.get_input()
     
     #stats, i = add_sample(0)
     N = data.get_dimension_size(self.axis)
     ax = data.get_dimension_axis(self.axis)
     stats = None
     i = 0
     while i < N:
         stats , i = DataStatMoments.add_sample(data, i, self.axis, stats, offset=self.offset)
     self.offset += N
     labels = ['StatisticalMoments']
     
     labels += [data.dimension_labels[i] \
                for i in range(len(data.dimension_labels)) if i != ax]
     y = DataContainer( stats[:4] , False, 
                 dimension_labels=labels)
     return y
Esempio n. 14
0
 def testGb_creation_nocopy(self):
     X, Y, Z = 512, 512, 512
     X, Y, Z = 256, 512, 512
     steps = [timer()]
     a = numpy.ones((X, Y, Z), dtype='float32')
     steps.append(timer())
     t0 = dt(steps)
     print("test clone")
     #print("a refcount " , sys.getrefcount(a))
     ds = DataContainer(a, False, ['X', 'Y', 'Z'])
     #print("a refcount " , sys.getrefcount(a))
     self.assertEqual(sys.getrefcount(a), 3)
     ds1 = ds.copy()
     self.assertNotEqual(aid(ds.as_array()), aid(ds1.as_array()))
     ds1 = ds.clone()
     self.assertNotEqual(aid(ds.as_array()), aid(ds1.as_array()))
Esempio n. 15
0
    def binary_add(self):
        print("Test binary add")
        X, Y, Z = 512, 512, 512
        #X, Y, Z = 1024, 512, 512
        steps = [timer()]
        a = numpy.ones((X, Y, Z), dtype='float32')
        steps.append(timer())
        t0 = dt(steps)

        #print("a refcount " , sys.getrefcount(a))
        ds = DataContainer(a, False, ['X', 'Y', 'Z'])
        ds1 = ds.copy()
        out = ds.copy()

        steps.append(timer())
        ds.add(ds1, out=out)
        steps.append(timer())
        t1 = dt(steps)
        print("ds.add(ds1, out=ds)", dt(steps))
        steps.append(timer())
        ds2 = ds.add(ds1)
        steps.append(timer())
        t2 = dt(steps)
        print("ds2 = ds.add(ds1)", dt(steps))

        #self.assertLess(t1, t2)
        self.assertEqual(out.as_array()[0][0][0], 2.)
        self.assertNumpyArrayEqual(out.as_array(), ds2.as_array())
        
        ds0 = ds
        dt1 = 0
        dt2 = 0
        for i in range(10):
            steps.append(timer())
            ds0.add(2, out=out)
            steps.append(timer())
            print("ds0.add(2,out=out)", dt(steps), 3, ds0.as_array()[0][0][0])
            self.assertEqual(3., out.as_array()[0][0][0])

            dt1 += dt(steps)/10
            steps.append(timer())
            ds3 = ds0.add(2)
            steps.append(timer())
            print("ds3 = ds0.add(2)", dt(steps), 5, ds3.as_array()[0][0][0])
            dt2 += dt(steps)/10
        
        self.assertNumpyArrayEqual(out.as_array(), ds3.as_array())
Esempio n. 16
0
 def create_image_data(self):
     inputsize = self.size()[1]
     return DataContainer(numpy.random.randn(self.volume_geometry.channels,
                                             inputsize[0],
                                             inputsize[1]))
Esempio n. 17
0
    def test_subset(self):
        shape = (4, 3, 2)
        a = [i for i in range(2*3*4)]
        a = numpy.asarray(a)
        a = numpy.reshape(a, shape)
        ds = DataContainer(a, True, ['X', 'Y', 'Z'])
        sub = ds.subset(['X'])
        res = True
        try:
            numpy.testing.assert_array_equal(sub.as_array(),
                                             numpy.asarray([0, 6, 12, 18]))
        except AssertionError as err:
            res = False
            print(err)
        self.assertTrue(res)

        sub = ds.subset(['X'], Y=2, Z=0)
        res = True
        try:
            numpy.testing.assert_array_equal(sub.as_array(),
                                             numpy.asarray([4, 10, 16, 22]))
        except AssertionError as err:
            res = False
            print(err)
        self.assertTrue(res)

        sub = ds.subset(['Y'])
        try:
            numpy.testing.assert_array_equal(
                sub.as_array(), numpy.asarray([0, 2, 4]))
            res = True
        except AssertionError as err:
            res = False
            print(err)
        self.assertTrue(res)

        sub = ds.subset(['Z'])
        try:
            numpy.testing.assert_array_equal(
                sub.as_array(), numpy.asarray([0, 1]))
            res = True
        except AssertionError as err:
            res = False
            print(err)
        self.assertTrue(res)
        sub = ds.subset(['Z'], X=1, Y=2)
        try:
            numpy.testing.assert_array_equal(
                sub.as_array(), numpy.asarray([10, 11]))
            res = True
        except AssertionError as err:
            res = False
            print(err)
        self.assertTrue(res)

        print(a)
        sub = ds.subset(['X', 'Y'], Z=1)
        res = True
        try:
            numpy.testing.assert_array_equal(sub.as_array(),
                                             numpy.asarray([[1,  3,  5],
                                                            [7,  9, 11],
                                                            [13, 15, 17],
                                                            [19, 21, 23]]))
        except AssertionError as err:
            res = False
            print(err)
        self.assertTrue(res)
Esempio n. 18
0
 def test_dot(self):
     a0 = numpy.asarray([i for i in range(2*3*4)])
     a1 = numpy.asarray([2*i for i in range(2*3*4)])
     
             
     ds0 = DataContainer(numpy.reshape(a0,(2,3,4)))
     ds1 = DataContainer(numpy.reshape(a1,(2,3,4)))
     
     numpy.testing.assert_equal(ds0.dot(ds1), a0.dot(a1))
     
     a2 = numpy.asarray([2*i for i in range(2*3*5)])
     ds2 = DataContainer(numpy.reshape(a2,(2,3,5)))
     
     # it should fail if the shape is wrong
     try:
         ds2.dot(ds0)
         self.assertTrue(False)
     except ValueError as ve:
         self.assertTrue(True)
         
     print ("test dot numpy")
     n0 = (ds0 * ds1).sum()
     n1 = ds0.as_array().ravel().dot(ds1.as_array().ravel())
     self.assertEqual(n0, n1)
Esempio n. 19
0
    def test_unary_operations(self):
        print("Test unary operations")
        X, Y, Z = 1024, 512, 512
        X, Y, Z = 256, 512, 512
        steps = [timer()]
        a = -numpy.ones((X, Y, Z), dtype='float32')
        steps.append(timer())
        t0 = dt(steps)
        print(t0)
        #print("a refcount " , sys.getrefcount(a))
        ds = DataContainer(a, False, ['X', 'Y', 'Z'])

        ds.sign(out=ds)
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], -1.)

        ds.abs(out=ds)
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 1.)

        ds.__imul__(2)
        ds.sqrt(out=ds)
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0],
                         numpy.sqrt(2., dtype='float32'))
Esempio n. 20
0
import numpy as np
import matplotlib.pyplot as plt

# Problem data.
m = 30
n = 20
np.random.seed(1)
Amat = np.random.randn(m, n)
A = LinearOperatorMatrix(Amat)
bmat = np.random.randn(m)
bmat.shape = (bmat.shape[0], 1)

# A = Identity()
# Change n to equal to m.

b = DataContainer(bmat)

# Regularization parameter
lam = 10

# Create object instances with the test data A and b.
f = Norm2sq(A, b, c=0.5, memopt=True)
g0 = ZeroFun()

# Initial guess
x_init = DataContainer(np.zeros((n, 1)))

f.grad(x_init)
opt = {'memopt': True}
# Run FISTA for least squares plus zero function.
x_fista0, it0, timing0, criter0 = FISTA(x_init, f, g0)
Esempio n. 21
0
ig = ImageGeometry(n, n)
ag = AcquisitionGeometry('parallel', '2D', angles, n, 1)
Aop = AstraProjectorSimple(ig, ag, 'gpu')

# loop to reconstruct energy channels
REC_chan = np.zeros((totChannels, n, n), 'float32')
for i in range(0, totChannels, 1):
    sino_channel = sino_all_channels[:,
                                     i, :]  # extract a sinogram for i-th channel

    print("Initial guess")
    x_init = ImageData(geometry=ig)

    # Create least squares object instance with projector and data.
    print("Create least squares object instance with projector and data.")
    f = Norm2sq(Aop, DataContainer(sino_channel), c=0.5)

    print("Run FISTA-TV for least squares")
    lamtv = 5
    opt = {'tol': 1e-4, 'iter': 200}
    g_fgp = FGP_TV(lambdaReg=lamtv,
                   iterationsTV=50,
                   tolerance=1e-6,
                   methodTV=0,
                   nonnegativity=0,
                   printing=0,
                   device='gpu')

    x_fista_fgp, it1, timing1, criter_fgp = FISTA(x_init, f, g_fgp, opt)
    REC_chan[i, :, :] = x_fista_fgp.array
    """
    def test_DataProcessorChaining(self):
        shape = (2, 3, 4, 5)
        size = shape[0]
        for i in range(1, len(shape)):
            size = size * shape[i]
        #print("a refcount " , sys.getrefcount(a))
        a = numpy.asarray([i for i in range(size)])
        a = numpy.reshape(a, shape)
        ds = DataContainer(a, False, ['X', 'Y', 'Z', 'W'])
        c = ds.subset(['Z', 'W', 'X'])
        arr = c.as_array()
        #[ 0 60  1 61  2 62  3 63  4 64  5 65  6 66  7 67  8 68  9 69 10 70 11 71
        # 12 72 13 73 14 74 15 75 16 76 17 77 18 78 19 79]

        ax = AX()
        ax.scalar = 2
        ax.set_input(c)
        #ax.apply()
        print("ax  in {0} out {1}".format(
            c.as_array().flatten(),
            ax.get_output().as_array().flatten()))
        numpy.testing.assert_array_equal(ax.get_output().as_array(), arr * 2)

        cast = CastDataContainer(dtype=numpy.float32)
        cast.set_input(c)
        out = cast.get_output()
        self.assertTrue(out.as_array().dtype == numpy.float32)
        out *= 0
        axm = AX()
        axm.scalar = 0.5
        axm.set_input(c)
        axm.get_output(out)
        numpy.testing.assert_array_equal(out.as_array(), arr * 0.5)

        # check out in DataSetProcessor
        #a = numpy.asarray([i for i in range( size )])

        # create a PixelByPixelDataProcessor

        #define a python function which will take only one input (the pixel value)
        pyfunc = lambda x: -x if x > 20 else x
        clip = PixelByPixelDataProcessor()
        clip.pyfunc = pyfunc
        clip.set_input(c)
        #clip.apply()
        v = clip.get_output().as_array()

        self.assertTrue(v.max() == 19)
        self.assertTrue(v.min() == -79)

        print("clip in {0} out {1}".format(c.as_array(),
                                           clip.get_output().as_array()))

        #dsp = DataProcessor()
        #dsp.set_input(ds)
        #dsp.input = a
        # pipeline

        chain = AX()
        chain.scalar = 0.5
        chain.set_input_processor(ax)
        print("chain in {0} out {1}".format(ax.get_output().as_array(),
                                            chain.get_output().as_array()))
        numpy.testing.assert_array_equal(chain.get_output().as_array(), arr)
Esempio n. 23
0
    def test_FISTA_Norm1_cvx(self):
        if not cvx_not_installable:
            try:
                opt = {'memopt': True}
                # Problem data.
                m = 30
                n = 20
                np.random.seed(1)
                Amat = np.random.randn(m, n)
                A = LinearOperatorMatrix(Amat)
                bmat = np.random.randn(m)
                bmat.shape = (bmat.shape[0], 1)

                # A = Identity()
                # Change n to equal to m.

                b = DataContainer(bmat)

                # Regularization parameter
                lam = 10
                opt = {'memopt': True}
                # Create object instances with the test data A and b.
                f = Norm2sq(A, b, c=0.5, memopt=True)
                g0 = ZeroFun()

                # Initial guess
                x_init = DataContainer(np.zeros((n, 1)))

                # Create 1-norm object instance
                g1 = Norm1(lam)

                g1(x_init)
                g1.prox(x_init, 0.02)

                # Combine with least squares and solve using generic FISTA implementation
                x_fista1, it1, timing1, criter1 = FISTA(x_init, f, g1, opt=opt)

                # Print for comparison
                print(
                    "FISTA least squares plus 1-norm solution and objective value:"
                )
                print(x_fista1.as_array().squeeze())
                print(criter1[-1])

                # Compare to CVXPY

                # Construct the problem.
                x1 = Variable(n)
                objective1 = Minimize(0.5 *
                                      sum_squares(Amat * x1 - bmat.T[0]) +
                                      lam * norm(x1, 1))
                prob1 = Problem(objective1)

                # The optimal objective is returned by prob.solve().
                result1 = prob1.solve(verbose=False, solver=SCS, eps=1e-9)

                # The optimal solution for x is stored in x.value and optimal objective value
                # is in result as well as in objective.value
                print(
                    "CVXPY least squares plus 1-norm solution and objective value:"
                )
                print(x1.value)
                print(objective1.value)

                self.assertNumpyArrayAlmostEqual(numpy.squeeze(x_fista1.array),
                                                 x1.value, 6)
            except SolverError as se:
                print(str(se))
                self.assertTrue(True)
        else:
            self.assertTrue(cvx_not_installable)
Esempio n. 24
0
    def testInlineAlgebra(self):
        print("Test Inline Algebra")
        X, Y, Z = 1024, 512, 512
        X, Y, Z = 256, 512, 512
        steps = [timer()]
        a = numpy.ones((X, Y, Z), dtype='float32')
        steps.append(timer())
        t0 = dt(steps)
        print(t0)
        #print("a refcount " , sys.getrefcount(a))
        ds = DataContainer(a, False, ['X', 'Y', 'Z'])
        #ds.__iadd__( 2 )
        ds += 2
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 3.)
        #ds.__isub__( 2 )
        ds -= 2
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 1.)
        #ds.__imul__( 2 )
        ds *= 2
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 2.)
        #ds.__idiv__( 2 )
        ds /= 2
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 1.)

        ds1 = ds.copy()
        #ds1.__iadd__( 1 )
        ds1 += 1
        #ds.__iadd__( ds1 )
        ds += ds1
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 3.)
        #ds.__isub__( ds1 )
        ds -= ds1
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 1.)
        #ds.__imul__( ds1 )
        ds *= ds1
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 2.)
        #ds.__idiv__( ds1 )
        ds /= ds1
        steps.append(timer())
        print(dt(steps))
        self.assertEqual(ds.as_array()[0][0][0], 1.)
Esempio n. 25
0
 def create_image_data(self):
     inputsize = self.size()[1]
     return DataContainer(numpy.random.randn(inputsize[0],
                                             inputsize[1]))
import numpy as np
import matplotlib.pyplot as plt

# Problem data.
m = 30
n = 20
np.random.seed(1)
Amat = np.random.randn(m, n)
A = LinearOperatorMatrix(Amat)
bmat = np.random.randn(m)
bmat.shape = (bmat.shape[0],1)

# A = Identity()
# Change n to equal to m.

b = DataContainer(bmat)

# Regularization parameter
lam = 10
opt = {'memopt':True}
# Create object instances with the test data A and b.
f = Norm2sq(A,b,c=0.5, memopt=True)
g0 = ZeroFun()

# Initial guess
x_init = DataContainer(np.zeros((n,1)))

f.grad(x_init)

# Run FISTA for least squares plus zero function.
x_fista0, it0, timing0, criter0 = FISTA(x_init, f, g0 , opt=opt)
Esempio n. 27
0
 def allocate_adjoint(self):
     '''allocate the memory to hold the result of direct'''
     #numpy.dot(self.A.transpose(),x.as_array())
     M_A, N_A = self.A.shape
     out = numpy.zeros((M_A, 1))
     return DataContainer(out)