Пример #1
0
def save_absolute_phase_real_fourier(run_dir,
                                     output_folder,
                                     i=None,
                                     shift=True,
                                     save_img=True):
    if i == None:
        i = return_last_iteration_integer(os.path.join(run_dir, 'output_mnt'))
    model = spimage.sp_image_read(
        '{r}/output_mnt/model_{i}.h5'.format(r=run_dir, i=i), 0)
    fmodel = spimage.sp_image_read(
        '{r}/output_mnt/fmodel_{i}.h5'.format(r=run_dir, i=i), 0)
    if model == None or fmodel == None:
        print run_dir + ' failed'
        return
    if shift:
        model = spimage.sp_image_shift(model)
        fmodel = spimage.sp_image_shift(fmodel)
    s = np.shape(model.image)[0] / 2
    #matplotlib.rcParams.update({'font.size': 16})
    f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 15))
    ax1.set_title('Absolute')
    ax1.imshow(np.absolute(model.image[s, :, :]))
    ax2.set_title('Phase')
    ax2.imshow(np.angle(model.image[s, :, :]), cmap='PiYG')
    ax3.set_title('Real part')
    ax3.imshow(np.real(model.image[s, :, :]), cmap='coolwarm')
    ax4.set_title('Fourier')
    ax4.imshow(np.absolute(fmodel.image[s, :, :]), norm=LogNorm())
    f.subplots_adjust(wspace=1, hspace=1)
    plt.tight_layout()
    if save_img:
        plt.savefig(os.path.join(output_folder, run_dir + '.png'))
    spimage.sp_image_free(model)
    spimage.sp_image_free(fmodel)
    plt.close(f)
Пример #2
0
def crop_image(in_file, out_file, side, center=None):
    """Function to crop an h5 image and pad with zeros around it"""

    img = spimage.sp_image_read(in_file, 0)

    if not center:
        center = img.detector.image_center[:2]

    shifted = 0
    if img.shifted:
        shifted = 1
        img = spimage.sp_image_shift(img)

    cropped = spimage.sp_image_alloc(side, side, 1)
    cropped.image[:, :] = image_manipulation.crop_and_pad(
        img.image, center, side)
    cropped.mask[:, :] = image_manipulation.crop_and_pad(
        img.mask, center, side)

    if shifted:
        cropped = spimage.sp_image_shift(cropped)

    spimage.sp_image_write(cropped, out_file, 16)

    spimage.sp_image_free(img)
    spimage.sp_image_free(cropped)

    print("end")
Пример #3
0
def show_support_fmodel_model_slice_2D(run_dir,
                                       iteration=None,
                                       save_imgs=False,
                                       output_folder='pngs'):
    if iteration == None:
        iteration = return_last_iteration_integer(run_dir + '/output_mnt/')
    print os.getcwd(), iteration
    model = spimage.sp_image_shift(
        spimage.sp_image_read(
            '{r}/output_mnt/model_{i}.h5'.format(r=run_dir, i=iteration), 0))
    fmodel = spimage.sp_image_shift(
        spimage.sp_image_read(
            '{r}/output_mnt/fmodel_{i}.h5'.format(r=run_dir, i=iteration), 0))
    support = spimage.sp_image_shift(
        spimage.sp_image_read(
            '{r}/output_mnt/support_{i}.h5'.format(r=run_dir, i=iteration), 0))
    s = np.shape(model.image)[0] / 2
    matplotlib.rcParams.update({'font.size': 16})
    f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(30, 10))
    ax1.set_title('Model')
    ax1.imshow(np.absolute(model.image))
    ax2.set_title('Fourier amplitude')
    ax2.imshow(log10(np.absolute(fmodel.image)))
    ax3.set_title('Support')
    ax3.imshow(np.absolute(support.image))
    plt.tight_layout()
    if save_imgs:
        plt.savefig(os.path.join(output_folder, run_dir + '.png'))
        plt.close(f)
Пример #4
0
def crop_image(in_file, out_file, sideX, sideY = 0):
    if sideY == 0:
        sideY = sideX
    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        print "Error: %s is not a readable .h5 file\n" % in_file
        exit(1)

    shifted = 0
    if img.shifted:
        shifted = 1
        img = spimage.sp_image_shift(img)

    print "shifted = ", shifted

    lowX = img.detector.image_center[0]-(sideX/2.0-0.5)
    highX = img.detector.image_center[0]+(sideX/2.0-0.5)
    lowY = img.detector.image_center[1]-(sideY/2.0-0.5)
    highY = img.detector.image_center[1]+(sideY/2.0-0.5)

    print lowX, " ", highX
    print lowY, " ", highY

    if lowX != pylab.floor(lowX):
        lowX = int(pylab.floor(lowX))
        highX = int(pylab.floor(highX))
        img.detector.image_center[0] -= 0.5
    else:
        lowX = int(lowX)
        highX = int(highX)
    if lowY != pylab.floor(lowY):
        lowY = int(pylab.floor(lowY))
        highY = int(pylab.floor(highY))
        img.detector.image_center[1] -= 0.5
    else:
        lowY = int(lowY)
        highY = int(highY)

    cropped = spimage.rectangle_crop(img,lowX,lowY,highX,highY)

    print "did crop"

    if shifted:
        cropped = spimage.sp_image_shift(cropped)

    print "shifted (or not)"

    print "write ", out_file

    #print "orientation = ", cropped.detector.orientation
    #print spimage.sp_3matrix_get(cropped.detector.orientation,0,0,0)

    try:
        spimage.sp_image_write(cropped,out_file,16)
    except:
        print "Error: can not write to %s\n" % out_file

    print "end"
Пример #5
0
def show_2Dhawk_result_real_fourier(iteration):
    re = spimage.sp_image_shift(
        spimage.sp_image_read('real_space-{0:07}.h5'.format(iteration), 0))
    fo = spimage.sp_image_shift(
        spimage.sp_image_read('fourier_space-{0:07}.h5'.format(iteration), 0))
    f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 8))
    ax1.imshow(np.absolute(re.image))
    ax2.imshow(log10(absolute(fo.image)))
    plt.tight_layout()
    plt.savefig('real_and_fourier_{i}.png'.format(i=str(iteration)))
Пример #6
0
def plot_prtf_results_3D(d,
                         input_image,
                         downsampling,
                         save_file=True,
                         image_name='PRTF_results.png',
                         zoom=True):
    f, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2,
                                                         3,
                                                         figsize=(20, 13))
    ax1.set_title('Average Real space')
    avg_img = spimage.sp_image_shift(
        spimage.sp_image_read(os.path.join(d, 'PRTF-avg_image.h5'), 0))
    avg_f = spimage.sp_image_shift(
        spimage.sp_image_read(os.path.join(d, 'PRTF-avg_fft.h5'), 0))
    input_img = spimage.sp_image_read(input_image, 0)
    size = np.shape(input_img.image)[0]
    sl = (size / 2, slice(None), slice(None))
    if zoom:
        z = int(
            (size - np.count_nonzero(avg_img.image[size / 2, size / 2, :])) /
            2.2)
        sl_real = (size / 2, slice(z, size - z), slice(z, size - z))
    elif zoom == False:
        sl_real = sl
    print sl_real
    ax1.imshow(np.absolute(avg_img.image)[sl_real])
    ax2.set_title('Input pattern')
    ax2.imshow(np.absolute(input_img.image * input_img.mask)[sl],
               norm=LogNorm())
    ax3.set_title('PRTF')
    prtf_radavg, q = prtf_radial_average(d, downsampling)
    ax3.plot(q, prtf_radavg, lw=1.5)
    ax3.set_xlabel(r'$|q|[nm^{-1}]$', fontsize=18)
    ax3.set_ylabel(r'$PRTF$', fontsize=18)
    ax3.axhline(1 / math.e, c='k')
    ax4.set_title('Phase')
    ax4.imshow(np.angle(avg_img.image)[sl_real], cmap='PiYG')
    ax5.set_title('Average Fourier Space')
    ax5.imshow(np.absolute(avg_f.image)[sl])
    ax6.set_title('Errors')
    errors = extract_final_errors(os.getcwd())
    errors.sort(order='fourier_error')
    ax6.plot(range(len(errors['fourier_error'])),
             errors['fourier_error'],
             lw=1.5,
             label='Fourier Error')
    errors.sort(order='real_error')
    ax6.plot(range(len(errors['real_error'])),
             errors['real_error'],
             lw=1.5,
             label='Real Error')
    plt.legend()
    plt.tight_layout()
    if save_file:
        plt.savefig(image_name)
Пример #7
0
def plot_prtf_results_2D(d,
                         input_image,
                         shift_input=False,
                         save_file=True,
                         image_name='PRTF_results.png'):
    f, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2,
                                                         3,
                                                         figsize=(30, 20))
    ax1.set_title('Average Real space')
    avg_img = spimage.sp_image_shift(
        spimage.sp_image_read(os.path.join(d, 'PRTF-avg_image.h5'), 0))
    avg_f = spimage.sp_image_shift(
        spimage.sp_image_read(os.path.join(d, 'PRTF-avg_fft.h5'), 0))
    if shift_input:
        input_img = spimage.sp_image_shift(
            spimage.sp_image_read(input_image, 0))
    else:
        input_img = spimage.sp_image_read(input_image, 0)
    ax1.imshow(np.absolute(avg_img.image))
    ax2.set_title('Input pattern')
    ax2.imshow(np.absolute(input_img.image * input_img.mask), norm=LogNorm())
    ax3.set_title('PRTF')
    prtf_radavg, q = prtf_radial_average(d, downsampling)
    ax3.plot(pix_to_q(p[:, 0], 1.035e-9, 0.7317, 0.0006), p[:, 1], lw=1.5)
    ax3.set_xlabel(r'$|q|[nm^{-1}]$', fontsize=18)
    ax3.set_ylabel(r'$PRTF$', fontsize=18)
    ax3.axhline(1 / math.e, c='k')
    ax4.set_title('Phase')
    ax4.imshow(np.angle(avg_img.image), cmap='PiYG')
    ax5.set_title('Average Fourier Space')
    ax5.imshow(np.absolute(avg_f.image))
    ax6.set_title('Errors')
    errors = extract_final_errors(os.getcwd())
    errors.sort(order='fourier_error')
    ax6.plot(range(len(errors['fourier_error'])),
             errors['fourier_error'],
             lw=1.5,
             c='r',
             label='Fourier Error')
    errors.sort(order='real_error')
    ax6.plot(range(len(errors['real_error'])),
             errors['real_error'],
             lw=1.5,
             c='g',
             label='Real Error')
    plt.legend()
    plt.tight_layout()
    if save_file:
        plt.savefig(image_name)
Пример #8
0
def intensities_array_to_h5(img0,msk0,cx=None,cy=None,cropLength=None,save_to_file=None):
    import spimage,imgtools
    Nx = img0.shape[1]
    Ny = img0.shape[0]
    img = img0
    msk = msk0
    if cropLength != None:
        img = imgtools.crop(img0,cropLength,center=[cy,cx])
        msk = imgtools.crop(msk0,cropLength,center=[cy,cx])
        Nx = cropLength
        Ny = cropLength
    elif cx != None and cy != None:
        img = imgtools.recenter(img0,cx,cy)
        msk = imgtools.recenter(msk0,cx,cy)
    I = spimage.sp_image_alloc(Nx,Ny,1)
    I.image[:,:] = img[:,:]
    I.mask[:,:] = msk[:,:]
    I2 = spimage.sp_image_shift(I)
    I2.shifted = 0
    I2.phased = 0
    spimage.sp_image_free(I)
    if save_to_file != None:
        spimage.sp_image_write(I2,save_to_file,0)
    else:
        return I2
Пример #9
0
def plot_real_space(n, png_output='real_space_pngs', iteration='4009'):
    for j in range(n):
        fig, axes = plt.subplots(figsize=(9, 3), nrows=1, ncols=3)
        real_space = np.real(
            spimage.sp_image_shift(
                spimage.sp_image_read(
                    'run_%04d/output_mnt/model_%s.h5' % (j, iteration),
                    0)).image)
        dim = np.shape(real_space)[0]
        nonzero = np.shape(real_space[real_space > 0.])[0]
        new_dim = (dim / 2 - nonzero**(1 / 3)) / 2
        vmax = real_space.max()
        vmin = real_space.min()
        axes[0].imshow(real_space[dim / 2, new_dim:-new_dim, new_dim:-new_dim],
                       vmax=vmax,
                       vmin=vmin)
        axes[1].imshow(real_space[new_dim:-new_dim, dim / 2, new_dim:-new_dim],
                       vmax=vmax,
                       vmin=vmin)
        im = axes[2].imshow(real_space[new_dim:-new_dim, new_dim:-new_dim,
                                       dim / 2],
                            vmax=vmax,
                            vmin=vmin)
        fig.colorbar(im, ax=axes.ravel().tolist())
        print png_output + '/%04d.png' % j
        plt.savefig(png_output + '/%04d.png' % j)
        plt.close(fig)
Пример #10
0
def center_image_2d(img, radius):
    """For an image with an object surounded by empty space, this function
    puts it in the center. A rough idea about the size of the object is
    needed in the form of the variable radius."""
    sigma = radius
    x_coordinates = (
        _numpy.arange(_numpy.shape(img.image)[0], dtype='float64') -
        _numpy.shape(img.image)[0] / 2 + 0.5)
    y_coordinates = (
        _numpy.arange(_numpy.shape(img.image)[1], dtype='float64') -
        _numpy.shape(img.image)[1] / 2 + 0.5)
    kernel = _numpy.exp(-(x_coordinates[:, _numpy.newaxis]**2 +
                          y_coordinates[_numpy.newaxis, :]**2) / 2 / sigma**2)

    img_ft = _numpy.fft.fft2(_numpy.fft.fftshift(img.image))
    kernel_ft = _numpy.fft.fft2(_numpy.fft.fftshift(kernel))
    kernel_ft *= _numpy.conj(img_ft)
    img_bt = _numpy.fft.ifft2(kernel_ft)

    min_v = 0.
    min_x = 0
    min_y = 0
    for x_index in range(_numpy.shape(img_bt)[0]):
        for y_index in range(_numpy.shape(img_bt)[1]):
            if abs(img_bt[y_index, x_index]) > min_v:
                min_v = abs(img_bt[y_index, x_index])
                min_x = x_index
                min_y = y_index
    print(min_x, min_y)
    _spimage.sp_image_translate(img, -(-min_x + _numpy.shape(img_bt)[0] // 2),
                                -(-min_y + _numpy.shape(img_bt)[1] // 2), 0,
                                _spimage.SP_TRANSLATE_WRAP_AROUND)
    shift = _spimage.sp_image_shift(img)
    _spimage.sp_image_free(img)
    return shift
Пример #11
0
def image_histogram(file_name,
                    shift=False,
                    mode='absolute',
                    only_nonzero=True,
                    cf=0.,
                    radius_cutoff=None,
                    b=100):
    if mode == 'absolute': f = np.absolute
    elif mode == 'angle': f = np.angle
    elif mode == 'real': f = np.real
    elif mode == 'imag': f = np.imag
    print type(file_name)
    if type(file_name) == str:
        img = spimage.sp_image_read(file_name, 0)
    elif type(file_name) != str:
        img = file_name
    if shift:
        print 'shifting image'
        img = spimage.sp_image_shift(img)
    if radius_cutoff != None:
        r = stuff.r_array_3D(np.shape(img.image)[0])
        new_img = img.image[np.where(r < radius_cutoff)]
        flat_img = f(new_img).flatten()
    else:
        flat_img = f(img.image[:]).flatten()
    print flat_img
    if only_nonzero:
        flat_img = flat_img[flat_img != 0.]
    if cf != 0.:
        flat_img = flat_img[flat_img > cf]
    plt.hist(flat_img, bins=b)
    return flat_img
Пример #12
0
def show_slice(input_file, shift=True):
    im = spimage.sp_image_read(input_file, 0)
    if shift:
        im = spimage.sp_image_shift(im)
    s = np.shape(im.image)[0] / 2
    fig = plt.figure(1, figsize=(10, 10))
    fig.clear()
    plt.imshow(np.absolute(im.image)[s, :, :])
Пример #13
0
def show_support_fmodel_model_slice(run_dir,
                                    iteration=None,
                                    save_imgs=False,
                                    output_folder='pngs',
                                    s='x'):
    if iteration == None:
        iteration = ida_phasing.return_last_iteration_integer(run_dir +
                                                              '/output_mnt/')
    print os.getcwd(), iteration
    model = spimage.sp_image_shift(
        spimage.sp_image_read(
            '{r}/output_mnt/model_{i}.h5'.format(r=run_dir, i=iteration), 0))
    fmodel = spimage.sp_image_shift(
        spimage.sp_image_read(
            '{r}/output_mnt/fmodel_{i}.h5'.format(r=run_dir, i=iteration), 0))
    support = spimage.sp_image_shift(
        spimage.sp_image_read(
            '{r}/output_mnt/support_{i}.h5'.format(r=run_dir, i=iteration), 0))
    sh = np.shape(model.image)[0] / 2
    #matplotlib.rcParams.update({'font.size': 16})
    f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 15))
    print s
    if s == 'x':
        sl = (sh, slice(None), slice(None))
        print 'x'
    if s == 'y':
        sl = (slice(None), sh, slice(None))
        print 'y'
    if s == 'z':
        sl = (slice(None), slice(None), sh)
        print 'z'
    ax1.set_title('Model')
    ax1.imshow(np.absolute(model.image[sl]))
    ax2.set_title('Fourier amplitude')
    ax2.imshow(log10(np.absolute(fmodel.image[sl])))
    ax3.set_title('Support')
    ax3.imshow(np.absolute(support.image[sl]))
    ax4.set_title('Phase')
    ax4.imshow(np.angle(model.image[sl]))
    if save_imgs:
        plt.savefig(os.path.join(output_folder, run_dir + '.png'))
        plt.close(f)
Пример #14
0
def to_png(input_dir, output_dir, plot_setup):
    files = read_files(input_dir)

    support_function = get_support_function(plot_setup.get_mask())

    for f in files:
        img = spimage.sp_image_read(f, 0)
        support_function(img)
        img = spimage.sp_image_shift(img)
        output_file = output_dir + "/" + f[:-2] + "png"
        spimage.sp_image_write(img, output_file, plot_setup.get_color())
        spimage.sp_image_free(img)
Пример #15
0
def image_to_png(in_filename, out_filename, colorscale, shift):
    try:
        img = spimage.sp_image_read(in_filename,0)
    except:
        raise TypeError("%s is not a readable file" % in_filename)

    if shift == 1:
        img = spimage.sp_image_shift(img)

    try:
        spimage.sp_image_write(img,out_filename,colorscale)
    except:
        raise TypeError("Can not write %s" % out_filename)
Пример #16
0
def image_to_png(in_filename, out_filename, colorscale, shift):
    try:
        img = spimage.sp_image_read(in_filename, 0)
    except IOError:
        raise TypeError(f"{in_filename} is not a readable file")

    if shift == 1:
        img = spimage.sp_image_shift(img)

    try:
        spimage.sp_image_write(img, out_filename, colorscale)
    except IOError:
        raise TypeError(f"Can not write {out_filename}")
Пример #17
0
def crop_image(in_file, out_file, side, center=None):
    """Function to crop an h5 image and pad with zeros around it"""

    img = spimage.sp_image_read(in_file, 0)

    if not center:
        center = img.detector.image_center[:2]

    shifted = 0
    if img.shifted:
        shifted = 1
        img = spimage.sp_image_shift(img)

    print "shifted = ", shifted

    # cropped = spimage.rectangle_crop(img,lowX,lowY,highX,highY)
    cropped = spimage.sp_image_alloc(side, side, 1)
    cropped.image[:, :] = image_manipulation.crop_and_pad(img.image, center, side)
    cropped.mask[:, :] = image_manipulation.crop_and_pad(img.mask, center, side)

    print "did crop"

    if shifted:
        cropped = spimage.sp_image_shift(cropped)

    print "shifted (or not)"

    print "write ", out_file

    # print "orientation = ", cropped.detector.orientation
    # print spimage.sp_3matrix_get(cropped.detector.orientation,0,0,0)

    spimage.sp_image_write(cropped, out_file, 16)

    spimage.sp_image_free(img)
    spimage.sp_image_free(cropped)

    print "end"
Пример #18
0
def show_support_fmodel_model_slice2(iteration,
                                     save_imgs=False,
                                     output_folder='pngs'):
    model = spimage.sp_image_shift(
        spimage.sp_image_read('model_{i}.h5'.format(i=iteration), 0))
    fmodel = spimage.sp_image_shift(
        spimage.sp_image_read('fmodel_{i}.h5'.format(i=iteration), 0))
    support = spimage.sp_image_shift(
        spimage.sp_image_read('support_{i}.h5'.format(i=iteration), 0))
    s = np.shape(model.image)[0] / 2
    #matplotlib.rcParams.update({'font.size': 16})
    f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 15))
    ax1.set_title('Model')
    ax1.imshow(np.absolute(model.image[s, :, :]))
    ax2.set_title('Fourier amplitude')
    ax2.imshow(log10(np.absolute(fmodel.image[s, :, :])))
    ax3.set_title('Support')
    ax3.imshow(np.absolute(support.image[s, :, :]))
    ax4.set_title('Phase')
    ax4.imshow(np.angle(model.image[s, :, :]))
    if save_imgs:
        plt.savefig(os.path.join(output_folder, '{i}.png'.format(i=iteration)))
        plt.close(f)
Пример #19
0
def plot_image(in_file,*arguments):
    
    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        print "Error: %s is not a readable .h5 file\n" % in_file

    plot_flags = ['abs','mask','phase','real','imag']
    shift_flags = ['shift']
    log_flags = ['log']

    plot_flag = 0
    shift_flag = 0
    log_flag = 0

    for flag in arguments:
        flag = flag.lower()
        if flag in plot_flags:
            plot_flag = flag
        elif flag in shift_flags:
            shift_flag = flag
        elif flag in log_flags:
            log_flag = flag
        else:
            print "unknown flag %s" % flag

    if shift_flag:
        img = spimage.sp_image_shift(img)

    def no_log(x):
        return x

    if log_flag:
        log_function = pylab.log
    else:
        log_function = no_log

    if (plot_flag == "mask"):
        pylab.imshow(img.mask,origin='lower',interpolation="nearest")
    elif(plot_flag == "phase"):
        pylab.imshow(pylab.angle(img.image),cmap='hsv',origin='lower',interpolation="nearest")
    elif(plot_flag == "real"):
        pylab.imshow(log_function(pylab.real(img.image)),origin='lower',interpolation="nearest")
    elif(plot_flag == "imag"):
        pylab.imshow(log_function(pylab.imag(img.image)),origin='lower',interpolation="nearest")
    else:
        pylab.imshow(log_function(abs(img.image)),origin='lower',interpolation="nearest")

    pylab.show()
Пример #20
0
def shift_image(in_file,out_file = 0):
    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        raise IOError("Can't read %s" % in_file)

    img_s = spimage.sp_image_shift(img)

    if out_file == 0:
        out_file = in_file

    try:
        spimage.sp_image_write(img_s,out_file,0)
    except:
        print "Error: Can not write to %s" % out_file
Пример #21
0
def shift_image(in_file, out_file=0):
    try:
        img = spimage.sp_image_read(in_file, 0)
    except IOError:
        raise IOError(f"Can't read {in_file}")

    img_s = spimage.sp_image_shift(img)

    if out_file == 0:
        out_file = in_file

    try:
        spimage.sp_image_write(img_s, out_file, 0)
    except IOError:
        print(f"Error: Can not write to {out_file}")
Пример #22
0
def show_img_and_phase(input_file,
                       save_fig=False,
                       output_file=None,
                       shift=True):
    im = spimage.sp_image_read(input_file, 0)
    if shift:
        im = spimage.sp_image_shift(im)
    s = np.shape(im.image)[0] / 2
    fig = plt.figure(1, figsize=(20, 10))
    fig.clear()
    fig.add_subplot(1, 2, 1)
    plt.imshow(np.absolute(im.image[s, :, :]))
    fig.add_subplot(1, 2, 2)
    plt.imshow(np.angle(im.image[s, :, :]), cmap='PiYG')
    if save_fig:
        plt.savefig(output_file)
Пример #23
0
def shift_image(in_file,out_file = 0):
    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        print "Error: Can not read image %s" % in_file
        return

    img_s = spimage.sp_image_shift(img)

    if out_file == 0:
        out_file = in_file

    try:
        spimage.sp_image_write(img_s,out_file,0)
    except:
        print "Error: Can not write to %s" % out_file
Пример #24
0
def plot_model_fdiff(j, png_output, iteration):
    try:
        os.mkdir(png_output)
    except OSError:
        None
    error = pickle.load(open('final_errors.p'))['fourier_error']
    sorting_order = error.argsort()
    fig, axes = plt.subplots(figsize=(9, 6), nrows=2, ncols=3)
    real_space = np.real(
        spimage.sp_image_shift(
            spimage.sp_image_read(
                'run_%04d/output_mnt/model_%s.h5' % (j, iteration), 0)).image)
    fourier_phase = np.angle(
        ida_phasing.phase_shift(
            spimage.sp_image_shift(
                spimage.sp_image_read(
                    'run_%04d/output_mnt/fmodel_%s.h5' % (j, iteration),
                    0))).image[:])
    fourier_amplitude = spimage.sp_image_shift(
        spimage.sp_image_read(
            'run_%04d/output_mnt/fmodel_%s.h5' % (j, iteration), 0)).image
    input_amplitudes = spimage.sp_image_shift(
        spimage.sp_image_read('run_%04d/input_amplitudes.h5' % j, 0)).image
    mask = spimage.sp_image_shift(
        spimage.sp_image_read('run_%04d/input_amplitudes.h5' % j, 0)).mask
    support = np.real(
        spimage.sp_image_shift(
            spimage.sp_image_read(
                'run_%04d/output_mnt/support_%s.h5' % (j, iteration),
                0)).image)
    dim = np.shape(real_space)[0]
    nonzero = np.shape(real_space[real_space > 0.])[0]
    new_dim = (dim - nonzero**(1 / 3.)) / 2.4
    vmax = real_space.max()
    vmin = real_space.min()
    axes[0][0].imshow(real_space[dim / 2, new_dim:-new_dim, new_dim:-new_dim],
                      vmax=vmax,
                      vmin=vmin)
    axes[0][1].imshow(real_space[new_dim:-new_dim, dim / 2, new_dim:-new_dim],
                      vmax=vmax,
                      vmin=vmin)
    im = axes[0][2].imshow(real_space[new_dim:-new_dim, new_dim:-new_dim,
                                      dim / 2],
                           vmax=vmax,
                           vmin=vmin)
    fig.colorbar(im, ax=axes[0][2])
    diff_amp = (np.absolute(fourier_amplitude - input_amplitudes)) * mask
    axes[1][0].imshow(diff_amp[dim / 2, :, :], vmax=30.)
    axes[1][1].imshow(diff_amp[:, dim / 2, :], vmax=30.)
    axes[1][2].imshow(diff_amp[:, :, dim / 2], vmax=30.)
    #fig.tight_layout()
    print str(sorting_order[j])
    plt.savefig(png_output + '/%s_%04d.png' % (str(sorting_order[j]), j))
    plt.close(fig)
Пример #25
0
def radavg_from_file(file_name,
                     mode='absolute',
                     mask=False,
                     log_scale=False,
                     shift=False,
                     s='x',
                     plot=False,
                     do_return=False):
    im = spimage.sp_image_read(file_name, 0)
    if shift:
        im = spimage.sp_image_shift(im)
    dim = len(np.shape(im.image))
    if dim == 3 and s == 'x':
        sl = (np.shape(im.image)[0] / 2, slice(None), slice(None))
    elif dim == 3 and s == 'y':
        sl = (slice(None), np.shape(im.image)[1] / 2, slice(None))
    elif dim == 3 and s == 'z':
        sl = (slice(None), slice(None), np.shape(im.image)[2] / 2)
    elif dim == 2:
        sl = (slice(None), slice(None))

    if mask:
        msk = im.mask
    if not mask:
        msk = np.ones_like(im.image)

    if mode == 'absolute': f = np.absolute
    elif mode == 'angle': f = np.angle
    elif mode == 'real': f = np.real
    elif mode == 'imag': f = np.imag

    radavg = spimage.radialMeanImage(
        f(im.image[sl]), msk=msk[sl]
    )  #cx=im.detector.image_center[0], cy=im.detector.image_center[1])
    if log_scale:
        radavg = log10(radavg)
    if plot:
        plt.plot(radavg)
    if do_return:
        return radavg
Пример #26
0
def show_absolute_phase_real(input_file, shift=True, save_img=False):
    im = spimage.sp_image_read(input_file, 0)
    if shift:
        im = spimage.sp_image_shift(im)
    s = np.shape(im.image)[0] / 2
    fig = plt.figure(1, figsize=(25, 10))
    fig.clear()
    fig.add_subplot(1, 3, 1)
    plt.title('Absolute')
    plt.imshow(np.absolute(im.image[s, :, :]))
    fig.add_subplot(1, 3, 2)
    plt.title('Phase')
    plt.imshow(np.angle(im.image[s, :, :]), cmap='PiYG')
    fig.add_subplot(1, 3, 3)
    plt.title('Real part')
    m = array(np.absolute(np.real(im.image[64, :, :]).min()),
              np.absolute(np.real(im.image[s, :, :]).max())).max()
    plt.imshow(np.real(im.image[s, :, :]), vmin=-m, vmax=m, cmap='coolwarm')
    plt.tight_layout()
    if save_img:
        path = '/'.join(input_file.split('/')[:-1])
        plt.savefig(os.path.join(path, 'absolute_phase_real_x_slice.png'))
Пример #27
0
 def shift_function(img):
     ret = spimage.sp_image_shift(img)
     spimage.sp_image_free(img)
     return ret
Пример #28
0
import h5py

run_id = str(sys.argv[1])
INPUT_DIR = sys.argv[2]
OUTPUT_DIR = sys.argv[3]
numpy.random.seed()
spimage.sp_srand(numpy.random.randint(1e6))

NUMBER_OF_ITERATIONS = 10000
NUMBER_OF_REFINE_ITERATIONS = 1000

# Amplitudes
diffraction_pattern_file = os.path.join(INPUT_DIR,
                                        'particle_detected_intensity.h5')
diffraction_pattern_raw = spimage.sp_image_read(diffraction_pattern_file, 0)
amplitudes = spimage.sp_image_shift(diffraction_pattern_raw)

# Hack around the sqrt invalid value crash
adim = amplitudes.image.shape[0]
amp_flat = amplitudes.image.flatten()
amp_abs = numpy.abs(amp_flat)

for i in range(len(amp_abs)):
    try:
        amp_abs[i] = numpy.sqrt(amp_abs[i])
    except RuntimeWarning:
        print i

amplitudes.image[:] = amp_abs.reshape([adim, adim])
# End hack
Пример #29
0
if __name__ == "__main__":
    parser = OptionParser(usage="%name -n NUMBER_OF_ITERATIONS -f DIFFRACTION_PATTERN -r REAL_SPACE_MODEL -s SUPPORT [-o OUTPUT_DIR -a AFFIX]")
    parser.add_option("-n", action="store", type="int", default=100, dest="number_of_iterations", help="Number of iterations of ER")
    parser.add_option("-f", action="store", type="string", default=None, dest="pattern", help="Diffraction pattern")
    parser.add_option("-r", action="store", type="string", default=None, dest="real_space", help="Starting real-space model")
    parser.add_option("-s", action="store", type="string", default=None, dest="support", help="Support")
    parser.add_option("-o", action="store", type="string", default=".", dest="output_dir", help="Output directory")
    parser.add_option("-a", action="store", type="string", default="refined", dest="output_affix", help="This name will be added to all output files.")
    options, args = parser.parse_args()

    _numpy.random.seed()
    _spimage.sp_srand(_numpy.random.randint(1e6))
    intensities = _spimage.sp_image_read(options.pattern, 0)
    if intensities.shifted == 0:
        amplitudes = _spimage.sp_image_shift(intensities)
    else:
        amplitudes = _spimage.sp_image_duplicate(intensities, _spimage.SP_COPY_ALL)
    _spimage.sp_image_dephase(amplitudes)
    _spimage.sp_image_to_amplitudes(amplitudes)

    real_space = _spimage.sp_image_read(options.real_space, 0)
    support = _spimage.sp_image_read(options.support, 0)

    phase_alg = _spimage.sp_phasing_er_alloc(_spimage.SpNoConstraints)

    sup_alg = _spimage.sp_support_array_init(_spimage.sp_support_static_alloc(), 20)

    # create phaser
    phaser = _spimage.sp_phaser_alloc()
    _spimage.sp_phaser_init(phaser, phase_alg, sup_alg, _spimage.SpEngineCUDA)
Пример #30
0
# img.image[img.image < 0.0] = 0.0

options = ["shift", "log", "mask"]

for o in sys.argv:
    if o in options:
        if o.lower() == "shift":
            shift = True
        if o.lower() == "log":
            log = True
        if o.lower() == "mask":
            plot_mask = True

if shift:
    img_s = spimage.sp_image_shift(img)
    spimage.sp_image_free(img)
    img = img_s

if plot_mask:
    plot_array = img.mask
else:
    plot_array = abs(img.image)

if log:
    s = mlab.pipeline.scalar_field(log10(0.001 * max(plot_array.flatten()) + plot_array))
else:
    s = mlab.pipeline.scalar_field(plot_array)

# mlab.figure(size=(1000,900))
Пример #31
0
def plot_individual_phasing_results(n,
                                    png_output,
                                    iteration,
                                    n_start=0,
                                    sort_by_error=True,
                                    error='default'):
    try:
        os.mkdir(png_output)
    except OSError:
        None
    if sort_by_error:
        if error == 'default':
            error = pickle.load(open('final_errors.p'))['fourier_error']
        sorting_order = error.argsort()
    for j in range(n_start, n):
        fig, axes = plt.subplots(figsize=(9, 9), nrows=3, ncols=3)
        real_space = np.real(
            spimage.sp_image_shift(
                spimage.sp_image_read(
                    'run_%04d/output_mnt/model_%s.h5' % (j, iteration),
                    0)).image)
        real_phase = np.angle(
            spimage.sp_image_shift(
                spimage.sp_image_read(
                    'run_%04d/output_mnt/model_%s.h5' % (j, iteration),
                    0)).image)
        fourier_phase = np.angle(
            ida_phasing.phase_shift(
                spimage.sp_image_shift(
                    spimage.sp_image_read(
                        'run_%04d/output_mnt/fmodel_%s.h5' % (j, iteration),
                        0))).image[:])
        fourier_amplitude = absolute(
            spimage.sp_image_shift(
                spimage.sp_image_read(
                    'run_%04d/output_mnt/fmodel_%s.h5' % (j, iteration),
                    0)).image)
        print fourier_amplitude.max()
        support = np.real(
            spimage.sp_image_shift(
                spimage.sp_image_read(
                    'run_%04d/output_mnt/support_%s.h5' % (j, iteration),
                    0)).image)
        dim = np.shape(real_space)[0]
        nonzero = np.shape(real_space[real_space > 0.])[0]
        new_dim = (dim - nonzero**(1 / 3.)) / 2.4
        vmax = real_space.max()
        vmin = real_space.min()
        axes[0][0].imshow(real_space[dim / 2, new_dim:-new_dim,
                                     new_dim:-new_dim],
                          vmax=vmax,
                          vmin=vmin)
        axes[0][1].imshow(real_space[new_dim:-new_dim, dim / 2,
                                     new_dim:-new_dim],
                          vmax=vmax,
                          vmin=vmin)
        im = axes[0][2].imshow(real_space[new_dim:-new_dim, new_dim:-new_dim,
                                          dim / 2],
                               vmax=vmax,
                               vmin=vmin)
        fig.colorbar(im, ax=axes[0][2])
        axes[1][0].imshow(fourier_amplitude[dim / 2, :, :],
                          norm=LogNorm())  #cmap='hsv')
        axes[1][1].imshow(fourier_amplitude[:, dim / 2, :],
                          norm=LogNorm())  #cmap='hsv')
        im2 = axes[1][2].imshow(fourier_amplitude[:, :, dim / 2],
                                norm=LogNorm())  #, cmap='hsv')
        fig.colorbar(im2, ax=axes[1][2])
        axes[2][0].imshow(real_phase[dim / 2, new_dim:-new_dim,
                                     new_dim:-new_dim],
                          cmap='RdBu')
        axes[2][1].imshow(real_phase[new_dim:-new_dim, dim / 2,
                                     new_dim:-new_dim],
                          cmap='RdBu')
        axes[2][2].imshow(real_phase[new_dim:-new_dim, new_dim:-new_dim,
                                     dim / 2],
                          cmap='RdBu')
        print str(sorting_order[j])
        plt.savefig(png_output + '/%s_%04d.png' % (str(sorting_order[j]), j))
        plt.close(fig)
Пример #32
0
 def shift_function(img):
     ret = spimage.sp_image_shift(img)
     spimage.sp_image_free(img)
     return ret
Пример #33
0
def image_to_png(arguments):
    if isinstance(arguments,str):
        arguments = [arguments]
    elif not isinstance(arguments,list):
        print "function to_png takes must have a list or string input"
        return

    if len(sys.argv) <= 1:
        print """
    Usage:  python_script_image_to_png <image_in.h5> <image_out.h5> [colorscale]

    Colorscales:
    Jet
    Gray
    PosNeg
    InvertedPosNeg
    Phase
    InvertedPhase
    Log (can be combined with the others)
    Shift (can be combined with the others)

    """
        exit(1)

    try:
        img = spimage.sp_image_read(arguments[0],0)
    except:
        print "Error: %s is not a readable .h5 file\n" % arguments[0]
        exit(1)

    log_flag = 0
    shift_flag = 0

    for flag in arguments[2:]:
        if flag == 'PosNeg':
            color = 8192
        elif flag == 'InvertedPosNeg':
            color = 16384
        elif flag == 'Phase':
            color = 256
        elif flag == 'InvertedPhase':
            color = 4096
        elif flag == 'Jet':
            color = 16
        elif flag == 'Gray':
            color = 1
        elif flag == 'Log':
            log_flag = 1
        elif flag == 'Shift':
            shift_flag = 1
        else:
            print "unknown flag %s" % flag

    if log_flag == 1:
        color += 128

    if shift_flag == 1:
        img = spimage.sp_image_shift(img)

    try:
        spimage.sp_image_write(img,arguments[1],color)
    except:
        print "Error: Can not write %s\n" % arguments[1]
        exit(1)
Пример #34
0
def show_x_y_z_slice(input_file,
                     shift=True,
                     mode='absolute',
                     added_slice=False,
                     one_slice=False,
                     prefix='slice fig',
                     save_file=False,
                     mask=False,
                     mask_array=None,
                     mask_center=False,
                     pix=13.5,
                     log_scale=False):
    "Plot x, y and z slices of image. Choices: shift image, true or false, mode: absolute, angle, real or imag. added_slice true or false, one_slice true or false, shows only x slice if true, prefix sets image name, save_file true or false, mask true or false, if true masks image with mask, log_scale true (norm=LogNorm()) or false"
    if mode == 'absolute': f = np.absolute
    elif mode == 'angle': f = np.angle
    elif mode == 'real': f = np.real
    elif mode == 'imag': f = np.imag
    print f
    n = None
    if log_scale:
        n = LogNorm()

    if type(input_file) == str:
        print 'loading file with spimage'
        im = spimage.sp_image_read(input_file, 0)

    if type(input_file) != str:
        print 'image is not read'
        im = input_file

    cm = 'viridis'
    if mode != 'absolute' and log_scale == False:
        cm = 'RdYlBu'
        cm = 'seismic'

    if mask:
        im.image[:] = im.image * im.mask

    if mask_array != None:
        im.image[:] = im.image * mask_array

    if shift:
        im = spimage.sp_image_shift(im)

    if mask_center:
        r_array = stuff.r_array_3D(im.image.shape[0])
        mask = np.ones_like(im.image)
        mask[r_array < pix] = 0
        im.image[:] = im.image * mask

    if im.image.min() < 0. and (mode == 'real' or mode == 'imag'):
        vmax = np.absolute(im.image).max()
        vmin = -1 * vmax
    else:
        vmax = None
        vmin = None
    c = np.shape(im.image)[0] / 2
    z = int((c * 2 - np.count_nonzero(im.image[c, c, :])) / 2.2)

    if one_slice:
        fig = plt.figure(prefix, figsize=(10, 10))
        if added_slice:
            plt.imshow(f(np.sum(im.image, axis=0))[z:-z, z:-z],
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
        else:
            plt.imshow(f(im.image[c, z:-z, z:-z]),
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
    else:
        fig = plt.figure(prefix, figsize=(30, 10))
        fig.add_subplot(1, 3, 1)
        plt.title('X slice')
        if added_slice:
            plt.imshow(f(np.sum(im.image, axis=0))[z:-z, z:-z],
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
        else:
            plt.imshow(f(im.image[c, z:-z, z:-z]),
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
        fig.add_subplot(1, 3, 2)
        plt.title('Y slice')
        if added_slice:
            plt.imshow(f(np.sum(im.image, axis=1))[z:-z, z:-z],
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
        else:
            plt.imshow(f(im.image[z:-z, c, z:-z]),
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
        fig.add_subplot(1, 3, 3)
        plt.title('Z slice')
        if added_slice:
            plt.imshow(f(np.sum(im.image, axis=2))[z:-z, z:-z],
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
        else:
            plt.imshow(f(im.image[z:-z, z:-z, c]),
                       vmax=vmax,
                       vmin=vmin,
                       norm=n,
                       cmap=cm)
    if save_file:
        plt.savefig(prefix)
Пример #35
0
                        "--number_of_iterations",
                        type=int,
                        default=100,
                        help="Number of iterations of ER")
    parser.add_argument("-o", "--outdir", default=".", help="Output directory")
    parser.add_argument("-a",
                        "--affix",
                        default="refined",
                        help="This name will be added to all output files.")
    args = parser.parse_args()

    _numpy.random.seed()
    _spimage.sp_srand(_numpy.random.randint(1e6))
    intensities = _spimage.sp_image_read(args.pattern, 0)
    if intensities.shifted == 0:
        amplitudes = _spimage.sp_image_shift(intensities)
    else:
        amplitudes = _spimage.sp_image_duplicate(intensities,
                                                 _spimage.SP_COPY_ALL)
    _spimage.sp_image_dephase(amplitudes)
    _spimage.sp_image_to_amplitudes(amplitudes)

    real_space = _spimage.sp_image_read(args.real_space, 0)
    support = _spimage.sp_image_read(args.support, 0)

    phase_alg = _spimage.sp_phasing_er_alloc(_spimage.SpNoConstraints)

    sup_alg = _spimage.sp_support_array_init(
        _spimage.sp_support_static_alloc(), 20)

    # create phaser