def svd_power_method(arr, geo, angles, **kwargs): """ method to determine the largest singular value for the rectangular A projection matrix. :param arr: (np.ndarray, dtype=np.float32) random vector :param geo: (tigre.geometry()) geometry of the set up :param angles: (np.ndarray, dtype=np.float32) angles of projection :param kwargs: optional arguments :keyword maxiter: (int) number of iterations to run unless margin of error epsilon has been reached. Default: 100 :keyword epsilon: (float) margin of error for the algorithm. Default: 0.001 :keyword verbose: (bool) print stuff. Default: False :return: (float) the largest singular value of the A matrix. """ maxiter = 100 if "maxiter" in kwargs: maxiter = kwargs["maxiter"] # very optimistic value for epsilon (it turns out) epsilon = 0.001 if "epsilon" in kwargs: epsilon = kwargs["epsilon"] verbose = False if "verbose" in kwargs: verbose = kwargs["verbose"] error = np.inf arr_old = arr.copy() i = 0 while error >= epsilon: if verbose: if i == 0: print("using SVD power method to calculate " "Lipschitz const") if np.mod(i, 10) == 0: print("error for val is:" + str(error)) # very verbose and inefficient for now omega = tigre.Ax(arr_old, geo, angles) alpha = np.linalg.norm(omega) u = (1.0 / alpha) * omega z = tigre.Atb(u, geo, angles) beta = np.linalg.norm(z) arr = (1.0 / beta) * z error = np.linalg.norm(tigre.Ax(arr, geo, angles) - beta * u) sigma = beta arr_old = arr i += 1 if i >= maxiter: return sigma return sigma
def run_main_iter(self): self.l2l = np.zeros([self.niter], dtype=np.float32) avgtime = [] for i in range(self.niter): if i == 0: print("CGLS Algorithm in progress.") toc = time.clock() if i == 1: tic = time.clock() print('Esitmated time until completetion (s): ' + str((self.niter - 1) * (tic - toc))) avgtic = time.clock() q = tigre.Ax(self.__p__, self.geo, self.angles, 'ray-voxel') q_norm = np.linalg.norm(q) alpha = self.__gamma__ / (q_norm * q_norm) self.res += alpha * self.__p__ avgtoc = time.clock() avgtime.append(abs(avgtic - avgtoc)) for item in self.__dict__: if isinstance(getattr(self, item), np.ndarray): if np.isnan(getattr(self, item)).any(): raise ValueError('nan found for ' + item + ' at iteraton ' + str(i)) aux = self.proj - \ tigre.Ax(self.res, self.geo, self.angles, 'ray-voxel') self.l2l[i] = np.linalg.norm(aux) if i > 0 and self.l2l[i] > self.l2l[i - 1]: print('re-initilization of CGLS called at iteration:' + str(i)) if self.re_init_at_iteration + 1 == i: print( 'Algorithm exited with two consecutive reinitializations.' ) return self.res self.res -= alpha * self.__p__ self.reinitialise_cgls() self.re_init_at_iteration = i self.__r__ -= alpha * q s = tigre.Atb(self.__r__, self.geo, self.angles) s_norm = np.linalg.norm(s) gamma1 = s_norm * s_norm beta = gamma1 / self.__gamma__ if self.log_parameters: self.parameter_history['alpha'][i] = alpha self.parameter_history['beta'][i] = beta self.parameter_history['gamma'][i] = self.__gamma__ self.parameter_history['q_norm'][i] = q_norm self.parameter_history['s_norm'][i] = s_norm self.__gamma__ = gamma1 self.__p__ = s + beta * self.__p__ print('Average time taken for each iteration for CGLS:' + str(sum(avgtime) / len(avgtime)) + '(s)')
def update_image(self, geo, angle, iteration): """ VERBOSE: for j in range(angleblocks): angle = np.array([alpha[j]], dtype=np.float32) proj_err = proj[angle_index[j]] - Ax(res, geo, angle, 'Siddon') backprj = Atb(proj_err, geo, angle, 'FDK') res += backprj res[res<0]=0 :return: None """ self.res += ( self.__bm__ * 2 * tigre.Atb( ( self.proj[self.angle_index[iteration]] - tigre.Ax(self.res, geo, angle, "interpolated", gpuids=self.gpuids) ), geo, angle, "matched", gpuids=self.gpuids, ) )
def ray_trace(self, phantom2, tile): if self.tigre_works: # resort to astra if tigre doesn't work try: return np.squeeze(tigre.Ax(phantom2, self.geomet, self.angles)) except Exception: logging.info("WARNING: Tigre GPU not working") self.tigre_works = False
def setUp(**kwargs): if kwargs.get('mode') == 'cone': geo = tigre.geometry(mode='cone', nVoxel=kwargs.get('nVoxel'), default_geo=True) angles_1 = np.linspace(0, 2 * np.pi, 100, dtype=np.float32) angles_3 = np.zeros((100), dtype=np.float32) angles = np.vstack((angles_1, angles_3, angles_3)).T img = data_loader.load_head_phantom(number_of_voxels=geo.nVoxel) proj = tigre.Ax(img, geo, angles, kwargs.get('krylov')) if kwargs.get('alglist') == 'all': alglist = ['sart', 'sirt', 'ossart', 'asd_pocs', 'FDK', 'cgls'] else: alglist = kwargs.pop('alglist').split() plot_algs(alglist, proj, geo, angles, niter=int(kwargs.pop('niter')), **kwargs) if kwargs.get('mode') == 'parallel': geo = tigre.geometry(mode='parallel', nVoxel=kwargs.get('nVoxel'), default_geo=True) angles_1 = np.linspace(0, 2 * np.pi, 100, dtype=np.float32) angles_3 = np.zeros((100), dtype=np.float32) angles = np.vstack((angles_1, angles_3, angles_3)).T img = data_loader.load_head_phantom(number_of_voxels=geo.nVoxel) proj = tigre.Ax(img, geo, angles, kwargs.get('krylov')) if kwargs.get('alglist') == 'all': alglist = ['sart', 'sirt', 'ossart', 'asd_pocs', 'fbp', 'cgls'] else: alglist = kwargs.pop('alglist').split() plot_algs(alglist, proj, geo, angles, niter=int(kwargs.pop('niter')), **kwargs)
def svd_power_method(arr, geo, angles, **kwargs): maxiter = 100 if 'maxiter' in kwargs: maxiter = kwargs['maxiter'] #very optimistic value for epsilon (it turns out) epsilon = 0.001 if 'epsilon' in kwargs: epsilon = kwargs['epsilon'] verbose = False if 'verbose' in kwargs: verbose = kwargs['verbose'] error = np.inf arr_old = arr.copy() i = 0 while error >= epsilon: if verbose: if i == 0: print('using SVD power method to calculate ' 'Lipschitz const') if np.mod(i, 10) == 0: print('error for val is:' + str(error)) # very verbose and inefficient for now omega = tigre.Ax(arr_old, geo, angles) alpha = np.linalg.norm(omega) u = (1. / alpha) * omega z = tigre.Atb(u, geo, angles) beta = np.linalg.norm(z) arr = (1. / beta) * z error = np.linalg.norm(tigre.Ax(arr, geo, angles) - beta * u) sigma = beta arr_old = arr i += 1 if i >= maxiter: return sigma return sigma # http://www.anstuocmath.ro/mathematics/anale2015vol2/Bentbib_A.H.__Kanber_A..pdf
def test(self): head = load_head_phantom(self.geo.nVoxel) proj = tigre.Ax(head, self.geo, self.angles) if self.algorithm in ["FDK", "fbp"]: self.output = getattr(tigre.algorithms, self.algorithm)(proj, self.geo, self.angles) self.rmse = Measure_Quality(self.output, head, ["nRMSE"]) self.algorithm_finished = True return self.timestarted = time.asctime() self.output = getattr(tigre.algorithms, self.algorithm)( proj, self.geo, self.angles, self.niter, **self.kwargs ) self.timeended = time.asctime() self.algorithm_finished = True self.rmse = Measure_Quality(self.output, head, ["nRMSE"])
def test(self): if self.algorithm == 'fbp' and self.geo.mode != 'parallel': print('WARNING: fbp was implemented in cone beam.') print('Test ignored.\n') raise SystemExit() head = load_head_phantom(self.geo.nVoxel) proj = tigre.Ax(head, self.geo, self.angles) if self.algorithm in ['FDK', 'fbp']: self.output = getattr(tigre.algorithms, self.algorithm)(proj, self.geo, self.angles) self.rmse = Measure_Quality(self.output, head, ['nRMSE']) self.algorithm_finished = True return self.timestarted = time.asctime() self.output = getattr(tigre.algorithms, self.algorithm)(proj, self.geo, self.angles, self.niter, **self.kwargs) self.timeended = time.asctime() self.algorithm_finished = True self.rmse = Measure_Quality(self.output, head, ['nRMSE'])
import time import sys from tigre.demos.Test_data import data_loader from matplotlib import pyplot as plt from tigre.utilities.Measure_Quality import Measure_Quality #geo1 = tigre.geometry(mode='cone', high_quality=False, default=True) geo = tigre.geometry(mode='cone', nVoxel=np.array([256,256,256]),default=True) geo.dDetector = np.array([0.8, 0.8])*2 # size of each pixel (mm) geo.sDetector = geo.dDetector * geo.nDetector niter = 10 nangles = 100 angles = np.linspace(0, 2 * np.pi, nangles, dtype=np.float32) #head = np.load('src_img_cubic_256.npy') #data_loader.load_head_phantom(geo.nVoxel) head = data_loader.load_head_phantom(geo.nVoxel) proj = tigre.Ax(head,geo,angles) fdkout = algs.fdk(proj,geo,angles) sirtout = algs.ossart(proj,geo,angles,20,blocksize=20) # 'RMSE' # 'MSSIM' # 'SSD' # 'UQI' print('RMSE fdk:') print(Measure_Quality(fdkout,head,['nRMSE'])) print('RMSE ossart') print(Measure_Quality(sirtout,head,['nRMSE'])) plt.subplot(211) plt.imshow(fdkout[geo.nVoxel[0]//2]) plt.subplot(212) plt.imshow(sirtout[geo.nVoxel[0]//2])
geo.accuracy = 0.5 # Accuracy of FWD proj (vx/sample) # lets do just one angles angles = np.array([0]) #%% Description # The difference between them is that `Siddon` will compute the # intersection of a ray crossing each voxel, and the `interpolated` will # sample the voxels at a given sample rate. #%% Main difference head = sample_loader.load_head_phantom(geo.nVoxel) start_time = time.time() projInterp = tigre.Ax(head, geo, angles, "interpolated") interptime = time.time() - start_time start_time = time.time() projray = tigre.Ax(head, geo, angles, "Siddon") raytime = time.time() - start_time # It is relatively clear that discretization artefacts appear with the # ray-voxel approach (middle one) tigre.plotproj( np.concatenate([np.abs(projInterp - projray), projray, projInterp], axis=1), angles) # But also the ray voxel approach is faster (more obvious at bigger sizes) print("Time interpolated: " + str(interptime)) print("Time Siddon : " + str(raytime)) #%% With small voxel the errors are more obvious
def run_main_iter(self): self.l2l = np.zeros([self.niter], dtype=np.float32) avgtime = [] for i in range(self.niter): if i == 0: if self.verbose: print("CGLS Algorithm in progress.") toc = default_timer() if i == 1: tic = default_timer() if self.verbose: print("Esitmated time until completetion (s): " + str((self.niter - 1) * (tic - toc))) avgtic = default_timer() q = tigre.Ax(self.__p__, self.geo, self.angles, "Siddon", gpuids=self.gpuids) q_norm = np.linalg.norm(q) alpha = self.__gamma__ / (q_norm * q_norm) self.res += alpha * self.__p__ avgtoc = default_timer() avgtime.append(abs(avgtic - avgtoc)) for item in self.__dict__: if isinstance(getattr(self, item), np.ndarray): if np.isnan(getattr(self, item)).any(): raise ValueError("nan found for " + item + " at iteraton " + str(i)) aux = self.proj - tigre.Ax( self.res, self.geo, self.angles, "Siddon", gpuids=self.gpuids) self.l2l[i] = np.linalg.norm(aux) if i > 0 and self.l2l[i] > self.l2l[i - 1]: if self.verbose: print("re-initilization of CGLS called at iteration:" + str(i)) if self.re_init_at_iteration + 1 == i: if self.verbose: print( "Algorithm exited with two consecutive reinitializations." ) return self.res self.res -= alpha * self.__p__ self.reinitialise_cgls() self.re_init_at_iteration = i self.__r__ -= alpha * q s = tigre.Atb(self.__r__, self.geo, self.angles, gpuids=self.gpuids) s_norm = np.linalg.norm(s) gamma1 = s_norm * s_norm beta = gamma1 / self.__gamma__ if self.log_parameters: self.parameter_history["alpha"][i] = alpha self.parameter_history["beta"][i] = beta self.parameter_history["gamma"][i] = self.__gamma__ self.parameter_history["q_norm"][i] = q_norm self.parameter_history["s_norm"][i] = s_norm self.__gamma__ = gamma1 self.__p__ = s + beta * self.__p__ if self.verbose: print("Average time taken for each iteration for CGLS:" + str(sum(avgtime) / len(avgtime)) + "(s)")
import numpy as np from tigre.utilities import sample_loader from tigre.utilities import CTnoise import tigre.algorithms as algs from matplotlib import pyplot as plt #%% Geometry geo = tigre.geometry_default(high_resolution=False) #%% Load data and generate projections # define angles angles = np.linspace(0, 2 * np.pi, 100) # Load thorax phatom data head = sample_loader.load_head_phantom(geo.nVoxel) # generate projections projections = tigre.Ax(head, geo, angles) # add noise noise_projections = CTnoise.add(projections, Poisson=1e5, Gaussian=np.array([0, 10])) ## FISTA is a quadratically converging algorithm. # 'hyper': This parameter should approximate the largest # eigenvalue in the A matrix in the equation Ax-b and Atb. # Empirical tests show that for, the headphantom object: # # geo.nVoxel = [64,64,64]' , hyper (approx=) 2.e8 # geo.nVoxel = [512,512,512]' , hyper (approx=) 2.e4 # Default: 2.e8 # 'tviter': Number of iterations of Im3ddenoise to use. Default: 20
class TestStdout(unittest.TestCase): pass def test_generator(algorithm, proj, geo, angles, niter): def test(self): capturedOutput = StringIO.StringIO() sys.stdout = capturedOutput getattr(algs, algorithm)(proj, geo, angles, niter=niter, verbose=False) self.assertIs(capturedOutput.getvalue(), "") sys.stdout = sys.__stdout__ return test if __name__ == "__main__": geo = tigre.geometry(mode="cone", default=True, high_quality=False) print(geo) true_img = data_loader.load_head_phantom(geo.nVoxel) angles = np.linspace(0, 2 * np.pi, 100) niter = 5 proj = tigre.Ax(true_img, geo, angles) for alg in algs.__all__: if alg != "fbp": test_name = "test_print_%s" % (alg) test = test_generator(alg, proj, geo, angles, niter) setattr(TestStdout, test_name, test) unittest.main()
# Geometry #geo1 = tigre.geometry(mode='cone', high_quality=False, default=True) geo = tigre.geometry(mode='cone', nVoxel=np.array([256, 256, 256]), default=True) geo.dDetector = np.array([0.8, 0.8]) * 2 # size of each pixel (mm) geo.sDetector = geo.dDetector * geo.nDetector # print(geo) nangles = 100 angles = np.linspace(0, 2 * np.pi, nangles, endpoint=False, dtype=np.float32) # Prepare projection data #head = np.load('src_img_cubic_256.npy') head = data_loader.load_head_phantom(geo.nVoxel) proj = tigre.Ax(head, geo, angles, gpuids=gpuids) # Reconstruct niter = 20 fdkout = algs.fdk(proj, geo, angles, gpuids=gpuids) sirtout = algs.ossart(proj, geo, angles, niter, blocksize=20, gpuids=gpuids) # Measure Quality # 'RMSE', 'MSSIM', 'SSD', 'UQI' print('RMSE fdk:') print(Measure_Quality(fdkout, head, ['nRMSE'])) print('RMSE ossart') print(Measure_Quality(sirtout, head, ['nRMSE'])) # Plot fig, axes = plt.subplots(3, 2)
geo = tigre.geometry_default(high_resolution=False) angles = np.linspace(0, 2 * np.pi, 100) angles = np.hstack([angles, angles, angles]) # loop 3 times # Load thorax phatom data head = sample_loader.load_head_phantom(geo.nVoxel) # This makes it helical geo.offOrigin = np.zeros((angles.shape[0], 3)) geo.offOrigin[:, 2] = np.linspace( -1024 / 2 + 128, 1024 / 2 - 128, angles.shape[0]) # about 256^3 images fit int he detector with this size. # project data data = tigre.Ax(head, geo, angles) # Uncomment if you want to see the data # plotProj(data,angles); ## Reconstruct Helical SIRTimg = algs.sirt(data, geo, angles, 30) # SARTimg=SART(data,geo,angles,30); # takes time CGLSimg = algs.cgls(data, geo, angles, 20) ## Plot results # CGLS and SIRT tigre.plotImg(np.concatenate([head, SIRTimg, CGLSimg], axis=1), dim="z", step=3, clims=[0, 1])
import tigre import tigre.algorithms as algs import numpy as np geo = tigre.geometry(mode='cone', nVoxel=np.array([32, 64, 128]), default_geo=True) from tigre.demos.Test_data import data_loader img = data_loader.load_head_phantom(geo.nVoxel) angles = np.linspace(0, np.pi * 2, 100, dtype=np.float32) proj = tigre.Ax(img, geo, angles) algs.fdk(proj, geo, angles)
# --------------------------- CGLS for both modes--------------------------------------- do_algs(['cgls'], proj_par, geo_par, angles, mode='Parallel', **dict(nVoxel = [64 ,64 ,64])) do_algs(['cgls'], proj_con, geo_con, angles, mode='Cone', **dict(nVoxel = [64 ,64 ,64])) """ import tigre.algorithms as algs nangles = 100 angles_1 = np.linspace(0, 2 * np.pi, nangles, dtype=np.float32) angles_2 = np.ones( (nangles), dtype=np.float32) * np.array(np.pi / 4, dtype=np.float32) angles_3 = np.zeros((nangles), dtype=np.float32) angles = np.vstack((angles_1, angles_3, angles_3)).T geo = tigre.geometry(mode='cone', nVoxel=nVoxel, default_geo=True) source_img = data_loader.load_head_phantom(number_of_voxels=geo.nVoxel) proj = tigre.Ax(source_img, geo, angles) res = algs.awasd_pocs(proj, geo, angles, niter=10, **dict(blocksize=nangles)) from matplotlib import pyplot as plt plt.imshow(res[32]) plt.show() """ from tigre.utilities.Atb import Atb Atb(proj,geo,angles,'FDK')[32] #plt.colorbar() #plt.title('FDK') mat = Atb(proj,geo,angles,'matched') plt.subplot(221) plt.imshow(mat[32]) plt.subplot(222) plt.imshow(mat[:,32]) plt.subplot(223)
from tigre.utilities import sample_loader from tigre.utilities import CTnoise import tigre.algorithms as algs from matplotlib import pyplot as plt from tigre.utilities.im3Dnorm import im3DNORM #%% Geometry geo = tigre.geometry_default(high_resolution=False) #%% Load data and generate projections # define angles angles = np.linspace(0, 2 * np.pi, 100) # Load thorax phatom data head = sample_loader.load_head_phantom(geo.nVoxel) # generate projections projections = tigre.Ax(head, geo, angles) # add noise noise_projections = CTnoise.add(projections, Poisson=1e5, Gaussian=np.array([0, 10])) #%% Lets create a OS-SART test for comparison imgOSSART = algs.ossart(noise_projections, geo, angles, 10) #%% Total Variation algorithms # # ASD-POCS: Adaptative Steeppest Descent-Projection On Convex Subsets # Often called POCS # ========================================================================== # ========================================================================== # ASD-POCS minimizes At-B and the TV norm separately in each iteration, # i.e. reconstructs the image first and then reduces the TV norm, every # iteration. As the other algorithms the mandatory inputs are projections,
def testandlog(alglist, geo, angles, niter, saveresult=False, newsubdirectory=False, **kwargs): nangles = angles.shape[0] # createlogfile dirname = os.path.dirname(__file__) kwargs.update(dict(blocksize=20)) # create top level folder if this does not exist if 'logs' not in os.listdir(dirname): os.system('mkdir ' + 'logs') logdirectory = os.path.join(dirname, 'logs') logdate = time.strftime("%a_%b_%d") if logdate not in os.listdir(logdirectory): os.system('mkdir ' + os.path.join(logdirectory, logdate)) subdirectory = os.path.join(logdirectory, logdate) if 'subdirectoryname' in kwargs: subdirectoryname = kwargs['subdirectoryname'] else: subdirectoryname = 'test' + str(len(os.listdir(subdirectory)) - 1) if newsubdirectory: subdirectoryname = 'test' + str(len(os.listdir(subdirectory))) # create subdirectory for test if this does not exist if subdirectoryname not in os.listdir(subdirectory): os.system('mkdir ' + os.path.join(subdirectory, subdirectoryname)) subdirectory = os.path.join(logdirectory, logdate, subdirectoryname) timestamp = str(time.asctime()).replace(' ', '_') # create/append to log file logfilename = None for filename in os.listdir(subdirectory): if os.path.splitext(filename)[-1] == '.log': logfilename = os.path.split(filename)[-1] logflist = [] if logfilename is not None: logflist.extend( open(os.path.join(subdirectory, logfilename), 'r').readlines()) else: logfilename = timestamp + '.log' try: algsuccess = np.load( os.path.join(subdirectory, os.path.splitext(logfilename)[0]) + '.npy').item() except Exception: algsuccess = dict() # TODO: need to fix directory path here. repo_path = os.path.join(dirname, '..', '..', '.git/') repo = Repo(repo_path) commit = list(repo.iter_commits(repo.active_branch))[0] uname = str(os.uname()) current_config = dict(uname=uname, commithash=commit.hexsha) try: prev_config = open( os.path.join(subdirectory, os.path.splitext(logfilename)[0] + '_config') + '.npy').item() except Exception: prev_config = dict() prev_config.update(current_config) for item in current_config: if prev_config[item] != current_config[item]: logflist.append( '------------------------------------------------\n') logflist.append('Configuration changed for' + item + ':\n') logflist.append('From: ' + str(prev_config[item])) logflist.append('To : ' + str(current_config[item])) if len(logflist) == 0: # If file is empty # MACHINE logflist.append(uname + '\n') # GIT header for logfile if not repo.bare: logflist.append( '------------------------------------------------\n') logflist.append(make_repository_str(repo)) # create list of commits then print some of them to stdout logflist.append(make_commit_str(commit)) logflist.append( '\n------------------------------------------------\n') else: print('Could not load repository at {} :('.format(repo_path)) logflist.append('GEOMETRY used for instance of testandlog: \n') for item in geo.__dict__: logflist.append(item + ': ' + str(getattr(geo, item)) + '\n') logflist.append('------------------------------------------------\n') # Run the algorithms source_img = data_loader.load_head_phantom(number_of_voxels=geo.nVoxel) proj = tigre.Ax(source_img, geo, angles) for alg in alglist: logflist.append(str(alg).upper() + ' ' + time.asctime() + '\n') logflist.append('nproj: ' + str(nangles) + ' niter: ' + str(niter) + '\n') if np.sum(angles[:, 1]) != 0 or np.sum(angles[:, 2]) != 0: spherical = True else: spherical = False logflist.append('spherical projection: ' + str(spherical) + '\n') algpassed = False try: tic = time.clock() res = getattr(algs, alg)(proj, geo, angles, niter=niter, **kwargs) algpassed = True except Exception: formatedlines = traceback.format_exc() logflist.append('ERROR at ' + str(time.strftime("%H:%M:%S") + '\n')) logflist.append(''.join(formatedlines) + '\n') finally: toc = time.clock() algsuccess.update({alg: algpassed}) np.save( os.path.join(subdirectory, os.path.splitext(logfilename)[0]), algsuccess) np.save( os.path.join(subdirectory, os.path.splitext(logfilename)[0]) + '_config', current_config) pass if algpassed: logflist.append('total time taken: ' + str(abs(tic - toc)) + '\n') logflist.append('------------------------------------------------\n') logf = open(os.path.join(subdirectory, logfilename), 'w') logf.write(''.join(logflist)) logf.close() if saveresult and algpassed: warnings.filterwarnings("ignore") plt.figure() plt.subplot(3, 1, 1) plt.imshow(res[geo.nVoxel[0] / 2]) plt.title('results for ' + alg) plt.ylabel('dim 0') plt.subplot(3, 1, 2) plt.imshow(res[:, geo.nVoxel[1] / 2]) plt.ylabel('dim 1') plt.subplot(3, 1, 3) plt.imshow(res[:, :, geo.nVoxel[2] / 2]) plt.ylabel('dim 2') plt.savefig( os.path.join(subdirectory, alg + '_' + geo.mode + '_' + timestamp + '.png')) warnings.filterwarnings("error")
def run_main_iter(self): self.l2l = np.zeros((1, self.niter), dtype=np.float32) avgtime = [] for i in range(self.niter): if self.verbose: self._estimate_time_until_completion(i) if self.Quameasopts is not None: res_prev = copy.deepcopy(self.res) avgtic = default_timer() q = tigre.Ax(self.__p__, self.geo, self.angles, "Siddon", gpuids=self.gpuids) q_norm = np.linalg.norm(q) alpha = self.__gamma__ / (q_norm * q_norm) self.res += alpha * self.__p__ avgtoc = default_timer() avgtime.append(abs(avgtic - avgtoc)) for item in self.__dict__: if (isinstance(getattr(self, item), np.ndarray) and np.isnan(getattr(self, item)).any()): raise ValueError("nan found for " + item + " at iteraton " + str(i)) aux = self.proj - tigre.Ax( self.res, self.geo, self.angles, "Siddon", gpuids=self.gpuids) self.l2l[0, i] = np.linalg.norm(aux) if i > 0 and self.l2l[0, i] > self.l2l[0, i - 1]: if self.verbose: print("re-initilization of CGLS called at iteration:" + str(i)) if self.re_init_at_iteration + 1 == i: if self.verbose: print( "Algorithm exited with two consecutive reinitializations." ) return self.res self.res -= alpha * self.__p__ self.reinitialise_cgls() self.re_init_at_iteration = i self.__r__ -= alpha * q s = tigre.Atb(self.__r__, self.geo, self.angles, backprojection_type="matched", gpuids=self.gpuids) s_norm = np.linalg.norm(s) gamma1 = s_norm * s_norm beta = gamma1 / self.__gamma__ if self.log_parameters: self.parameter_history["alpha"][i] = alpha self.parameter_history["beta"][i] = beta self.parameter_history["gamma"][i] = self.__gamma__ self.parameter_history["q_norm"][i] = q_norm self.parameter_history["s_norm"][i] = s_norm self.__gamma__ = gamma1 self.__p__ = s + beta * self.__p__ if self.Quameasopts is not None: self.error_measurement(res_prev, i) if self.verbose: print("Average time taken for each iteration for CGLS:" + str(sum(avgtime) / len(avgtime)) + "(s)")