Example #1
0
    def create_warped_image(self, detector_id):
        img = self.images_dict[detector_id]
        panel = self.instr._detectors[detector_id]

        # map corners
        corners = np.vstack(
            [panel.corner_ll,
             panel.corner_lr,
             panel.corner_ur,
             panel.corner_ul,
             ]
        )
        mp = panel.map_to_plane(corners, self.dplane.rmat,
                                self.dplane.tvec)

        col_edges = self.dpanel.col_edge_vec
        row_edges = self.dpanel.row_edge_vec
        j_col = cellIndices(col_edges, mp[:, 0])
        i_row = cellIndices(row_edges, mp[:, 1])

        src = np.vstack([j_col, i_row]).T

        # Save detector corners in pixel coordinates
        self.detector_corners[detector_id] = src

        dst = panel.cartToPixel(corners, pixels=True)
        dst = dst[:, ::-1]

        tform3 = tf.ProjectiveTransform()
        tform3.estimate(src, dst)

        res = tf.warp(img, tform3,
                      output_shape=(self.dpanel.rows, self.dpanel.cols))
        self.warp_dict[detector_id] = res
        return res
Example #2
0
    def interpolate_nearest(self, xy, img, pad_with_nans=True):
        """
        TODO: revisit normalization in here?

        """
        is_2d = img.ndim == 2
        right_shape = img.shape[0] == self.rows and img.shape[1] == self.cols
        assert is_2d and right_shape,\
            "input image must be 2-d with shape (%d, %d)"\
            % (self.rows, self.cols)

        # initialize output with nans
        if pad_with_nans:
            int_xy = np.nan * np.ones(len(xy))
        else:
            int_xy = np.zeros(len(xy))

        # clip away points too close to or off the edges of the detector
        xy_clip, on_panel = self.clip_to_panel(xy, buffer_edges=True)

        # get pixel indices of clipped points
        i_src = cellIndices(self.row_pixel_vec, xy_clip[:, 1])
        j_src = cellIndices(self.col_pixel_vec, xy_clip[:, 0])

        # next interpolate across cols
        int_vals = img[i_src, j_src]
        int_xy[on_panel] = int_vals
        return int_xy
Example #3
0
    def interpolate_nearest(self, xy, img, pad_with_nans=True):
        """
        TODO: revisit normalization in here?

        """
        is_2d = img.ndim == 2
        right_shape = img.shape[0] == self.rows and img.shape[1] == self.cols
        assert is_2d and right_shape,\
            "input image must be 2-d with shape (%d, %d)"\
            % (self.rows, self.cols)

        # initialize output with nans
        if pad_with_nans:
            int_xy = np.nan*np.ones(len(xy))
        else:
            int_xy = np.zeros(len(xy))

        # clip away points too close to or off the edges of the detector
        xy_clip, on_panel = self.clip_to_panel(xy, buffer_edges=True)

        # get pixel indices of clipped points
        i_src = cellIndices(self.row_pixel_vec, xy_clip[:, 1])
        j_src = cellIndices(self.col_pixel_vec, xy_clip[:, 0])

        # next interpolate across cols
        int_vals = img[i_src, j_src]
        int_xy[on_panel] = int_vals
        return int_xy
Example #4
0
def simulate_diffractions(grain_params):
    pbar = ProgressBar(widgets=['simulate_diffractions',
                                Percentage(),
                                Bar()],
                       maxval=len(grain_params)).start()

    image_stack = np.zeros((nframes, nrows, ncols), dtype=bool)
    for i in range(len(grain_params)):
        sim_results = xrdutil.simulateGVecs(pd,
                                            detector_params,
                                            grain_params[i],
                                            panel_dims=panel_dims,
                                            pixel_pitch=pixel_size,
                                            ome_range=ome_range,
                                            ome_period=ome_period,
                                            distortion=None)
        valid_ids, valid_hkl, valid_ang, valid_xy, ang_ps = sim_results
        j_pix = gridutil.cellIndices(x_col_edges, valid_xy[:, 0])
        i_pix = gridutil.cellIndices(y_row_edges, valid_xy[:, 1])
        k_frame = gridutil.cellIndices(ome_edges, valid_ang[:, 2])

        # assign intensity
        for j, k in enumerate(k_frame):
            image_stack[k][i_pix[j], j_pix[j]] = True
        pbar.update(i + 1)
        pass
    pbar.finish()

    #np.save('gold_cubes.npy', image_stack)
    return image_stack
Example #5
0
    def plot_dplane(self):
        dpanel = self.dpanel
        nrows_map = dpanel.rows
        ncols_map = dpanel.cols
        warped = np.zeros((nrows_map, ncols_map))
        for i in range(len(self.images)):
            detector_id = self.panel_ids[i]
            if self.active_panel_mode:
                if not detector_id == self._active_panel_id:
                    continue

            img = self.images[i]
            panel = self.instr._detectors[detector_id]

            # map corners
            corners = np.vstack([
                panel.corner_ll,
                panel.corner_lr,
                panel.corner_ur,
                panel.corner_ul,
            ])
            mp = panel.map_to_plane(corners, self.dplane.rmat,
                                    self.dplane.tvec)

            col_edges = dpanel.col_edge_vec
            row_edges = dpanel.row_edge_vec
            j_col = cellIndices(col_edges, mp[:, 0])
            i_row = cellIndices(row_edges, mp[:, 1])

            src = np.vstack([j_col, i_row]).T
            dst = panel.cartToPixel(corners, pixels=True)
            dst = dst[:, ::-1]

            tform3 = tf.ProjectiveTransform()
            tform3.estimate(src, dst)

            warped += tf.warp(img,
                              tform3,
                              output_shape=(self.dpanel.rows,
                                            self.dpanel.cols))
        """
        IMAGE PLOTTING AND LIMIT CALCULATION
        """
        #img = equalize_adapthist(warped, clip_limit=0.05, nbins=2**16)
        #img = equalize_hist(warped, nbins=2**14)
        cmap = plt.cm.inferno
        cmap.set_under = 'b'
        img = warped
        vmin = np.percentile(img, 50)
        vmax = np.percentile(img, 99)
        if self.image is None:
            self.image = self._axes.imshow(img,
                                           cmap=cmap,
                                           vmin=vmin,
                                           vmax=vmax,
                                           interpolation="none")
        else:
            self.image.set_data(img)
            self._figure.canvas.draw()
        self._axes.format_coord = self.format_coord
Example #6
0
def simulate_diffractions(grain_params):
    pbar = ProgressBar(widgets=['simulate_diffractions', Percentage(), Bar()],
                       maxval=len(grain_params)).start()

    image_stack = np.zeros((nframes, nrows, ncols), dtype=bool)
    for i in range(len(grain_params)):
        sim_results = xrdutil.simulateGVecs(pd,
                                            detector_params,
                                            grain_params[i],
                                            panel_dims=panel_dims,
                                            pixel_pitch=pixel_size,
                                            ome_range=ome_range,
                                            ome_period=ome_period,
                                            distortion=None)
        valid_ids, valid_hkl, valid_ang, valid_xy, ang_ps = sim_results
        j_pix = gridutil.cellIndices(x_col_edges, valid_xy[:, 0])
        i_pix = gridutil.cellIndices(y_row_edges, valid_xy[:, 1])
        k_frame = gridutil.cellIndices(ome_edges, valid_ang[:, 2])

        # assign intensity
        for j, k in enumerate(k_frame):
            image_stack[k][i_pix[j], j_pix[j]] = True
        pbar.update(i+1)
        pass
    pbar.finish()

    #np.save('gold_cubes.npy', image_stack)
    return image_stack
Example #7
0
    def interpolate_bilinear(self, xy, img, pad_with_nans=True):
        """
        TODO: revisit normalization in here?
        """
        is_2d = img.ndim == 2
        right_shape = img.shape[0] == self.rows and img.shape[1] == self.cols
        assert is_2d and right_shape,\
            "input image must be 2-d with shape (%d, %d)"\
            % (self.rows, self.cols)

        # initialize output with nans
        if pad_with_nans:
            int_xy = np.nan * np.ones(len(xy))
        else:
            int_xy = np.zeros(len(xy))

        # clip away points too close to or off the edges of the detector
        xy_clip, on_panel = self.clip_to_panel(xy, buffer_edges=True)

        # grab fractional pixel indices of clipped points
        ij_frac = self.cartToPixel(xy_clip)

        # get floors/ceils from array of pixel _centers_
        i_floor = cellIndices(self.row_pixel_vec, xy_clip[:, 1])
        j_floor = cellIndices(self.col_pixel_vec, xy_clip[:, 0])
        i_ceil = i_floor + 1
        j_ceil = j_floor + 1

        # first interpolate at top/bottom rows
        row_floor_int = \
            (j_ceil - ij_frac[:, 1])*img[i_floor, j_floor] \
            + (ij_frac[:, 1] - j_floor)*img[i_floor, j_ceil]
        row_ceil_int = \
            (j_ceil - ij_frac[:, 1])*img[i_ceil, j_floor] \
            + (ij_frac[:, 1] - j_floor)*img[i_ceil, j_ceil]

        # next interpolate across cols
        int_vals = \
            (i_ceil - ij_frac[:, 0])*row_floor_int \
            + (ij_frac[:, 0] - i_floor)*row_ceil_int
        int_xy[on_panel] = int_vals
        return int_xy
Example #8
0
    def interpolate_bilinear(self, xy, img, pad_with_nans=True):
        """
        TODO: revisit normalization in here?
        """
        is_2d = img.ndim == 2
        right_shape = img.shape[0] == self.rows and img.shape[1] == self.cols
        assert is_2d and right_shape,\
            "input image must be 2-d with shape (%d, %d)"\
            % (self.rows, self.cols)

        # initialize output with nans
        if pad_with_nans:
            int_xy = np.nan*np.ones(len(xy))
        else:
            int_xy = np.zeros(len(xy))

        # clip away points too close to or off the edges of the detector
        xy_clip, on_panel = self.clip_to_panel(xy, buffer_edges=True)

        # grab fractional pixel indices of clipped points
        ij_frac = self.cartToPixel(xy_clip)

        # get floors/ceils from array of pixel _centers_
        i_floor = cellIndices(self.row_pixel_vec, xy_clip[:, 1])
        j_floor = cellIndices(self.col_pixel_vec, xy_clip[:, 0])
        i_ceil = i_floor + 1
        j_ceil = j_floor + 1

        # first interpolate at top/bottom rows
        row_floor_int = \
            (j_ceil - ij_frac[:, 1])*img[i_floor, j_floor] \
            + (ij_frac[:, 1] - j_floor)*img[i_floor, j_ceil]
        row_ceil_int = \
            (j_ceil - ij_frac[:, 1])*img[i_ceil, j_floor] \
            + (ij_frac[:, 1] - j_floor)*img[i_ceil, j_ceil]

        # next interpolate across cols
        int_vals = \
            (i_ceil - ij_frac[:, 0])*row_floor_int \
            + (ij_frac[:, 0] - i_floor)*row_ceil_int
        int_xy[on_panel] = int_vals
        return int_xy
Example #9
0
    def create_warped_image(self, detector_id):
        img = self.images_dict[detector_id]
        panel = self.instr._detectors[detector_id]

        if HexrdConfig().show_detector_borders:
            # Draw a border around the detector panel
            max_int = np.percentile(img, 99.95)
            # 0.5% is big enough for cartesian mode
            pbuf = int(0.005 * np.mean(img.shape))
            img[:, :pbuf] = max_int
            img[:, -pbuf:] = max_int
            img[:pbuf, :] = max_int
            img[-pbuf:, :] = max_int

        # map corners
        corners = np.vstack(
            [panel.corner_ll,
             panel.corner_lr,
             panel.corner_ur,
             panel.corner_ul,
             ]
        )
        mp = panel.map_to_plane(corners, self.dplane.rmat,
                                self.dplane.tvec)

        col_edges = self.dpanel.col_edge_vec
        row_edges = self.dpanel.row_edge_vec
        j_col = cellIndices(col_edges, mp[:, 0])
        i_row = cellIndices(row_edges, mp[:, 1])

        src = np.vstack([j_col, i_row]).T
        dst = panel.cartToPixel(corners, pixels=True)
        dst = dst[:, ::-1]

        tform3 = tf.ProjectiveTransform()
        tform3.estimate(src, dst)

        res = tf.warp(img, tform3,
                      output_shape=(self.dpanel.rows, self.dpanel.cols))
        self.warp_dict[detector_id] = res
        return res
Example #10
0
def make_reflection_patches(instr_cfg,
                            tth_eta,
                            ang_pixel_size,
                            omega=None,
                            tth_tol=0.2,
                            eta_tol=1.0,
                            rMat_c=np.eye(3),
                            tVec_c=np.zeros((3, 1)),
                            distortion=None,
                            npdiv=1,
                            quiet=False,
                            compute_areas_func=gutil.compute_areas,
                            beamVec=None):
    """
    prototype function for making angular patches on a detector

    panel_dims are [(xmin, ymin), (xmax, ymax)] in mm

    pixel_pitch is [row_size, column_size] in mm

    FIXME: DISTORTION HANDING IS STILL A KLUDGE!!!

    patches are:

                 delta tth
   d  ------------- ... -------------
   e  | x | x | x | ... | x | x | x |
   l  ------------- ... -------------
   t                 .
   a                 .
                     .
   e  ------------- ... -------------
   t  | x | x | x | ... | x | x | x |
   a  ------------- ... -------------

   outputs are:
       (tth_vtx, eta_vtx),
       (x_vtx, y_vtx),
       connectivity,
       subpixel_areas,
       (x_center, y_center),
       (i_row, j_col)
    """
    npts = len(tth_eta)

    # detector frame
    rMat_d = xfcapi.makeRotMatOfExpMap(
        np.r_[instr_cfg['detector']['transform']['tilt']])
    tVec_d = np.r_[instr_cfg['detector']['transform']['translation']]
    pixel_size = instr_cfg['detector']['pixels']['size']

    frame_nrows = instr_cfg['detector']['pixels']['rows']
    frame_ncols = instr_cfg['detector']['pixels']['columns']

    panel_dims = (
        -0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]],
        0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]])
    row_edges = np.arange(frame_nrows + 1)[::-1]*pixel_size[1] \
        + panel_dims[0][1]
    col_edges = np.arange(frame_ncols + 1)*pixel_size[0] \
        + panel_dims[0][0]

    # sample frame
    chi = instr_cfg['oscillation_stage']['chi']
    tVec_s = np.r_[instr_cfg['oscillation_stage']['translation']]

    # beam vector
    if beamVec is None:
        beamVec = xfcapi.bVec_ref

    # data to loop
    # ...WOULD IT BE CHEAPER TO CARRY ZEROS OR USE CONDITIONAL?
    if omega is None:
        full_angs = np.hstack([tth_eta, np.zeros((npts, 1))])
    else:
        full_angs = np.hstack([tth_eta, omega.reshape(npts, 1)])

    patches = []
    for angs, pix in zip(full_angs, ang_pixel_size):
        ndiv_tth = npdiv * np.ceil(tth_tol / np.degrees(pix[0]))
        ndiv_eta = npdiv * np.ceil(eta_tol / np.degrees(pix[1]))

        tth_del = np.arange(0, ndiv_tth + 1)*tth_tol/float(ndiv_tth) \
            - 0.5*tth_tol
        eta_del = np.arange(0, ndiv_eta + 1)*eta_tol/float(ndiv_eta) \
            - 0.5*eta_tol

        # store dimensions for convenience
        #   * etas and tths are bin vertices, ome is already centers
        sdims = [len(eta_del) - 1, len(tth_del) - 1]

        # FOR ANGULAR MESH
        conn = gutil.cellConnectivity(sdims[0], sdims[1], origin='ll')

        # meshgrid args are (cols, rows), a.k.a (fast, slow)
        m_tth, m_eta = np.meshgrid(tth_del, eta_del)
        npts_patch = m_tth.size

        # calculate the patch XY coords from the (tth, eta) angles
        # * will CHEAT and ignore the small perturbation the different
        #   omega angle values causes and simply use the central value
        gVec_angs_vtx = np.tile(angs, (npts_patch, 1)) \
            + np.radians(
                np.vstack(
                    [m_tth.flatten(),
                     m_eta.flatten(),
                     np.zeros(npts_patch)]
                ).T
            )

        xy_eval_vtx, _ = _project_on_detector_plane(gVec_angs_vtx,
                                                    rMat_d,
                                                    rMat_c,
                                                    chi,
                                                    tVec_d,
                                                    tVec_c,
                                                    tVec_s,
                                                    distortion,
                                                    beamVec=beamVec)

        areas = compute_areas_func(xy_eval_vtx, conn)

        # EVALUATION POINTS
        #   * for lack of a better option will use centroids
        tth_eta_cen = gutil.cellCentroids(np.atleast_2d(gVec_angs_vtx[:, :2]),
                                          conn)

        gVec_angs = np.hstack(
            [tth_eta_cen, np.tile(angs[2], (len(tth_eta_cen), 1))])

        xy_eval, _ = _project_on_detector_plane(gVec_angs,
                                                rMat_d,
                                                rMat_c,
                                                chi,
                                                tVec_d,
                                                tVec_c,
                                                tVec_s,
                                                distortion,
                                                beamVec=beamVec)

        row_indices = gutil.cellIndices(row_edges, xy_eval[:, 1])
        col_indices = gutil.cellIndices(col_edges, xy_eval[:, 0])

        # append patch data to list
        patches.append(
            ((gVec_angs_vtx[:, 0].reshape(m_tth.shape),
              gVec_angs_vtx[:, 1].reshape(m_tth.shape)),
             (xy_eval_vtx[:, 0].reshape(m_tth.shape),
              xy_eval_vtx[:, 1].reshape(m_tth.shape)), conn,
             areas.reshape(sdims[0],
                           sdims[1]), (xy_eval[:,
                                               0].reshape(sdims[0], sdims[1]),
                                       xy_eval[:,
                                               1].reshape(sdims[0], sdims[1])),
             (row_indices.reshape(sdims[0], sdims[1]),
              col_indices.reshape(sdims[0], sdims[1]))))
        pass  # close loop over angles
    return patches
Example #11
0
def make_reflection_patches(instr_cfg,
                            tth_eta,
                            ang_pixel_size,
                            omega=None,
                            tth_tol=0.2,
                            eta_tol=1.0,
                            rmat_c=np.eye(3),
                            tvec_c=np.zeros((3, 1)),
                            npdiv=1,
                            quiet=False,
                            compute_areas_func=gutil.compute_areas):
    """
    Make angular patches on a detector.

    panel_dims are [(xmin, ymin), (xmax, ymax)] in mm

    pixel_pitch is [row_size, column_size] in mm

    FIXME: DISTORTION HANDING IS STILL A KLUDGE!!!

    patches are:

                 delta tth
    d  ------------- ... -------------
    e  | x | x | x | ... | x | x | x |
    l  ------------- ... -------------
    t                 .
    a                 .
                     .
    e  ------------- ... -------------
    t  | x | x | x | ... | x | x | x |
    a  ------------- ... -------------

    outputs are:
        (tth_vtx, eta_vtx),
        (x_vtx, y_vtx),
        connectivity,
        subpixel_areas,
        (x_center, y_center),
        (i_row, j_col)
    """
    npts = len(tth_eta)

    # detector quantities
    rmat_d = xfcapi.makeRotMatOfExpMap(
        np.r_[instr_cfg['detector']['transform']['tilt']])
    tvec_d = np.r_[instr_cfg['detector']['transform']['translation']]
    pixel_size = instr_cfg['detector']['pixels']['size']

    frame_nrows = instr_cfg['detector']['pixels']['rows']
    frame_ncols = instr_cfg['detector']['pixels']['columns']

    panel_dims = (
        -0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]],
        0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]])
    row_edges = np.arange(frame_nrows + 1)[::-1]*pixel_size[1] \
        + panel_dims[0][1]
    col_edges = np.arange(frame_ncols + 1)*pixel_size[0] \
        + panel_dims[0][0]

    # handle distortion
    distortion = None
    if distortion_key in instr_cfg['detector']:
        distortion_cfg = instr_cfg['detector'][distortion_key]
        if distortion_cfg is not None:
            try:
                func_name = distortion_cfg['function_name']
                dparams = distortion_cfg['parameters']
                distortion = distortion_pkg.get_mapping(func_name, dparams)
            except (KeyError):
                raise RuntimeError("problem with distortion specification")

    # sample frame
    chi = instr_cfg['oscillation_stage']['chi']
    tvec_s = np.r_[instr_cfg['oscillation_stage']['translation']]

    # beam vector
    bvec = np.r_[instr_cfg['beam']['vector']]

    # data to loop
    # ??? WOULD IT BE CHEAPER TO CARRY ZEROS OR USE CONDITIONAL?
    if omega is None:
        full_angs = np.hstack([tth_eta, np.zeros((npts, 1))])
    else:
        full_angs = np.hstack([tth_eta, omega.reshape(npts, 1)])

    patches = []
    for angs, pix in zip(full_angs, ang_pixel_size):
        # calculate bin edges for patch based on local angular pixel size
        # tth
        ntths, tth_edges = gutil.make_tolerance_grid(bin_width=np.degrees(
            pix[0]),
                                                     window_width=tth_tol,
                                                     num_subdivisions=npdiv)

        # eta
        netas, eta_edges = gutil.make_tolerance_grid(bin_width=np.degrees(
            pix[1]),
                                                     window_width=eta_tol,
                                                     num_subdivisions=npdiv)

        # FOR ANGULAR MESH
        conn = gutil.cellConnectivity(netas, ntths, origin='ll')

        # meshgrid args are (cols, rows), a.k.a (fast, slow)
        m_tth, m_eta = np.meshgrid(tth_edges, eta_edges)
        npts_patch = m_tth.size

        # calculate the patch XY coords from the (tth, eta) angles
        # !!! will CHEAT and ignore the small perturbation the different
        #     omega angle values causes and simply use the central value
        gVec_angs_vtx = np.tile(angs, (npts_patch, 1)) \
            + np.radians(
                np.vstack([m_tth.flatten(),
                            m_eta.flatten(),
                            np.zeros(npts_patch)
                ]).T
            )

        xy_eval_vtx, rmats_s, on_plane = _project_on_detector_plane(
            gVec_angs_vtx,
            rmat_d,
            rmat_c,
            chi,
            tvec_d,
            tvec_c,
            tvec_s,
            distortion,
            beamVec=bvec)

        areas = compute_areas_func(xy_eval_vtx, conn)

        # EVALUATION POINTS
        # !!! for lack of a better option will use centroids
        tth_eta_cen = gutil.cellCentroids(np.atleast_2d(gVec_angs_vtx[:, :2]),
                                          conn)

        gVec_angs = np.hstack(
            [tth_eta_cen, np.tile(angs[2], (len(tth_eta_cen), 1))])

        xy_eval, rmats_s, on_plane = _project_on_detector_plane(gVec_angs,
                                                                rmat_d,
                                                                rmat_c,
                                                                chi,
                                                                tvec_d,
                                                                tvec_c,
                                                                tvec_s,
                                                                distortion,
                                                                beamVec=bvec)

        row_indices = gutil.cellIndices(row_edges, xy_eval[:, 1])
        col_indices = gutil.cellIndices(col_edges, xy_eval[:, 0])

        # append patch data to list
        patches.append(
            ((gVec_angs_vtx[:, 0].reshape(m_tth.shape),
              gVec_angs_vtx[:, 1].reshape(m_tth.shape)),
             (xy_eval_vtx[:, 0].reshape(m_tth.shape),
              xy_eval_vtx[:, 1].reshape(m_tth.shape)), conn,
             areas.reshape(netas, ntths), (xy_eval[:, 0].reshape(netas, ntths),
                                           xy_eval[:, 1].reshape(netas,
                                                                 ntths)),
             (row_indices.reshape(netas,
                                  ntths), col_indices.reshape(netas, ntths))))
        pass  # close loop over angles
    return patches
Example #12
0
def check_indexing_plots(cfg_filename, plot_trials=False, plot_from_grains=False):
    cfg = config.open(cfg_filename)[0]    # use first block, like indexing

    working_dir = cfg.working_dir
    analysis_dir = os.path.join(working_dir, cfg.analysis_name)
    
    #instrument parameters
    icfg = get_instrument_parameters(cfg)
    chi = icfg['oscillation_stage']['chi']

    # load maps that were used
    oem = cPickle.load(
        open(cfg.find_orientations.orientation_maps.file, 'r')
        )
    nmaps = len(oem.dataStore)
    omeEdges = np.degrees(oem.omeEdges); nome = len(omeEdges) - 1
    etaEdges = np.degrees(oem.etaEdges); neta = len(etaEdges) - 1
    delta_ome = abs(omeEdges[1]-omeEdges[0])

    full_ome_range = xf.angularDifference(omeEdges[0], omeEdges[-1]) == 0
    full_eta_range = xf.angularDifference(etaEdges[0], etaEdges[-1]) == 0
    
    # grab plane data and figure out IDs of map HKLS
    pd = oem.planeData
    gvids = [pd.hklDataList[i]['hklID'] for i in np.where(pd.exclusions == False)[0].tolist()]

    # load orientations
    quats = np.atleast_2d(np.loadtxt(os.path.join(working_dir, 'accepted_orientations.dat')))
    if plot_trials:
        scored_trials = np.load(os.path.join(working_dir, 'scored_orientations.dat'))
        quats = scored_orientations[:4, scored_orientations[-1, :] >= cfg.find_orientations.clustering.completeness]
        pass
    expMaps = np.tile(2. * np.arccos(quats[:, 0]), (3, 1))*unitVector(quats[:, 1:].T)

    ##########################################
    #      SPECIAL CASE FOR FIT GRAINS       #
    ##########################################
    if plot_from_grains:
        distortion = (GE_41RT, icfg['detector']['distortion']['parameters'])
        #
        grain_table = np.atleast_2d(np.loadtxt(os.path.join(analysis_dir, 'grains.out')))
        ngrains = len(grain_table)
        #
        expMaps = grain_table[:, 3:6]
        tVec_c = grain_table[:, 6:9]
        vInv = grain_table[:, 6:12]
        #
        rMat_d = xf.makeDetectorRotMat(icfg['detector']['transform']['tilt_angles'])
        tVec_d = np.vstack(icfg['detector']['transform']['t_vec_d'])
        #
        chi = icfg['oscillation_stage']['chi']
        tVec_s = np.vstack(icfg['oscillation_stage']['t_vec_s'])
        #
        oes = np.zeros(oem.dataStore.shape)
        for i_grn in range(ngrains):
            spots_table = np.loadtxt(os.path.join(analysis_dir, 'spots_%05d.out' %i_grn))
            idx_m = spots_table[:, 0] >= 0
            for i_map in range(nmaps):
                idx_g = spots_table[:, 1] == gvids[i_map]
                idx = np.logical_and(idx_m, idx_g)
                nrefl = sum(idx)
                
                omes_fit = xf.mapAngle(spots_table[idx, 9], np.radians(cfg.find_orientations.omega.period), units='radians')
                xy_det = spots_table[idx, -3:]
                xy_det[:, 2] = np.zeros(nrefl)
                
                rMat_s_array = xfcapi.makeOscillRotMatArray(chi, omes_fit)
                
                # form in-plane vectors for detector points list in DETECTOR FRAME
                P2_d = xy_det.T
                
                # in LAB FRAME
                P2_l = np.dot(rMat_d, P2_d) + tVec_d # point on detector
                P0_l = np.hstack(
                    [tVec_s + np.dot(rMat_s_array[j], tVec_c[i_grn, :].reshape(3, 1)) for j in range(nrefl)]
                ) # origin of CRYSTAL FRAME

                # diffraction unit vector components in LAB FRAME
                dHat_l = unitVector(P2_l - P0_l)
                P2_l = np.dot(rMat_d, xy_det.T) + tVec_d
                
                # angles for reference frame
                dHat_ref_l = unitVector(P2_l)
    
                # append etas and omes
                etas_fit = np.arctan2(dHat_ref_l[1, :], dHat_ref_l[0, :]).flatten()
           
                # find indices, then truncate or wrap
                i_ome = cellIndices(oem.omeEdges, omes_fit)
                if full_ome_range:
                    i_ome[i_ome < 0] = np.mod(i_ome, nome) + 1
                    i_ome[i_ome >= nome] = np.mod(i_ome, nome)
                else:
                    incl = np.logical_or(i_ome >= 0, i_ome < nome)
                    i_ome = i_ome[incl]
                j_eta = cellIndices(oem.etaEdges, etas_fit)
                if full_eta_range:
                    j_eta[j_eta < 0] = np.mod(j_eta, neta) + 1
                    j_eta[j_eta >= neta] = np.mod(j_eta, neta)
                else:
                    incl = np.logical_or(j_eta >= 0, j_eta < neta)
                    j_eta = j_eta[incl]

                #if np.max(i_ome) >= nome or np.min(i_ome) < 0 or np.max(j_eta) >= neta or np.min(j_eta) < 0:
                #    import pdb; pdb.set_trace()
                # add to map
                oes[i_map][i_ome, j_eta] = 1
            pass
        pass
    
    # simulate quaternion points
    if not plot_from_grains:
        oes = simulateOmeEtaMaps(omeEdges, etaEdges, pd,
                                 expMaps,
                                 chi=chi,
                                 etaTol=0.01, omeTol=0.01,
                                 etaRanges=None, omeRanges=None,
                                 bVec=xf.bVec_ref, eVec=xf.eta_ref, vInv=xf.vInv_ref)
    
    # tick labling
    omes = np.degrees(oem.omeEdges)
    etas = np.degrees(oem.etaEdges)
    num_ticks = 7
    xmin = np.amin(etas); xmax = np.amax(etas)
    dx = (xmax - xmin) / (num_ticks - 1.); dx1 = (len(etas) - 1) / (num_ticks - 1.)
    xtlab = ["%.0f" % (xmin + i*dx) for i in range(num_ticks)]
    xtloc = np.array([i*dx1 for i in range(num_ticks)]) - 0.5
    ymin = np.amin(omes); ymax = np.amax(omes)
    dy = (ymax - ymin) / (num_ticks - 1.); dy1 = (len(omes) - 1) / (num_ticks - 1.)
    ytlab = ["%.0f" % (ymin + i*dy) for i in range(num_ticks)]
    ytloc = np.array([i*dy1 for i in range(num_ticks)]) - 0.5
    
    # Plot the three kernel density estimates
    n_maps = len(oem.iHKLList)
    
    fig_list =[plt.figure(num=i+1) for i in range(n_maps)]
    ax_list = [fig_list[i].gca() for i in range(n_maps)]
    for i_map in range(n_maps):
        y, x = np.where(oes[i_map] > 0)
        ax_list[i_map].hold(True)
        ax_list[i_map].imshow(oem.dataStore[i_map] > 0.1, cmap=cm.bone)
        ax_list[i_map].set_title(r'Map for $\{%d %d %d\}$' %tuple(pd.hkls[:, i_map]))
        ax_list[i_map].set_xlabel(r'Azimuth channel, $\eta$; $\Delta\eta=%.3f$' %delta_ome)
        ax_list[i_map].set_ylabel(r'Rotation channel, $\omega$; $\Delta\omega=%.3f$' %delta_ome)
        ax_list[i_map].plot(x, y, 'c+')
        ax_list[i_map].xaxis.set_ticks(xtloc)
        ax_list[i_map].xaxis.set_ticklabels(xtlab)
        ax_list[i_map].yaxis.set_ticks(ytloc)
        ax_list[i_map].yaxis.set_ticklabels(ytlab)
        ax_list[i_map].axis('tight')
    plt.show()
    return fig_list, oes
Example #13
0
    def plot_dplane(self):
        dpanel = self.dpanel
        nrows_map = dpanel.rows
        ncols_map = dpanel.cols
        warped = np.zeros((nrows_map, ncols_map))
        for i in range(len(self.images)):
            detector_id = self.panel_ids[i]
            if self.active_panel_mode:
                if not detector_id == self._active_panel_id:
                    continue

            img = self.images[i]
            max_int = np.percentile(img, 99.95)
            pbuf = 10
            img[:, :pbuf] = max_int
            img[:, -pbuf:] = max_int
            img[:pbuf, :] = max_int
            img[-pbuf:, :] = max_int
            panel = self.instr._detectors[detector_id]

            # map corners
            corners = np.vstack(
                [panel.corner_ll,
                 panel.corner_lr,
                 panel.corner_ur,
                 panel.corner_ul,
                 ]
            )
            mp = panel.map_to_plane(corners, self.dplane.rmat, self.dplane.tvec)

            col_edges = dpanel.col_edge_vec
            row_edges = dpanel.row_edge_vec
            j_col = cellIndices(col_edges, mp[:, 0])
            i_row = cellIndices(row_edges, mp[:, 1])

            src = np.vstack([j_col, i_row]).T
            dst = panel.cartToPixel(corners, pixels=True)
            dst = dst[:, ::-1]

            tform3 = tf.ProjectiveTransform()
            tform3.estimate(src, dst)

            warped += tf.warp(img, tform3,
                              output_shape=(self.dpanel.rows,
                                            self.dpanel.cols))
        """
        IMAGE PLOTTING AND LIMIT CALCULATION
        """
        img = equalize_adapthist(warped, clip_limit=0.1, nbins=2**16)
        # img = equalize_hist(warped, nbins=2**14)
        #img = warped
        cmap = plt.cm.magma_r
        cmap.set_under='b'
        vmin = np.percentile(img, 50)
        vmax = np.percentile(img, 99.95)
        if self.image is None:
            self.image = self._axes.imshow(
                    img, cmap=cmap,
                    vmin=vmin, vmax=vmax,
                    interpolation="none")
        else:
            self.image.set_data(img)
            self._figure.canvas.draw()
        self._axes.format_coord = self.format_coord
#%%
#Calculate Intercepts for diffraction events from grains

pixel_data = []

for ii in np.arange(grain_params_list.shape[0]):
    print "processing grain %d..." %ii
    
    simg = simulateGVecs(plane_data, detector_params, grain_params_list[ii,3:15],distortion=None)
    
    valid_ids, valid_hkl, valid_ang, valid_xy, ang_ps = simg
    
    #ax.plot(valid_xy[:, 0], valid_xy[:, 1], 'b.', ms=2)
    this_frame = sp.sparse.coo_matrix((nrows, ncols), np.uint16)
    frame_indices = cellIndices(ome_edges, np.degrees(valid_ang[:, 2]))
    i_row = cellIndices(row_edges, valid_xy[:, 1])
    j_col = cellIndices(col_edges, valid_xy[:, 0])
    pixel_data.append(np.vstack([i_row, j_col, frame_indices]))
   

pixd = np.hstack(pixel_data)



frame_cache_data=[sp.sparse.coo_matrix([2048,2048],dtype='uint16')]*nframes

filter_size=np.round(det_psf_fwhm*5)
if filter_size % 2 == 0:
    filter_size+=1
    
def make_reflection_patches(
    instr_cfg,
    tth_eta,
    ang_pixel_size,
    omega=None,
    tth_tol=0.2,
    eta_tol=1.0,
    rMat_c=np.eye(3),
    tVec_c=np.c_[0.0, 0.0, 0.0].T,
    distortion=distortion,
    npdiv=1,
    quiet=False,
    compute_areas_func=compute_areas,
):
    """
    prototype function for making angular patches on a detector

    panel_dims are [(xmin, ymin), (xmax, ymax)] in mm

    pixel_pitch is [row_size, column_size] in mm

    DISTORTION HANDING IS STILL A KLUDGE

    patches are:

                 delta tth
   d  ------------- ... -------------
   e  | x | x | x | ... | x | x | x |
   l  ------------- ... -------------
   t                 .
   a                 .
                     .
   e  ------------- ... -------------
   t  | x | x | x | ... | x | x | x |
   a  ------------- ... -------------

    """
    npts = len(tth_eta)

    # detector frame
    rMat_d = xfcapi.makeDetectorRotMat(instr_cfg["detector"]["transform"]["tilt_angles"])
    tVec_d = np.r_[instr_cfg["detector"]["transform"]["t_vec_d"]]
    pixel_size = instr_cfg["detector"]["pixels"]["size"]

    frame_nrows = instr_cfg["detector"]["pixels"]["rows"]
    frame_ncols = instr_cfg["detector"]["pixels"]["columns"]

    panel_dims = (
        -0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]],
        0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]],
    )
    row_edges = np.arange(frame_nrows + 1)[::-1] * pixel_size[1] + panel_dims[0][1]
    col_edges = np.arange(frame_ncols + 1) * pixel_size[0] + panel_dims[0][0]

    # sample frame
    chi = instr_cfg["oscillation_stage"]["chi"]
    tVec_s = np.r_[instr_cfg["oscillation_stage"]["t_vec_s"]]

    # data to loop
    # ...WOULD IT BE CHEAPER TO CARRY ZEROS OR USE CONDITIONAL?
    if omega is None:
        full_angs = np.hstack([tth_eta, np.zeros((npts, 1))])
    else:
        full_angs = np.hstack([tth_eta, omega.reshape(npts, 1)])
    patches = []
    for angs, pix in zip(full_angs, ang_pixel_size):
        # need to get angular pixel size
        rMat_s = xfcapi.makeOscillRotMat([chi, angs[2]])

        ndiv_tth = npdiv * np.ceil(tth_tol / np.degrees(pix[0]))
        ndiv_eta = npdiv * np.ceil(eta_tol / np.degrees(pix[1]))

        tth_del = np.arange(0, ndiv_tth + 1) * tth_tol / float(ndiv_tth) - 0.5 * tth_tol
        eta_del = np.arange(0, ndiv_eta + 1) * eta_tol / float(ndiv_eta) - 0.5 * eta_tol

        # store dimensions for convenience
        #   * etas and tths are bin vertices, ome is already centers
        sdims = [len(eta_del) - 1, len(tth_del) - 1]

        # meshgrid args are (cols, rows), a.k.a (fast, slow)
        m_tth, m_eta = np.meshgrid(tth_del, eta_del)
        npts_patch = m_tth.size

        # calculate the patch XY coords from the (tth, eta) angles
        # * will CHEAT and ignore the small perturbation the different
        #   omega angle values causes and simply use the central value
        gVec_angs_vtx = np.tile(angs, (npts_patch, 1)) + np.radians(
            np.vstack([m_tth.flatten(), m_eta.flatten(), np.zeros(npts_patch)]).T
        )

        # will need this later
        rMat_s = xfcapi.makeOscillRotMat([chi, angs[2]])

        # FOR ANGULAR MESH
        conn = gutil.cellConnectivity(sdims[0], sdims[1], origin="ll")
        gVec_c = xf.anglesToGVec(gVec_angs_vtx, xf.bVec_ref, xf.eta_ref, rMat_s=rMat_s, rMat_c=rMat_c)

        xy_eval_vtx = xfcapi.gvecToDetectorXY(gVec_c.T, rMat_d, rMat_s, rMat_c, tVec_d, tVec_s, tVec_c)
        if distortion is not None and len(distortion) == 2:
            xy_eval_vtx = distortion[0](xy_eval_vtx, distortion[1], invert=True)
            pass

        areas = compute_areas_func(xy_eval_vtx, conn)

        # EVALUATION POINTS
        #   * for lack of a better option will use centroids
        tth_eta_cen = gutil.cellCentroids(np.atleast_2d(gVec_angs_vtx[:, :2]), conn)
        gVec_angs = np.hstack([tth_eta_cen, np.tile(angs[2], (len(tth_eta_cen), 1))])
        gVec_c = xf.anglesToGVec(gVec_angs, xf.bVec_ref, xf.eta_ref, rMat_s=rMat_s, rMat_c=rMat_c)

        xy_eval = xfcapi.gvecToDetectorXY(gVec_c.T, rMat_d, rMat_s, rMat_c, tVec_d, tVec_s, tVec_c)
        if distortion is not None and len(distortion) == 2:
            xy_eval = distortion[0](xy_eval, distortion[1], invert=True)
            pass
        row_indices = gutil.cellIndices(row_edges, xy_eval[:, 1])
        col_indices = gutil.cellIndices(col_edges, xy_eval[:, 0])

        patches.append(
            (
                (gVec_angs_vtx[:, 0].reshape(m_tth.shape), gVec_angs_vtx[:, 1].reshape(m_tth.shape)),
                (xy_eval_vtx[:, 0].reshape(m_tth.shape), xy_eval_vtx[:, 1].reshape(m_tth.shape)),
                conn,
                areas.reshape(sdims[0], sdims[1]),
                (row_indices.reshape(sdims[0], sdims[1]), col_indices.reshape(sdims[0], sdims[1])),
            )
        )
        pass
    return patches
Example #16
0
def make_reflection_patches(instr_cfg,
                            tth_eta,
                            ang_pixel_size,
                            omega=None,
                            tth_tol=0.2,
                            eta_tol=1.0,
                            rMat_c=np.eye(3),
                            tVec_c=np.c_[0., 0., 0.].T,
                            distortion=distortion,
                            npdiv=1,
                            quiet=False,
                            compute_areas_func=compute_areas):
    """
    prototype function for making angular patches on a detector

    panel_dims are [(xmin, ymin), (xmax, ymax)] in mm

    pixel_pitch is [row_size, column_size] in mm

    DISTORTION HANDING IS STILL A KLUDGE

    patches are:

                 delta tth
   d  ------------- ... -------------
   e  | x | x | x | ... | x | x | x |
   l  ------------- ... -------------
   t                 .
   a                 .
                     .
   e  ------------- ... -------------
   t  | x | x | x | ... | x | x | x |
   a  ------------- ... -------------

    """
    npts = len(tth_eta)

    # detector frame
    rMat_d = xfcapi.makeDetectorRotMat(
        instr_cfg['detector']['transform']['tilt_angles'])
    tVec_d = np.r_[instr_cfg['detector']['transform']['t_vec_d']]
    pixel_size = instr_cfg['detector']['pixels']['size']

    frame_nrows = instr_cfg['detector']['pixels']['rows']
    frame_ncols = instr_cfg['detector']['pixels']['columns']

    panel_dims = (
        -0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]],
        0.5 * np.r_[frame_ncols * pixel_size[1], frame_nrows * pixel_size[0]])
    row_edges = np.arange(frame_nrows +
                          1)[::-1] * pixel_size[1] + panel_dims[0][1]
    col_edges = np.arange(frame_ncols + 1) * pixel_size[0] + panel_dims[0][0]

    # sample frame
    chi = instr_cfg['oscillation_stage']['chi']
    tVec_s = np.r_[instr_cfg['oscillation_stage']['t_vec_s']]

    # data to loop
    # ...WOULD IT BE CHEAPER TO CARRY ZEROS OR USE CONDITIONAL?
    if omega is None:
        full_angs = np.hstack([tth_eta, np.zeros((npts, 1))])
    else:
        full_angs = np.hstack([tth_eta, omega.reshape(npts, 1)])
    patches = []
    for angs, pix in zip(full_angs, ang_pixel_size):
        # need to get angular pixel size
        rMat_s = xfcapi.makeOscillRotMat([chi, angs[2]])

        ndiv_tth = npdiv * np.ceil(tth_tol / np.degrees(pix[0]))
        ndiv_eta = npdiv * np.ceil(eta_tol / np.degrees(pix[1]))

        tth_del = np.arange(
            0, ndiv_tth + 1) * tth_tol / float(ndiv_tth) - 0.5 * tth_tol
        eta_del = np.arange(
            0, ndiv_eta + 1) * eta_tol / float(ndiv_eta) - 0.5 * eta_tol

        # store dimensions for convenience
        #   * etas and tths are bin vertices, ome is already centers
        sdims = [len(eta_del) - 1, len(tth_del) - 1]

        # meshgrid args are (cols, rows), a.k.a (fast, slow)
        m_tth, m_eta = np.meshgrid(tth_del, eta_del)
        npts_patch = m_tth.size

        # calculate the patch XY coords from the (tth, eta) angles
        # * will CHEAT and ignore the small perturbation the different
        #   omega angle values causes and simply use the central value
        gVec_angs_vtx = np.tile(angs, (npts_patch, 1)) \
                        + np.radians(
                            np.vstack([m_tth.flatten(),
                                       m_eta.flatten(),
                                       np.zeros(npts_patch)
                                       ]).T
                                     )

        # will need this later
        rMat_s = xfcapi.makeOscillRotMat([chi, angs[2]])

        # FOR ANGULAR MESH
        conn = gutil.cellConnectivity(sdims[0], sdims[1], origin='ll')
        gVec_c = xf.anglesToGVec(gVec_angs_vtx,
                                 xf.bVec_ref,
                                 xf.eta_ref,
                                 rMat_s=rMat_s,
                                 rMat_c=rMat_c)

        xy_eval_vtx = xfcapi.gvecToDetectorXY(gVec_c.T, rMat_d, rMat_s, rMat_c,
                                              tVec_d, tVec_s, tVec_c)
        if distortion is not None and len(distortion) == 2:
            xy_eval_vtx = distortion[0](xy_eval_vtx,
                                        distortion[1],
                                        invert=True)
            pass

        areas = compute_areas_func(xy_eval_vtx, conn)

        # EVALUATION POINTS
        #   * for lack of a better option will use centroids
        tth_eta_cen = gutil.cellCentroids(np.atleast_2d(gVec_angs_vtx[:, :2]),
                                          conn)
        gVec_angs = np.hstack(
            [tth_eta_cen, np.tile(angs[2], (len(tth_eta_cen), 1))])
        gVec_c = xf.anglesToGVec(gVec_angs,
                                 xf.bVec_ref,
                                 xf.eta_ref,
                                 rMat_s=rMat_s,
                                 rMat_c=rMat_c)

        xy_eval = xfcapi.gvecToDetectorXY(gVec_c.T, rMat_d, rMat_s, rMat_c,
                                          tVec_d, tVec_s, tVec_c)
        if distortion is not None and len(distortion) == 2:
            xy_eval = distortion[0](xy_eval, distortion[1], invert=True)
            pass
        row_indices = gutil.cellIndices(row_edges, xy_eval[:, 1])
        col_indices = gutil.cellIndices(col_edges, xy_eval[:, 0])

        patches.append(
            ((gVec_angs_vtx[:, 0].reshape(m_tth.shape),
              gVec_angs_vtx[:, 1].reshape(m_tth.shape)),
             (xy_eval_vtx[:, 0].reshape(m_tth.shape),
              xy_eval_vtx[:, 1].reshape(m_tth.shape)), conn,
             areas.reshape(sdims[0],
                           sdims[1]), (row_indices.reshape(sdims[0], sdims[1]),
                                       col_indices.reshape(sdims[0],
                                                           sdims[1]))))
        pass
    return patches
    def plot_dplane(self, warped=None):
        dpanel = self.dpanel
        nrows_map = dpanel.rows
        ncols_map = dpanel.cols

        if warped is None:
            warped = np.zeros((nrows_map, ncols_map))
            for i in range(len(self.images)):
                detector_id = self.panel_ids[i]
                if self.active_panel_mode:
                    if not detector_id == self._active_panel_id:
                        continue

                img = self.images[i]
                panel = self.instr._detectors[detector_id]

                # map corners
                corners = np.vstack([
                    panel.corner_ll,
                    panel.corner_lr,
                    panel.corner_ur,
                    panel.corner_ul,
                ])
                mp = panel.map_to_plane(corners, self.dplane.rmat,
                                        self.dplane.tvec)

                col_edges = dpanel.col_edge_vec
                row_edges = dpanel.row_edge_vec
                j_col = cellIndices(col_edges, mp[:, 0])
                i_row = cellIndices(row_edges, mp[:, 1])

                src = np.vstack([j_col, i_row]).T
                dst = panel.cartToPixel(corners, pixels=True)
                dst = dst[:, ::-1]

                tform3 = tf.ProjectiveTransform()
                tform3.estimate(src, dst)

                warped += tf.warp(img,
                                  tform3,
                                  output_shape=(self.dpanel.rows,
                                                self.dpanel.cols))
            img = equalize_adapthist(warped, clip_limit=0.05, nbins=2**16)
        else:
            img = warped
            #img = equalize_adapthist(warped/np.amax(warped), clip_limit=0.5, nbins=2**16)

        mycmap = plt.cm.bone
        if self.image is None:
            self.image = self._axes.imshow(img,
                                           cmap=mycmap,
                                           vmax=None,
                                           interpolation="none")
        else:
            shp = img.shape

            self.image.set_data(img)
            self.image.set_clim(vmax=np.amax(img))
            self._figure.canvas.draw()
            self.image.set_extent([0, shp[1], shp[0], 0])  # l, r, b, t
        self._axes.format_coord = self.format_coord
Example #18
0
def check_indexing_plots(cfg_filename,
                         plot_trials=False,
                         plot_from_grains=False):
    cfg = config.open(cfg_filename)[0]  # use first block, like indexing

    working_dir = cfg.working_dir
    analysis_dir = os.path.join(working_dir, cfg.analysis_name)

    #instrument parameters
    icfg = get_instrument_parameters(cfg)
    chi = icfg['oscillation_stage']['chi']

    # load maps that were used
    oem = cPickle.load(open(cfg.find_orientations.orientation_maps.file, 'r'))
    nmaps = len(oem.dataStore)
    omeEdges = np.degrees(oem.omeEdges)
    nome = len(omeEdges) - 1
    etaEdges = np.degrees(oem.etaEdges)
    neta = len(etaEdges) - 1
    delta_ome = abs(omeEdges[1] - omeEdges[0])

    full_ome_range = xf.angularDifference(omeEdges[0], omeEdges[-1]) == 0
    full_eta_range = xf.angularDifference(etaEdges[0], etaEdges[-1]) == 0

    # grab plane data and figure out IDs of map HKLS
    pd = oem.planeData
    gvids = [
        pd.hklDataList[i]['hklID']
        for i in np.where(pd.exclusions == False)[0].tolist()
    ]

    # load orientations
    quats = np.atleast_2d(
        np.loadtxt(os.path.join(working_dir, 'accepted_orientations.dat')))
    if plot_trials:
        scored_trials = np.load(
            os.path.join(working_dir, 'scored_orientations.dat'))
        quats = scored_orientations[:4, scored_orientations[
            -1, :] >= cfg.find_orientations.clustering.completeness]
        pass
    expMaps = np.tile(2. * np.arccos(quats[:, 0]),
                      (3, 1)) * unitVector(quats[:, 1:].T)

    ##########################################
    #      SPECIAL CASE FOR FIT GRAINS       #
    ##########################################
    if plot_from_grains:
        distortion = (GE_41RT, icfg['detector']['distortion']['parameters'])
        #
        grain_table = np.atleast_2d(
            np.loadtxt(os.path.join(analysis_dir, 'grains.out')))
        ngrains = len(grain_table)
        #
        expMaps = grain_table[:, 3:6]
        tVec_c = grain_table[:, 6:9]
        vInv = grain_table[:, 6:12]
        #
        rMat_d = xf.makeDetectorRotMat(
            icfg['detector']['transform']['tilt_angles'])
        tVec_d = np.vstack(icfg['detector']['transform']['t_vec_d'])
        #
        chi = icfg['oscillation_stage']['chi']
        tVec_s = np.vstack(icfg['oscillation_stage']['t_vec_s'])
        #
        oes = np.zeros(oem.dataStore.shape)
        for i_grn in range(ngrains):
            spots_table = np.loadtxt(
                os.path.join(analysis_dir, 'spots_%05d.out' % i_grn))
            idx_m = spots_table[:, 0] >= 0
            for i_map in range(nmaps):
                idx_g = spots_table[:, 1] == gvids[i_map]
                idx = np.logical_and(idx_m, idx_g)
                nrefl = sum(idx)

                omes_fit = xf.mapAngle(spots_table[idx, 9],
                                       np.radians(
                                           cfg.find_orientations.omega.period),
                                       units='radians')
                xy_det = spots_table[idx, -3:]
                xy_det[:, 2] = np.zeros(nrefl)

                rMat_s_array = xfcapi.makeOscillRotMatArray(chi, omes_fit)

                # form in-plane vectors for detector points list in DETECTOR FRAME
                P2_d = xy_det.T

                # in LAB FRAME
                P2_l = np.dot(rMat_d, P2_d) + tVec_d  # point on detector
                P0_l = np.hstack([
                    tVec_s +
                    np.dot(rMat_s_array[j], tVec_c[i_grn, :].reshape(3, 1))
                    for j in range(nrefl)
                ])  # origin of CRYSTAL FRAME

                # diffraction unit vector components in LAB FRAME
                dHat_l = unitVector(P2_l - P0_l)
                P2_l = np.dot(rMat_d, xy_det.T) + tVec_d

                # angles for reference frame
                dHat_ref_l = unitVector(P2_l)

                # append etas and omes
                etas_fit = np.arctan2(dHat_ref_l[1, :],
                                      dHat_ref_l[0, :]).flatten()

                # find indices, then truncate or wrap
                i_ome = cellIndices(oem.omeEdges, omes_fit)
                if full_ome_range:
                    i_ome[i_ome < 0] = np.mod(i_ome, nome) + 1
                    i_ome[i_ome >= nome] = np.mod(i_ome, nome)
                else:
                    incl = np.logical_or(i_ome >= 0, i_ome < nome)
                    i_ome = i_ome[incl]
                j_eta = cellIndices(oem.etaEdges, etas_fit)
                if full_eta_range:
                    j_eta[j_eta < 0] = np.mod(j_eta, neta) + 1
                    j_eta[j_eta >= neta] = np.mod(j_eta, neta)
                else:
                    incl = np.logical_or(j_eta >= 0, j_eta < neta)
                    j_eta = j_eta[incl]

                #if np.max(i_ome) >= nome or np.min(i_ome) < 0 or np.max(j_eta) >= neta or np.min(j_eta) < 0:
                #    import pdb; pdb.set_trace()
                # add to map
                oes[i_map][i_ome, j_eta] = 1
            pass
        pass

    # simulate quaternion points
    if not plot_from_grains:
        oes = simulateOmeEtaMaps(omeEdges,
                                 etaEdges,
                                 pd,
                                 expMaps,
                                 chi=chi,
                                 etaTol=0.01,
                                 omeTol=0.01,
                                 etaRanges=None,
                                 omeRanges=None,
                                 bVec=xf.bVec_ref,
                                 eVec=xf.eta_ref,
                                 vInv=xf.vInv_ref)

    # tick labling
    omes = np.degrees(oem.omeEdges)
    etas = np.degrees(oem.etaEdges)
    num_ticks = 7
    xmin = np.amin(etas)
    xmax = np.amax(etas)
    dx = (xmax - xmin) / (num_ticks - 1.)
    dx1 = (len(etas) - 1) / (num_ticks - 1.)
    xtlab = ["%.0f" % (xmin + i * dx) for i in range(num_ticks)]
    xtloc = np.array([i * dx1 for i in range(num_ticks)]) - 0.5
    ymin = np.amin(omes)
    ymax = np.amax(omes)
    dy = (ymax - ymin) / (num_ticks - 1.)
    dy1 = (len(omes) - 1) / (num_ticks - 1.)
    ytlab = ["%.0f" % (ymin + i * dy) for i in range(num_ticks)]
    ytloc = np.array([i * dy1 for i in range(num_ticks)]) - 0.5

    # Plot the three kernel density estimates
    n_maps = len(oem.iHKLList)

    fig_list = [plt.figure(num=i + 1) for i in range(n_maps)]
    ax_list = [fig_list[i].gca() for i in range(n_maps)]
    for i_map in range(n_maps):
        y, x = np.where(oes[i_map] > 0)
        ax_list[i_map].hold(True)
        ax_list[i_map].imshow(oem.dataStore[i_map] > 0.1, cmap=cm.bone)
        ax_list[i_map].set_title(r'Map for $\{%d %d %d\}$' %
                                 tuple(pd.hkls[:, i_map]))
        ax_list[i_map].set_xlabel(
            r'Azimuth channel, $\eta$; $\Delta\eta=%.3f$' % delta_ome)
        ax_list[i_map].set_ylabel(
            r'Rotation channel, $\omega$; $\Delta\omega=%.3f$' % delta_ome)
        ax_list[i_map].plot(x, y, 'c+')
        ax_list[i_map].xaxis.set_ticks(xtloc)
        ax_list[i_map].xaxis.set_ticklabels(xtlab)
        ax_list[i_map].yaxis.set_ticks(ytloc)
        ax_list[i_map].yaxis.set_ticklabels(ytlab)
        ax_list[i_map].axis('tight')
    plt.show()
    return fig_list, oes