def matchOmegas(xyo_det, hkls_idx, chi, rMat_c, bMat, wavelength, vInv=vInv_ref, beamVec=bVec_ref, etaVec=eta_ref, omePeriod=None): """ For a given list of (x, y, ome) points, outputs the index into the results from oscillAnglesOfHKLs, including the calculated omega values. """ # get omegas for rMat_s calculation if omePeriod is not None: meas_omes = xf.mapAngle(xyo_det[:, 2], omePeriod) else: meas_omes = xyo_det[:, 2] oangs0, oangs1 = xf.oscillAnglesOfHKLs(hkls_idx, chi, rMat_c, bMat, wavelength, vInv=vInv, beamVec=beamVec, etaVec=etaVec) if omePeriod is not None: calc_omes = np.vstack( [xf.mapAngle(oangs0[2, :], omePeriod), xf.mapAngle(oangs1[2, :], omePeriod) ] ) else: calc_omes = np.vstack( [xf.mapAngle(oangs0[2, :]), xf.mapAngle(oangs1[2, :]) ] ) match_omes = np.argsort(abs(np.tile(meas_omes, (2, 1)) - calc_omes), axis=0) == 0 calc_omes = calc_omes.T.flatten()[match_omes.T.flatten()] return match_omes, calc_omes
def matchOmegas(xyo_det, hkls_idx, chi, rMat_c, bMat, wavelength, vInv=vInv_ref, beamVec=bVec_ref, etaVec=eta_ref, omePeriod=None): """ For a given list of (x, y, ome) points, outputs the index into the results from oscillAnglesOfHKLs, including the calculated omega values. """ # get omegas for rMat_s calculation if omePeriod is not None: meas_omes = xf.mapAngle(xyo_det[:, 2], omePeriod) else: meas_omes = xyo_det[:, 2] oangs0, oangs1 = xfcapi.oscillAnglesOfHKLs(hkls_idx.T, chi, rMat_c, bMat, wavelength, vInv=vInv, beamVec=beamVec, etaVec=etaVec) if np.any(np.isnan(oangs0)): nanIdx = np.where(np.isnan(oangs0[:, 0]))[0] errorString = "Infeasible parameters for hkls:\n" for i in range(len(nanIdx)): errorString += "%d %d %d\n" % tuple(hkls_idx[:, nanIdx[i]]) raise RuntimeError, errorString else: # CAPI version gives vstacked angles... must be (2, nhkls) calc_omes = np.vstack([oangs0[:, 2], oangs1[:, 2]]) if omePeriod is not None: calc_omes = np.vstack([xf.mapAngle(oangs0[:, 2], omePeriod), xf.mapAngle(oangs1[:, 2], omePeriod)]) # do angular difference diff_omes = xf.angularDifference(np.tile(meas_omes, (2, 1)), calc_omes) match_omes = np.argsort(diff_omes, axis=0) == 0 calc_omes = calc_omes.T.flatten()[match_omes.T.flatten()] return match_omes, calc_omes
def calibrateDetectorFromSX(xyo_det, hkls_idx, bMat, wavelength, tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, vInv=vInv_ref, beamVec=bVec_ref, etaVec=eta_ref, distortion=(dFunc_ref, dParams_ref, dFlag_ref, dScl_ref), pFlag=pFlag_ref, pScl=pScl_ref, omePeriod=None, factor=0.1, xtol=1e-8, ftol=1e-8): """ """ if omePeriod is not None: xyo_det[:, 2] = xf.mapAngle(xyo_det[:, 2], omePeriod) dFunc = distortion[0] dParams = distortion[1] dFlag = distortion[2] dScl = distortion[3] # p = np.zeros(16) # # p[0] = tiltAngles[0] # p[1] = tiltAngles[1] # p[2] = tiltAngles[2] # p[3] = tVec_d[0] # p[4] = tVec_d[1] # p[5] = tVec_d[2] # p[6] = chi # p[7] = tVec_s[0] # p[8] = tVec_s[1] # p[9] = tVec_s[2] # p[10] = expMap_c[0] # p[11] = expMap_c[1] # p[12] = expMap_c[2] # p[13] = tVec_c[0] # p[14] = tVec_c[1] # p[15] = tVec_c[2] # # pFull = np.hstack([p, dParams]) pFull = geomParamsToInput(tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, dParams) refineFlag = np.hstack([pFlag, dFlag]) scl = np.hstack([pScl, dScl]) pFit = pFull[refineFlag] fitArgs = (pFull, pFlag, dFunc, dFlag, xyo_det, hkls_idx, bMat, vInv, wavelength, beamVec, etaVec, omePeriod) results = opt.leastsq(objFuncSX, pFit, args=fitArgs, diag=scl[refineFlag].flatten(), factor=factor, xtol=xtol, ftol=ftol) pFit_opt = results[0] retval = pFull retval[refineFlag] = pFit_opt return retval
def calibrateDetectorFromSX(xyo_det, hkls_idx, bMat, wavelength, tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, vInv=vInv_ref, beamVec=bVec_ref, etaVec=eta_ref, distortion=(dFunc_ref, dParams_ref, dFlag_ref, dScl_ref), pFlag=pFlag_ref, pScl=pScl_ref, omePeriod=None, factor=0.1, xtol=1e-4, ftol=1e-4): """ """ if omePeriod is not None: xyo_det[:, 2] = xf.mapAngle(xyo_det[:, 2], omePeriod) dFunc = distortion[0] dParams = distortion[1] dFlag = distortion[2] dScl = distortion[3] # p = np.zeros(16) # # p[0] = tiltAngles[0] # p[1] = tiltAngles[1] # p[2] = tiltAngles[2] # p[3] = tVec_d[0] # p[4] = tVec_d[1] # p[5] = tVec_d[2] # p[6] = chi # p[7] = tVec_s[0] # p[8] = tVec_s[1] # p[9] = tVec_s[2] # p[10] = expMap_c[0] # p[11] = expMap_c[1] # p[12] = expMap_c[2] # p[13] = tVec_c[0] # p[14] = tVec_c[1] # p[15] = tVec_c[2] # # pFull = np.hstack([p, dParams]) pFull = geomParamsToInput(tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, dParams) refineFlag = np.hstack([pFlag, dFlag]) scl = np.hstack([pScl, dScl]) pFit = pFull[refineFlag] fitArgs = (pFull, pFlag, dFunc, dFlag, xyo_det, hkls_idx, bMat, vInv, wavelength, beamVec, etaVec, omePeriod) results = optimize.leastsq(objFuncSX, pFit, args=fitArgs, diag=1./scl[refineFlag].flatten(), factor=factor, xtol=xtol, ftol=ftol) pFit_opt = results[0] retval = pFull retval[refineFlag] = pFit_opt return retval
def fit_grains(self, grain_id, grain_params): """ Executes lsq fits of grains based on spot files REFLECTION TABLE Cols as follows: 0-6: ID PID H K L sum(int) max(int) 6-9: pred tth pred eta pred ome 9-12: meas tth meas eta meas ome 12-15: meas X meas Y meas ome """ ome_start = self._p['omega_start'] ome_step = self._p['omega_step'] ome_stop = self._p['omega_stop'] refl_table = np.loadtxt(self._p['spots_stem'] % grain_id) valid_refl_ids = refl_table[:, 0] >= 0 unsat_spots = refl_table[:, 6] < self._p['saturation_level'] pred_ome = refl_table[:, 9] if angularDifference(ome_start, ome_stop, units='degrees') > 0: # if here, incomplete have omega range and # clip the refelctions very close to the edges to avoid # problems with the least squares... if np.sign(ome_step) < 0: idx_ome = np.logical_and( pred_ome < np.radians(ome_start + 2*ome_step), pred_ome > np.radians(ome_stop - 2*ome_step) ) else: idx_ome = np.logical_and( pred_ome > np.radians(ome_start + 2*ome_step), pred_ome < np.radians(ome_stop - 2*ome_step) ) idx = np.logical_and( valid_refl_ids, np.logical_and(unsat_spots, idx_ome) ) else: idx = np.logical_and(valid_refl_ids, unsat_spots) hkls = refl_table[idx, 2:5].T # must be column vectors self._p['hkls'] = hkls xyo_det = refl_table[idx, -3:] # these are the cartesian centroids + ome xyo_det[:, 2] = mapAngle(xyo_det[:, 2], self._p['omega_period']) self._p['xyo_det'] = xyo_det if sum(idx) <= 12: return grain_params, 0 grain_params = fitGrain( xyo_det, hkls, self._p['bMat'], self._p['wlen'], self._p['detector_params'], grain_params[:3], grain_params[3:6], grain_params[6:], beamVec=bVec_ref, etaVec=eta_ref, distortion=self._p['distortion'], gFlag=gFlag, gScl=gScl, omePeriod=self._p['omega_period'] ) completeness = sum(valid_refl_ids)/float(len(valid_refl_ids)) return grain_params, completeness
def fitGrain( xyo_det, hkls_idx, bMat, wavelength, detectorParams, expMap_c, tVec_c, vInv, beamVec=bVec_ref, etaVec=eta_ref, distortion=(dFunc_ref, dParams_ref), gFlag=gFlag_ref, gScl=gScl_ref, omePeriod=None, factor=0.1, xtol=1e-4, ftol=1e-4, ): """ """ if omePeriod is not None: xyo_det[:, 2] = xf.mapAngle(xyo_det[:, 2], omePeriod) dFunc = distortion[0] dParams = distortion[1] gFull = np.hstack([expMap_c.flatten(), tVec_c.flatten(), vInv.flatten()]) gFit = gFull[gFlag] fitArgs = ( gFull, gFlag, detectorParams, xyo_det, hkls_idx, bMat, wavelength, beamVec, etaVec, dFunc, dParams, omePeriod, ) results = optimize.leastsq( objFuncFitGrain, gFit, args=fitArgs, diag=1.0 / gScl[gFlag].flatten(), factor=0.1, xtol=xtol, ftol=ftol ) gFit_opt = results[0] retval = gFull retval[gFlag] = gFit_opt return retval
def simulate_diffractions(grain_params, experiment, controller): """actual forward simulation of the diffraction""" image_stack = np.zeros( (experiment.nframes, experiment.nrows, experiment.ncols), dtype=bool) count = len(grain_params) subprocess = 'simulate diffractions' _project = xrdutil._project_on_detector_plane rD = experiment.rMat_d chi = experiment.chi tD = experiment.tVec_d tS = experiment.tVec_s distortion = experiment.distortion eta_range = [ (-np.pi, np.pi), ] ome_range = experiment.ome_range ome_period = (-np.pi, np.pi) full_hkls = xrdutil._fetch_hkls_from_planedata(experiment.plane_data) bMat = experiment.plane_data.latVecOps['B'] wlen = experiment.plane_data.wavelength controller.start(subprocess, count) for i in range(count): rC = xfcapi.makeRotMatOfExpMap(grain_params[i][0:3]) tC = np.ascontiguousarray(grain_params[i][3:6]) vInv_s = np.ascontiguousarray(grain_params[i][6:12]) ang_list = np.vstack( xfcapi.oscillAnglesOfHKLs(full_hkls[:, 1:], chi, rC, bMat, wlen, vInv=vInv_s)) # hkls not needed here all_angs, _ = xrdutil._filter_hkls_eta_ome(full_hkls, ang_list, eta_range, ome_range) all_angs[:, 2] = xf.mapAngle(all_angs[:, 2], ome_period) det_xy, _ = _project(all_angs, rD, rC, chi, tD, tC, tS, distortion) _write_pixels(det_xy, all_angs[:, 2], image_stack, experiment.base, experiment.inv_deltas, experiment.clip_vals) controller.update(i + 1) controller.finish(subprocess) return image_stack
def fit_grains(self, grain_id, grain_params): ome_start = self._p['omega_start'] ome_step = self._p['omega_step'] ome_stop = self._p['omega_stop'] refl_table = np.loadtxt(self._p['spots_stem'] % grain_id) valid_refl_ids = refl_table[:, 0] >= 0 unsat_spots = refl_table[:, 5] < self._p['saturation_level'] pred_ome = refl_table[:, 8] if angularDifference(ome_start, ome_stop, units='degrees') > 0: # if here, incomplete have omega range and # clip the refelctions very close to the edges to avoid # problems with the least squares... if np.sign(ome_step) < 0: idx_ome = np.logical_and( pred_ome < np.radians(ome_start + 2 * ome_step), pred_ome > np.radians(ome_stop - 2 * ome_step)) else: idx_ome = np.logical_and( pred_ome > np.radians(ome_start + 2 * ome_step), pred_ome < np.radians(ome_stop - 2 * ome_step)) idx = np.logical_and(unsat_spots, np.logical_and(valid_refl_ids, idx_ome)) else: idx = np.logical_and(valid_refl_ids, unsat_spots) hkls = refl_table[idx, 1:4].T # must be column vectors self._p['hkls'] = hkls xyo_det = refl_table[idx, -3:] # these are the cartesian centroids + ome xyo_det[:, 2] = mapAngle(xyo_det[:, 2], self._p['omega_period']) self._p['xyo_det'] = xyo_det if sum(idx) <= 12: return grain_params, 0 grain_params = fitGrain(xyo_det, hkls, self._p['bMat'], self._p['wlen'], self._p['detector_params'], grain_params[:3], grain_params[3:6], grain_params[6:], beamVec=bVec_ref, etaVec=eta_ref, distortion=self._p['distortion'], gFlag=gFlag, gScl=gScl, omePeriod=self._p['omega_period']) completeness = sum(idx) / float(len(idx)) return grain_params, completeness
def simulate_diffractions(grain_params, experiment, controller): """actual forward simulation of the diffraction""" # use a packed array for the image_stack array_dims = (experiment.nframes, experiment.ncols, ((experiment.nrows - 1)//8) + 1) image_stack = np.zeros(array_dims, dtype = np.uint8) count = len(grain_params) subprocess = 'simulate diffractions' _project = xrdutil._project_on_detector_plane rD = experiment.rMat_d chi = experiment.chi tD = experiment.tVec_d tS = experiment.tVec_s distortion = experiment.distortion eta_range = [(-np.pi, np.pi), ] ome_range = experiment.ome_range ome_period = (-np.pi, np.pi) full_hkls = xrdutil._fetch_hkls_from_planedata(experiment.plane_data) bMat = experiment.plane_data.latVecOps['B'] wlen = experiment.plane_data.wavelength controller.start(subprocess, count) for i in range(count): rC = xfcapi.makeRotMatOfExpMap(grain_params[i][0:3]) tC = np.ascontiguousarray(grain_params[i][3:6]) vInv_s = np.ascontiguousarray(grain_params[i][6:12]) ang_list = np.vstack(xfcapi.oscillAnglesOfHKLs(full_hkls[:, 1:], chi, rC, bMat, wlen, vInv=vInv_s)) # hkls not needed here all_angs, _ = xrdutil._filter_hkls_eta_ome(full_hkls, ang_list, eta_range, ome_range) all_angs[:, 2] =xf.mapAngle(all_angs[:, 2], ome_period) det_xy, _ = _project(all_angs, rD, rC, chi, tD, tC, tS, distortion) _write_pixels(det_xy, all_angs[:,2], image_stack, experiment.base, experiment.inv_deltas, experiment.clip_vals) controller.update(i+1) controller.finish(subprocess) return image_stack
def fit_grains(self, grain_id, grain_params): ome_start = self._p['omega_start'] ome_step = self._p['omega_step'] ome_stop = self._p['omega_stop'] refl_table = np.loadtxt(self._p['spots_stem'] % grain_id) valid_refl_ids = refl_table[:, 0] >= 0 unsat_spots = refl_table[:, 5] < self._p['saturation_level'] pred_ome = refl_table[:, 8] if angularDifference(ome_start, ome_stop, units='degrees') > 0: # if here, incomplete have omega range and # clip the refelctions very close to the edges to avoid # problems with the least squares... if np.sign(ome_step) < 0: idx_ome = np.logical_and( pred_ome < np.radians(ome_start + 2*ome_step), pred_ome > np.radians(ome_stop - 2*ome_step) ) else: idx_ome = np.logical_and( pred_ome > np.radians(ome_start + 2*ome_step), pred_ome < np.radians(ome_stop - 2*ome_step) ) idx = np.logical_and( unsat_spots, np.logical_and(valid_refl_ids, idx_ome) ) else: idx = np.logical_and(valid_refl_ids, unsat_spots) hkls = refl_table[idx, 1:4].T # must be column vectors self._p['hkls'] = hkls xyo_det = refl_table[idx, -3:] # these are the cartesian centroids + ome xyo_det[:, 2] = mapAngle(xyo_det[:, 2], self._p['omega_period']) self._p['xyo_det'] = xyo_det if sum(idx) <= 12: return grain_params, 0 grain_params = fitGrain( xyo_det, hkls, self._p['bMat'], self._p['wlen'], self._p['detector_params'], grain_params[:3], grain_params[3:6], grain_params[6:], beamVec=bVec_ref, etaVec=eta_ref, distortion=self._p['distortion'], gFlag=gFlag, gScl=gScl, omePeriod=self._p['omega_period'] ) completeness = sum(idx)/float(len(idx)) return grain_params, completeness
def fitGrain(xyo_det, hkls_idx, bMat, wavelength, detectorParams, expMap_c, tVec_c, vInv, beamVec=bVec_ref, etaVec=eta_ref, distortion=(dFunc_ref, dParams_ref), gFlag=gFlag_ref, gScl=gScl_ref, omePeriod=None, factor=0.1, xtol=sqrt_epsf, ftol=sqrt_epsf): """ """ if omePeriod is not None: xyo_det[:, 2] = xf.mapAngle(xyo_det[:, 2], omePeriod) dFunc = distortion[0] dParams = distortion[1] gFull = np.hstack([expMap_c.flatten(), tVec_c.flatten(), vInv.flatten()]) gFit = gFull[gFlag] fitArgs = (gFull, gFlag, detectorParams, xyo_det, hkls_idx, bMat, wavelength, beamVec, etaVec, dFunc, dParams, omePeriod) results = optimize.leastsq(objFuncFitGrain, gFit, args=fitArgs, diag=1. / gScl[gFlag].flatten(), factor=0.1, xtol=xtol, ftol=ftol) gFit_opt = results[0] retval = gFull retval[gFlag] = gFit_opt return retval
def fit_grains(self, grain_id, grain_params): ome_start = self._p['omega_start'] ome_step = self._p['omega_step'] ome_stop = self._p['omega_stop'] gtable = np.loadtxt(self._p['spots_stem'] % grain_id) valid_refl_ids = gtable[:, 0] >= 0 pred_ome = gtable[:, 6] if np.sign(ome_step) < 0: idx_ome = np.logical_and( pred_ome < np.radians(ome_start + 2*ome_step), pred_ome > np.radians(ome_stop - 2*ome_step) ) else: idx_ome = np.logical_and( pred_ome > np.radians(ome_start + 2*ome_step), pred_ome < np.radians(ome_stop - 2*ome_step) ) idx = np.logical_and(valid_refl_ids, idx_ome) hkls = gtable[idx, 1:4].T # must be column vectors self._p['hkls'] = hkls xyo_det = gtable[idx, -3:] # these are the cartesian centroids + ome xyo_det[:, 2] = mapAngle(xyo_det[:, 2], self._p['omega_period']) self._p['xyo_det'] = xyo_det if sum(idx) <= 12: return grain_params, 0 grain_params = fitGrain( xyo_det, hkls, self._p['bMat'], self._p['wlen'], self._p['detector_params'], grain_params[:3], grain_params[3:6], grain_params[6:], beamVec=bVec_ref, etaVec=eta_ref, distortion=self._p['distortion'], gFlag=gFlag, gScl=gScl, omePeriod=self._p['omega_period'] ) completeness = sum(idx)/float(len(idx)) return grain_params, completeness
def calibrateDetectorFromSX( xyo_det, hkls_idx, bMat, wavelength, tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, vInv=vInv_ref, beamVec=bVec_ref, etaVec=eta_ref, distortion=(dFunc_ref, dParams_ref, dFlag_ref, dScl_ref), pFlag=pFlag_ref, pScl=pScl_ref, omePeriod=None, factor=0.1, xtol=sqrt_epsf, ftol=sqrt_epsf): """ """ if omePeriod is not None: xyo_det[:, 2] = xf.mapAngle(xyo_det[:, 2], omePeriod) # FIXME: this format for distortion needs to go away ASAP <JVB 2017-03-27> dFunc = distortion[0] dParams = distortion[1] dFlag = distortion[2] dScl = distortion[3] """ p = np.zeros(17) p[0] = wavelength p[1] = tiltAngles[0] p[2] = tiltAngles[1] p[3] = tiltAngles[2] p[4] = tVec_d[0] p[5] = tVec_d[1] p[6] = tVec_d[2] p[7] = chi p[8] = tVec_s[0] p[9] = tVec_s[1] p[10] = tVec_s[2] p[11] = expMap_c[0] p[12] = expMap_c[1] p[13] = expMap_c[2] p[14] = tVec_c[0] p[15] = tVec_c[1] p[16] = tVec_c[2] pFull = np.hstack([p, dParams]) """ pFull = geomParamsToInput( wavelength, tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, dParams ) # TODO: check scaling <JVB 2017-03-27> refineFlag = np.array(np.hstack([pFlag, dFlag]), dtyp=bool) scl = np.hstack([pScl, dScl]) pFit = pFull[refineFlag] fitArgs = (pFull, pFlag, dFunc, dFlag, xyo_det, hkls_idx, bMat, vInv, beamVec, etaVec, omePeriod) results = optimize.leastsq(objFuncSX, pFit, args=fitArgs, diag=1./scl[refineFlag].flatten(), factor=factor, xtol=xtol, ftol=ftol) pFit_opt = results[0] retval = pFull retval[refineFlag] = pFit_opt return retval
for i in range(2): gtable = np.loadtxt(filename %grainID) # load pull_spots output table idx0 = gtable[:, 0] >= 0 # select valid reflections # pred_ome = gtable[:, 6] if np.sign(ome_delta) < 0: idx_ome = np.logical_and(pred_ome < d2r*(ome_start + 2*ome_delta), pred_ome > d2r*(ome_stop - 2*ome_delta)) else: idx_ome = np.logical_and(pred_ome > d2r*(ome_start + 2*ome_delta), pred_ome < d2r*(ome_stop - 2*ome_delta)) # idx = np.logical_and(idx0, idx_ome) hkls = gtable[idx, 1:4].T # must be column vectors xyo_det = gtable[idx, -3:] # these are the cartesian centroids + ome xyo_det[:, 2] = xf.mapAngle(xyo_det[:, 2], ome_period) print "completeness: %f%%" %(100. * sum(idx)/float(len(idx))) if sum(idx) > 12: g_initial = grain_params g_refined = fitting.fitGrain(xyo_det, hkls, bMat, wlen, detector_params, g_initial[:3], g_initial[3:6], g_initial[6:], beamVec=bVec_ref, etaVec=eta_ref, distortion=(dFunc, dParams), gFlag=gFlag, gScl=gScl, omePeriod=ome_period) if i == 0: fid = open(filename %grainID, 'w') sd = xrdutil.pullSpots(pd, detector_params, g_refined, reader, distortion=(dFunc, dParams), eta_range=etaRange, ome_period=ome_period,
def paintGridThis(quat): """ """ # Unpack common parameters into locals symHKLs = paramMP['symHKLs'] symHKLs_ix = paramMP['symHKLs_ix'] wavelength = paramMP['wavelength'] hklList = paramMP['hklList'] omeMin = paramMP['omeMin'] omeMax = paramMP['omeMax'] omeTol = paramMP['omeTol'] omePeriod = paramMP['omePeriod'] omeIndices = paramMP['omeIndices'] omeEdges = paramMP['omeEdges'] etaMin = paramMP['etaMin'] etaMax = paramMP['etaMax'] etaTol = paramMP['etaTol'] etaIndices = paramMP['etaIndices'] etaEdges = paramMP['etaEdges'] etaOmeMaps = paramMP['etaOmeMaps'] bMat = paramMP['bMat'] threshold = paramMP['threshold'] # need this for proper index generation delOmeSign = num.sign(omeEdges[1] - omeEdges[0]) del_ome = abs(omeEdges[1] - omeEdges[0]) del_eta = abs(etaEdges[1] - etaEdges[0]) dpix_ome = round(omeTol / del_ome) dpix_eta = round(etaTol / del_eta) debug = False if debug: print "using ome, eta dilitations of (%d, %d) pixels" \ % (dpix_ome, dpix_eta) nHKLs = len(symHKLs_ix) - 1 rMat = rotMatOfQuat(quat) nPredRefl = 0 nMeasRefl = 0 reflInfoList = [] dummySpotInfo = num.nan * num.ones(3) # Compute the oscillation angles of all the symHKLs at once oangs_pair = xfcapi.oscillAnglesOfHKLs( symHKLs, 0., rMat, bMat, wavelength) # Interleave the two produced oang solutions to simplify later processing oangs = num.empty((len(symHKLs)*2, 3), dtype=oangs_pair[0].dtype) oangs[0::2] = oangs_pair[0] oangs[1::2] = oangs_pair[1] # Map all of the angles at once oangs[:, 1] = xf.mapAngle(oangs[:, 1]) oangs[:, 2] = xf.mapAngle(oangs[:, 2], omePeriod) # Create a mask of the good ones oangMask = num.logical_and( ~num.isnan(oangs[:, 0]), num.logical_and( xf.validateAngleRanges(oangs[:, 1], etaMin, etaMax), xf.validateAngleRanges(oangs[:, 2], omeMin, omeMax))) hklCounterP = 0 # running count of excpected (predicted) HKLs hklCounterM = 0 # running count of "hit" HKLs for iHKL in range(nHKLs): start, stop = symHKLs_ix[iHKL:iHKL+2] start, stop = (2*start, 2*stop) angList = oangs[start:stop] angMask = oangMask[start:stop] allAngs_m = angList[angMask, :] if len(allAngs_m) > 0: # not output # # duplicate HKLs # not output # allHKLs_m = num.vstack( # [these_hkls, these_hkls] # )[angMask, :] culledTTh = allAngs_m[:, 0] culledEta = allAngs_m[:, 1] culledOme = allAngs_m[:, 2] # not output # culledHKLs = allHKLs_m.T nThisPredRefl = len(culledTTh) hklCounterP += nThisPredRefl for iTTh in range(nThisPredRefl): culledEtaIdx = num.where(etaEdges - culledEta[iTTh] > 0)[0] if len(culledEtaIdx) > 0: culledEtaIdx = culledEtaIdx[0] - 1 if culledEtaIdx < 0: culledEtaIdx = None else: culledEtaIdx = None culledOmeIdx = num.where(omeEdges - culledOme[iTTh] > 0)[0] if len(culledOmeIdx) > 0: if delOmeSign > 0: culledOmeIdx = culledOmeIdx[0] - 1 else: culledOmeIdx = culledOmeIdx[-1] if culledOmeIdx < 0: culledOmeIdx = None else: culledOmeIdx = None if culledEtaIdx is not None and culledOmeIdx is not None: if dpix_ome > 0 or dpix_eta > 0: i_dil, j_dil = _meshgrid2d( num.arange(-dpix_ome, dpix_ome + 1), num.arange(-dpix_eta, dpix_eta + 1) ) i_sup = omeIndices[culledOmeIdx] + num.array( [i_dil.flatten()], dtype=int ) j_sup = etaIndices[culledEtaIdx] + num.array( [j_dil.flatten()], dtype=int ) # catch shit that falls off detector... # ...maybe make this fancy enough to wrap at 2pi? i_max, j_max = etaOmeMaps[iHKL].shape idx_mask = num.logical_and( num.logical_and(i_sup >= 0, i_sup < i_max), num.logical_and(j_sup >= 0, j_sup < j_max) ) pixelVal = etaOmeMaps[iHKL][ i_sup[idx_mask], j_sup[idx_mask] ] else: pixelVal = etaOmeMaps[iHKL][ omeIndices[culledOmeIdx], etaIndices[culledEtaIdx] ] isHit = num.any(pixelVal >= threshold[iHKL]) if isHit: hklCounterM += 1 # if debug: # print "hkl %d -->\t%d\t%d\t%d\t" % ( # iHKL, culledHKLs[0, iTTh], culledHKLs[1, iTTh], # culledHKLs[2, iTTh] # ) \ # + "isHit=%d\tpixel value: %g\n" % (isHit, pixelVal) \ # + "eta index: %d,%d\tetaP: %g\n" % ( # culledEtaIdx, etaIndices[culledEtaIdx], # r2d*culledEta[iTTh] # ) \ # + "ome index: %d,%d\tomeP: %g\n" % ( # culledOmeIdx, omeIndices[culledOmeIdx], # r2d*culledOme[iTTh] # ) # # close conditional on valid reflections # close loop on signed reflections # close loop on HKL if hklCounterP == 0: retval = 0. else: retval = float(hklCounterM) / float(hklCounterP) return retval
def paintGridThis(quat): """ """ # pull local vars from globals set in paintGrid global symHKLs_MP, wavelength_MP global omeMin_MP, omeMax_MP, omeTol_MP global etaMin_MP, etaMax_MP, etaTol_MP global omeIndices_MP, etaIndices_MP global omeEdges_MP, etaEdges_MP global hklList_MP, hklIDs_MP global etaOmeMaps_MP global bMat_MP global threshold_MP symHKLs = symHKLs_MP wavelength = wavelength_MP hklIDs = hklIDs_MP hklList = hklList_MP omeMin = omeMin_MP omeMax = omeMax_MP omeTol = omeTol_MP omeIndices = omeIndices_MP omeEdges = omeEdges_MP etaMin = etaMin_MP etaMax = etaMax_MP etaTol = etaTol_MP etaIndices = etaIndices_MP etaEdges = etaEdges_MP etaOmeMaps = etaOmeMaps_MP bMat = bMat_MP threshold = threshold_MP # need this for proper index generation omegas = [omeEdges[0] + (i+0.5)*(omeEdges[1] - omeEdges[0]) for i in range(len(omeEdges) - 1)] etas = [etaEdges[0] + (i+0.5)*(etaEdges[1] - etaEdges[0]) for i in range(len(etaEdges) - 1)] delOmeSign = num.sign(omegas[1] - omegas[0]) del_ome = abs(omegas[1] - omegas[0]) del_eta = abs(etas[1] - etas[0]) dpix_ome = round(omeTol / del_ome) dpix_eta = round(etaTol / del_eta) debug = False if debug: print "using ome, eta dilitations of (%d, %d) pixels" % (dpix_ome, dpix_eta) nHKLs = len(hklIDs) rMat = rotMatOfQuat(quat) nPredRefl = 0 nMeasRefl = 0 reflInfoList = [] dummySpotInfo = num.nan * num.ones(3) hklCounterP = 0 # running count of excpected (predicted) HKLs hklCounterM = 0 # running count of "hit" HKLs for iHKL in range(nHKLs): # select and C-ify symmetric HKLs these_hkls = num.array(symHKLs[hklIDs[iHKL]].T, dtype=float, order='C') # oscillation angle arrays oangs = xfcapi.oscillAnglesOfHKLs(these_hkls, 0., rMat, bMat, wavelength) angList = num.vstack(oangs) if not num.all(num.isnan(angList)): angList[:, 1] = xf.mapAngle(angList[:, 1]) angList[:, 2] = xf.mapAngle(angList[:, 2]) if omeMin is None: omeMin = [-num.pi, ] omeMax = [ num.pi, ] if etaMin is None: etaMin = [-num.pi, ] etaMax = [ num.pi, ] angMask = num.logical_and( xf.validateAngleRanges(angList[:, 1], etaMin, etaMax), xf.validateAngleRanges(angList[:, 2], omeMin, omeMax)) allAngs_m = angList[angMask, :] # not output # # duplicate HKLs # not output # allHKLs_m = num.vstack([these_hkls, these_hkls])[angMask, :] culledTTh = allAngs_m[:, 0] culledEta = allAngs_m[:, 1] culledOme = allAngs_m[:, 2] # not output # culledHKLs = allHKLs_m.T nThisPredRefl = len(culledTTh) hklCounterP += nThisPredRefl for iTTh in range(nThisPredRefl): culledEtaIdx = num.where(etaEdges - culledEta[iTTh] > 0)[0] if len(culledEtaIdx) > 0: culledEtaIdx = culledEtaIdx[0] - 1 if culledEtaIdx < 0: culledEtaIdx = None else: culledEtaIdx = None culledOmeIdx = num.where(omeEdges - culledOme[iTTh] > 0)[0] if len(culledOmeIdx) > 0: if delOmeSign > 0: culledOmeIdx = culledOmeIdx[0] - 1 else: culledOmeIdx = culledOmeIdx[-1] if culledOmeIdx < 0: culledOmeIdx = None else: culledOmeIdx = None if culledEtaIdx is not None and culledOmeIdx is not None: if dpix_ome > 0 or dpix_eta > 0: i_dil, j_dil = num.meshgrid(num.arange(-dpix_ome, dpix_ome + 1), num.arange(-dpix_eta, dpix_eta + 1)) i_sup = omeIndices[culledOmeIdx] + num.array([i_dil.flatten()], dtype=int) j_sup = etaIndices[culledEtaIdx] + num.array([j_dil.flatten()], dtype=int) # catch shit that falls off detector... # ...maybe make this fancy enough to wrap at 2pi? i_max, j_max = etaOmeMaps[iHKL].shape idx_mask = num.logical_and(num.logical_and(i_sup >= 0, i_sup < i_max), num.logical_and(j_sup >= 0, j_sup < j_max)) pixelVal = etaOmeMaps[iHKL][i_sup[idx_mask], j_sup[idx_mask]] else: pixelVal = etaOmeMaps[iHKL][omeIndices[culledOmeIdx], etaIndices[culledEtaIdx] ] isHit = num.any(pixelVal >= threshold[iHKL]) if isHit: hklCounterM += 1 pass pass # disabled # if debug: # disabled # print "hkl %d -->\t%d\t%d\t%d\t" % (iHKL, culledHKLs[0, iTTh], culledHKLs[1, iTTh], culledHKLs[2, iTTh]) + \ # disabled # "isHit=%d\tpixel value: %g\n" % (isHit, pixelVal) + \ # disabled # "eta index: %d,%d\tetaP: %g\n" % (culledEtaIdx, etaIndices[culledEtaIdx], r2d*culledEta[iTTh]) + \ # disabled # "ome index: %d,%d\tomeP: %g\n" % (culledOmeIdx, omeIndices[culledOmeIdx], r2d*culledOme[iTTh]) # disabled # pass pass # close conditional on valid reflections pass # close loop on signed reflections pass # close loop on HKL if hklCounterP == 0: retval = 0. else: retval = float(hklCounterM) / float(hklCounterP) return retval
def paintGridThis(quat): """ """ # pull local vars from globals set in paintGrid global symHKLs_MP, wavelength_MP global omeMin_MP, omeMax_MP, omeTol_MP, omePeriod_MP global etaMin_MP, etaMax_MP, etaTol_MP global omeIndices_MP, etaIndices_MP global omeEdges_MP, etaEdges_MP global hklList_MP, hklIDs_MP global etaOmeMaps_MP global bMat_MP global threshold_MP symHKLs = symHKLs_MP wavelength = wavelength_MP hklIDs = hklIDs_MP hklList = hklList_MP omeMin = omeMin_MP omeMax = omeMax_MP omeTol = omeTol_MP omePeriod = omePeriod_MP omeIndices = omeIndices_MP omeEdges = omeEdges_MP etaMin = etaMin_MP etaMax = etaMax_MP etaTol = etaTol_MP etaIndices = etaIndices_MP etaEdges = etaEdges_MP etaOmeMaps = etaOmeMaps_MP bMat = bMat_MP threshold = threshold_MP # need this for proper index generation omegas = [ omeEdges[0] + (i + 0.5) * (omeEdges[1] - omeEdges[0]) for i in range(len(omeEdges) - 1) ] etas = [ etaEdges[0] + (i + 0.5) * (etaEdges[1] - etaEdges[0]) for i in range(len(etaEdges) - 1) ] delOmeSign = num.sign(omegas[1] - omegas[0]) del_ome = abs(omegas[1] - omegas[0]) del_eta = abs(etas[1] - etas[0]) dpix_ome = round(omeTol / del_ome) dpix_eta = round(etaTol / del_eta) debug = False if debug: print "using ome, eta dilitations of (%d, %d) pixels" % (dpix_ome, dpix_eta) nHKLs = len(hklIDs) rMat = rotMatOfQuat(quat) nPredRefl = 0 nMeasRefl = 0 reflInfoList = [] dummySpotInfo = num.nan * num.ones(3) hklCounterP = 0 # running count of excpected (predicted) HKLs hklCounterM = 0 # running count of "hit" HKLs for iHKL in range(nHKLs): # select and C-ify symmetric HKLs these_hkls = num.array(symHKLs[hklIDs[iHKL]].T, dtype=float, order='C') # oscillation angle arrays oangs = xfcapi.oscillAnglesOfHKLs(these_hkls, 0., rMat, bMat, wavelength) angList = num.vstack(oangs) if not num.all(num.isnan(angList)): idx = -num.isnan(angList[:, 0]) angList = angList[idx, :] angList[:, 1] = xf.mapAngle(angList[:, 1]) angList[:, 2] = xf.mapAngle(angList[:, 2], omePeriod) if omeMin is None: omeMin = [ -num.pi, ] omeMax = [ num.pi, ] if etaMin is None: etaMin = [ -num.pi, ] etaMax = [ num.pi, ] angMask = num.logical_and( xf.validateAngleRanges(angList[:, 1], etaMin, etaMax), xf.validateAngleRanges(angList[:, 2], omeMin, omeMax)) allAngs_m = angList[angMask, :] # not output # # duplicate HKLs # not output # allHKLs_m = num.vstack([these_hkls, these_hkls])[angMask, :] culledTTh = allAngs_m[:, 0] culledEta = allAngs_m[:, 1] culledOme = allAngs_m[:, 2] # not output # culledHKLs = allHKLs_m.T nThisPredRefl = len(culledTTh) hklCounterP += nThisPredRefl for iTTh in range(nThisPredRefl): culledEtaIdx = num.where(etaEdges - culledEta[iTTh] > 0)[0] if len(culledEtaIdx) > 0: culledEtaIdx = culledEtaIdx[0] - 1 if culledEtaIdx < 0: culledEtaIdx = None else: culledEtaIdx = None culledOmeIdx = num.where(omeEdges - culledOme[iTTh] > 0)[0] if len(culledOmeIdx) > 0: if delOmeSign > 0: culledOmeIdx = culledOmeIdx[0] - 1 else: culledOmeIdx = culledOmeIdx[-1] if culledOmeIdx < 0: culledOmeIdx = None else: culledOmeIdx = None if culledEtaIdx is not None and culledOmeIdx is not None: if dpix_ome > 0 or dpix_eta > 0: i_dil, j_dil = num.meshgrid( num.arange(-dpix_ome, dpix_ome + 1), num.arange(-dpix_eta, dpix_eta + 1)) i_sup = omeIndices[culledOmeIdx] + num.array( [i_dil.flatten()], dtype=int) j_sup = etaIndices[culledEtaIdx] + num.array( [j_dil.flatten()], dtype=int) # catch shit that falls off detector... # ...maybe make this fancy enough to wrap at 2pi? i_max, j_max = etaOmeMaps[iHKL].shape idx_mask = num.logical_and( num.logical_and(i_sup >= 0, i_sup < i_max), num.logical_and(j_sup >= 0, j_sup < j_max)) pixelVal = etaOmeMaps[iHKL][i_sup[idx_mask], j_sup[idx_mask]] else: pixelVal = etaOmeMaps[iHKL][omeIndices[culledOmeIdx], etaIndices[culledEtaIdx]] isHit = num.any(pixelVal >= threshold[iHKL]) if isHit: hklCounterM += 1 pass pass # disabled # if debug: # disabled # print "hkl %d -->\t%d\t%d\t%d\t" % (iHKL, culledHKLs[0, iTTh], culledHKLs[1, iTTh], culledHKLs[2, iTTh]) + \ # disabled # "isHit=%d\tpixel value: %g\n" % (isHit, pixelVal) + \ # disabled # "eta index: %d,%d\tetaP: %g\n" % (culledEtaIdx, etaIndices[culledEtaIdx], r2d*culledEta[iTTh]) + \ # disabled # "ome index: %d,%d\tomeP: %g\n" % (culledOmeIdx, omeIndices[culledOmeIdx], r2d*culledOme[iTTh]) # disabled # pass pass # close conditional on valid reflections pass # close loop on signed reflections pass # close loop on HKL if hklCounterP == 0: retval = 0. else: retval = float(hklCounterM) / float(hklCounterP) return retval
def calibrateDetectorFromSX(xyo_det, hkls_idx, bMat, wavelength, tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, vInv=vInv_ref, beamVec=bVec_ref, etaVec=eta_ref, distortion=(dFunc_ref, dParams_ref, dFlag_ref, dScl_ref), pFlag=pFlag_ref, pScl=pScl_ref, omePeriod=None, factor=0.1, xtol=sqrt_epsf, ftol=sqrt_epsf): """ """ if omePeriod is not None: xyo_det[:, 2] = xf.mapAngle(xyo_det[:, 2], omePeriod) # FIXME: this format for distortion needs to go away ASAP <JVB 2017-03-27> dFunc = distortion[0] dParams = distortion[1] dFlag = distortion[2] dScl = distortion[3] """ p = np.zeros(17) p[0] = wavelength p[1] = tiltAngles[0] p[2] = tiltAngles[1] p[3] = tiltAngles[2] p[4] = tVec_d[0] p[5] = tVec_d[1] p[6] = tVec_d[2] p[7] = chi p[8] = tVec_s[0] p[9] = tVec_s[1] p[10] = tVec_s[2] p[11] = expMap_c[0] p[12] = expMap_c[1] p[13] = expMap_c[2] p[14] = tVec_c[0] p[15] = tVec_c[1] p[16] = tVec_c[2] pFull = np.hstack([p, dParams]) """ pFull = geomParamsToInput(wavelength, tiltAngles, chi, expMap_c, tVec_d, tVec_s, tVec_c, dParams) # TODO: check scaling <JVB 2017-03-27> refineFlag = np.array(np.hstack([pFlag, dFlag]), dtyp=bool) scl = np.hstack([pScl, dScl]) pFit = pFull[refineFlag] fitArgs = (pFull, pFlag, dFunc, dFlag, xyo_det, hkls_idx, bMat, vInv, beamVec, etaVec, omePeriod) results = optimize.leastsq(objFuncSX, pFit, args=fitArgs, diag=1. / scl[refineFlag].flatten(), factor=factor, xtol=xtol, ftol=ftol) pFit_opt = results[0] retval = pFull retval[refineFlag] = pFit_opt return retval
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
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