예제 #1
0
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)
예제 #2
0
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)
예제 #3
0
 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"])
예제 #4
0
    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'])
예제 #5
0
파일: testforlog.py 프로젝트: CERN/TIGRE
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")
예제 #6
0
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()
예제 #7
0
파일: example.py 프로젝트: dyycy/TIGRE
# 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
예제 #8
0
import tigre
import numpy as np
from tigre import Ax
from tigre.demos.Test_data import data_loader
from cil.utilities.display import plotter2D

geo = tigre.geometry_default(high_quality=False)
print(geo.dDetector)
geo.nDetector[0] = 1
print(geo.nDetector)
geo.sDetector = geo.dDetector * geo.nDetector
print(geo.sDetector)
geo.nVoxel[0] = 1
geo.sVoxel = geo.nVoxel * geo.dVoxel
# print (geo)
# define angles
angles = np.linspace(0, 2 * np.pi, dtype=np.float32)
# load head phantom data
head = data_loader.load_head_phantom(number_of_voxels=geo.nVoxel)
# generate projections
projections = Ax(head, geo, angles, 'interpolated')

print(geo.nVoxel, head.shape, projections.shape)
# plotter2D([head[0], projections[:,0,:]])
예제 #9
0
파일: devtest.py 프로젝트: CERN/TIGRE
from __future__ import print_function
import tigre
import copy
import tigre.algorithms as algs
import numpy as np
import tigre.algorithms as algs
from tigre.demos.Test_data import data_loader
from matplotlib import pyplot as plt

geo = tigre.geometry(mode='cone', nVoxel=np.array([64, 64, 62]), default_geo=True)
niter = 10
nangles = 100
angles = np.linspace(0, 2 * np.pi, nangles, dtype=np.float32)
#angles_2 = np.zeros((nangles, ), dtype=np.float32)
#angles_3 = np.ones((nangles, ), dtype=np.float32)
#angles = np.vstack((angles_1, angles_2, angles_3)).T
head = data_loader.load_head_phantom(geo.nVoxel)
proj = tigre.Ax(head,geo,angles)
output = algs.sart(proj,geo,angles,niter=5)
plt.imshow(output[geo.nVoxel[0]/2])
plt.colorbar()
plt.show()
예제 #10
0
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")
예제 #11
0
import numpy as np
from matplotlib import pyplot as plt
from tigre.demos.Test_data import data_loader
from tigre.utilities.Ax import Ax
import tigre.algorithms as algs
from tigre.algorithms.iterative_recon_alg import IterativeReconAlg

# ----------------PROFILINGIMPORT-------------------

from line_profiler import LineProfiler

# ---------------GEOMETRY---------------------------

geo = tigre.geometry(mode='parallel', nVoxel=np.array([64, 64, 64]))
source_img = data_loader.load_head_phantom(number_of_voxels=geo.nVoxel)

# ---------------------ANGLES-------------------------

angles_1 = np.linspace(0, 2 * np.pi, 100, dtype=np.float32)
angles_2 = np.ones((100), dtype=np.float32) * np.array(np.pi / 4, dtype=np.float32)
angles_3 = np.zeros((100), dtype=np.float32)
angles = np.vstack((angles_1, angles_3, angles_3)).T

# --------------------PROJECTION----------------------

proj = Ax(source_img, geo, angles)


# ---------------------RECONSTRUCTION------------------