def hedm(self): """Return the HEDMInstrument class.""" if not hasattr(self, '_hedm'): with open(self.configuration, 'r') as f: icfg = yaml.load(f, Loader=NumPyIncludeLoader) self._hedm = instrument.HEDMInstrument(icfg) return self._hedm
def run_powder_calibration(): # Set up the tilt calibration mapping rme = HexrdConfig().rotation_matrix_euler() # Set up the instrument iconfig = HexrdConfig().instrument_config instr = instrument.HEDMInstrument(instrument_config=iconfig, tilt_calibration_mapping=rme) flags = HexrdConfig().get_statuses_instrument_format() if len(flags) != len(instr.calibration_flags): msg = 'Length of internal flags does not match instr.calibration_flags' raise Exception(msg) instr.calibration_flags = flags # Plane data and images plane_data = HexrdConfig().active_material.planeData img_dict = HexrdConfig().current_images_dict() # tolerances for patches tth_tol = HexrdConfig().config['calibration']['powder']['tth_tol'] eta_tol = HexrdConfig().config['calibration']['powder']['eta_tol'] pktype = HexrdConfig().config['calibration']['powder']['pk_type'] # powder calibrator pc = PowderCalibrator(instr, plane_data, img_dict, tth_tol=tth_tol, eta_tol=eta_tol, pktype=pktype) # make instrument calibrator ic = InstrumentCalibrator(pc) use_robust_optimization = False ic.run_calibration(use_robust_optimization) # We might need to use this at some point # data_dict = pc._extract_powder_lines() # Add this so the calibration crystal gets written cal_crystal = iconfig.get('calibration_crystal') output_dict = instr.write_config(calibration_dict=cal_crystal) # Add the saturation levels, as they seem to be missing sl = 'saturation_level' for det in output_dict['detectors'].keys(): output_dict['detectors'][det][sl] = iconfig['detectors'][det][sl] # Add status values HexrdConfig().add_status(output_dict) # Update the config HexrdConfig().config['instrument'] = output_dict # Set the previous statuses to be the current statuses HexrdConfig().set_statuses_from_instrument_format(flags)
def hedm(self): """Return the HEDMInstrument class.""" if not hasattr(self, '_hedm'): with open(self.configuration, 'r') as f: icfg = yaml.safe_load(f) self._hedm = instrument.HEDMInstrument(icfg) return self._hedm
def hedm(self, yml): """Set the HEDMInstrument class.""" with open(yml, 'r') as f: icfg = yaml.load(f, Loader=NumPyIncludeLoader) kwargs = { 'instrument_config': icfg, 'max_workers': self._max_workers, } self._hedm = instrument.HEDMInstrument(**kwargs)
def load_instrument(yml): with file(yml, 'r') as f: icfg = yaml.load(f) instr = instrument.HEDMInstrument(instrument_config=icfg) for det_key in instr.detectors: if 'saturation_level' in icfg['detectors'][det_key].keys(): sat_level = icfg['detectors'][det_key]['saturation_level'] print("INFO: Setting panel '%s' saturation level to %e" % (det_key, sat_level)) instr.detectors[det_key].saturation_level = sat_level return instr
def hedm(self): """Return the HEDMInstrument class.""" if not hasattr(self, '_hedm'): with open(self.configuration, 'r') as f: icfg = yaml.load(f, Loader=NumPyIncludeLoader) kwargs = { 'instrument_config': icfg, 'max_workers': self._max_workers, } self._hedm = instrument.HEDMInstrument(**kwargs) return self._hedm
def cartesian_viewer(): images_dict = HexrdConfig().current_images_dict() plane_data = HexrdConfig().active_material.planeData pixel_size = HexrdConfig().cartesian_pixel_size # HEDMInstrument expects None Euler angle convention for the # config. Let's get it as such. iconfig = HexrdConfig().instrument_config_none_euler_convention rme = HexrdConfig().rotation_matrix_euler() instr = instrument.HEDMInstrument(instrument_config=iconfig, tilt_calibration_mapping=rme) # Make sure each key in the image dict is in the panel_ids if images_dict.keys() != instr._detectors.keys(): msg = ('Images do not match the panel ids!\n' + 'Images: ' + str(list(images_dict.keys())) + '\n' + 'PanelIds: ' + str(list(instr._detectors.keys()))) raise Exception(msg) return InstrumentViewer(instr, images_dict, plane_data, pixel_size)
from hexrd import imageseries Pims = imageseries.process.ProcessedImageSeries #============================================================================== #%% INITIALIZATION #============================================================================== # make input yaml files working_dir = '/home/beams/S1IDUSER/workspace/PUP_AFRL_Mar17' image_dir = '/home/beams/S1IDUSER/mnt/s1b/PUP_AFRL_mar17/nf/Au2_NF' image_stem = 'Au2_NF_%06d.tif' instr_cfg_file = os.path.join(working_dir, 'Retiga_Mar17.yml') icfg = yaml.load(open(instr_cfg_file, 'r')) instr = instrument.HEDMInstrument(instrument_config=icfg) yml_tmplate = ''' image-files: directory: %s files: "%s" options: empty-frames: 0 max-frames: 0 meta: panel: %s ''' nf = 720 l0_start = 2543
def mockup_experiment(): # user options # each grain is provided in the form of a quaternion. # The following array contains the quaternions for the array. Note that the # quaternions are in the columns, with the first row (row 0) being the real # part w. We assume that we are dealing with unit quaternions quats = np.array([[0.91836393, 0.90869942], [0.33952917, 0.18348350], [0.17216207, 0.10095837], [0.10811041, 0.36111851]]) n_grains = quats.shape[-1] # last dimension provides the number of grains phis = 2. * np.arccos( quats[0, :]) # phis are the angles for the quaternion # ns contains the rotation axis as an unit vector ns = hexrd.matrixutil.unitVector(quats[1:, :]) exp_maps = np.array([phis[i] * ns[:, i] for i in range(n_grains)]) rMat_c = rotations.rotMatOfQuat(quats) cvec = np.arange(-25, 26) X, Y, Z = np.meshgrid(cvec, cvec, cvec) crd0 = 1e-3 * np.vstack([X.flatten(), Y.flatten(), Z.flatten()]).T crd1 = crd0 + np.r_[0.100, 0.100, 0] crds = np.array([crd0, crd1]) # make grain parameters grain_params = [] for i in range(n_grains): for j in range(len(crd0)): grain_params.append( np.hstack([exp_maps[i, :], crds[i][j, :], vInv_ref])) # scan range and period ome_period = (0, 2 * np.pi) ome_range = [ ome_period, ] ome_step = np.radians(1.) nframes = 0 for i in range(len(ome_range)): nframes += int((ome_range[i][1] - ome_range[i][0]) / ome_step) ome_edges = np.arange(nframes + 1) * ome_step # instrument with open('./retiga.yml', 'r') as fildes: instr = instrument.HEDMInstrument(yaml.safe_load(fildes)) panel = next(iter(instr.detectors.values())) # !!! there is only 1 # tranform paramters # Sample chi = instr.chi tVec_s = instr.tvec # Detector rMat_d = panel.rmat tilt_angles_xyzp = np.asarray(rotations.angles_from_rmat_xyz(rMat_d)) tVec_d = panel.tvec # pixels row_ps = panel.pixel_size_row col_ps = panel.pixel_size_col pixel_size = (row_ps, col_ps) nrows = panel.rows ncols = panel.cols # panel dimensions panel_dims = [tuple(panel.corner_ll), tuple(panel.corner_ur)] x_col_edges = panel.col_edge_vec y_row_edges = panel.row_edge_vec rx, ry = np.meshgrid(x_col_edges, y_row_edges) max_pixel_tth = instrument.max_tth(instr) detector_params = np.hstack([tilt_angles_xyzp, tVec_d, chi, tVec_s]) distortion = panel.distortion # !!! must be None for now # a different parametrization for the sensor # (makes for faster quantization) base = np.array([x_col_edges[0], y_row_edges[0], ome_edges[0]]) deltas = np.array([ x_col_edges[1] - x_col_edges[0], y_row_edges[1] - y_row_edges[0], ome_edges[1] - ome_edges[0] ]) inv_deltas = 1.0 / deltas clip_vals = np.array([ncols, nrows]) # dilation max_diameter = np.sqrt(3) * 0.005 row_dilation = int(np.ceil(0.5 * max_diameter / row_ps)) col_dilation = int(np.ceil(0.5 * max_diameter / col_ps)) # crystallography data beam_energy = valunits.valWUnit("beam_energy", "energy", instr.beam_energy, "keV") beam_wavelength = constants.keVToAngstrom(beam_energy.getVal('keV')) dmin = valunits.valWUnit( "dmin", "length", 0.5 * beam_wavelength / np.sin(0.5 * max_pixel_tth), "angstrom") gold = material.Material() gold.latticeParameters = [4.0782] gold.dmin = dmin gold.beamEnergy = beam_energy gold.planeData.exclusions = None gold.planeData.tThMax = max_pixel_tth # note this comes detector ns = argparse.Namespace() # grains related information ns.n_grains = n_grains # this can be derived from other values... ns.rMat_c = rMat_c # n_grains rotation matrices (one per grain) ns.exp_maps = exp_maps # n_grains exp_maps (one per grain) ns.plane_data = gold.planeData ns.detector_params = detector_params ns.pixel_size = pixel_size ns.ome_range = ome_range ns.ome_period = ome_period ns.x_col_edges = x_col_edges ns.y_row_edges = y_row_edges ns.ome_edges = ome_edges ns.ncols = ncols ns.nrows = nrows ns.nframes = nframes # used only in simulate... ns.rMat_d = rMat_d ns.tVec_d = tVec_d ns.chi = chi # note this is used to compute S... why is it needed? ns.tVec_s = tVec_s ns.rMat_c = rMat_c ns.row_dilation = row_dilation ns.col_dilation = col_dilation ns.distortion = distortion ns.panel_dims = panel_dims # used only in simulate... ns.base = base ns.inv_deltas = inv_deltas ns.clip_vals = clip_vals return grain_params, ns
def hedm(self): return instrument.HEDMInstrument(self.beam, self.detector_dict, self.oscillation_stage)
def __init__(self, instr_file): self._configuration = instr_file with open(instr_file, 'r') as f: icfg = yaml.safe_load(f) self._hedm = instrument.HEDMInstrument(icfg)
def run_line_picked_calibration(line_data): # Set up the tilt calibration mapping rme = HexrdConfig().rotation_matrix_euler() print('Setting up the instrument...') # Set up the instrument iconfig = HexrdConfig().instrument_config_none_euler_convention instr = instrument.HEDMInstrument(instrument_config=iconfig, tilt_calibration_mapping=rme) flags = HexrdConfig().get_statuses_instrument_format() if np.count_nonzero(flags) == 0: msg = 'There are no refinable parameters' raise Exception(msg) if len(flags) != len(instr.calibration_flags): msg = 'Length of internal flags does not match instr.calibration_flags' raise Exception(msg) print('Running optimization...') # Run calibration opt_result = calibrate_instrument_from_picks(instr, line_data, param_flags=flags, xtol=1e-4, ftol=1e-4) if not opt_result.success: print('Optimization failed!') return False print('Optimization succeeded!') # Add this so the calibration crystal gets written cal_crystal = iconfig.get('calibration_crystal') output_dict = instr.write_config(calibration_dict=cal_crystal) # Convert back to whatever convention we were using before eac = HexrdConfig().euler_angle_convention if eac is not None: convert_tilt_convention(output_dict, None, eac) # Add the saturation levels, as they seem to be missing sl = 'saturation_level' for det in output_dict['detectors'].keys(): output_dict['detectors'][det][sl] = iconfig['detectors'][det][sl] print('Updating the config') # Save the previous iconfig to restore the statuses prev_iconfig = HexrdConfig().config['instrument'] # Update the config HexrdConfig().config['instrument'] = output_dict # This adds in any missing keys. In particular, it is going to # add in any "None" detector distortions HexrdConfig().set_detector_defaults_if_missing() # Add status values HexrdConfig().add_status(output_dict) # Set the previous statuses to be the current statuses HexrdConfig().set_statuses_from_prev_iconfig(prev_iconfig) return True
def load_instrument(yml): with open(yml, 'r') as f: icfg = yaml.safe_load(f) return instrument.HEDMInstrument(instrument_config=icfg)
def hedm(self, yml): """Set the HEDMInstrument class.""" with open(yml, 'r') as f: icfg = yaml.load(f, Loader=NumPyIncludeLoader) self._hedm = instrument.HEDMInstrument(icfg)
def load_instrument(config): rme = HexrdConfig().rotation_matrix_euler() return instrument.HEDMInstrument(instrument_config=config, tilt_calibration_mapping=rme)
def hedm(self, yml): """Set the HEDMInstrument class.""" with open(yml, 'r') as f: icfg = yaml.safe_load(f) self._hedm = instrument.HEDMInstrument(icfg)
def load_instrument(yml): with file(yml, 'r') as f: icfg = yaml.load(f) return instrument.HEDMInstrument(instrument_config=icfg)
def hedm(self, yml): with open(yml, 'r') as f: icfg = yaml.safe_load(f) self._hedm = instrument.HEDMInstrument(icfg)