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_Gradient_linearity(self): nc, nz, ny, nx = 3, 4, 5, 6 ig = ImageGeometry(voxel_num_x=nx, voxel_num_y=ny, voxel_num_z=nz, channels=nc) grad = Gradient(ig, bnd_cond='Neumann', correlation='SpaceChannels', backend='c') self.assertTrue(LinearOperator.dot_test(grad)) grad = Gradient(ig, bnd_cond='Periodic', correlation='SpaceChannels', backend='c') self.assertTrue(LinearOperator.dot_test(grad)) grad = Gradient(ig, bnd_cond='Neumann', correlation='SpaceChannels', backend='numpy') self.assertTrue(LinearOperator.dot_test(grad)) grad = Gradient(ig, bnd_cond='Periodic', correlation='SpaceChannels', backend='numpy') self.assertTrue(LinearOperator.dot_test(grad))
def test_SymmetrizedGradient2a(self): ########################################################################### # 2D geometry with channels # ig2 = ImageGeometry(N, M, channels = C) Grad2 = Gradient(self.ig2, correlation = 'Space') E2 = SymmetrizedGradient(Grad2.range_geometry()) numpy.testing.assert_almost_equal(E2.norm(iterations=self.iterations), numpy.sqrt(8), decimal = self.decimal)
def test_SymmetrizedGradient1a(self): ########################################################################### ## Symmetrized Gradient Tests print ("Test SymmetrizedGradient") ########################################################################### # 2D geometry no channels # ig = ImageGeometry(N, M) Grad = Gradient(self.ig) E1 = SymmetrizedGradient(Grad.range_geometry()) numpy.testing.assert_almost_equal(E1.norm(iterations=self.iterations), numpy.sqrt(8), decimal = self.decimal)
def test_SymmetrizedGradient3a(self): ########################################################################### # 3D geometry no channels #ig3 = ImageGeometry(N, M, K) Grad3 = Gradient(self.ig3, correlation = 'Space') E3 = SymmetrizedGradient(Grad3.range_geometry()) norm1 = E3.norm() norm2 = E3.calculate_norm(iterations=100) print (norm1,norm2) numpy.testing.assert_almost_equal(norm2, numpy.sqrt(12), decimal = self.decimal)
def test_SymmetrizedGradient2(self): ########################################################################### # 2D geometry with channels # ig2 = ImageGeometry(N, M, channels = C) Grad2 = Gradient(self.ig2, correlation = 'Space') E2 = SymmetrizedGradient(Grad2.range_geometry()) u2 = E2.domain_geometry().allocate('random_int') w2 = E2.range_geometry().allocate('random_int', symmetry = True) # lhs2 = E2.direct(u2).dot(w2) rhs2 = u2.dot(E2.adjoint(w2)) numpy.testing.assert_almost_equal(lhs2, rhs2)
def test_CompositionOperator_adjoint6(self): ig = self.ig data = self.data G = Gradient(domain_geometry=ig) Id1 = 3 * Identity(ig) Id = ZeroOperator(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(), 0 * out1.as_array())
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 test_CompositionOperator_adjoint2(self): ig = self.ig data = self.data G = Gradient(domain_geometry=ig) Id1 = 2 * Identity(ig) Id2 = Identity(ig) d = CompositionOperator(G, Id1) 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_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_FISTA_Denoising(self): print ("FISTA Denoising Poisson Noise Tikhonov") # adapted from demo FISTA_Tikhonov_Poisson_Denoising.py in CIL-Demos repository #loader = TestData(data_dir=os.path.join(sys.prefix, 'share','ccpi')) loader = TestData() data = loader.load(TestData.SHAPES) ig = data.geometry ag = ig N=300 # Create Noisy data with Poisson noise scale = 5 n1 = TestData.random_noise( data.as_array()/scale, mode = 'poisson', seed = 10)*scale noisy_data = ImageData(n1) # Regularisation Parameter alpha = 10 # Setup and run the FISTA algorithm operator = Gradient(ig) fid = KullbackLeibler(b=noisy_data) reg = FunctionOperatorComposition(alpha * L2NormSquared(), operator) x_init = ig.allocate() fista = FISTA(x_init=x_init , f=reg, g=fid) fista.max_iteration = 3000 fista.update_objective_interval = 500 fista.run(verbose=True) rmse = (fista.get_output() - data).norm() / data.as_array().size print ("RMSE", rmse) self.assertLess(rmse, 4.2e-4)
def test_SymmetrizedGradient3b(self): ########################################################################### # 3D geometry no channels #ig3 = ImageGeometry(N, M, K) Grad3 = Gradient(self.ig3, correlation = 'Space') E3 = SymmetrizedGradient(Grad3.range_geometry()) u3 = E3.domain_geometry().allocate('random_int') w3 = E3.range_geometry().allocate('random_int', symmetry = True) # lhs3 = E3.direct(u3).dot(w3) rhs3 = u3.dot(E3.adjoint(w3)) numpy.testing.assert_almost_equal(lhs3, rhs3) self.assertAlmostEqual(lhs3, rhs3) print (lhs3, rhs3, abs((rhs3-lhs3)/rhs3) , 1.5 * 10**(-4), abs((rhs3-lhs3)/rhs3) < 1.5 * 10**(-4)) self.assertTrue( LinearOperator.dot_test(E3, range_init = w3, domain_init=u3) )
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_Norm(self): print ("test_BlockOperator") ## numpy.random.seed(1) N, M = 200, 300 ig = ImageGeometry(N, M) G = Gradient(ig) t0 = timer() norm = G.norm() t1 = timer() norm2 = G.norm() t2 = timer() norm3 = G.norm(force=True) t3 = timer() print ("Norm dT1 {} dT2 {} dT3 {}".format(t1-t0,t2-t1, t3-t2)) self.assertLess(t2-t1, t1-t0) self.assertLess(t2-t1, t3-t2) numpy.random.seed(1) t4 = timer() norm4 = G.norm(iterations=50, force=True) t5 = timer() self.assertLess(t2-t1, t5-t4) numpy.random.seed(1) t4 = timer() norm5 = G.norm(x_init=ig.allocate('random'), iterations=50, force=True) t5 = timer() self.assertLess(t2-t1, t5-t4) for n in [norm, norm2, norm3, norm4, norm5]: print ("norm {}", format(n))
def test_SymmetrizedGradient1b(self): ########################################################################### ## Symmetrized Gradient Tests print ("Test SymmetrizedGradient") ########################################################################### # 2D geometry no channels # ig = ImageGeometry(N, M) Grad = Gradient(self.ig) E1 = SymmetrizedGradient(Grad.range_geometry()) u1 = E1.domain_geometry().allocate('random_int') w1 = E1.range_geometry().allocate('random_int', symmetry = True) lhs = E1.direct(u1).dot(w1) rhs = u1.dot(E1.adjoint(w1)) # self.assertAlmostEqual(lhs, rhs) numpy.testing.assert_almost_equal(lhs, rhs)
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())
raise ValueError('Unsupported Noise ', noise) # 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 op1 = Gradient(ig) op2 = Aop # Create BlockOperator operator = BlockOperator(op1, op2, shape=(2, 1)) # Compute operator Norm normK = operator.norm() # Create functions if noise == 'poisson': alpha = 20 f2 = KullbackLeibler(noisy_data) g = IndicatorBox(lower=0) sigma = 1 tau = 1 / (sigma * normK**2)
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() # Regularisation Parameter alpha = 10 # Setup and run the FISTA algorithm operator = Gradient(ig) fid = KullbackLeibler(noisy_data) def KL_Prox_PosCone(x, tau, out=None): if out is None: tmp = 0.5 * ((x - fid.bnoise - tau) + ((x + fid.bnoise - tau)**2 + 4 * tau * fid.b).sqrt()) return tmp.maximum(0) else: tmp = 0.5 * ((x - fid.bnoise - tau) + ((x + fid.bnoise - tau)**2 + 4 * tau * fid.b).sqrt()) x.add(fid.bnoise, out=out) out -= tau out *= out
angles = np.linspace(0,np.pi,180) ag = AcquisitionGeometry('parallel','2D', angles, detectors, channels = np.shape(phantom_2Dt)[0]) Aop = AstraProjectorMC(ig, ag, dev) sin = Aop.direct(data) scale = 2 n1 = scale * np.random.poisson(sin.as_array()/scale) noisy_data = AcquisitionData(n1, ag) # Regularisation Parameter alpha = 10 # Create operators #op1 = Gradient(ig) op1 = Gradient(ig, correlation='SpaceChannels') op2 = Aop # Create BlockOperator operator = BlockOperator(op1, op2, shape=(2,1) ) # Create functions f1 = alpha * MixedL21Norm() f2 = KullbackLeibler(noisy_data) f = BlockFunction(f1, f2) g = ZeroFunction() normK = operator.norm() # Primal & dual stepsizes
#%% show reconstruction show_4D_channel_slice(fista_sol_TV_channel_wise, 5, 'FISTA TV channel-wise reconstruction') show_4D_channel_slice(fista_sol_TV_channel_wise, 10, 'FISTA TV channel-wise reconstruction') show_4D_channel_slice(fista_sol_TV_channel_wise, 15, 'FISTA TV channel-wise reconstruction') #%% Coupling Total variation reconstruction in 4D volume. For this case there is no GPU implementation # But we can use another algorithm called PDHG ( primal - dual hybrid gradient) # Set up operators: Projection and Gradient op1 = A3D_chan op2 = Gradient(ig) # Set up a BlockOperator operator = BlockOperator(op1, op2, shape=(2, 1)) # Compute the operator norm normK = operator.norm() alpha_coupled = 0.05 f1 = 0.5 * L2NormSquared(b=data) f2 = alpha_coupled * MixedL21Norm() f = BlockFunction(f1, f2) g = IndicatorBox(lower=0) sigma = 1
data = ImageData(data) ig = ImageGeometry(voxel_num_x=N, voxel_num_y=N) ag = ig n1 = TestData.random_noise(data.as_array(), mode='s&p', salt_vs_pepper=0.9, amount=0.2) noisy_data = ImageData(n1) # Regularisation Parameter alpha = 5 ############################################################################### # Setup and run the FISTA algorithm 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)
plt.title('Time {}'.format(tindex[2])) 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()
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)
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)
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_Gradient(self): N, M, K = 20, 30, 40 channels = 10 numpy.random.seed(1) # check range geometry, examples ig1 = ImageGeometry(voxel_num_x=M, voxel_num_y=N) ig2 = ImageGeometry(voxel_num_x=M, voxel_num_y=N, voxel_num_z=K) ig3 = ImageGeometry(voxel_num_x=M, voxel_num_y=N, channels=channels) ig4 = ImageGeometry(voxel_num_x=M, voxel_num_y=N, channels=channels, voxel_num_z=K) G1 = Gradient(ig1, correlation='Space', backend='numpy') print(G1.range_geometry().shape, '2D no channels') G4 = Gradient(ig3, correlation='SpaceChannels', backend='numpy') print(G4.range_geometry().shape, '2D with channels corr') G5 = Gradient(ig3, correlation='Space', backend='numpy') print(G5.range_geometry().shape, '2D with channels no corr') G6 = Gradient(ig4, correlation='Space', backend='numpy') print(G6.range_geometry().shape, '3D with channels no corr') G7 = Gradient(ig4, correlation='SpaceChannels', backend='numpy') print(G7.range_geometry().shape, '3D with channels with corr') u = ig1.allocate(ImageGeometry.RANDOM) w = G1.range_geometry().allocate(ImageGeometry.RANDOM_INT) LHS = (G1.direct(u) * w).sum() RHS = (u * G1.adjoint(w)).sum() numpy.testing.assert_approx_equal(LHS, RHS, significant=1) numpy.testing.assert_approx_equal(G1.norm(), numpy.sqrt(2 * 4), significant=1) u1 = ig3.allocate('random') w1 = G4.range_geometry().allocate('random') LHS1 = (G4.direct(u1) * w1).sum() RHS1 = (u1 * G4.adjoint(w1)).sum() numpy.testing.assert_approx_equal(LHS1, RHS1, significant=1) numpy.testing.assert_almost_equal(G4.norm(), numpy.sqrt(3 * 4), decimal=0) u2 = ig4.allocate('random') w2 = G7.range_geometry().allocate('random') LHS2 = (G7.direct(u2) * w2).sum() RHS2 = (u2 * G7.adjoint(w2)).sum() numpy.testing.assert_approx_equal(LHS2, RHS2, significant=3) numpy.testing.assert_approx_equal(G7.norm(), numpy.sqrt(3 * 4), significant=1) #check direct/adjoint for space/channels correlation ig_channel = ImageGeometry(voxel_num_x=2, voxel_num_y=3, channels=2) G_no_channel = Gradient(ig_channel, correlation='Space', backend='numpy') G_channel = Gradient(ig_channel, correlation='SpaceChannels', backend='numpy') u3 = ig_channel.allocate('random_int') res_no_channel = G_no_channel.direct(u3) res_channel = G_channel.direct(u3) print(" Derivative for 3 directions, first is wrt Channel direction\n") print(res_channel[0].as_array()) print(res_channel[1].as_array()) print(res_channel[2].as_array()) print(" Derivative for 2 directions, no Channel direction\n") print(res_no_channel[0].as_array()) print(res_no_channel[1].as_array()) ig2D = ImageGeometry(voxel_num_x=2, voxel_num_y=3) u4 = ig2D.allocate('random_int') G2D = Gradient(ig2D, backend='numpy') res = G2D.direct(u4) print(res[0].as_array()) print(res[1].as_array()) M, N = 20, 30 ig = ImageGeometry(M, N) arr = ig.allocate('random_int') # check direct of Gradient and sparse matrix G = Gradient(ig, backend='numpy') norm1 = G.norm(iterations=300) print("should be sqrt(8) {} {}".format(numpy.sqrt(8), norm1)) numpy.testing.assert_almost_equal(norm1, numpy.sqrt(8), decimal=1) ig4 = ImageGeometry(M, N, channels=3) G4 = Gradient(ig4, correlation="SpaceChannels", backend='numpy') norm4 = G4.norm(iterations=300) print("should be sqrt(12) {} {}".format(numpy.sqrt(12), norm4)) self.assertTrue((norm4 - numpy.sqrt(12)) / norm4 < 0.2)
alpha = .2 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))
ag = AcquisitionGeometry('parallel', '2D', angles, detectors) device = input('Available device: GPU==1 / CPU==0 ') if device == '1': 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))
def test_dot_test2(self): Grad3 = Gradient(self.ig3, correlation = 'SpaceChannel', backend='c') # self.assertAlmostEqual(lhs3, rhs3) self.assertTrue( LinearOperator.dot_test(Grad3 , verbose=True)) self.assertTrue( LinearOperator.dot_test(Grad3 , decimal=6, verbose=True))