def scan_detector_parm(image_stack, experiment,test_crds,controller,parm_to_opt,parm_vector,slice_shape): #0-distance #1-x center #2-xtilt #3-ytilt #4-ztilt multiprocessing_start_method = 'fork' if hasattr(os, 'fork') else 'spawn' #current detector parameters, note the value for the actively optimized parameters will be ignored distance=experiment.detector_params[5]#mm x_cen=experiment.detector_params[3]#mm xtilt=experiment.detector_params[0] ytilt=experiment.detector_params[1] ztilt=experiment.detector_params[2] num_parm_pts=len(parm_vector) trial_data=np.zeros([num_parm_pts,slice_shape[0],slice_shape[1]]) tmp_td=copy.copy(experiment.tVec_d) for jj in np.arange(num_parm_pts): print('cycle %d of %d'%(jj+1,num_parm_pts)) if parm_to_opt==0: tmp_td[2]=parm_vector[jj] else: tmp_td[2]=distance if parm_to_opt==1: tmp_td[0]=parm_vector[jj] else: tmp_td[0]=x_cen if parm_to_opt==2: rMat_d_tmp=makeDetectorRotMat([parm_vector[jj],ytilt,ztilt]) elif parm_to_opt==3: rMat_d_tmp=makeDetectorRotMat([xtilt,parm_vector[jj],ztilt]) elif parm_to_opt==4: rMat_d_tmp=makeDetectorRotMat([xtilt,ytilt,parm_vector[jj]]) else: rMat_d_tmp=makeDetectorRotMat([xtilt,ytilt,ztilt]) experiment.rMat_d = rMat_d_tmp experiment.tVec_d = tmp_td conf=test_orientations(image_stack, experiment, test_crds, controller,multiprocessing_start_method) trial_data[jj]=np.max(conf,axis=0).reshape(slice_shape) return trial_data
def set_tilt(self, tilt): """ default geometry defined in transforms... detector normal is local Z """ self.__rMat = xf.makeDetectorRotMat(tilt) self.__nVec = np.dot(self.__rMat, Z_ref) self.__tilt = tilt return
def sxcal_obj_func(plist_fit, plist_full, param_flags, dfuncs, dparam_flags, ndparams, instr, xyo_det, hkls_idx, bmat, vinv_s, ome_period, bvec, evec, sim_only=False, return_value_flag=None): """ """ # stack flags and force bool repr refine_flags = np.array(np.hstack([param_flags, dparam_flags]), dtype=bool) # fill out full parameter list # !!! no scaling for now plist_full[refine_flags] = plist_fit # instrument quantities wavelength = plist_full[0] chi = plist_full[1] tvec_s = plist_full[2:5] # calibration crystal quantities rmat_c = xfcapi.makeRotMatOfExpMap(plist_full[5:8]) tvec_c = plist_full[8:11] # right now just stuck on the end and assumed # to all be the same length... FIX THIS dparams_all = plist_full[-len(dparam_flags):] xy_unwarped = {} meas_omes = {} calc_omes = {} calc_xy = {} ii = 11 # offset to start of panels... jj = 0 npts_tot = 0 for det_key, panel in instr.detectors.iteritems(): xy_unwarped[det_key] = xyo_det[det_key][:, :2] npts_tot += len(xyo_det[det_key]) dfunc = dfuncs[det_key] len_these_dps = ndparams[det_key] if dfunc is not None: # do unwarping dparams = dparams_all[jj:jj + len_these_dps] jj += len_these_dps xy_unwarped[det_key] = dfunc(xy_unwarped[det_key], dparams) pass meas_omes[det_key] = xyo_det[det_key][:, 2] # get these panel params for convenience gparams = plist_full[ii:ii + 6] rmat_d = xfcapi.makeDetectorRotMat(gparams[:3]) tvec_d = gparams[3:].reshape(3, 1) # transform G-vectors: # 1) convert inv. stretch tensor from MV notation in to 3x3 # 2) take reciprocal lattice vectors from CRYSTAL to SAMPLE frame # 3) apply stretch tensor # 4) normalize reciprocal lattice vectors in SAMPLE frame # 5) transform unit reciprocal lattice vetors back to CRYSAL frame gvec_c = np.dot(bmat, hkls_idx[det_key].T) vmat_s = mutil.vecMVToSymm(vinv_s) ghat_s = mutil.unitVector(np.dot(vmat_s, np.dot(rmat_c, gvec_c))) ghat_c = np.dot(rmat_c.T, ghat_s) match_omes, calc_omes_tmp = fitting.matchOmegas(xyo_det[det_key], hkls_idx[det_key].T, chi, rmat_c, bmat, wavelength, vInv=vinv_s, beamVec=bvec, etaVec=evec, omePeriod=ome_period) rmat_s_arr = xfcapi.makeOscillRotMatArray( chi, np.ascontiguousarray(calc_omes_tmp)) calc_xy_tmp = xfcapi.gvecToDetectorXYArray(ghat_c.T, rmat_d, rmat_s_arr, rmat_c, tvec_d, tvec_s, tvec_c) if np.any(np.isnan(calc_xy_tmp)): print("infeasible parameters: " + "may want to scale back finite difference step size") calc_omes[det_key] = calc_omes_tmp calc_xy[det_key] = calc_xy_tmp ii += 6 pass # return values if sim_only: retval = {} for det_key in calc_xy.keys(): # ??? calc_xy is always 2-d retval[det_key] = np.vstack( [calc_xy[det_key].T, calc_omes[det_key]]).T else: meas_xy_all = [] calc_xy_all = [] meas_omes_all = [] calc_omes_all = [] for det_key in xy_unwarped.keys(): meas_xy_all.append(xy_unwarped[det_key]) calc_xy_all.append(calc_xy[det_key]) meas_omes_all.append(meas_omes[det_key]) calc_omes_all.append(calc_omes[det_key]) pass meas_xy_all = np.vstack(meas_xy_all) calc_xy_all = np.vstack(calc_xy_all) meas_omes_all = np.hstack(meas_omes_all) calc_omes_all = np.hstack(calc_omes_all) diff_vecs_xy = calc_xy_all - meas_xy_all diff_ome = xfcapi.angularDifference(calc_omes_all, meas_omes_all) retval = np.hstack([diff_vecs_xy, diff_ome.reshape(npts_tot, 1)]).flatten() if return_value_flag == 1: retval = sum(abs(retval)) elif return_value_flag == 2: denom = npts_tot - len(plist_fit) - 1. if denom != 0: nu_fac = 1. / denom else: nu_fac = 1. nu_fac = 1 / (npts_tot - len(plist_fit) - 1.) retval = nu_fac * sum(retval**2) return retval
import sys, os, time, random import numpy as np from hexrd.xrd import transforms as xf from hexrd.xrd import transforms_CAPI as xfcapi epsf = 2.2e-16 vec = np.array([[random.uniform(-np.pi,np.pi),random.uniform(-np.pi,np.pi),random.uniform(-np.pi,np.pi)]]) vHat1 = xf.unitVector(vec.T) vHat2 = xfcapi.unitRowVector(vec) print "unitVector results match: ",np.linalg.norm(vHat1.T-vHat2)/np.linalg.norm(vHat1) < epsf tAng = np.array([0.0011546340766314521,-0.0040527538387122993,-0.0026221336905160211]) rMat1 = xf.makeDetectorRotMat(tAng) rMat2 = xfcapi.makeDetectorRotMat(tAng) print "makeDetectorRotMat results match: ",np.linalg.norm(rMat1-rMat2)/np.linalg.norm(rMat1) < epsf oAng = np.array([-0.0011591608938627839,0.0011546340766314521]) rMat1 = xf.makeOscillRotMat(oAng) rMat2 = xfcapi.makeOscillRotMat(oAng) print "makeOscillRotMat results match: ",np.linalg.norm(rMat1-rMat2)/np.linalg.norm(rMat1) < epsf eMap = np.array([ 0.66931818,-0.98578066,0.73593251]) rMat1 = xf.makeRotMatOfExpMap(eMap) rMat2 = xfcapi.makeRotMatOfExpMap(eMap) print "makeRotMatOfExpMap results match: ",np.linalg.norm(rMat1-rMat2)/np.linalg.norm(rMat1) < epsf axis = np.array([ 0.66931818,-0.98578066,0.73593251]) rMat1 = xf.makeBinaryRotMat(axis) rMat2 = xfcapi.makeBinaryRotMat(axis)
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.1834835], [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 = mutil.unitVector( quats[1:, :]) # ns contains the rotation axis as an unit vector exp_maps = np.array([phis[i] * ns[:, i] for i in range(n_grains)]) rMat_c = rot.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, :], xf.vInv_ref.flatten()])) # 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)): del_ome = ome_range[i][1] - ome_range[i][0] 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_cfg = yaml.load(fildes) tiltAngles = instr_cfg['detector']['transform']['tilt_angles'] tVec_d = np.array(instr_cfg['detector']['transform']['t_vec_d']).reshape( 3, 1) chi = instr_cfg['oscillation_stage']['chi'] tVec_s = np.array(instr_cfg['oscillation_stage']['t_vec_s']).reshape(3, 1) rMat_d = xfcapi.makeDetectorRotMat(tiltAngles) rMat_s = xfcapi.makeOscillRotMat([chi, 0.]) pixel_size = instr_cfg['detector']['pixels']['size'] nrows = instr_cfg['detector']['pixels']['rows'] ncols = instr_cfg['detector']['pixels']['columns'] col_ps = pixel_size[1] row_ps = pixel_size[0] row_dim = row_ps * nrows # in mm col_dim = col_ps * ncols # in mm panel_dims = [(-0.5 * ncols * col_ps, -0.5 * nrows * row_ps), (0.5 * ncols * col_ps, 0.5 * nrows * row_ps)] x_col_edges = col_ps * (np.arange(ncols + 1) - 0.5 * ncols) y_row_edges = row_ps * (np.arange(nrows, -1, -1) - 0.5 * nrows) #x_col_edges = np.arange(panel_dims[0][0], panel_dims[1][0] + 0.5*col_ps, col_ps) #y_row_edges = np.arange(panel_dims[0][1], panel_dims[1][1] + 0.5*row_ps, row_ps) rx, ry = np.meshgrid(x_col_edges, y_row_edges) gcrds = xfcapi.detectorXYToGvec( np.vstack([rx.flatten(), ry.flatten()]).T, rMat_d, rMat_s, tVec_d, tVec_s, np.zeros(3)) max_pixel_tth = np.amax(gcrds[0][0]) detector_params = np.hstack( [tiltAngles, tVec_d.flatten(), chi, tVec_s.flatten()]) distortion = None # 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 = np.ceil(0.5 * max_diameter / row_ps) col_dilation = np.ceil(0.5 * max_diameter / col_ps) # crystallography data from hexrd import valunits gold = material.Material('gold') gold.sgnum = 225 gold.latticeParameters = [ 4.0782, ] gold.hklMax = 200 gold.beamEnergy = valunits.valWUnit("wavelength", "ENERGY", 52, "keV") gold.planeData.exclusions = None gold.planeData.tThMax = max_pixel_tth #note this comes from info in the 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 -angle * rotation axis- (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_s = rMat_s # 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 objFuncFitGrain(gFit, gFull, gFlag, detectorParams, xyo_det, hkls_idx, bMat, wavelength, bVec, eVec, dFunc, dParams, omePeriod, simOnly=False, returnScalarValue=returnScalarValue): """ gFull[0] = expMap_c[0] gFull[1] = expMap_c[1] gFull[2] = expMap_c[2] gFull[3] = tVec_c[0] gFull[4] = tVec_c[1] gFull[5] = tVec_c[2] gFull[6] = vInv_MV[0] gFull[7] = vInv_MV[1] gFull[8] = vInv_MV[2] gFull[9] = vInv_MV[3] gFull[10] = vInv_MV[4] gFull[11] = vInv_MV[5] detectorParams[0] = tiltAngles[0] detectorParams[1] = tiltAngles[1] detectorParams[2] = tiltAngles[2] detectorParams[3] = tVec_d[0] detectorParams[4] = tVec_d[1] detectorParams[5] = tVec_d[2] detectorParams[6] = chi detectorParams[7] = tVec_s[0] detectorParams[8] = tVec_s[1] detectorParams[9] = tVec_s[2] """ npts = len(xyo_det) gFull[gFlag] = gFit xy_unwarped = dFunc(xyo_det[:, :2], dParams) rMat_d = xfcapi.makeDetectorRotMat(detectorParams[:3]) tVec_d = detectorParams[3:6].reshape(3, 1) chi = detectorParams[6] tVec_s = detectorParams[7:10].reshape(3, 1) rMat_c = xfcapi.makeRotMatOfExpMap(gFull[:3]) tVec_c = gFull[3:6].reshape(3, 1) vInv_s = gFull[6:] vMat_s = mutil.vecMVToSymm(vInv_s) # NOTE: Inverse of V from F = V * R gVec_c = np.dot(bMat, hkls_idx) # gVecs with magnitudes in CRYSTAL frame gVec_s = np.dot(vMat_s, np.dot(rMat_c, gVec_c)) # stretched gVecs in SAMPLE frame gHat_c = mutil.unitVector( np.dot(rMat_c.T, gVec_s)) # unit reciprocal lattice vectors in CRYSTAL frame match_omes, calc_omes = matchOmegas(xyo_det, hkls_idx, chi, rMat_c, bMat, wavelength, vInv=vInv_s, beamVec=bVec, etaVec=eVec, omePeriod=omePeriod) calc_xy = np.zeros((npts, 2)) for i in range(npts): rMat_s = xfcapi.makeOscillRotMat([chi, calc_omes[i]]) calc_xy[i, :] = xfcapi.gvecToDetectorXY(gHat_c[:, i], rMat_d, rMat_s, rMat_c, tVec_d, tVec_s, tVec_c, beamVec=bVec).flatten() pass if np.any(np.isnan(calc_xy)): print "infeasible pFull" # return values if simOnly: retval = np.hstack([calc_xy, calc_omes.reshape(npts, 1)]) else: diff_vecs_xy = calc_xy - xy_unwarped[:, :2] diff_ome = xf.angularDifference( calc_omes, xyo_det[:, 2] ) retval = mutil.rowNorm( np.hstack([diff_vecs_xy, diff_ome.reshape(npts, 1) ]) ).flatten() if returnScalarValue: retval = sum( retval ) return retval
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.1834835 ], [ 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 = mutil.unitVector(quats[1:, :]) # ns contains the rotation axis as an unit vector exp_maps = np.array([phis[i]*ns[:, i] for i in range(n_grains)]) rMat_c = rot.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, :], xf.vInv_ref.flatten()]) ) # 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)): del_ome = ome_range[i][1]-ome_range[i][0] 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_cfg = yaml.load(fildes) tiltAngles = instr_cfg['detector']['transform']['tilt_angles'] tVec_d = np.array(instr_cfg['detector']['transform']['t_vec_d']).reshape(3,1) chi = instr_cfg['oscillation_stage']['chi'] tVec_s = np.array(instr_cfg['oscillation_stage']['t_vec_s']).reshape(3,1) rMat_d = xfcapi.makeDetectorRotMat(tiltAngles) rMat_s = xfcapi.makeOscillRotMat([chi, 0.]) pixel_size = instr_cfg['detector']['pixels']['size'] nrows = instr_cfg['detector']['pixels']['rows'] ncols = instr_cfg['detector']['pixels']['columns'] col_ps = pixel_size[1] row_ps = pixel_size[0] row_dim = row_ps*nrows # in mm col_dim = col_ps*ncols # in mm panel_dims = [(-0.5*ncols*col_ps, -0.5*nrows*row_ps), ( 0.5*ncols*col_ps, 0.5*nrows*row_ps)] x_col_edges = col_ps * (np.arange(ncols + 1) - 0.5*ncols) y_row_edges = row_ps * (np.arange(nrows, -1, -1) - 0.5*nrows) #x_col_edges = np.arange(panel_dims[0][0], panel_dims[1][0] + 0.5*col_ps, col_ps) #y_row_edges = np.arange(panel_dims[0][1], panel_dims[1][1] + 0.5*row_ps, row_ps) rx, ry = np.meshgrid(x_col_edges, y_row_edges) gcrds = xfcapi.detectorXYToGvec(np.vstack([rx.flatten(), ry.flatten()]).T, rMat_d, rMat_s, tVec_d, tVec_s, np.zeros(3)) max_pixel_tth = np.amax(gcrds[0][0]) detector_params = np.hstack([tiltAngles, tVec_d.flatten(), chi, tVec_s.flatten()]) distortion = None # 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 = np.ceil(0.5 * max_diameter/row_ps) col_dilation = np.ceil(0.5 * max_diameter/col_ps) # crystallography data from hexrd import valunits gold = material.Material('gold') gold.sgnum = 225 gold.latticeParameters = [4.0782, ] gold.hklMax = 200 gold.beamEnergy = valunits.valWUnit("wavelength", "ENERGY", 52, "keV") gold.planeData.exclusions = None gold.planeData.tThMax = max_pixel_tth #note this comes from info in the 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 -angle * rotation axis- (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_s = rMat_s # 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 rmat(self): return makeDetectorRotMat(self.tilt)
from hexrd.utils import profiler import matplotlib matplotlib.use('Qt4Agg') from matplotlib import pyplot as plt # load in config files for convenience instr_cfg = yaml.load(open('./analysis/ge_detector.yml', 'r')) pixel_pitch = instr_cfg['detector']['pixels']['size'] # load material file mat_list = cPickle.load(open('./include/materials.cpl', 'r')) pd = mat_list[-1].planeData # define instrument params rMat_d = xfcapi.makeDetectorRotMat( instr_cfg['detector']['transform']['tilt_angles']) tVec_d = np.r_[instr_cfg['detector']['transform']['t_vec_d']] rMat_s = np.eye(3) tVec_s = np.zeros(3) rMat_c = np.eye(3) tVec_c = np.zeros(3) try: #dfunc = instr_cfg['detector']['distortion']['function_name'] dparams = instr_cfg['detector']['distortion']['parameters'] distortion = (xf.dFunc_ref, dparams) except (KeyError): distortion = None # for defining patches delta_eta = 0.5
def __init__(self): self.tilt = np.zeros(3) self.rmat = xfcapi.makeDetectorRotMat(self.tilt) self.tvec = np.r_[0., 0., -1000.]
def gen_trial_exp_data(grain_out_file,det_file,mat_file, x_ray_energy, mat_name, max_tth, comp_thresh, chi2_thresh, misorientation_bnd, \ misorientation_spacing,ome_range_deg, nframes, beam_stop_width): print('Loading Grain Data.....') #gen_grain_data ff_data=np.loadtxt(grain_out_file) #ff_data=np.atleast_2d(ff_data[2,:]) exp_maps=ff_data[:,3:6] t_vec_ds=ff_data[:,6:9] # completeness=ff_data[:,1] chi2=ff_data[:,2] n_grains=exp_maps.shape[0] rMat_c = rot.rotMatOfExpMap(exp_maps.T) cut=np.where(np.logical_and(completeness>comp_thresh,chi2<chi2_thresh))[0] exp_maps=exp_maps[cut,:] t_vec_ds=t_vec_ds[cut,:] chi2=chi2[cut] # Add Misorientation mis_amt=misorientation_bnd*np.pi/180. spacing=misorientation_spacing*np.pi/180. ori_pts = np.arange(-mis_amt, (mis_amt+(spacing*0.999)),spacing) num_ori_grid_pts=ori_pts.shape[0]**3 num_oris=exp_maps.shape[0] XsO, YsO, ZsO = np.meshgrid(ori_pts, ori_pts, ori_pts) grid0 = np.vstack([XsO.flatten(), YsO.flatten(), ZsO.flatten()]).T exp_maps_expanded=np.zeros([num_ori_grid_pts*num_oris,3]) t_vec_ds_expanded=np.zeros([num_ori_grid_pts*num_oris,3]) for ii in np.arange(num_oris): pts_to_use=np.arange(num_ori_grid_pts)+ii*num_ori_grid_pts exp_maps_expanded[pts_to_use,:]=grid0+np.r_[exp_maps[ii,:] ] t_vec_ds_expanded[pts_to_use,:]=np.r_[t_vec_ds[ii,:] ] exp_maps=exp_maps_expanded t_vec_ds=t_vec_ds_expanded n_grains=exp_maps.shape[0] rMat_c = rot.rotMatOfExpMap(exp_maps.T) print('Loading Instrument Data.....') instr_cfg = yaml.load(open(det_file, 'r')) tiltAngles = instr_cfg['detector']['transform']['tilt_angles'] tVec_d = np.array(instr_cfg['detector']['transform']['t_vec_d']).reshape(3, 1) #tVec_d[0] = -0.05 chi = instr_cfg['oscillation_stage']['chi'] tVec_s = np.array(instr_cfg['oscillation_stage']['t_vec_s']).reshape(3, 1) rMat_d = makeDetectorRotMat(tiltAngles) rMat_s = makeOscillRotMat([chi, 0.]) pixel_size = instr_cfg['detector']['pixels']['size'] nrows = instr_cfg['detector']['pixels']['rows'] ncols = instr_cfg['detector']['pixels']['columns'] # row_dim = pixel_size[0]*nrows # in mm # col_dim = pixel_size[1]*ncols # in mm x_col_edges = pixel_size[1]*(np.arange(ncols+1) - 0.5*ncols) y_row_edges = pixel_size[0]*(np.arange(nrows+1) - 0.5*nrows)[::-1] panel_dims = [(-0.5*ncols*pixel_size[1], -0.5*nrows*pixel_size[0]), ( 0.5*ncols*pixel_size[1], 0.5*nrows*pixel_size[0])] # a bit overkill, but grab max two-theta from all pixel transforms rx, ry = np.meshgrid(x_col_edges, y_row_edges) gcrds = detectorXYToGvec(np.vstack([rx.flatten(), ry.flatten()]).T, rMat_d, rMat_s, tVec_d, tVec_s, np.zeros(3)) pixel_tth = gcrds[0][0] detector_params = np.hstack([tiltAngles, tVec_d.flatten(), chi, tVec_s.flatten()]) ome_period_deg=(ome_range_deg[0][0], (ome_range_deg[0][0]+360.)) #degrees ome_step_deg=(ome_range_deg[0][1]-ome_range_deg[0][0])/nframes #degrees ome_period = (ome_period_deg[0]*np.pi/180.,ome_period_deg[1]*np.pi/180.) ome_range = [(ome_range_deg[0][0]*np.pi/180.,ome_range_deg[0][1]*np.pi/180.)] ome_step = ome_step_deg*np.pi/180. ome_edges = np.arange(nframes+1)*ome_step+ome_range[0][0]#fixed 2/26/17 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]) print('Loading Material Data.....') #Load Material Data materials=cpl.load(open( mat_file, "rb" )) check=np.zeros(len(materials)) for ii in np.arange(len(materials)): #print materials[ii].name check[ii]=materials[ii].name==mat_name mat_used=materials[np.where(check)[0][0]] #niti_mart.beamEnergy = valunits.valWUnit("wavelength","ENERGY",61.332,"keV") mat_used.beamEnergy = valunits.valWUnit("wavelength","ENERGY",x_ray_energy,"keV") mat_used.planeData.exclusions = np.zeros(len(mat_used.planeData.exclusions), dtype=bool) if max_tth>0.: mat_used.planeData.tThMax = np.amax(np.radians(max_tth)) else: mat_used.planeData.tThMax = np.amax(pixel_tth) pd=mat_used.planeData print('Final Assembly.....') experiment = argparse.Namespace() # grains related information experiment.n_grains = n_grains # this can be derived from other values... experiment.rMat_c = rMat_c # n_grains rotation matrices (one per grain) experiment.exp_maps = exp_maps # n_grains exp_maps -angle * rotation axis- (one per grain) experiment.plane_data = pd experiment.detector_params = detector_params experiment.pixel_size = pixel_size experiment.ome_range = ome_range experiment.ome_period = ome_period experiment.x_col_edges = x_col_edges experiment.y_row_edges = y_row_edges experiment.ome_edges = ome_edges experiment.ncols = ncols experiment.nrows = nrows experiment.nframes = nframes# used only in simulate... experiment.rMat_d = rMat_d experiment.tVec_d = np.atleast_2d(detector_params[3:6]).T experiment.chi = detector_params[6] # note this is used to compute S... why is it needed? experiment.tVec_s = np.atleast_2d(detector_params[7:]).T experiment.rMat_c = rMat_c experiment.distortion = None experiment.panel_dims = panel_dims # used only in simulate... experiment.base = base experiment.inv_deltas = inv_deltas experiment.clip_vals = clip_vals experiment.bsw = beam_stop_width nf_to_ff_id_map=cut return experiment, nf_to_ff_id_map
def objFuncFitGrain(gFit, gFull, gFlag, detectorParams, xyo_det, hkls_idx, bMat, wavelength, bVec, eVec, dFunc, dParams, omePeriod, simOnly=False, return_value_flag=return_value_flag): """ gFull[0] = expMap_c[0] gFull[1] = expMap_c[1] gFull[2] = expMap_c[2] gFull[3] = tVec_c[0] gFull[4] = tVec_c[1] gFull[5] = tVec_c[2] gFull[6] = vInv_MV[0] gFull[7] = vInv_MV[1] gFull[8] = vInv_MV[2] gFull[9] = vInv_MV[3] gFull[10] = vInv_MV[4] gFull[11] = vInv_MV[5] detectorParams[0] = tiltAngles[0] detectorParams[1] = tiltAngles[1] detectorParams[2] = tiltAngles[2] detectorParams[3] = tVec_d[0] detectorParams[4] = tVec_d[1] detectorParams[5] = tVec_d[2] detectorParams[6] = chi detectorParams[7] = tVec_s[0] detectorParams[8] = tVec_s[1] detectorParams[9] = tVec_s[2] """ npts = len(xyo_det) gFull[gFlag] = gFit xy_unwarped = dFunc(xyo_det[:, :2], dParams) rMat_d = xfcapi.makeDetectorRotMat(detectorParams[:3]) tVec_d = detectorParams[3:6].reshape(3, 1) chi = detectorParams[6] tVec_s = detectorParams[7:10].reshape(3, 1) rMat_c = xfcapi.makeRotMatOfExpMap(gFull[:3]) tVec_c = gFull[3:6].reshape(3, 1) vInv_s = gFull[6:] vMat_s = mutil.vecMVToSymm(vInv_s) # NOTE: Inverse of V from F = V * R gVec_c = np.dot(bMat, hkls_idx) # gVecs with magnitudes in CRYSTAL frame gVec_s = np.dot(vMat_s, np.dot(rMat_c, gVec_c)) # stretched gVecs in SAMPLE frame gHat_c = mutil.unitVector(np.dot( rMat_c.T, gVec_s)) # unit reciprocal lattice vectors in CRYSTAL frame match_omes, calc_omes = matchOmegas(xyo_det, hkls_idx, chi, rMat_c, bMat, wavelength, vInv=vInv_s, beamVec=bVec, etaVec=eVec, omePeriod=omePeriod) rMat_s = xfcapi.makeOscillRotMatArray(chi, calc_omes) calc_xy = xfcapi.gvecToDetectorXYArray(gHat_c.T, rMat_d, rMat_s, rMat_c, tVec_d, tVec_s, tVec_c, beamVec=bVec) if np.any(np.isnan(calc_xy)): print "infeasible pFull" # return values if simOnly: retval = np.hstack([calc_xy, calc_omes.reshape(npts, 1)]) else: diff_vecs_xy = calc_xy - xy_unwarped[:, :2] diff_ome = xf.angularDifference(calc_omes, xyo_det[:, 2]) retval = np.hstack([diff_vecs_xy, diff_ome.reshape(npts, 1)]).flatten() if return_value_flag == 1: retval = sum(abs(retval)) elif return_value_flag == 2: denom = npts - len(gFit) - 1. if denom != 0: nu_fac = 1. / denom else: nu_fac = 1. retval = nu_fac * sum(retval**2 / abs( np.hstack([calc_xy, calc_omes.reshape(npts, 1)]).flatten())) return retval
import matplotlib matplotlib.use("Qt4Agg") from matplotlib import pyplot as plt # load in config files for convenience instr_cfg = yaml.load(open("./analysis/ge_detector.yml", "r")) pixel_pitch = instr_cfg["detector"]["pixels"]["size"] # load material file mat_list = cPickle.load(open("./include/materials.cpl", "r")) pd = mat_list[-1].planeData # define instrument params rMat_d = xfcapi.makeDetectorRotMat(instr_cfg["detector"]["transform"]["tilt_angles"]) tVec_d = np.r_[instr_cfg["detector"]["transform"]["t_vec_d"]] rMat_s = np.eye(3) tVec_s = np.zeros(3) rMat_c = np.eye(3) tVec_c = np.zeros(3) try: # dfunc = instr_cfg['detector']['distortion']['function_name'] dparams = instr_cfg["detector"]["distortion"]["parameters"] distortion = (xf.dFunc_ref, dparams) except (KeyError): distortion = None # for defining patches delta_eta = 0.5
nframes += int((ome_range[i][1] - ome_range[i][0]) / ome_step) pass ome_edges = np.arange(nframes + 1) * ome_step #============================================================================== # %% INSTRUMENT #============================================================================== # load config instr_cfg = yaml.load(open('./retiga.yml', 'r')) tiltAngles = instr_cfg['detector']['transform']['tilt_angles'] tVec_d = np.array(instr_cfg['detector']['transform']['t_vec_d']).reshape(3, 1) chi = instr_cfg['oscillation_stage']['chi'] tVec_s = np.array(instr_cfg['oscillation_stage']['t_vec_s']).reshape(3, 1) rMat_d = makeDetectorRotMat(tiltAngles) rMat_s = makeOscillRotMat([chi, 0.]) pixel_size = instr_cfg['detector']['pixels']['size'] nrows = instr_cfg['detector']['pixels']['rows'] ncols = instr_cfg['detector']['pixels']['columns'] row_dim = pixel_size[0] * nrows # in mm col_dim = pixel_size[1] * ncols # in mm x_col_edges = pixel_size[1] * (np.arange(ncols + 1) - 0.5 * ncols) y_row_edges = pixel_size[0] * (np.arange(nrows + 1) - 0.5 * nrows)[::-1] panel_dims = [(-0.5 * ncols * pixel_size[1], -0.5 * nrows * pixel_size[0]), (0.5 * ncols * pixel_size[1], 0.5 * nrows * pixel_size[0])]
def __init__(self, tilt=tilt_DFTL, tvec=tvec_DFLT): self.tilt = tilt self.rmat = xfcapi.makeDetectorRotMat(self.tilt) self.tvec = tvec
#Image Info nrows = int((panel_dims[1][1] - panel_dims[0][1]) / float(pixel_pitch[0])) ncols = int((panel_dims[1][0] - panel_dims[0][0]) / float(pixel_pitch[1])) row_edges = (np.arange(nrows+1)*pixel_pitch[0] + panel_dims[0][1])[::-1] col_edges = np.arange(ncols+1)*pixel_pitch[1] + panel_dims[0][0] nframes = int(360./float(delta_ome)) ome_edges = np.arange(nframes + 1)*delta_ome - 180. #extract transform objects; rotations and translations # detector first, rotation, then translation # - rotation takes comps from det frame to lab rMat_d = xfcapi.makeDetectorRotMat(detector_params[:3]) tVec_d = np.r_[detector_params[3:6]] # rotation stage (omega) # - chi is ccw tilt about lab X; rMat_s is omega dependent # - takes comps in sample to lab frame chi = detector_params[6] tVec_s = np.zeros((3,1)) # crystal; this will be a list of things, computed from quaternions # - trivial case here... rMat_c = np.eye(3) tVec_c = np.zeros((3,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
def gen_trial_exp_data(grain_out_file,det_file,mat_file, x_ray_energy, mat_name, max_tth, comp_thresh, chi2_thresh, misorientation_bnd, \ misorientation_spacing,ome_range_deg, nframes, beam_stop_width): print('Loading Grain Data.....') #gen_grain_data ff_data = np.loadtxt(grain_out_file) #ff_data=np.atleast_2d(ff_data[2,:]) exp_maps = ff_data[:, 3:6] t_vec_ds = ff_data[:, 6:9] # completeness = ff_data[:, 1] chi2 = ff_data[:, 2] n_grains = exp_maps.shape[0] rMat_c = rot.rotMatOfExpMap(exp_maps.T) cut = np.where( np.logical_and(completeness > comp_thresh, chi2 < chi2_thresh))[0] exp_maps = exp_maps[cut, :] t_vec_ds = t_vec_ds[cut, :] chi2 = chi2[cut] # Add Misorientation mis_amt = misorientation_bnd * np.pi / 180. spacing = misorientation_spacing * np.pi / 180. mis_steps = int(misorientation_bnd / misorientation_spacing) ori_pts = np.arange(-mis_amt, (mis_amt + (spacing * 0.999)), spacing) num_ori_grid_pts = ori_pts.shape[0]**3 num_oris = exp_maps.shape[0] XsO, YsO, ZsO = np.meshgrid(ori_pts, ori_pts, ori_pts) grid0 = np.vstack([XsO.flatten(), YsO.flatten(), ZsO.flatten()]).T exp_maps_expanded = np.zeros([num_ori_grid_pts * num_oris, 3]) t_vec_ds_expanded = np.zeros([num_ori_grid_pts * num_oris, 3]) for ii in np.arange(num_oris): pts_to_use = np.arange(num_ori_grid_pts) + ii * num_ori_grid_pts exp_maps_expanded[pts_to_use, :] = grid0 + np.r_[exp_maps[ii, :]] t_vec_ds_expanded[pts_to_use, :] = np.r_[t_vec_ds[ii, :]] exp_maps = exp_maps_expanded t_vec_ds = t_vec_ds_expanded n_grains = exp_maps.shape[0] rMat_c = rot.rotMatOfExpMap(exp_maps.T) print('Loading Instrument Data.....') instr_cfg = yaml.load(open(det_file, 'r')) tiltAngles = instr_cfg['detector']['transform']['tilt_angles'] tVec_d = np.array(instr_cfg['detector']['transform']['t_vec_d']).reshape( 3, 1) #tVec_d[0] = -0.05 chi = instr_cfg['oscillation_stage']['chi'] tVec_s = np.array(instr_cfg['oscillation_stage']['t_vec_s']).reshape(3, 1) rMat_d = makeDetectorRotMat(tiltAngles) rMat_s = makeOscillRotMat([chi, 0.]) pixel_size = instr_cfg['detector']['pixels']['size'] nrows = instr_cfg['detector']['pixels']['rows'] ncols = instr_cfg['detector']['pixels']['columns'] # row_dim = pixel_size[0]*nrows # in mm # col_dim = pixel_size[1]*ncols # in mm x_col_edges = pixel_size[1] * (np.arange(ncols + 1) - 0.5 * ncols) y_row_edges = pixel_size[0] * (np.arange(nrows + 1) - 0.5 * nrows)[::-1] panel_dims = [(-0.5 * ncols * pixel_size[1], -0.5 * nrows * pixel_size[0]), (0.5 * ncols * pixel_size[1], 0.5 * nrows * pixel_size[0])] # a bit overkill, but grab max two-theta from all pixel transforms rx, ry = np.meshgrid(x_col_edges, y_row_edges) gcrds = detectorXYToGvec( np.vstack([rx.flatten(), ry.flatten()]).T, rMat_d, rMat_s, tVec_d, tVec_s, np.zeros(3)) pixel_tth = gcrds[0][0] detector_params = np.hstack( [tiltAngles, tVec_d.flatten(), chi, tVec_s.flatten()]) ome_period_deg = (ome_range_deg[0][0], (ome_range_deg[0][0] + 360.) ) #degrees ome_step_deg = (ome_range_deg[0][1] - ome_range_deg[0][0]) / nframes #degrees ome_period = (ome_period_deg[0] * np.pi / 180., ome_period_deg[1] * np.pi / 180.) ome_range = [(ome_range_deg[0][0] * np.pi / 180., ome_range_deg[0][1] * np.pi / 180.)] ome_step = ome_step_deg * np.pi / 180. ome_edges = np.arange(nframes + 1) * ome_step + ome_range[0][0] #fixed 2/26/17 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]) print('Loading Material Data.....') #Load Material Data materials = cpl.load(open(mat_file, "rb")) check = np.zeros(len(materials)) for ii in np.arange(len(materials)): #print materials[ii].name check[ii] = materials[ii].name == mat_name mat_used = materials[np.where(check)[0][0]] #niti_mart.beamEnergy = valunits.valWUnit("wavelength","ENERGY",61.332,"keV") mat_used.beamEnergy = valunits.valWUnit("wavelength", "ENERGY", x_ray_energy, "keV") mat_used.planeData.exclusions = np.zeros(len( mat_used.planeData.exclusions), dtype=bool) if max_tth > 0.: mat_used.planeData.tThMax = np.amax(np.radians(max_tth)) else: mat_used.planeData.tThMax = np.amax(pixel_tth) pd = mat_used.planeData print('Final Assembly.....') experiment = argparse.Namespace() # grains related information experiment.n_grains = n_grains # this can be derived from other values... experiment.rMat_c = rMat_c # n_grains rotation matrices (one per grain) experiment.exp_maps = exp_maps # n_grains exp_maps -angle * rotation axis- (one per grain) experiment.plane_data = pd experiment.detector_params = detector_params experiment.pixel_size = pixel_size experiment.ome_range = ome_range experiment.ome_period = ome_period experiment.x_col_edges = x_col_edges experiment.y_row_edges = y_row_edges experiment.ome_edges = ome_edges experiment.ncols = ncols experiment.nrows = nrows experiment.nframes = nframes # used only in simulate... experiment.rMat_d = rMat_d experiment.tVec_d = np.atleast_2d(detector_params[3:6]).T experiment.chi = detector_params[ 6] # note this is used to compute S... why is it needed? experiment.tVec_s = np.atleast_2d(detector_params[7:]).T experiment.rMat_c = rMat_c experiment.distortion = None experiment.panel_dims = panel_dims # used only in simulate... experiment.base = base experiment.inv_deltas = inv_deltas experiment.clip_vals = clip_vals experiment.bsw = beam_stop_width if mis_steps == 0: nf_to_ff_id_map = cut else: nf_to_ff_id_map = np.tile(cut, 27 * mis_steps) return experiment, nf_to_ff_id_map
epsf = 2.2e-16 vec = np.array([[ random.uniform(-np.pi, np.pi), random.uniform(-np.pi, np.pi), random.uniform(-np.pi, np.pi) ]]) vHat1 = xf.unitVector(vec.T) vHat2 = xfcapi.unitRowVector(vec) print "unitVector results match: ", np.linalg.norm( vHat1.T - vHat2) / np.linalg.norm(vHat1) < epsf tAng = np.array( [0.0011546340766314521, -0.0040527538387122993, -0.0026221336905160211]) rMat1 = xf.makeDetectorRotMat(tAng) rMat2 = xfcapi.makeDetectorRotMat(tAng) print "makeDetectorRotMat results match: ", np.linalg.norm( rMat1 - rMat2) / np.linalg.norm(rMat1) < epsf oAng = np.array([-0.0011591608938627839, 0.0011546340766314521]) rMat1 = xf.makeOscillRotMat(oAng) rMat2 = xfcapi.makeOscillRotMat(oAng) print "makeOscillRotMat results match: ", np.linalg.norm( rMat1 - rMat2) / np.linalg.norm(rMat1) < epsf eMap = np.array([0.66931818, -0.98578066, 0.73593251]) rMat1 = xf.makeRotMatOfExpMap(eMap) rMat2 = xfcapi.makeRotMatOfExpMap(eMap) print "makeRotMatOfExpMap results match: ", np.linalg.norm( rMat1 - rMat2) / np.linalg.norm(rMat1) < epsf
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
nframes += int((ome_range[i][1]-ome_range[i][0])/ome_step) pass ome_edges = np.arange(nframes+1)*ome_step #============================================================================== # %% INSTRUMENT #============================================================================== # load config instr_cfg = yaml.load(open('./retiga.yml', 'r')) tiltAngles = instr_cfg['detector']['transform']['tilt_angles'] tVec_d = np.array(instr_cfg['detector']['transform']['t_vec_d']).reshape(3, 1) chi = instr_cfg['oscillation_stage']['chi'] tVec_s = np.array(instr_cfg['oscillation_stage']['t_vec_s']).reshape(3, 1) rMat_d = makeDetectorRotMat(tiltAngles) rMat_s = makeOscillRotMat([chi, 0.]) pixel_size = instr_cfg['detector']['pixels']['size'] nrows = instr_cfg['detector']['pixels']['rows'] ncols = instr_cfg['detector']['pixels']['columns'] row_dim = pixel_size[0]*nrows # in mm col_dim = pixel_size[1]*ncols # in mm x_col_edges = pixel_size[1]*(np.arange(ncols+1) - 0.5*ncols) y_row_edges = pixel_size[0]*(np.arange(nrows+1) - 0.5*nrows)[::-1] panel_dims = [(-0.5*ncols*pixel_size[1], -0.5*nrows*pixel_size[0]),