def test_PowerMethod(self): print ("test_BlockOperator") N, M = 200, 300 niter = 10 ig = ImageGeometry(N, M) Id = Identity(ig) G = Gradient(ig) uid = Id.domain_geometry().allocate(ImageGeometry.RANDOM_INT, seed=1) a = LinearOperator.PowerMethod(Id, niter, uid) #b = LinearOperator.PowerMethodNonsquare(Id, niter, uid) b = LinearOperator.PowerMethod(Id, niter) print ("Edo impl", a[0]) print ("None impl", b[0]) #self.assertAlmostEqual(a[0], b[0]) self.assertNumpyArrayAlmostEqual(a[0],b[0],decimal=6) a = LinearOperator.PowerMethod(G, niter, uid) b = LinearOperator.PowerMethod(G, niter) #b = LinearOperator.PowerMethodNonsquare(G, niter, uid) print ("Edo impl", a[0]) #print ("old impl", b[0]) self.assertNumpyArrayAlmostEqual(a[0],b[0],decimal=2)
def stest_NestedBlockDataContainer2(self): M, N = 2, 3 ig = ImageGeometry(voxel_num_x=M, voxel_num_y=N) ag = ig u = ig.allocate(1) op1 = Gradient(ig) op2 = Identity(ig, ag) operator = BlockOperator(op1, op2, shape=(2, 1)) d1 = op1.direct(u) d2 = op2.direct(u) d = operator.direct(u) dd = operator.domain_geometry() ww = operator.range_geometry() print(d.get_item(0).get_item(0).as_array()) print(d.get_item(0).get_item(1).as_array()) print(d.get_item(1).as_array()) c1 = d + d c2 = 2 * d c3 = d / (d + 0.0001) c5 = d.get_item(0).power(2).sum()
def test_CompositionOperator_direct3(self): ig = self.ig data = self.data G = Gradient(domain_geometry=ig) Id1 = 2 * Identity(ig) Id2 = Identity(ig) d = CompositionOperator(G, Id2) out1 = G.direct(data) d_out = d.direct(data) d1 = Id2.direct(data) d2 = G.direct(d1) numpy.testing.assert_array_almost_equal(d2.get_item(0).as_array(), d_out.get_item(0).as_array()) numpy.testing.assert_array_almost_equal(d2.get_item(1).as_array(), d_out.get_item(1).as_array()) G2Id = G.compose(2*Id2) d2g = G2Id.direct(data) numpy.testing.assert_array_almost_equal(d2g.get_item(0).as_array(), 2 * d_out.get_item(0).as_array()) numpy.testing.assert_array_almost_equal(d2g.get_item(1).as_array(), 2 * d_out.get_item(1).as_array())
def test_Identity(self): print ("test_Identity") ig = ImageGeometry(10,20,30) img = ig.allocate() # img.fill(numpy.ones((30,20,10))) self.assertTrue(img.shape == (30,20,10)) #self.assertEqual(img.sum(), 2*float(10*20*30)) self.assertEqual(img.sum(), 0.) Id = Identity(ig) y = Id.direct(img) numpy.testing.assert_array_equal(y.as_array(), img.as_array())
def test_SumOperator(self): # numpy.random.seed(1) ig = self.ig data = self.data Id1 = 2 * Identity(ig) Id2 = Identity(ig) # z = ZeroOperator(domain_geometry=ig) # sym = SymmetrizedGradient(domain_geometry=ig) c = SumOperator(Id1,Id2) out = c.direct(data) numpy.testing.assert_array_almost_equal(out.as_array(),3 * data.as_array())
def test_CompositionOperator_adjoint5(self): ig = self.ig data = self.data G = Gradient(domain_geometry=ig) Id1 = 3 * Identity(ig) Id = Id1 - Identity(ig) d = G.compose(Id) da = d.direct(data) out1 = G.adjoint(da) out2 = d.adjoint(da) numpy.testing.assert_array_almost_equal(out2.as_array(), 2 * out1.as_array())
def test_FISTA_Norm2Sq(self): print ("Test FISTA Norm2Sq") ig = ImageGeometry(127,139,149) b = ig.allocate(ImageGeometry.RANDOM) # fill with random numbers x_init = ig.allocate(ImageGeometry.RANDOM) identity = Identity(ig) #### it seems FISTA does not work with Nowm2Sq norm2sq = LeastSquares(identity, b) #norm2sq.L = 2 * norm2sq.c * identity.norm()**2 #norm2sq = FunctionOperatorComposition(L2NormSquared(b=b), identity) opt = {'tol': 1e-4, 'memopt':False} print ("initial objective", norm2sq(x_init)) alg = FISTA(x_init=x_init, f=norm2sq, g=ZeroFunction()) alg.max_iteration = 2 alg.run(20, verbose=True) self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array()) alg = FISTA(x_init=x_init, 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=True) self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())
def test_ScaledOperator(self): print ("test_ScaledOperator") ig = ImageGeometry(10,20,30) img = ig.allocate() scalar = 0.5 sid = scalar * Identity(ig) numpy.testing.assert_array_equal(scalar * img.as_array(), sid.direct(img).as_array())
def test_CompositionOperator_adjoint1(self): ig = self.ig data = self.data G = Gradient(domain_geometry=ig) Id1 = 2 * Identity(ig) Id2 = Identity(ig) d = CompositionOperator(G, Id2) da = d.direct(data) out1 = G.adjoint(da) out2 = d.adjoint(da) numpy.testing.assert_array_almost_equal(out2.as_array(), out1.as_array())
def test_Function(self): N = 3 ig = ImageGeometry(N, N) ag = ig op1 = Gradient(ig) op2 = Identity(ig, ag) # Form Composite Operator operator = BlockOperator(op1, op2, shape=(2, 1)) # Create functions noisy_data = ag.allocate(ImageGeometry.RANDOM_INT) d = ag.allocate(ImageGeometry.RANDOM_INT) 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.assertEqual(a3, g.convex_conjugate(d))
def test_GradientDescentArmijo(self): print ("Test GradientDescent") ig = ImageGeometry(12,13,14) x_init = ig.allocate() # b = x_init.copy() # fill with random numbers # b.fill(numpy.random.random(x_init.shape)) b = ig.allocate('random') identity = Identity(ig) norm2sq = LeastSquares(identity, b) rate = None alg = GradientDescent(x_init=x_init, objective_function=norm2sq, rate=rate) alg.max_iteration = 100 alg.run() self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array()) alg = GradientDescent(x_init=x_init, objective_function=norm2sq, max_iteration=20, update_objective_interval=2) #alg.max_iteration = 20 self.assertTrue(alg.max_iteration == 20) self.assertTrue(alg.update_objective_interval==2) alg.run(20, verbose=True) self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())
def test_FISTA_catch_Lipschitz(self): print ("Test FISTA catch Lipschitz") ig = ImageGeometry(127,139,149) x_init = ImageData(geometry=ig) x_init = ig.allocate() b = x_init.copy() # fill with random numbers b.fill(numpy.random.random(x_init.shape)) x_init = ig.allocate(ImageGeometry.RANDOM) identity = Identity(ig) #### it seems FISTA does not work with Nowm2Sq norm2sq = LeastSquares(identity, b) print ('Lipschitz', norm2sq.L) norm2sq.L = None #norm2sq.L = 2 * norm2sq.c * identity.norm()**2 #norm2sq = FunctionOperatorComposition(L2NormSquared(b=b), identity) opt = {'tol': 1e-4, 'memopt':False} print ("initial objective", norm2sq(x_init)) try: alg = FISTA(x_init=x_init, f=norm2sq, g=ZeroFunction()) self.assertTrue(False) except ValueError as ve: print (ve) self.assertTrue(True)
def test_CGLS(self): print ("Test CGLS") #ig = ImageGeometry(124,153,154) ig = ImageGeometry(10,2) numpy.random.seed(2) x_init = ig.allocate(0.) b = ig.allocate('random') # b = x_init.copy() # fill with random numbers # b.fill(numpy.random.random(x_init.shape)) # b = ig.allocate() # bdata = numpy.reshape(numpy.asarray([i for i in range(20)]), (2,10)) # b.fill(bdata) identity = Identity(ig) alg = CGLS(x_init=x_init, operator=identity, data=b) alg.max_iteration = 200 alg.run(20, verbose=True) self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array()) alg = CGLS(x_init=x_init, 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=True) self.assertNumpyArrayAlmostEqual(alg.x.as_array(), b.as_array())
def stest_CompositionOperator_direct4(self): ig = self.ig data = self.data G = Gradient(domain_geometry=ig) sym = SymmetrizedGradient(domain_geometry=ig) Id2 = Identity(ig) d = CompositionOperator(sym, Id2) out1 = G.direct(data) out2 = d.direct(data) numpy.testing.assert_array_almost_equal(out2.get_item(0).as_array(), out1.get_item(0).as_array()) numpy.testing.assert_array_almost_equal(out2.get_item(1).as_array(), out1.get_item(1).as_array())
def test_BlockOperatorLinearValidity(self): print ("test_BlockOperatorLinearValidity") 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') w = B.range_geometry().allocate(ImageGeometry.RANDOM_INT) w1 = B.direct(u) u1 = B.adjoint(w) self.assertEqual((w * w1).sum() , (u1*u).sum())
def test_Norm2sq_as_FunctionOperatorComposition(self): print('Test for FunctionOperatorComposition') M, N = 50, 50 ig = ImageGeometry(voxel_num_x=M, voxel_num_y=N) b = ig.allocate('random_int') print('Check call with Identity operator... OK\n') operator = 3 * Identity(ig) u = ig.allocate('random_int', seed=50) func1 = FunctionOperatorComposition(0.5 * L2NormSquared(b=b), operator) func2 = LeastSquares(operator, b, 0.5) self.assertNumpyArrayAlmostEqual(func1(u), func2(u)) print('Check gradient with Identity operator... OK\n') tmp1 = ig.allocate() tmp2 = ig.allocate() res_gradient1 = func1.gradient(u) res_gradient2 = func2.gradient(u) func1.gradient(u, out=tmp1) func2.gradient(u, out=tmp2) self.assertNumpyArrayAlmostEqual(tmp1.as_array(), tmp2.as_array()) self.assertNumpyArrayAlmostEqual(res_gradient1.as_array(), res_gradient2.as_array()) print('Check call with LinearOperatorMatrix... OK\n') mat = np.random.randn(M, N) operator = LinearOperatorMatrix(mat) vg = VectorGeometry(N) b = vg.allocate('random_int') u = vg.allocate('random_int') func1 = FunctionOperatorComposition(0.5 * L2NormSquared(b=b), operator) func2 = LeastSquares(operator, b, 0.5) self.assertNumpyArrayAlmostEqual(func1(u), func2(u)) self.assertNumpyArrayAlmostEqual(func1.L, func2.L)
def test_FiniteDifference(self): print ("test FiniteDifference") ## N, M = 2, 3 ig = ImageGeometry(N, M) Id = Identity(ig) FD = FiniteDiff(ig, direction = 0, bnd_cond = 'Neumann') u = FD.domain_geometry().allocate('random_int') res = FD.domain_geometry().allocate(ImageGeometry.RANDOM_INT) FD.adjoint(u, out=res) w = FD.adjoint(u) self.assertNumpyArrayEqual(res.as_array(), w.as_array()) res = Id.domain_geometry().allocate(ImageGeometry.RANDOM_INT) Id.adjoint(u, out=res) w = Id.adjoint(u) self.assertNumpyArrayEqual(res.as_array(), w.as_array()) self.assertNumpyArrayEqual(u.as_array(), w.as_array()) G = Gradient(ig) u = G.range_geometry().allocate(ImageGeometry.RANDOM_INT) res = G.domain_geometry().allocate() G.adjoint(u, out=res) w = G.adjoint(u) self.assertNumpyArrayEqual(res.as_array(), w.as_array()) u = G.domain_geometry().allocate(ImageGeometry.RANDOM_INT) res = G.range_geometry().allocate() G.direct(u, out=res) w = G.direct(u) self.assertBlockDataContainerEqual(res, w)
beta = 2 * alpha # Fidelity if noise == 's&p': f3 = L1Norm(b=noisy_data) elif noise == 'poisson': f3 = KullbackLeibler(noisy_data) elif noise == 'gaussian': f3 = 0.5 * L2NormSquared(b=noisy_data) if method == '0': # Create operators op11 = Gradient(ig) op12 = Identity(op11.range_geometry()) op22 = SymmetrizedGradient(op11.domain_geometry()) op21 = ZeroOperator(ig, op22.range_geometry()) op31 = Identity(ig, ag) op32 = ZeroOperator(op22.domain_geometry(), ag) operator = BlockOperator(op11, -1 * op12, op21, op22, op31, op32, shape=(3, 2))
return BlockDataContainer(*res) if __name__ == '__main__': from ccpi.framework import ImageGeometry from ccpi.optimisation.operators import Gradient, Identity, \ SparseFiniteDiff, SymmetrizedGradient, ZeroOperator M, N = 4, 3 ig = ImageGeometry(M, N) arr = ig.allocate('random_int') G = Gradient(ig) Id = Identity(ig) B = BlockOperator(G, Id) print(B.sum_abs_row()) # Gx = SparseFiniteDiff(ig, direction=1, bnd_cond='Neumann') 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)
plt.subplot(2, 1, 1) plt.imshow(data.as_array()) plt.title('Ground Truth') plt.colorbar() plt.subplot(2, 1, 2) plt.imshow(noisy_data.as_array()) plt.title('Noisy Data') plt.colorbar() plt.show() # Setup and run the regularised CGLS algorithm (Tikhonov with Gradient) x_init = ig.allocate() alpha = 2 op = Gradient(ig) block_op = BlockOperator(Identity(ig), alpha * op, shape=(2, 1)) block_data = BlockDataContainer(noisy_data, op.range_geometry().allocate()) cgls = CGLS(x_init=x_init, operator=block_op, data=block_data) cgls.max_iteration = 200 cgls.update_objective_interval = 5 cgls.run(200, verbose=True) # Show results plt.figure(figsize=(20, 10)) plt.subplot(3, 1, 1) plt.imshow(data.as_array()) plt.title('Ground Truth') plt.subplot(3, 1, 2) plt.imshow(noisy_data.as_array()) plt.title('Noisy')
plt.colorbar() plt.show() # 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)
if __name__ == '__main__': M, N, K = 20, 30, 50 from ccpi.optimisation.functions import L2NormSquared, MixedL21Norm, L1Norm from ccpi.framework import ImageGeometry, BlockGeometry from ccpi.optimisation.operators import Gradient, Identity, BlockOperator import numpy import numpy as np ig = ImageGeometry(M, N) BG = BlockGeometry(ig, ig) u = ig.allocate('random_int') B = BlockOperator(Gradient(ig), Identity(ig)) U = B.direct(u) b = ig.allocate('random_int') f1 = 10 * MixedL21Norm() f2 = 0.5 * L2NormSquared(b=b) f = BlockFunction(f1, f2) tau = 0.3 print(" without out ") res_no_out = f.proximal_conjugate(U, tau) res_out = B.range_geometry().allocate() f.proximal_conjugate(U, tau, out=res_out)
# Show Ground Truth and Noisy Data plt.figure(figsize=(10, 10)) plt.subplot(1, 2, 2) plt.imshow(data.as_array()) plt.title('Ground Truth') plt.colorbar() plt.subplot(1, 2, 1) plt.imshow(noisy_data.as_array()) plt.title('Noisy Data') plt.colorbar() plt.show() # Create Operators op11 = Gradient(ig) op12 = Identity(op11.range_geometry()) op22 = SymmetrizedGradient(op11.domain_geometry()) op21 = ZeroOperator(ig, op22.range_geometry()) op31 = Aop op32 = ZeroOperator(op22.domain_geometry(), ag) operator = BlockOperator(op11, -1 * op12, op21, op22, op31, op32, shape=(3, 2)) normK = operator.norm() # Create functions if noise == 'poisson': alpha = 2 beta = 3 f3 = KullbackLeibler(noisy_data)
def skip_test_FBPD_Norm1_cvx(self): print ("test_FBPD_Norm1_cvx") 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} # Initial guess x_init = DataContainer(np.random.randn(n, 1)) # Create object instances with the test data A and b. f = LeastSquares(A, b, c=0.5, memopt=True) f.L = LinearOperator.PowerMethod(A, 25, x_init)[0] print ("Lipschitz", f.L) g0 = ZeroFun() # 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)
# Show Ground Truth and Noisy Data plt.figure(figsize=(10, 10)) plt.subplot(2, 1, 1) plt.imshow(data.as_array()) plt.title('Ground Truth') plt.colorbar() plt.subplot(2, 1, 2) plt.imshow(noisy_data.as_array()) plt.title('Noisy Data') plt.colorbar() plt.show() # Setup and run the CGLS algorithm alpha = 2 Grad = Gradient(ig) Id = Identity(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 = 50 cgls.run(1000, verbose=True) # Show results plt.figure(figsize=(5, 5)) plt.imshow(cgls.get_output().as_array()) plt.title('CGLS reconstruction')
operator = Gradient(ig) fidelity = L1Norm(b=noisy_data) regulariser = FunctionOperatorComposition(alpha * L2NormSquared(), operator) x_init = ig.allocate() opt = {'memopt': True} fista = FISTA(x_init=x_init, f=regulariser, g=fidelity, opt=opt) fista.max_iteration = 2000 fista.update_objective_interval = 50 fista.run(2000, verbose=False) ############################################################################### ############################################################################### # Setup and run the PDHG algorithm op1 = Gradient(ig) op2 = Identity(ig, ag) operator = BlockOperator(op1, op2, shape=(2, 1)) f = BlockFunction(alpha * L2NormSquared(), fidelity) g = ZeroFunction() normK = operator.norm() sigma = 1 tau = 1 / (sigma * normK**2) pdhg = PDHG(f=f, g=g, operator=operator, tau=tau, sigma=sigma, memopt=True) pdhg.max_iteration = 2000 pdhg.update_objective_interval = 200 pdhg.run(2000, verbose=False) ###############################################################################
fig1.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8, wspace=0.02, hspace=0.02) plt.tight_layout() plt.show() # Regularisation Parameter alpha = 0.3 # Create Gradient operators with different Space - Channel correlation op1 = Gradient(ig, correlation='Space') # No gradient in temporal direction op2 = Gradient(ig, correlation='SpaceChannels') # SpatioTemporal Gradient op3 = Identity(ig, ag) # Create BlockOperator operator1 = BlockOperator(op1, op3, shape=(2, 1)) operator2 = BlockOperator(op2, op3, shape=(2, 1)) # Create functions f1 = alpha * MixedL21Norm() f2 = 0.5 * L2NormSquared(b=noisy_data) f = BlockFunction(f1, f2) g = ZeroFunction() # Compute operator Norm normK1 = operator1.norm() normK2 = operator2.norm()
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())
def test_timedifference(self): print ("test_timedifference") M, N ,W = 100, 512, 512 ig = ImageGeometry(M, N, W) arr = ig.allocate('random_int') G = Gradient(ig, backend='numpy') Id = Identity(ig) B = BlockOperator(G, Id) # Nx1 case u = ig.allocate('random_int') steps = [timer()] i = 0 n = 10. t1 = t2 = 0 res = B.range_geometry().allocate() while (i < n): print ("i ", i) steps.append(timer()) z1 = B.direct(u) steps.append(timer()) t = dt(steps) #print ("B.direct(u) " ,t) t1 += t/n steps.append(timer()) B.direct(u, out = res) steps.append(timer()) t = dt(steps) #print ("B.direct(u, out=res) " ,t) t2 += t/n i += 1 print ("Time difference ", t1,t2) self.assertGreater(t1,t2) steps = [timer()] i = 0 #n = 50. t1 = t2 = 0 resd = B.domain_geometry().allocate() z1 = B.direct(u) #B.adjoint(z1, out=resd) print (type(res)) while (i < n): print ("i ", i) steps.append(timer()) w1 = B.adjoint(z1) steps.append(timer()) t = dt(steps) #print ("B.adjoint(z1) " ,t) t1 += t/n steps.append(timer()) B.adjoint(z1, out=resd) steps.append(timer()) t = dt(steps) #print ("B.adjoint(z1, out=res) " ,t) t2 += t/n i += 1 print ("Time difference ", t1,t2)