Пример #1
0
             0.10,
             "Rotation of the unit cell in degrees (Qx, Qz, Qy) = " +
             str(angles[0]) + "," + str(angles[1]) + "," + str(angles[2]),
             size=12)
    plt.pause(0.1)
    plt.savefig(savedir + 'sum_' + str(nbz) + '_' + str(nby) + '_' + str(nbx) +
                '_' + str(binning[0]) + '_' + str(binning[1]) + '_' +
                str(binning[2]) + '_rot_' + str(angles[0]) + '_' +
                str(angles[1]) + '_' + str(angles[2]) + '.png')

fig, _, _ = gu.contour_slices(struct_array, (qx, qz, qy),
                              sum_frames=False,
                              title='Simulated diffraction pattern',
                              slice_position=[pivot[0], pivot[1], pivot[2]],
                              levels=np.linspace(0,
                                                 struct_array.max(),
                                                 10,
                                                 endpoint=False),
                              plot_colorbar=False,
                              scale='linear',
                              is_orthogonal=True,
                              reciprocal_space=True)
fig.text(0.60, 0.25, "Energy = " + str(energy / 1000) + " keV", size=12)
fig.text(0.60, 0.20, "SDD = " + str(sdd) + " m", size=12)
fig.text(0.60,
         0.15,
         unitcell + " unit cell of parameter = " + str(unitcell_param) + " nm",
         size=12)
fig.text(0.60,
         0.10,
         "Rotation of the unit cell in degrees (Qx, Qz, Qy) = " +
         str(angles[0]) + "," + str(angles[1]) + "," + str(angles[2]),
Пример #2
0
            plt.close(fig)

    ############################
    # save final data and mask #
    ############################
    comment = comment + '_' + str(detector.binning[0]) + '_' + str(detector.binning[1]) + '_' + str(detector.binning[2])
    if not use_rawdata and len(q_vector) != 0:
        np.savez_compressed(savedir + 'QxQzQy_S' + str(scans[scan_nb]) + comment,
                            qx=q_vector[0], qz=q_vector[1], qy=q_vector[2])
        if save_to_mat:
            savemat(savedir + 'S' + str(scans[scan_nb]) + '_qx.mat', {'qx': q_vector[0]})
            savemat(savedir + 'S' + str(scans[scan_nb]) + '_qy.mat', {'qy': q_vector[1]})
            savemat(savedir + 'S' + str(scans[scan_nb]) + '_qz.mat', {'qz': q_vector[2]})

        fig, _, _ = gu.contour_slices(data, (q_vector[0], q_vector[1], q_vector[2]), sum_frames=True,
                                      title='Final data', plot_colorbar=True, scale='log', is_orthogonal=True,
                                      levels=np.linspace(0, int(np.log10(data.max())), 150, endpoint=False),
                                      reciprocal_space=True)
        fig.savefig(detector.savedir + 'final_reciprocal_space_S' + str(scans[scan_nb]) + comment + '.png')
        plt.close(fig)

    print('\nsaving to directory:', savedir)
    np.savez_compressed(savedir + 'S' + str(scans[scan_nb]) + '_pynx' + comment, data=data)
    np.savez_compressed(savedir + 'S' + str(scans[scan_nb]) + '_maskpynx' + comment, mask=mask)

    if save_to_mat:
        # save to .mat, the new order is x y z (outboard, vertical up, downstream)
        savemat(savedir + 'S' + str(scans[scan_nb]) + '_data.mat',
                {'data': np.moveaxis(data.astype(np.float32), [0, 1, 2], [-1, -2, -3])})
        savemat(savedir + 'S' + str(scans[scan_nb]) + '_mask.mat',
                {'data': np.moveaxis(mask.astype(np.int8), [0, 1, 2], [-1, -2, -3])})
Пример #3
0
    data = rgi(
        np.concatenate((new_z.reshape(
            (1, new_z.size)), new_y.reshape(
                (1, new_z.size)), new_x.reshape((1, new_z.size)))).transpose())
    data = data.reshape((nz, ny, nx))
    print('Interpolation done')
    del new_z, new_y, new_x, rgi
    gc.collect()

if debug:
    gu.contour_slices(data, (qx, qz, qy),
                      sum_frames=True,
                      title='data',
                      levels=np.linspace(0,
                                         np.ceil(np.log10(data.max())),
                                         150,
                                         endpoint=True),
                      plot_colorbar=True,
                      scale='log',
                      is_orthogonal=True,
                      reciprocal_space=True)

#########################################
# plot 3D isosurface (perspective view) #
#########################################
data = np.flip(
    data, 2)  # mayavi expects xyz, data order is downstream/upward/outboard
data[data == 0] = np.nan
if crop_symmetric:
    grid_qx, grid_qz, grid_qy = np.mgrid[qx_com -
                                         tick_spacing * half_labels:qx_com +
Пример #4
0
################
# contour plot #
################
if colorbar_range is None:  # use rounded acceptable values
    colorbar_range = (
        np.ceil(np.median(np.log10(data[np.logical_and(data != 0, ~np.isnan(data))]))),
        np.ceil(np.log10(data[np.logical_and(data != 0, ~np.isnan(data))].max())),
    )
if load_qvalues:
    fig, _, _ = gu.contour_slices(
        data,
        (qx, qz, qy),
        sum_frames=save_sum,
        title="Diffraction pattern",
        levels=np.linspace(colorbar_range[0], colorbar_range[1], 150, endpoint=True),
        plot_colorbar=True,
        scale="log",
        is_orthogonal=True,
        reciprocal_space=True,
    )
else:
    fig, _, _ = gu.multislices_plot(
        data,
        sum_frames=save_sum,
        scale="log",
        plot_colorbar=True,
        vmin=colorbar_range[0],
        vmax=colorbar_range[1],
        title="Diffraction pattern",
        is_orthogonal=True,
Пример #5
0
                        vmin=0,
                        vmax=np.log10(data).max(),
                        scale='log',
                        plot_colorbar=True,
                        cmap=my_cmap,
                        is_orthogonal=True,
                        reciprocal_space=True)

    if qvalues_flag:
        gu.contour_slices(data,
                          q_coordinates=(exp_qvalues['qx'], exp_qvalues['qz'],
                                         exp_qvalues['qy']),
                          sum_frames=True,
                          title='Experimental data',
                          levels=np.linspace(0,
                                             np.log10(data.max()) + 1,
                                             20,
                                             endpoint=False),
                          scale='log',
                          plot_colorbar=False,
                          is_orthogonal=True,
                          reciprocal_space=True)
    else:
        gu.contour_slices(data,
                          q_coordinates=q_values,
                          sum_frames=True,
                          title='Experimental data',
                          levels=np.linspace(0,
                                             np.log10(data.max()) + 1,
                                             20,
                                             endpoint=False),
Пример #6
0
def grid_cdi(
    data,
    mask,
    setup,
    frames_logical,
    correct_curvature=False,
    debugging=False,
    **kwargs,
):
    """
    Interpolate reciprocal space forward CDI data.

    The interpolation is done from the measurement cylindrical frame to the
    laboratory frame (cartesian coordinates). Note that it is based on PetraIII P10
    beamline ( counterclockwise rotation, detector seen from the front).

    :param data: the 3D data, already binned in the detector frame
    :param mask: the corresponding 3D mask
    :param setup: an instance of the class Setup
    :param frames_logical: array of initial length the number of measured frames.
     In case of padding the length changes. A frame whose index is set to 1 means
     that it is used, 0 means not used, -1 means padded (added) frame.
    :param correct_curvature: if True, will correct for the curvature of
     the Ewald sphere
    :param debugging: set to True to see plots
    :param kwargs:
     - 'fill_value': tuple of two real numbers, fill values to use for pixels outside
       of the interpolation range. The first value is for the data, the second for the
       mask. Default is (0, 0)

    :return: the data and mask interpolated in the laboratory frame, q values
     (downstream, vertical up, outboard)
    """
    fill_value = kwargs.get("fill_value", (0, 0))
    valid.valid_ndarray(arrays=(data, mask), ndim=3)
    if setup.name == "P10_SAXS":
        if setup.rocking_angle == "inplane":
            if setup.custom_scan:
                cdi_angle = setup.custom_motors["hprz"]
            else:
                cdi_angle, _, _ = setup.loader.motor_positions(setup=setup)
                # second return value is the X-ray energy, third the detector distance
        else:
            raise ValueError(
                "out-of-plane rotation not yet implemented for forward CDI data"
            )
    else:
        raise NotImplementedError(
            "Not yet implemented for beamlines other than P10")

    data, mask, cdi_angle, frames_logical = check_cdi_angle(
        data=data,
        mask=mask,
        cdi_angle=cdi_angle,
        frames_logical=frames_logical,
        debugging=debugging,
    )
    if debugging:
        print("\ncdi_angle", cdi_angle)
    nbz, nby, nbx = data.shape
    print("\nData shape after check_cdi_angle and before regridding:", nbz,
          nby, nbx)
    print("\nAngle range:", cdi_angle.min(), cdi_angle.max())

    (interp_data, interp_mask), q_values, corrected_dirbeam = setup.ortho_cdi(
        arrays=(data, mask),
        cdi_angle=cdi_angle,
        fill_value=fill_value,
        correct_curvature=correct_curvature,
        debugging=debugging,
    )
    qx, qz, qy = q_values

    # check for Nan
    interp_mask[np.isnan(interp_data)] = 1
    interp_data[np.isnan(interp_data)] = 0
    interp_mask[np.isnan(interp_mask)] = 1
    # set the mask as an array of integers, 0 or 1
    interp_mask[np.nonzero(interp_mask)] = 1
    interp_mask = interp_mask.astype(int)

    # apply the mask to the data
    interp_data[np.nonzero(interp_mask)] = 0

    # calculate the position in pixels of the origin of the reciprocal space
    pivot_z = int((setup.direct_beam[1] - setup.detector.roi[2]) /
                  setup.detector.binning[2])
    # 90 degrees conter-clockwise rotation of detector X around qz, downstream
    _, numy, numx = interp_data.shape
    pivot_y = int(numy - corrected_dirbeam[0])
    # detector Y vertical down, opposite to qz vertical up
    pivot_x = int(numx - corrected_dirbeam[1])
    # detector X inboard at P10, opposite to qy outboard
    print("\nOrigin of the reciprocal space (Qx,Qz,Qy): "
          f"({pivot_z}, {pivot_y}, {pivot_x})\n")

    # plot the gridded data
    final_binning = (
        setup.detector.preprocessing_binning[2] * setup.detector.binning[2],
        setup.detector.preprocessing_binning[1] * setup.detector.binning[1],
        setup.detector.preprocessing_binning[2] * setup.detector.binning[2],
    )
    plot_comment = (
        f"_{numx}_{numy}_{numx}"
        f"_{final_binning[0]}_{final_binning[1]}_{final_binning[2]}.png")
    # sample rotation around the vertical direction at P10: the effective
    # binning in axis 0 is binning[2]

    max_z = interp_data.sum(axis=0).max()
    fig, _, _ = gu.contour_slices(
        interp_data,
        (qx, qz, qy),
        sum_frames=True,
        title="Regridded data",
        levels=np.linspace(0, np.ceil(np.log10(max_z)), 150, endpoint=True),
        plot_colorbar=True,
        scale="log",
        is_orthogonal=True,
        reciprocal_space=True,
    )
    fig.text(
        0.55,
        0.30,
        "Origin of the reciprocal space (Qx,Qz,Qy):\n\n" +
        "     ({:d}, {:d}, {:d})".format(pivot_z, pivot_y, pivot_x),
        size=14,
    )
    fig.savefig(setup.detector.savedir + "reciprocal_space_sum" + plot_comment)
    plt.close(fig)

    fig, _, _ = gu.contour_slices(
        interp_data,
        (qx, qz, qy),
        sum_frames=False,
        title="Regridded data",
        levels=np.linspace(0,
                           np.ceil(np.log10(interp_data.max(initial=None))),
                           150,
                           endpoint=True),
        slice_position=(pivot_z, pivot_y, pivot_x),
        plot_colorbar=True,
        scale="log",
        is_orthogonal=True,
        reciprocal_space=True,
    )
    fig.text(
        0.55,
        0.30,
        "Origin of the reciprocal space (Qx,Qz,Qy):\n\n" +
        "     ({:d}, {:d}, {:d})".format(pivot_z, pivot_y, pivot_x),
        size=14,
    )
    fig.savefig(setup.detector.savedir + "reciprocal_space_central" +
                plot_comment)
    plt.close(fig)

    fig, _, _ = gu.multislices_plot(
        interp_data,
        sum_frames=False,
        scale="log",
        plot_colorbar=True,
        vmin=0,
        slice_position=(pivot_z, pivot_y, pivot_x),
        title="Regridded data",
        is_orthogonal=True,
        reciprocal_space=True,
    )
    fig.text(
        0.55,
        0.30,
        "Origin of the reciprocal space (Qx,Qz,Qy):\n\n" +
        "     ({:d}, {:d}, {:d})".format(pivot_z, pivot_y, pivot_x),
        size=14,
    )
    fig.savefig(setup.detector.savedir + "reciprocal_space_central_pix" +
                plot_comment)
    plt.close(fig)
    if debugging:
        gu.multislices_plot(
            interp_mask,
            sum_frames=False,
            scale="linear",
            plot_colorbar=True,
            vmin=0,
            title="Regridded mask",
            is_orthogonal=True,
            reciprocal_space=True,
        )

    return interp_data, interp_mask, [qx, qz, qy], frames_logical
Пример #7
0
    # save final data and mask #
    ############################
    print('\nSaving directory:', detector.savedir)
    print('Data type before saving:', data.dtype)
    mask[np.nonzero(mask)] = 1
    mask = mask.astype(int)
    print('Mask type before saving:', mask.dtype)
    if not use_rawdata and len(q_values) != 0:
        if save_to_npz:
            np.savez_compressed(detector.savedir + f'QxQzQy_S{scan_nb}' + comment, qx=qx, qz=qz, qy=qy)
        if save_to_mat:
            savemat(detector.savedir + f'S{scan_nb}_qx.mat', {'qx': qx})
            savemat(detector.savedir + f'S{scan_nb}_qy.mat', {'qy': qy})
            savemat(detector.savedir + f'S{scan_nb}_qz.mat', {'qz': qz})
        fig, _, _ = gu.contour_slices(data, (qx, qz, qy), sum_frames=True, title='Final data',
                                      levels=np.linspace(0, int(np.log10(data.max(initial=None))), 150,
                                                         endpoint=False),
                                      plot_colorbar=True, scale='log', is_orthogonal=True, reciprocal_space=True)
        fig.savefig(detector.savedir + f'final_reciprocal_space_S{scan_nb}' + comment + '.png')
        plt.close(fig)

    if save_to_npz:
        np.savez_compressed(detector.savedir + f'S{scan_nb}_pynx' + comment, data=data)
        np.savez_compressed(detector.savedir + f'S{scan_nb}_maskpynx' + comment, mask=mask)

    if save_to_mat:
        # save to .mat, the new order is x y z (outboard, vertical up, downstream)
        savemat(detector.savedir + 'S' + str(scan_nb) + '_data.mat',
                {'data': np.moveaxis(data.astype(np.float32), [0, 1, 2], [-1, -2, -3])})
        savemat(detector.savedir + 'S' + str(scan_nb) + '_mask.mat',
                {'data': np.moveaxis(mask.astype(np.int8), [0, 1, 2], [-1, -2, -3])})
Пример #8
0
# define the mask at radius radius_mean #
#########################################
mask = np.logical_and((distances < (radius_mean + dq)), (distances >
                                                         (radius_mean - dq)))
if debug:
    gu.multislices_plot(mask,
                        sum_frames=False,
                        reciprocal_space=True,
                        is_orthogonal=True,
                        title='mask')

####################################
# plot 2D diffrated intensity maps #
####################################
fig, (ax0, ax1, ax2, ax3), (plt0, plt1, plt2) = \
    gu.contour_slices(data, (qx, qz, qy), sum_frames=True, title='Regridded data', levels=150, plot_colorbar=True,
                      scale='log', is_orthogonal=True, reciprocal_space=True)

circle = plt.Circle((qyCOM, qzCOM),
                    radius_mean + dq,
                    color='0',
                    fill=False,
                    linestyle='dotted')
ax0.add_artist(circle)
circle = plt.Circle((qyCOM, qzCOM),
                    radius_mean - dq,
                    color='0',
                    fill=False,
                    linestyle='dotted')
ax0.add_artist(circle)
circle = plt.Circle((qyCOM, qxCOM),
                    radius_mean + dq,
Пример #9
0
if debug:
    gu.multislices_plot(mask,
                        sum_frames=False,
                        reciprocal_space=True,
                        is_orthogonal=True,
                        title="mask")

####################################
# plot 2D diffrated intensity maps #
####################################
fig, (ax0, ax1, ax2, ax3), (plt0, plt1, plt2) = gu.contour_slices(
    data,
    (qx, qz, qy),
    sum_frames=True,
    title="Regridded data",
    levels=150,
    plot_colorbar=True,
    scale="log",
    is_orthogonal=True,
    reciprocal_space=True,
)

circle = plt.Circle((qyCOM, qzCOM),
                    radius_mean + dq,
                    color="0",
                    fill=False,
                    linestyle="dotted")
ax0.add_artist(circle)
circle = plt.Circle((qyCOM, qzCOM),
                    radius_mean - dq,
                    color="0",