コード例 #1
0
ファイル: fitting.py プロジェクト: mwiebe/hexrd
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
コード例 #2
0
ファイル: fitting.py プロジェクト: lind9/hexrd
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
コード例 #3
0
ファイル: crystallography.py プロジェクト: darrencpagan/hexrd
    def makeScatteringVectors(hkls, rMat_c, bMat, wavelength, chiTilt=None):
        """
        Static method for calculating g-vectors and scattering vector angles for
        specified hkls, subject to the bragg conditions specified by lattice vectors, 
        orientation matrix, and wavelength
        """
        # arg munging
        if chiTilt is None:
            chi = 0.0
        else:
            chi = float(chiTilt)
        rMat_c = rMat_c.squeeze()

        # these are the reciprocal lattice vectors in the SAMPLE FRAME
        # ** NOTE **
        #   if strained, assumes that you handed it a bMat calculated from
        #   strained [a, b, c] in the CRYSTAL FRAME
        gVec_s = num.dot(rMat_c, num.dot(bMat, hkls))

        dim0, nRefl = gVec_s.shape
        assert dim0 == 3, "Looks like something is wrong with your lattice plane normals son!"

        # call model from transforms now
        oangs0, oangs1 = xfcapi.oscillAnglesOfHKLs(hkls.T, chi, rMat_c, bMat, wavelength)

        return gVec_s, oangs0.T, oangs1.T
コード例 #4
0
ファイル: new_simulate_nf.py プロジェクト: hsheng94/hexrd-1
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] = xfcapi.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
コード例 #5
0
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] = xfcapi.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
コード例 #6
0
def get_diffraction_angles_MP(fwd_model_input_i):
    '''
    Parallel processing worker for eta, two-th, omega calculation
    '''

    hkls = fwd_model_input_i['hkls']
    chi = fwd_model_input_i['chi']
    rmat_c = fwd_model_input_i['rmat_c']
    bmat = fwd_model_input_i['bmat']
    wavelength = fwd_model_input_i['wavelength']
    defgrad_i = fwd_model_input_i['defgrad_i']

    omega0, omega1 = xfcapi.oscillAnglesOfHKLs(hkls,
                                               chi,
                                               rmat_c,
                                               bmat,
                                               wavelength,
                                               vInv=defgrad_i)
    #    print hkls
    #    print omega0
    #    print omega1
    return np.concatenate((omega0, omega1), axis=0)
コード例 #7
0
    def simulate_rotation_series(self,
                                 plane_data,
                                 grain_param_list,
                                 eta_ranges=[
                                     (-np.pi, np.pi),
                                 ],
                                 ome_ranges=[
                                     (-np.pi, np.pi),
                                 ],
                                 ome_period=(-np.pi, np.pi),
                                 chi=0.,
                                 tVec_s=ct.zeros_3,
                                 wavelength=None):
        """
        """

        # grab B-matrix from plane data
        bMat = plane_data.latVecOps['B']

        # reconcile wavelength
        #   * added sanity check on exclusions here; possible to
        #   * make some reflections invalid (NaN)
        if wavelength is None:
            wavelength = plane_data.wavelength
        else:
            if plane_data.wavelength != wavelength:
                plane_data.wavelength = ct.keVToAngstrom(wavelength)
        assert not np.any(np.isnan(plane_data.getTTh())),\
            "plane data exclusions incompatible with wavelength"

        # vstacked G-vector id, h, k, l
        full_hkls = xrdutil._fetch_hkls_from_planedata(plane_data)
        """ LOOP OVER GRAINS """
        valid_ids = []
        valid_hkls = []
        valid_angs = []
        valid_xys = []
        ang_pixel_size = []
        for gparm in grain_param_list:

            # make useful parameters
            rMat_c = makeRotMatOfExpMap(gparm[:3])
            tVec_c = gparm[3:6]
            vInv_s = gparm[6:]

            # All possible bragg conditions as vstacked [tth, eta, ome]
            # for each omega solution
            angList = np.vstack(
                oscillAnglesOfHKLs(
                    full_hkls[:, 1:],
                    chi,
                    rMat_c,
                    bMat,
                    wavelength,
                    vInv=vInv_s,
                ))

            # filter by eta and omega ranges
            # ??? get eta range from detector?
            allAngs, allHKLs = xrdutil._filter_hkls_eta_ome(
                full_hkls, angList, eta_ranges, ome_ranges)
            allAngs[:, 2] = mapAngle(allAngs[:, 2], ome_period)

            # find points that fall on the panel
            det_xy, rMat_s = xrdutil._project_on_detector_plane(
                allAngs, self.rmat, rMat_c, chi, self.tvec, tVec_c, tVec_s,
                self.distortion)
            xys_p, on_panel = self.clip_to_panel(det_xy)
            valid_xys.append(xys_p)

            # grab hkls and gvec ids for this panel
            valid_hkls.append(allHKLs[on_panel, 1:])
            valid_ids.append(allHKLs[on_panel, 0])

            # reflection angles (voxel centers) and pixel size in (tth, eta)
            valid_angs.append(allAngs[on_panel, :])
            ang_pixel_size.append(self.angularPixelSize(xys_p))
        return valid_ids, valid_hkls, valid_angs, valid_xys, ang_pixel_size
コード例 #8
0
ファイル: indexer.py プロジェクト: B-Rich/hexrd
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
コード例 #9
0
material=mat.Material()
material.beamEnergy=15
material.sgnum=227
material.latticeParameters=[5.4310,]
material.name='Silicon'

#%%

samplePos=np.array([[0],[0],[0]])
crysPos=np.array([[0],[0],[0]])
rMat_c=np.identity(3)
bMat=material.planeData.latVecOps['B']
wavelength=material.planeData.wavelength

material.planeData.t

#%%
omega0,omega1=trans.oscillAnglesOfHKLs(material.planeData.hkls.T, 0, rMat_c, bMat, wavelength)




#%%

def VirtDiffWorker




コード例 #10
0
                                           [ 0.73593251] ] ) )

vInv_s = np.c_[ -2.10434927e-04,  -9.51655879e-05,   5.21695993e-05,
                -7.69921049e-05,  -7.75926245e-05,  -2.49452890e-04].T
# vInv_s = np.c_[1., 1., 1., 0., 0., 0.].T

# ######################################################################

# oscillation angle arrays
n=22
start1 = time.clock()                      # time this
for i in range(n):
    oangs01, oangs11 = xf.oscillAnglesOfHKLs(hklsT, chi, rMat_c, bMat, wavelength, 
                                             vInv=vInv_s, beamVec=bVec_ref, etaVec=eta_ref)
elapsed1 = (time.clock() - start1)
print "Time for Python oscillAnglesOfHKLs: %f"%elapsed1

start2 = time.clock()                      # time this
for i in range(n):
    oangs02, oangs12 = xfcapi.oscillAnglesOfHKLs(hkls, chi, rMat_c, bMat, wavelength, 
                                                 vInv=vInv_s, beamVec=bVec_ref, etaVec=eta_ref)
elapsed2 = (time.clock() - start2)
print "Time for CAPI oscillAnglesOfHKLs:   %f"%elapsed2
#print oangs01.shape, oangs11.shape
#print oangs02.shape, oangs12.shape
#print np.linalg.norm(oangs01[:,0]),np.linalg.norm(oangs01[:,1]),np.linalg.norm(oangs01[:,2])
#print np.linalg.norm(oangs11[:,0]),np.linalg.norm(oangs11[:,1]),np.linalg.norm(oangs11[:,2])
print "Maximum Relative Differences: %f, %f"%(np.linalg.norm(oangs01-oangs02.T)/np.linalg.norm(oangs01),np.linalg.norm(oangs11-oangs12.T)/np.linalg.norm(oangs11))

print "  Speedup: %f"%(elapsed1/elapsed2)
コード例 #11
0
                                             chi,
                                             rMat_c,
                                             bMat,
                                             wavelength,
                                             vInv=vInv_s,
                                             beamVec=bVec_ref,
                                             etaVec=eta_ref)
elapsed1 = (time.clock() - start1)
print "Time for Python oscillAnglesOfHKLs: %f" % elapsed1

start2 = time.clock()  # time this
for i in range(n):
    oangs02, oangs12 = xfcapi.oscillAnglesOfHKLs(hkls,
                                                 chi,
                                                 rMat_c,
                                                 bMat,
                                                 wavelength,
                                                 vInv=vInv_s,
                                                 beamVec=bVec_ref,
                                                 etaVec=eta_ref)
elapsed2 = (time.clock() - start2)
print "Time for CAPI oscillAnglesOfHKLs:   %f" % elapsed2
#print oangs01.shape, oangs11.shape
#print oangs02.shape, oangs12.shape
#print np.linalg.norm(oangs01[:,0]),np.linalg.norm(oangs01[:,1]),np.linalg.norm(oangs01[:,2])
#print np.linalg.norm(oangs11[:,0]),np.linalg.norm(oangs11[:,1]),np.linalg.norm(oangs11[:,2])
print "Maximum Relative Differences: %f, %f" % (
    np.linalg.norm(oangs01 - oangs02.T) / np.linalg.norm(oangs01),
    np.linalg.norm(oangs11 - oangs12.T) / np.linalg.norm(oangs11))

print "  Speedup: %f" % (elapsed1 / elapsed2)
コード例 #12
0
ファイル: detector.py プロジェクト: joelvbernier/hexrd
    def simulate_rotation_series(self, plane_data, grain_param_list,
                                 eta_ranges=[(-np.pi, np.pi), ],
                                 ome_ranges=[(-np.pi, np.pi), ],
                                 ome_period=(-np.pi, np.pi),
                                 chi=0., tVec_s=ct.zeros_3,
                                 wavelength=None):
        """
        """

        # grab B-matrix from plane data
        bMat = plane_data.latVecOps['B']

        # reconcile wavelength
        #   * added sanity check on exclusions here; possible to
        #   * make some reflections invalid (NaN)
        if wavelength is None:
            wavelength = plane_data.wavelength
        else:
            if plane_data.wavelength != wavelength:
                plane_data.wavelength = ct.keVToAngstrom(wavelength)
        assert not np.any(np.isnan(plane_data.getTTh())),\
            "plane data exclusions incompatible with wavelength"

        # vstacked G-vector id, h, k, l
        full_hkls = xrdutil._fetch_hkls_from_planedata(plane_data)

        """ LOOP OVER GRAINS """
        valid_ids = []
        valid_hkls = []
        valid_angs = []
        valid_xys = []
        ang_pixel_size = []
        for gparm in grain_param_list:

            # make useful parameters
            rMat_c = makeRotMatOfExpMap(gparm[:3])
            tVec_c = gparm[3:6]
            vInv_s = gparm[6:]

            # All possible bragg conditions as vstacked [tth, eta, ome]
            # for each omega solution
            angList = np.vstack(
                oscillAnglesOfHKLs(
                    full_hkls[:, 1:], chi,
                    rMat_c, bMat, wavelength,
                    vInv=vInv_s,
                    )
                )

            # filter by eta and omega ranges
            # ??? get eta range from detector?
            allAngs, allHKLs = xrdutil._filter_hkls_eta_ome(
                full_hkls, angList, eta_ranges, ome_ranges
                )
            allAngs[:, 2] = mapAngle(allAngs[:, 2], ome_period)

            # find points that fall on the panel
            det_xy, rMat_s = xrdutil._project_on_detector_plane(
                allAngs,
                self.rmat, rMat_c, chi,
                self.tvec, tVec_c, tVec_s,
                self.distortion)
            xys_p, on_panel = self.clip_to_panel(det_xy)
            valid_xys.append(xys_p)

            # grab hkls and gvec ids for this panel
            valid_hkls.append(allHKLs[on_panel, 1:])
            valid_ids.append(allHKLs[on_panel, 0])

            # reflection angles (voxel centers) and pixel size in (tth, eta)
            valid_angs.append(allAngs[on_panel, :])
            ang_pixel_size.append(self.angularPixelSize(xys_p))
        return valid_ids, valid_hkls, valid_angs, valid_xys, ang_pixel_size
コード例 #13
0
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
コード例 #14
0
ファイル: indexer.py プロジェクト: lind9/hexrd
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