Beispiel #1
0
def convert_polar_to_raw(line):
    line_data = []
    for key, panel in create_hedm_instrument().detectors.items():
        cart = panel.angles_to_cart(np.radians(line))
        raw = panel.cartToPixel(cart)
        line_data.append((key, raw))
    return line_data
Beispiel #2
0
    def __init__(self):
        self.type = ViewType.cartesian
        self.instr = create_hedm_instrument()
        self.images_dict = HexrdConfig().current_images_dict()

        # Perform some checks before proceeding
        self.check_keys_match()
        self.check_angles_feasible()

        self.pixel_size = HexrdConfig().cartesian_pixel_size
        self.warp_dict = {}
        self.detector_corners = {}

        dist = HexrdConfig().cartesian_virtual_plane_distance
        dplane_tvec = np.array([0., 0., -dist])

        rotate_x = HexrdConfig().cartesian_plane_normal_rotate_x
        rotate_y = HexrdConfig().cartesian_plane_normal_rotate_y

        dplane_tilt = np.radians(np.array(([rotate_x, rotate_y, 0.])))

        self.dplane = DisplayPlane(tvec=dplane_tvec, tilt=dplane_tilt)
        self.make_dpanel()

        # Check that the image size won't be too big...
        self.check_size_feasible()

        self.plot_dplane()
Beispiel #3
0
    def auto_generate_polar_params(self):
        # This will automatically generate and set values for the polar
        # pixel values based upon the config.
        # This function does not invoke a re-render.
        manager = multiprocessing.Manager()
        keys = ['max_tth_ps', 'max_eta_ps', 'min_tth', 'max_tth']
        results = {key: manager.list() for key in keys}

        f = partial(compute_polar_params, **results)
        instr = create_hedm_instrument()
        with multiprocessing.Pool() as pool:
            pool.map(f, instr.detectors.values())

        # Set these manually so no rerender signals are fired
        params = {
            'pixel_size_tth': 10 * np.degrees(max(results['max_tth_ps'])),
            'pixel_size_eta': 2 * np.degrees(max(results['max_eta_ps'])),
            'tth_min': np.degrees(min(results['min_tth'])),
            'tth_max': np.degrees(max(results['max_tth']))
        }

        # Sometimes, this is too big. Bring it down if it is.
        px_eta = params['pixel_size_eta']
        params['pixel_size_eta'] = px_eta if px_eta < 90 else 5

        HexrdConfig().config['image']['polar'].update(params)

        # Update all of the materials with the new tth_max
        HexrdConfig().reset_tth_max_all_materials()

        # Get the GUI to update with the new values
        self.update_gui_from_config()
Beispiel #4
0
    def run_calibration(self):
        picks = self.generate_pick_results()
        materials = self.pick_materials
        instr = create_hedm_instrument()
        flags = HexrdConfig().get_statuses_instrument_format()
        instr.calibration_flags = flags

        instr_calibrator = run_calibration(picks, instr, materials)
        self.write_instrument_to_hexrd_config(instr)

        # Update the lattice parameters and overlays
        overlays = [self.overlays[i] for i in self.all_overlay_picks]
        for overlay, calibrator in zip(overlays, instr_calibrator.calibrators):
            if calibrator.calibrator_type == 'powder':
                if calibrator.params.size == 0:
                    continue

                mat_name = overlay['material']
                mat = materials[mat_name]
                mat.latticeParameters = calibrator.params
                make_new_pdata(mat)
                HexrdConfig().flag_overlay_updates_for_material(mat_name)
                if mat is HexrdConfig().active_material:
                    HexrdConfig().active_material_modified.emit()
            elif calibrator.calibrator_type == 'laue':
                overlay['options']['crystal_params'] = calibrator.params

        # In case any overlays changed
        HexrdConfig().overlay_config_changed.emit()
        HexrdConfig().calibration_complete.emit()
Beispiel #5
0
    def _run(self):
        # First, have the user pick some options
        if not PowderCalibrationDialog(self.material, self.parent).exec_():
            # User canceled...
            return

        # The options they chose are saved here
        options = HexrdConfig().config['calibration']['powder']
        self.instr = create_hedm_instrument()

        # Assume there is only one image in each image series for now...
        img_dict = {k: x[0] for k, x in HexrdConfig().imageseries_dict.items()}

        statuses = self.refinement_flags_without_overlays
        self.cf = statuses
        self.instr.calibration_flags = statuses

        kwargs = {
            'instr': self.instr,
            'plane_data': self.material.planeData,
            'img_dict': img_dict,
            'flags': self.refinement_flags,
            'eta_tol': options['eta_tol'],
            'pktype': options['pk_type'],
        }

        self.pc = PowderCalibrator(**kwargs)
        self.ic = InstrumentCalibrator(self.pc)
        self.extract_powder_lines()
Beispiel #6
0
 def get_instrument_defaults(self):
     self.detector_defaults.clear()
     not_default = (self.ui.current_config.isChecked()
                    or not self.ui.default_config.isChecked())
     if self.config_file and not_default:
         if os.path.splitext(self.config_file)[1] in YAML_EXTS:
             with open(self.config_file, 'r') as f:
                 self.defaults = yaml.load(f, Loader=yaml.FullLoader)
         else:
             try:
                 with h5py.File(self.config_file, 'r') as f:
                     instr = create_hedm_instrument()
                     instr.unwrap_h5_to_dict(f, self.defaults)
             except Exception as e:
                 msg = (
                     f'ERROR - Could not read file: \n {e} \n'
                     f'File must be HDF5 or YAML.')
                 QMessageBox.warning(None, 'HEXRD', msg)
                 return False
     else:
         fname = f'{self.instrument.lower()}_reference_config.yml'
         text = resource_loader.load_resource(hexrd_resources, fname)
         self.defaults = yaml.load(text, Loader=yaml.FullLoader)
     self.detector_defaults['default_config'] = self.defaults
     self.set_detector_options()
     return True
Beispiel #7
0
    def __init__(self):
        self.type = ViewType.cartesian
        self.instr = create_hedm_instrument()
        self.images_dict = HexrdConfig().current_images_dict()

        # Make sure each key in the image dict is in the panel_ids
        if self.images_dict.keys() != self.instr._detectors.keys():
            msg = ('Images do not match the panel ids!\n' +
                   'Images: ' + str(list(self.images_dict.keys())) + '\n' +
                   'PanelIds: ' + str(list(self.instr._detectors.keys())))
            raise Exception(msg)

        self.pixel_size = HexrdConfig().cartesian_pixel_size
        self.warp_dict = {}
        self.detector_corners = {}

        dist = HexrdConfig().cartesian_virtual_plane_distance
        dplane_tvec = np.array([0., 0., -dist])

        rotate_x = HexrdConfig().cartesian_plane_normal_rotate_x
        rotate_y = HexrdConfig().cartesian_plane_normal_rotate_y

        dplane_tilt = np.radians(np.array(([rotate_x, rotate_y, 0.])))

        self.dplane = DisplayPlane(tvec=dplane_tvec, tilt=dplane_tilt)
        self.make_dpanel()
        self.plot_dplane()
Beispiel #8
0
def create_indexing_config():
    # Creates a hexrd.config class from the indexing configuration

    # Make a copy to modify
    indexing_config = copy.deepcopy(HexrdConfig().indexing_config)
    available_materials = list(HexrdConfig().materials.keys())
    selected_material = indexing_config.get('_selected_material')

    if selected_material not in available_materials:
        raise Exception(f'Selected material {selected_material} not available')

    material = HexrdConfig().material(selected_material)

    omaps = indexing_config['find_orientations']['orientation_maps']
    omaps['active_hkls'] = list(range(len(material.planeData.getHKLs())))

    # Set the active material on the config
    tmp = indexing_config.setdefault('material', {})
    tmp['active'] = material.name

    # Create the root config from the indexing config dict
    config = RootConfig(indexing_config)

    # Create and set instrument config
    iconfig = InstrumentConfig(config)
    iconfig._hedm = create_hedm_instrument()
    config.instrument = iconfig

    # Create and set material config
    mconfig = MaterialConfig(config)
    mconfig.materials = HexrdConfig().materials
    config.material = mconfig

    # Set this so the config won't over-write our tThWidth
    config.set('material:tth_width', np.degrees(material.planeData.tThWidth))

    # Use unaggregated images if possible
    ims_dict = HexrdConfig().unagg_images
    if ims_dict is None:
        # This probably means the image series was never aggregated.
        # Try using the imageseries dict.
        ims_dict = HexrdConfig().imageseries_dict

    # Load omega data if it is missing
    load_omegas_dict = {
        k: ims for k, ims in ims_dict.items() if 'omega' not in ims.metadata
    }
    if load_omegas_dict:
        ImageLoadManager().add_omega_metadata(load_omegas_dict)

    # Convert image series into OmegaImageSeries
    for key, ims in ims_dict.items():
        if not isinstance(ims, OmegaImageSeries):
            ims_dict[key] = OmegaImageSeries(ims)

    config.image_series = ims_dict

    return config
Beispiel #9
0
 def __init__(self, img, parent=None):
     self.parent = parent.image_tab_widget.image_canvases[0]
     self.ax = self.parent.axes_images[0]
     self.raw_axes = self.parent.raw_axes[0]
     self.panels = create_hedm_instrument().detectors
     self.img = img
     self.shape = None
     self.press = None
     self.total_rotation = 0
Beispiel #10
0
    def __init__(self):
        self.type = ViewType.polar
        self.instr = create_hedm_instrument()
        self.images_dict = HexrdConfig().current_images_dict()

        # Resolution settings
        # As far as I can tell, self.pixel_size won't actually change
        # anything for a polar plot, so just hard-code it.
        self.pixel_size = 0.5

        self.draw_polar()
Beispiel #11
0
 def __init__(self, parent=None):
     self.parent = parent.image_tab_widget.image_canvases[0]
     self.ax = self.parent.axes_images[0]
     self.raw_axes = self.parent.raw_axes[0]
     self.panels = create_hedm_instrument().detectors
     self.img = None
     self.shape = None
     self.press = None
     self.total_rotation = 0
     self.translating = True
     self.shape_styles = []
     self.parent.setFocusPolicy(Qt.ClickFocus)
Beispiel #12
0
def create_indexing_config():
    # Creates a hexrd.config class from the indexing configuration

    # Make a copy to modify
    indexing_config = copy.deepcopy(HexrdConfig().indexing_config)
    material = HexrdConfig().active_material
    omaps = indexing_config['find_orientations']['orientation_maps']
    omaps['active_hkls'] = active_hkl_indices(material.planeData)

    # Set the active material on the config
    tmp = indexing_config.setdefault('material', {})
    tmp['active'] = HexrdConfig().active_material_name

    # Create the root config from the indexing config dict
    config = RootConfig(indexing_config)

    # Create and set instrument config
    iconfig = InstrumentConfig()
    iconfig._hedm = create_hedm_instrument()
    config.instrument = iconfig

    # Create and set material config
    mconfig = MaterialConfig(config)
    mconfig.materials = HexrdConfig().materials
    config.material = mconfig

    # Use unaggregated images if possible
    ims_dict = ImageLoadManager().unaggregated_images
    if ims_dict is None:
        # This probably means the image series was never aggregated.
        # Try using the imageseries dict.
        ims_dict = HexrdConfig().imageseries_dict

    # Load omega data if it is missing
    load_omegas_dict = {
        k: ims
        for k, ims in ims_dict.items() if 'omega' not in ims.metadata
    }
    if load_omegas_dict:
        ImageLoadManager().add_omega_metadata(load_omegas_dict)

    # Convert image series into OmegaImageSeries
    for key, ims in ims_dict.items():
        ims_dict[key] = OmegaImageSeries(ims)

    config.image_series = ims_dict

    return config
Beispiel #13
0
    def validate(self):
        visible_overlays = self.visible_overlays
        if not visible_overlays:
            raise Exception('No visible overlays')

        if not all(self.has_widths(x) for x in visible_overlays):
            raise Exception('All visible overlays must have widths')

        flags = HexrdConfig().get_statuses_instrument_format().tolist()
        # Make sure the length of our flags matches up with the instruments
        instr = create_hedm_instrument()
        if len(flags) != len(instr.calibration_flags):
            msg = ('Length of internal flags does not match '
                   'instr.calibration_flags')
            raise Exception(msg)

        # Add overlay refinements
        for overlay in visible_overlays:
            flags += [x[1] for x in self.get_refinements(overlay)]

        if np.count_nonzero(flags) == 0:
            raise Exception('There are no refinable parameters')
Beispiel #14
0
    def dump_results(self):
        # This dumps out all results to files for testing
        # It is mostly intended for debug purposes
        import json
        import pickle

        class NumpyEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, np.ndarray):
                    return obj.tolist()
                return json.JSONEncoder.default(self, obj)

        for name, mat in self.pick_materials.items():
            # Dump out the material
            mat_file_name = f'{name}.pkl'
            print(f'Writing out material to {mat_file_name}')
            with open(mat_file_name, 'wb') as wf:
                pickle.dump(mat, wf)

        pick_results = self.generate_pick_results()
        out_file = 'calibration_picks.json'
        print(f'Writing out picks to {out_file}')
        with open(out_file, 'w') as wf:
            json.dump(pick_results, wf, cls=NumpyEncoder)

        # Dump out the instrument as well
        instr = create_hedm_instrument()
        print(f'Writing out instrument to instrument.pkl')
        with open('instrument.pkl', 'wb') as wf:
            pickle.dump(instr, wf)

        # Dump out refinement flags
        flags = HexrdConfig().get_statuses_instrument_format()
        print(f'Writing out refinement flags to refinement_flags.json')
        with open('refinement_flags.json', 'w') as wf:
            json.dump(flags, wf, cls=NumpyEncoder)
Beispiel #15
0
 def __init__(self):
     self.type = ViewType.raw
     self.instr = create_hedm_instrument()
Beispiel #16
0
def convert_raw_to_polar(det, line):
    panel = create_hedm_instrument().detectors[det]
    cart = panel.pixelToCart(line)
    tth, gvec = panel.cart_to_angles(cart)
    return [np.degrees(tth)]