Ejemplo n.º 1
0
    def __init__(self, I, **args):
        modes = Modes()
        
        # check if there is a background
        if isValid('background', args):
            if args['background'] is True :
                modes['B'] = np.random.random((I.shape)).astype(args['dtype'])
            else :
                modes['B'] = np.sqrt(args['background']).astype(args['dtype'])
        
            modes['B'] = afnumpy.array(modes['B'])

        if isValid('O', args):
            modes['O'] = args['O']
        else :
            modes['O'] = np.random.random(I.shape).astype(args['c_dtype'])

        modes['O'] = afnumpy.array(modes['O'])

        # this is the radial value for every pixel 
        # in the volume
        self.rs    = None 
        
        self.mask = 1
        if isValid('mask', args):
            self.mask = args['mask']
            if args['mask'] is not 1 :
                self.mask = afnumpy.array(self.mask)

        self.alpha = 1.0e-10
        if isValid('alpha', args):
            self.alpha = args['alpha']

        if isValid('mask', args) :
            self.I_norm = (args['mask'] * I).sum()
        else :
            self.I_norm = I.sum()
        
        self.amp   = afnumpy.sqrt(afnumpy.array(I.astype(args['dtype'])))

        # define the data projection
        # --------------------------
        if 'B' in modes.keys() :
            self.Pmod = self.Pmod_back
        else :
            self.Pmod = self.Pmod_single
    
        # define the support projection
        # -----------------------------
        if isValid('voxel_number', args) :
            self.voxel_number = args['voxel_number']
        else :
            self.voxel_number = False
            self.S    = afnumpy.array(args['support'])
        
        self.support = None
        if isValid('support', args):
            self.support = afnumpy.array(args['support'])

        self.modes = modes
Ejemplo n.º 2
0
    def __init__(self, I, **args):
        modes = Modes()

        # check if there is a background
        if isValid('background', args):
            if args['background'] is True:
                modes['B'] = np.random.random((I.shape)).astype(args['dtype'])
            else:
                modes['B'] = np.sqrt(args['background']).astype(args['dtype'])

            modes['B'] = afnumpy.array(modes['B'])

        if isValid('O', args):
            modes['O'] = args['O']
        else:
            modes['O'] = np.random.random(I.shape).astype(args['c_dtype'])

        modes['O'] = afnumpy.array(modes['O'])

        # this is the radial value for every pixel
        # in the volume
        self.rs = None

        self.mask = 1
        if isValid('mask', args):
            self.mask = args['mask']
            if args['mask'] is not 1:
                self.mask = afnumpy.array(self.mask)

        self.alpha = 1.0e-10
        if isValid('alpha', args):
            self.alpha = args['alpha']

        if isValid('mask', args):
            self.I_norm = (args['mask'] * I).sum()
        else:
            self.I_norm = I.sum()

        self.amp = afnumpy.sqrt(afnumpy.array(I.astype(args['dtype'])))

        # define the data projection
        # --------------------------
        if 'B' in list(modes.keys()):
            self.Pmod = self.Pmod_back
        else:
            self.Pmod = self.Pmod_single

        # define the support projection
        # -----------------------------
        if isValid('voxel_number', args):
            self.voxel_number = args['voxel_number']
        else:
            self.voxel_number = False
            self.S = afnumpy.array(args['support'])

        self.support = None
        if isValid('support', args):
            self.support = afnumpy.array(args['support'])

        self.modes = modes
Ejemplo n.º 3
0
 def Emod(self, modes):
     M = self.Imap(modes)
     eMod = afnumpy.sum(self.mask * (afnumpy.sqrt(M) - self.amp)**2)
     eMod = afnumpy.sqrt(eMod / self.I_norm)
     return eMod
Ejemplo n.º 4
0
def constructTestWaveField(npoints=256,ekeV=0.6,z1=5, show=False):  
    # Simple function for generating  simple Gaussian wavefield for testing purposes


    from wpg.srwlib import srwl_uti_ph_en_conv
    from extensions.gvrutils import calculate_theta_fwhm_cdr
    from wpg.generators import build_gauss_wavefront_xy


    # set wavefield parameters
    qnC        = 0.01
    wlambda    = srwl_uti_ph_en_conv(ekeV, _in_u='keV', _out_u='nm')
    theta_fwhm = calculate_theta_fwhm_cdr(ekeV,qnC)
    k          = 2*np.sqrt(2*np.log(2))
    range_xy   = (theta_fwhm/k*z1*5.)*2.0
    sigX       = 12.4e-10*k/(ekeV*4*np.pi*theta_fwhm)

    # construct wavefield
    wf0=build_gauss_wavefront_xy(nx=npoints, ny=npoints, ekev=ekeV,
                                              xMin=-range_xy/2 ,xMax=range_xy/2,
                                              yMin=-range_xy/2, yMax=range_xy/2,
                                              sigX=sigX, sigY=sigX,
                                              d2waist=z1,
                                              _mx=0, _my=0 )
    wfr = Wavefront(srwl_wavefront=wf0)    
    print('Wavelength=%f, theta FWWM=%f, range XY = %f, sig X = %f' % (wlambda, theta_fwhm, range_xy, sigX))

    wfr._srwl_wf.unitElFld = 1#'sqrt(Phot/s/0.1%bw/mm^2)'

    if show==True: #display the wavefield
        plotWavefront(wfr, 'Wavefield at source')

    return wfr



    
    def generate_mode_test(self, mode_no, eigenfn, outdir, gwaist = None):
        gauss_0 = primary_gaussian() # properties of gaussian
        gauss_0.d2waist = -9.0000
        if gwaist is not None:
            gauss_0.d2waist = gwaist
        print("Generating Mode {}".format(mode_no))
        _mx = eigenfn[mode_no][0]
        _my = eigenfn[mode_no][1]
        
        M2x = (2*_mx)+1
        M2y = (2*_my)+1
        
        GsnBm = SRWLGsnBm(_x = 0, _y = 0, _z = 0,
                          _sigX = 100e-06,#gauss_0.sigX*(M2x**-0.25),
                          _sigY = 100e-06,#gauss_0.sigY*(M2y**-0.25),
                          _xp = 0, #gauss_0.xp,
                          _yp = 0,#gauss_0.yp,
                          _mx = _mx,
                          _my = _my,
                          _avgPhotEn = gauss_0.E)
        
        wfr = Wavefront(build_gaussian(GsnBm,
                                       gauss_0.nx*2, gauss_0.ny*2,
                                       gauss_0.xMin*2, gauss_0.xMax*2,
                                       gauss_0.yMin*2, gauss_0.yMax*2))

        wfr.store_hdf5(outdir + "wfr_mode_{}.hdf5".format(mode_no))
        return wfr
Ejemplo n.º 5
0
def test_sqrt():
    a = afnumpy.random.random((2, 3))
    b = numpy.array(a)
    fassert(afnumpy.sqrt(a), numpy.sqrt(b))
Ejemplo n.º 6
0
def norm(x, ord=None, axis=None, keepdims=False):
    x = asarray(x)

    # Check the default case first and handle it immediately.
    if ord is None and axis is None:
        ndim = x.ndim
        x = x.ravel(order='K')
        if isComplexType(x.dtype.type):
            sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag)
        else:
            sqnorm = dot(x, x)
        ret = sqrt(sqnorm)
        if keepdims:
            ret = ret.reshape(ndim*[1])
        return ret

    # Normalize the `axis` argument to a tuple.
    nd = x.ndim
    if axis is None:
        axis = tuple(range(nd))
    elif not isinstance(axis, tuple):
        try:
            axis = int(axis)
        except:
            raise TypeError("'axis' must be None, an integer or a tuple of integers")
        axis = (axis,)

    if len(axis) == 1:
        if ord == Inf:
            return abs(x).max(axis=axis, keepdims=keepdims)
        elif ord == -Inf:
            return abs(x).min(axis=axis, keepdims=keepdims)
        elif ord == 0:
            # Zero norm
            return (x != 0).sum(axis=axis, keepdims=keepdims)
        elif ord == 1:
            # special case for speedup
            return afnumpy.sum(abs(x), axis=axis, keepdims=keepdims)
        elif ord is None or ord == 2:
            # special case for speedup
            s = (x.conj() * x).real
            return sqrt(afnumpy.sum(s, axis=axis, keepdims=keepdims))
        else:
            try:
                ord + 1
            except TypeError:
                raise ValueError("Invalid norm order for vectors.")
            if x.dtype.type is longdouble:
                # Convert to a float type, so integer arrays give
                # float results.  Don't apply asfarray to longdouble arrays,
                # because it will downcast to float64.
                absx = abs(x)
            else:
                absx = x if isComplexType(x.dtype.type) else asfarray(x)
                if absx.dtype is x.dtype:
                    absx = abs(absx)
                else:
                    # if the type changed, we can safely overwrite absx
                    abs(absx, out=absx)
            absx **= ord
            return afnumpy.sum(absx, axis=axis, keepdims=keepdims) ** (1.0 / ord)
    elif len(axis) == 2:
        row_axis, col_axis = axis
        if not (-nd <= row_axis < nd and -nd <= col_axis < nd):
            raise ValueError('Invalid axis %r for an array with shape %r' %
                             (axis, x.shape))
        if row_axis % nd == col_axis % nd:
            raise ValueError('Duplicate axes given.')
        if ord == 2:
            ret =  _multi_svd_norm(x, row_axis, col_axis, amax)
        elif ord == -2:
            ret = _multi_svd_norm(x, row_axis, col_axis, amin)
        elif ord == 1:
            if col_axis > row_axis:
                col_axis -= 1
            ret = afnumpy.sum(abs(x), axis=row_axis).max(axis=col_axis)
        elif ord == Inf:
            if row_axis > col_axis:
                row_axis -= 1
            ret = afnumpy.sum(abs(x), axis=col_axis).max(axis=row_axis)
        elif ord == -1:
            if col_axis > row_axis:
                col_axis -= 1
            ret = afnumpy.sum(abs(x), axis=row_axis).min(axis=col_axis)
        elif ord == -Inf:
            if row_axis > col_axis:
                row_axis -= 1
            ret = afnumpy.sum(abs(x), axis=col_axis).min(axis=row_axis)
        elif ord in [None, 'fro', 'f']:
            ret = sqrt(afnumpy.sum((x.conj() * x).real, axis=axis))
        else:
            raise ValueError("Invalid norm order for matrices.")
        if keepdims:
            ret_shape = list(x.shape)
            ret_shape[axis[0]] = 1
            ret_shape[axis[1]] = 1
            ret = ret.reshape(ret_shape)
        return ret
    else:
        raise ValueError("Improper number of dimensions to norm.")
Ejemplo n.º 7
0
def get_error(fourier, intensities):
    return np.abs((np.sqrt(intensities) - np.abs(fourier)).sum()) / np.sqrt(intensities).sum()
Ejemplo n.º 8
0
def data_constraint(fourier, intensities):
    return (fourier / np.abs(fourier)) * np.sqrt(intensities)
Ejemplo n.º 9
0
def data_constraint(fourier, intensities):
    return (fourier / np.abs(fourier)) * np.sqrt(intensities)
Ejemplo n.º 10
0
def norm(x, ord=None, axis=None, keepdims=False):
    x = asarray(x)

    # Check the default case first and handle it immediately.
    if ord is None and axis is None:
        ndim = x.ndim
        x = x.ravel(order='K')
        if isComplexType(x.dtype.type):
            sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag)
        else:
            sqnorm = dot(x, x)
        ret = sqrt(sqnorm)
        if keepdims:
            ret = ret.reshape(ndim * [1])
        return ret

    # Normalize the `axis` argument to a tuple.
    nd = x.ndim
    if axis is None:
        axis = tuple(range(nd))
    elif not isinstance(axis, tuple):
        try:
            axis = int(axis)
        except:
            raise TypeError(
                "'axis' must be None, an integer or a tuple of integers")
        axis = (axis, )

    if len(axis) == 1:
        if ord == Inf:
            return abs(x).max(axis=axis, keepdims=keepdims)
        elif ord == -Inf:
            return abs(x).min(axis=axis, keepdims=keepdims)
        elif ord == 0:
            # Zero norm
            return (x != 0).sum(axis=axis, keepdims=keepdims)
        elif ord == 1:
            # special case for speedup
            return afnumpy.sum(abs(x), axis=axis, keepdims=keepdims)
        elif ord is None or ord == 2:
            # special case for speedup
            s = (x.conj() * x).real
            return sqrt(afnumpy.sum(s, axis=axis, keepdims=keepdims))
        else:
            try:
                ord + 1
            except TypeError:
                raise ValueError("Invalid norm order for vectors.")
            if x.dtype.type is longdouble:
                # Convert to a float type, so integer arrays give
                # float results.  Don't apply asfarray to longdouble arrays,
                # because it will downcast to float64.
                absx = abs(x)
            else:
                absx = x if isComplexType(x.dtype.type) else asfarray(x)
                if absx.dtype is x.dtype:
                    absx = abs(absx)
                else:
                    # if the type changed, we can safely overwrite absx
                    abs(absx, out=absx)
            absx **= ord
            return afnumpy.sum(absx, axis=axis, keepdims=keepdims)**(1.0 / ord)
    elif len(axis) == 2:
        row_axis, col_axis = axis
        if not (-nd <= row_axis < nd and -nd <= col_axis < nd):
            raise ValueError('Invalid axis %r for an array with shape %r' %
                             (axis, x.shape))
        if row_axis % nd == col_axis % nd:
            raise ValueError('Duplicate axes given.')
        if ord == 2:
            ret = _multi_svd_norm(x, row_axis, col_axis, amax)
        elif ord == -2:
            ret = _multi_svd_norm(x, row_axis, col_axis, amin)
        elif ord == 1:
            if col_axis > row_axis:
                col_axis -= 1
            ret = afnumpy.sum(abs(x), axis=row_axis).max(axis=col_axis)
        elif ord == Inf:
            if row_axis > col_axis:
                row_axis -= 1
            ret = afnumpy.sum(abs(x), axis=col_axis).max(axis=row_axis)
        elif ord == -1:
            if col_axis > row_axis:
                col_axis -= 1
            ret = afnumpy.sum(abs(x), axis=row_axis).min(axis=col_axis)
        elif ord == -Inf:
            if row_axis > col_axis:
                row_axis -= 1
            ret = afnumpy.sum(abs(x), axis=col_axis).min(axis=row_axis)
        elif ord in [None, 'fro', 'f']:
            ret = sqrt(afnumpy.sum((x.conj() * x).real, axis=axis))
        else:
            raise ValueError("Invalid norm order for matrices.")
        if keepdims:
            ret_shape = list(x.shape)
            ret_shape[axis[0]] = 1
            ret_shape[axis[1]] = 1
            ret = ret.reshape(ret_shape)
        return ret
    else:
        raise ValueError("Improper number of dimensions to norm.")
Ejemplo n.º 11
0
def Pmod_back(amp, background, O, mask = 1, alpha = 1.0e-10):
    M = mask * amp / afnumpy.sqrt((O.conj() * O).real + background**2 + alpha)
    out         = O * M
    background *= M
    out += (1 - mask) * O
    return out, background
Ejemplo n.º 12
0
 def Emod(self, modes):
     M         = self.Imap(modes)
     eMod      = afnumpy.sum( self.mask * ( afnumpy.sqrt(M) - self.amp )**2 )
     eMod      = afnumpy.sqrt( eMod / self.I_norm )
     return eMod
Ejemplo n.º 13
0
def test_sqrt():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.sqrt(a), numpy.sqrt(b))
Ejemplo n.º 14
0
t0 = time.time()

# Start the reconstruction (using ER)
for i in range(nr_iterations):
    
    # Forward propagation
    fourier = fft.fftn(image)

    # Check convergence
    #error = get_error(fourier, intensities)
    #print "Iteration: %d, error: %f" %(i, error)
    #print i

    # Update plot
    #update_plot(i, image, fourier, error, support, intensities)
    
    # Apply data constraint
    #fourier = data_constraint(fourier, intensities)
    fourier /= np.abs(fourier)
    fourier *= np.sqrt(intensities)

    # Backward propagation
    image = fft.ifftn(fourier)

    # Apply support constraint
    #image *= support
    #image = support_constraint(image, support)

# Timing
print "%d Iterations took %d seconds using %s" %(nr_iterations, time.time() - t0, use)
Ejemplo n.º 15
0
def get_error(fourier, intensities):
    return np.abs((np.sqrt(intensities) -
                   np.abs(fourier)).sum()) / np.sqrt(intensities).sum()
Ejemplo n.º 16
0
def Pmod_back(amp, background, O, mask=1, alpha=1.0e-10):
    M = mask * amp / afnumpy.sqrt((O.conj() * O).real + background**2 + alpha)
    out = O * M
    background *= M
    out += (1 - mask) * O
    return out, background
Ejemplo n.º 17
0
    
# True image
true_image = fft.fftshift(fft.ifftn(data_fourier))
#import arrayfire
#print arrayfire.backend.name
#print type(true_image)
#print true_image.dtype
#print intensities.dtype
#print data_fourier.dtype

# Initial image
image = (1j + np.random.random(intensities.shape)).astype(np.complex64)

# Define support
yy,xx = np.meshgrid(np.arange(image.shape[0]), np.arange(image.shape[1]))
rr = np.sqrt((xx-image.shape[1]/2)**2 + (yy-image.shape[0]/2)**2)
support = rr < 24
#support = np.abs(true_image)>1

# Define Nr. of iterations
nr_iterations = 500

# Define data constraint
def data_constraint(fourier, intensities):
    return (fourier / np.abs(fourier)) * np.sqrt(intensities)

# Define support constraint
def support_constraint(img, support):
    img = img.flatten()
    img[support == 0] = 0
    #img *= support
Ejemplo n.º 18
0
# Start the reconstruction (using ER)
for i in range(nr_iterations):

    # Forward propagation
    fourier = fft.fftn(image)

    # Check convergence
    #error = get_error(fourier, intensities)
    #print "Iteration: %d, error: %f" %(i, error)
    #print i

    # Update plot
    #update_plot(i, image, fourier, error, support, intensities)

    # Apply data constraint
    #fourier = data_constraint(fourier, intensities)
    fourier /= np.abs(fourier)
    fourier *= np.sqrt(intensities)

    # Backward propagation
    image = fft.ifftn(fourier)

    # Apply support constraint
    #image *= support
    #image = support_constraint(image, support)

# Timing
print "%d Iterations took %d seconds using %s" % (nr_iterations,
                                                  time.time() - t0, use)