コード例 #1
0
ファイル: test_jit.py プロジェクト: Brainiarc7/afnumpy
def test_comparisons():
    a = afnumpy.arange(10, dtype="float32") - 5.
    b = afnumpy.ones((10), dtype="float32")
    a.eval()
    a_mask = a < 0.
    a_sum = a_mask.sum()
    a -= b
    assert(a_sum == a_mask.sum())
    a_mask = a > 0.
    a_sum = a_mask.sum()
    a -= b
    assert(a_sum == a_mask.sum())
    a_mask = a >= 0.
    a_sum = a_mask.sum()
    a -= b
    assert(a_sum == a_mask.sum())
    a_mask = a <= 0.
    a_sum = a_mask.sum()
    a -= b
    assert(a_sum == a_mask.sum())
    a_mask = a == 0.
    a_sum = a_mask.sum()
    a *= 0
    assert(a_sum == a_mask.sum())
    a = afnumpy.arange(10, dtype="float32") - 5.
    a.eval()
    a_mask = a != 0.
    a_sum = a_mask.sum()
    a *= 0
    assert(a_sum == a_mask.sum())
コード例 #2
0
def test_comparisons():
    a = afnumpy.arange(10, dtype="float32") - 5.
    b = afnumpy.ones((10), dtype="float32")
    a.eval()
    a_mask = a < 0.
    a_sum = a_mask.sum()
    a -= b
    assert (a_sum == a_mask.sum())
    a_mask = a > 0.
    a_sum = a_mask.sum()
    a -= b
    assert (a_sum == a_mask.sum())
    a_mask = a >= 0.
    a_sum = a_mask.sum()
    a -= b
    assert (a_sum == a_mask.sum())
    a_mask = a <= 0.
    a_sum = a_mask.sum()
    a -= b
    assert (a_sum == a_mask.sum())
    a_mask = a == 0.
    a_sum = a_mask.sum()
    a *= 0
    assert (a_sum == a_mask.sum())
    a = afnumpy.arange(10, dtype="float32") - 5.
    a.eval()
    a_mask = a != 0.
    a_sum = a_mask.sum()
    a *= 0
    assert (a_sum == a_mask.sum())
コード例 #3
0
ファイル: test_ndarray.py プロジェクト: FilipeMaia/afnumpy
def test_binary_arithmetic():
    a = afnumpy.random.rand(3)
    b = numpy.array(a)

    fassert(a+a, b+b)
    fassert(a+3, b+3)
    fassert(3+a, 3+b)

    fassert(a-a, b-b)
    fassert(a-3, b-3)
    fassert(3-a, 3-b)

    fassert(a*a, b*b)
    fassert(a*3, b*3)
    fassert(3*a, 3*b)

    fassert(a/a, b/b)
    fassert(a/3, b/3)
    fassert(3/a, 3/b)

    fassert(a**a, b**b)
    fassert(a**3, b**3)
    fassert(3**a, 3**b)

    fassert(a%a, b%b)
    fassert(a%3, b%3)
    fassert(3%a, 3%b)

    # Check for arguments of diffeernt types
    a = afnumpy.ones(3,dtype=numpy.uint32)
    b = numpy.array(a)
    fassert(a+3.0, b+3.0)
    # This is a tricky case we won't support for now
    # fassert(a+numpy.float32(3.0), b+numpy.float32(3.0))
    fassert(3.0+a, 3.0+b)

    fassert(a-3.0, b-3.0)
    fassert(3.0-a, 3.0-b)

    fassert(a*3.0, b*3.0)
    fassert(3.0*a, 3.0*b)

    fassert(a/3.0, b/3.0)
    fassert(3.0/a, 3.0/b)
    fassert(3/a, 3/b)

    fassert(a**3.0, b**3.0)
    fassert(3.0**a, 3.0**b)

    fassert(a%3.0, b%3.0)
    fassert(3.0%a, 3.0%b)

    assert(type(numpy.float32(3)+a) == afnumpy.ndarray)
コード例 #4
0
ファイル: test_ndarray.py プロジェクト: syurkevi/afnumpy
def test_binary_arithmetic():
    a = afnumpy.random.rand(3)
    b = numpy.array(a)

    fassert(a + a, b + b)
    fassert(a + 3, b + 3)
    fassert(3 + a, 3 + b)

    fassert(a - a, b - b)
    fassert(a - 3, b - 3)
    fassert(3 - a, 3 - b)

    fassert(a * a, b * b)
    fassert(a * 3, b * 3)
    fassert(3 * a, 3 * b)

    fassert(a / a, b / b)
    fassert(a / 3, b / 3)
    fassert(3 / a, 3 / b)

    fassert(a**a, b**b)
    fassert(a**3, b**3)
    fassert(3**a, 3**b)

    fassert(a % a, b % b)
    fassert(a % 3, b % 3)
    fassert(3 % a, 3 % b)

    # Check for arguments of diffeernt types
    a = afnumpy.ones(3, dtype=numpy.uint32)
    b = numpy.array(a)
    fassert(a + 3.0, b + 3.0)
    # This is a tricky case we won't support for now
    # fassert(a+numpy.float32(3.0), b+numpy.float32(3.0))
    fassert(3.0 + a, 3.0 + b)

    fassert(a - 3.0, b - 3.0)
    fassert(3.0 - a, 3.0 - b)

    fassert(a * 3.0, b * 3.0)
    fassert(3.0 * a, 3.0 * b)

    fassert(a / 3.0, b / 3.0)
    fassert(3.0 / a, 3.0 / b)
    fassert(3 / a, 3 / b)

    fassert(a**3.0, b**3.0)
    fassert(3.0**a, 3.0**b)

    fassert(a % 3.0, b % 3.0)
    fassert(3.0 % a, 3.0 % b)

    assert (type(numpy.float32(3) + a) == afnumpy.ndarray)
コード例 #5
0
def meshgrid(*xi, **kwargs):
    ndim = len(xi)

    copy_ = kwargs.pop('copy', True)
    sparse = kwargs.pop('sparse', False)
    indexing = kwargs.pop('indexing', 'xy')

    if kwargs:
        raise TypeError("meshgrid() got an unexpected keyword argument '%s'" %
                        (list(kwargs)[0], ))

    if indexing not in ['xy', 'ij']:
        raise ValueError("Valid values for `indexing` are 'xy' and 'ij'.")

    s0 = (1, ) * ndim

    output = [
        afnumpy.asanyarray(x).reshape(s0[:i] + (-1, ) + s0[i + 1::])
        for i, x in enumerate(xi)
    ]

    shape = [x.size for x in output]

    if indexing == 'xy' and ndim > 1:
        # switch first and second axis
        output[0].shape = (1, -1) + (1, ) * (ndim - 2)
        output[1].shape = (-1, 1) + (1, ) * (ndim - 2)
        shape[0], shape[1] = shape[1], shape[0]

    if sparse:
        if copy_:
            return [x.copy() for x in output]
        else:
            return output
    else:
        # Return the full N-D matrix (not only the 1-D vector)
        if copy_:
            # Numpy uses dtype=int but Arrayfire does not support int64 in all functions
            mult_fact = afnumpy.ones(shape, dtype=numpy.int32)
            return [x * mult_fact for x in output]
        else:
            return afnumpy.broadcast_arrays(*output)
コード例 #6
0
ファイル: function_base.py プロジェクト: Brainiarc7/afnumpy
def meshgrid(*xi, **kwargs):
    ndim = len(xi)

    copy_ = kwargs.pop('copy', True)
    sparse = kwargs.pop('sparse', False)
    indexing = kwargs.pop('indexing', 'xy')

    if kwargs:
        raise TypeError("meshgrid() got an unexpected keyword argument '%s'"
                        % (list(kwargs)[0],))

    if indexing not in ['xy', 'ij']:
        raise ValueError(
            "Valid values for `indexing` are 'xy' and 'ij'.")

    s0 = (1,) * ndim

    output = [afnumpy.asanyarray(x).reshape(s0[:i] + (-1,) + s0[i + 1::])
              for i, x in enumerate(xi)]

    shape = [x.size for x in output]

    if indexing == 'xy' and ndim > 1:
        # switch first and second axis
        output[0].shape = (1, -1) + (1,)*(ndim - 2)
        output[1].shape = (-1, 1) + (1,)*(ndim - 2)
        shape[0], shape[1] = shape[1], shape[0]

    if sparse:
        if copy_:
            return [x.copy() for x in output]
        else:
            return output
    else:
        # Return the full N-D matrix (not only the 1-D vector)
        if copy_:
            # Numpy uses dtype=int but Arrayfire does not support int64 in all functions
            mult_fact = afnumpy.ones(shape, dtype=numpy.int32)
            return [x * mult_fact for x in output]
        else:
            return afnumpy.broadcast_arrays(*output)
コード例 #7
0
ファイル: test_performance.py プロジェクト: syurkevi/afnumpy
def test_add(benchmark):
    a = afnumpy.ones((2048, 2048), dtype=numpy.complex64)
    b = afnumpy.ones((2048, 2048), dtype=numpy.complex64)
    benchmark(afnumpy.add, a, b)
コード例 #8
0
ファイル: test_performance.py プロジェクト: syurkevi/afnumpy
def test_array_copy(benchmark):
    a = afnumpy.ones((2048, 2048), dtype=numpy.complex64)
    benchmark(afnumpy.array, a, copy=True)
コード例 #9
0
ファイル: test_performance.py プロジェクト: syurkevi/afnumpy
def test_ifftshift(benchmark):
    a = afnumpy.ones((256, 256), dtype=numpy.complex64)
    benchmark(afnumpy.fft.ifftshift, a)
コード例 #10
0
def test_ones():
    a = afnumpy.ones(3)
    b = numpy.ones(3)
    iassert(a, b)
コード例 #11
0
def test_array_copy(benchmark):
    a = afnumpy.ones((2048,2048),dtype=numpy.complex64)
    benchmark(afnumpy.array, a, copy=True)
コード例 #12
0
def test_fftshift(benchmark):
    a = afnumpy.ones((256,256),dtype=numpy.complex64)
    benchmark(afnumpy.fft.fftshift, a)
コード例 #13
0
ファイル: tomoCam.py プロジェクト: arbrefleur/tomocam
def gpuMBIR(tomo,angles,center,input_params):
        """
        MBIR reconstruction using GPU based gridding operators
        Inputs: tomo : 3D numpy sinogram array with dimensions same as tomopy
        angles : Array of angles in radians
        center : Floating point center of rotation
        input_params : A dictionary with the keys
        'gpu_device' : Device id of the gpu (For a 4 GPU cluster ; 0-3)
        'oversamp_factor': A factor by which to pad the image/data for FFT
        'num_iter' : Max number of MBIR iterations
        'smoothness' : Regularization constant
        'p': MRF shape param
        """
        print('Starting GPU MBIR recon')
        #allocate space for final answer 
        af.set_device(input_params['gpu_device']) #Set the device number for gpu based code
        #Change tomopy format
        new_tomo=np.transpose(tomo,(1,2,0)) #slice, columns, angles
        im_size =  new_tomo.shape[1]
        num_slice = new_tomo.shape[0]
        num_angles=new_tomo.shape[2]
        pad_size=np.int16(im_size*input_params['oversamp_factor'])
#        nufft_scaling = (np.pi/pad_size)**2
        num_iter = input_params['num_iter']
        mrf_sigma = input_params['smoothness']
        mrf_p = input_params['p']
        print('MRF params p=%f sigma=%f' %(mrf_p,mrf_sigma))
        #Initialize structures for NUFFT
        sino={}
        geom={}
        sino['Ns'] =  pad_size#Sinogram size after padding
        sino['Ns_orig'] = im_size #size of original sinogram
        sino['center'] = center + (sino['Ns']/2 - sino['Ns_orig']/2)  #for padded sinogram
        sino['angles'] = angles
        
        #Initialize NUFFT parameters
        print('Initialize NUFFT params')
        nufft_params = init_nufft_params(sino,geom)

        temp_y = afnp.zeros((sino['Ns'],num_angles),dtype=afnp.complex64)
        temp_x = afnp.zeros((sino['Ns'],sino['Ns']),dtype=afnp.complex64)
        x_recon  = afnp.zeros((num_slice/2,sino['Ns_orig'],sino['Ns_orig']),dtype=afnp.complex64)
        
        pad_idx = slice(sino['Ns']/2-sino['Ns_orig']/2,sino['Ns']/2+sino['Ns_orig']/2)

        #allocate output array
        rec_mbir_final=np.zeros((num_slice,sino['Ns_orig'],sino['Ns_orig']),dtype=np.float32)
        
        #Move all data to GPU
        print('Moving data to GPU')
        slice_1=slice(0,num_slice,2)
        slice_2=slice(1,num_slice,2)
        gdata=afnp.array(new_tomo[slice_1]+1j*new_tomo[slice_2],dtype=afnp.complex64)
        gradient = afnp.zeros((num_slice/2,sino['Ns_orig'],sino['Ns_orig']), dtype=afnp.complex64)#temp array to store the derivative of cost func
        z_recon  = afnp.zeros((num_slice/2,sino['Ns_orig'],sino['Ns_orig']),dtype=afnp.complex64)#Nesterov method variables
        t_nes = 1
        
        #Compute Lipschitz of gradient
        print('Computing Lipschitz of gradient')
        x_ones= afnp.ones((1,sino['Ns_orig'],sino['Ns_orig']),dtype=afnp.complex64)
        temp_x[pad_idx,pad_idx]=x_ones[0]
        temp_proj=forward_project(temp_x,nufft_params)
        temp_backproj=(back_project(temp_proj,nufft_params))[pad_idx,pad_idx]
        print('Adding Hessian of regularizer')
        temp_backproj2=afnp.zeros((1,sino['Ns_orig'],sino['Ns_orig']),dtype=afnp.complex64)
        temp_backproj2[0]=temp_backproj
        add_hessian(mrf_sigma,x_ones, temp_backproj2)
        L = np.max([temp_backproj2.real.max(),temp_backproj2.imag.max()])
        print('Lipschitz constant = %f' %(L))
        del x_ones,temp_proj,temp_backproj,temp_backproj2

        #loop over all slices
        for iter_num in range(num_iter):
          print('Iteration %d of %d'%(iter_num,num_iter))
        #Derivative of the data fitting term
          for i in range(num_slice/2):
            temp_x[pad_idx,pad_idx]=x_recon[i]
            Ax = forward_project(temp_x,nufft_params)
            temp_y[pad_idx]=gdata[i]
            gradient[i] =(back_project((Ax-temp_y),nufft_params))[pad_idx,pad_idx] #nufft_scaling
        #Derivative of regularization term
          tvd_update(mrf_p,mrf_sigma,x_recon, gradient) 
          #x_recon-=gradient/L
          x_recon,z_recon,t_nes=nesterovOGM2update(x_recon,z_recon,t_nes,gradient,L)
        
        #Move to CPU
        #Rescale result to match tomopy
        rec_mbir=np.array(x_recon,dtype=np.complex64)
        rec_mbir_final[slice_1]=np.array(rec_mbir.real,dtype=np.float32)
        rec_mbir_final[slice_2]=np.array(rec_mbir.imag,dtype=np.float32)
        return rec_mbir_final
コード例 #14
0
ファイル: test_core.py プロジェクト: daurer/afnumpy
def test_ones():
    a = afnumpy.ones(3)
    b = numpy.ones(3)
    iassert(a, b)
コード例 #15
0
ファイル: test_performance.py プロジェクト: syurkevi/afnumpy
def test_fft2(benchmark):
    a = afnumpy.ones((256, 256), dtype=numpy.complex64)
    benchmark(afnumpy.fft.fftn, a)
コード例 #16
0
ファイル: tomoCam.py プロジェクト: arbrefleur/tomocam
def gpuSIRT(tomo, angles, center, input_params):
    print('Starting GPU SIRT recon')
    #allocate space for final answer
    af.set_device(
        input_params['gpu_device'])  #Set the device number for gpu based code
    #Change tomopy format
    new_tomo = np.transpose(tomo, (1, 2, 0))  #slice, columns, angles
    im_size = new_tomo.shape[1]
    num_slice = new_tomo.shape[0]
    num_angles = new_tomo.shape[2]
    pad_size = np.int16(im_size * input_params['oversamp_factor'])
    nufft_scaling = (np.pi / pad_size)**2
    num_iter = input_params['num_iter']
    #Initialize structures for NUFFT
    sino = {}
    geom = {}
    sino['Ns'] = pad_size  #Sinogram size after padding
    sino['Ns_orig'] = im_size  #size of original sinogram
    sino['center'] = center + (sino['Ns'] / 2 - sino['Ns_orig'] / 2
                               )  #for padded sinogram
    sino['angles'] = angles

    #Initialize NUFFT parameters
    nufft_params = init_nufft_params(sino, geom)
    temp_y = afnp.zeros((sino['Ns'], num_angles), dtype=afnp.complex64)
    temp_x = afnp.zeros((sino['Ns'], sino['Ns']), dtype=afnp.complex64)
    x_recon = afnp.zeros((num_slice / 2, sino['Ns_orig'], sino['Ns_orig']),
                         dtype=afnp.complex64)
    pad_idx = slice(sino['Ns'] / 2 - sino['Ns_orig'] / 2,
                    sino['Ns'] / 2 + sino['Ns_orig'] / 2)

    #allocate output array
    rec_sirt_final = np.zeros((num_slice, sino['Ns_orig'], sino['Ns_orig']),
                              dtype=np.float32)

    #Pre-compute diagonal scaling matrices ; one the same size as the image and the other the same as data
    #initialize an image of all ones
    x_ones = afnp.ones((sino['Ns_orig'], sino['Ns_orig']),
                       dtype=afnp.complex64)
    temp_x[pad_idx, pad_idx] = x_ones
    temp_proj = forward_project(temp_x,
                                nufft_params) * (sino['Ns'] * afnp.pi / 2)
    R = 1 / afnp.abs(temp_proj)
    R[afnp.isnan(R)] = 0
    R[afnp.isinf(R)] = 0
    R = afnp.array(R, dtype=afnp.complex64)

    #Initialize a sinogram of all ones
    y_ones = afnp.ones((sino['Ns_orig'], num_angles), dtype=afnp.complex64)
    temp_y[pad_idx] = y_ones
    temp_backproj = back_project(temp_y, nufft_params) * nufft_scaling / 2
    C = 1 / (afnp.abs(temp_backproj))
    C[afnp.isnan(C)] = 0
    C[afnp.isinf(C)] = 0
    C = afnp.array(C, dtype=afnp.complex64)

    #Move all data to GPU
    slice_1 = slice(0, num_slice, 2)
    slice_2 = slice(1, num_slice, 2)
    gdata = afnp.array(new_tomo[slice_1] + 1j * new_tomo[slice_2],
                       dtype=afnp.complex64)

    #loop over all slices
    for i in range(num_slice / 2):
        for iter_num in range(num_iter):
            #filtered back-projection
            temp_x[pad_idx, pad_idx] = x_recon[i]
            Ax = (np.pi / 2) * sino['Ns'] * forward_project(
                temp_x, nufft_params)
            temp_y[pad_idx] = gdata[i]
            x_recon[i] = x_recon[i] + (
                C * back_project(R * (temp_y - Ax), nufft_params) *
                nufft_scaling / 2)[pad_idx, pad_idx]

    #Move to CPU
    #Rescale result to match tomopy
    rec_sirt = np.array(x_recon, dtype=np.complex64)
    rec_sirt_final[slice_1] = np.array(rec_sirt.real, dtype=np.float32)
    rec_sirt_final[slice_2] = np.array(rec_sirt.imag, dtype=np.float32)
    return rec_sirt_final
コード例 #17
0
def test_add(benchmark):
    a = afnumpy.ones((2048,2048),dtype=numpy.complex64)
    b = afnumpy.ones((2048,2048),dtype=numpy.complex64)
    benchmark(afnumpy.add, a, b)
コード例 #18
0
def test_ifft2(benchmark):
    a = afnumpy.ones((256,256),dtype=numpy.complex64)
    benchmark(afnumpy.fft.ifftn, a)
コード例 #19
0
#! /usr/bin/env python

import gnufft
import afnumpy as afnp


vol = afnp.ones((25,256,256), dtype='f')
vol = vol + 1j * vol
fcn = afnp.zeros((25,256,256), dtype='complex64')
mrf_sigma = afnp.ones(1, dtype='f')
gnufft.add_hessian(mrf_sigma[0], vol, fcn)

print fcn[0,:10,:10]
print fcn[0,:10,:10]