Exemplo n.º 1
0
def refit_makemap(colf, pars, grains):
    """
    Takes a columnfile, parameters and list of grains
    and repeats the refinement of each grain, keeping
    the same grain assignments
    Returns : new grains
    """
    global TESTING
    for i, g in enumerate(grains):
        d = colf.copy()
        d.filter(d.labels == i)
        # Take peaks belonging to this grain only
        sc = d.sc
        fc = d.fc
        om = d.omega
        hkls = np.array((d.h, d.k, d.l))
        if i == 1004:
            TESTING = 3
        # Get new t, UB, S
        t, UB, S = fitone(g.UB, g.translation, sc, fc, om, hkls, pars)
        for ncycle in range(5):
            t, UB, S = fitone(UB, t, sc, fc, om, hkls, pars)
            if S.sh_esd.max() < 1e-10:
                break
            if TESTING:
                print("translation", t)
                print("Cell", indexing.ubitocellpars(np.linalg.inv(UB)))
        print("Translation %.5f %.5f %.5f" % tuple(t))
        print("Cell %.7f %.7f %.7f %.8f %.8f %.8f" %
              (indexing.ubitocellpars(np.linalg.inv(UB))))
        g.translation = t
        g.set_ubi(np.linalg.inv(UB))
    return grains
Exemplo n.º 2
0
 def fit_ubi_omega(self):
     
     print indexing.ubitocellpars(self.g.ubi)
     f = self.omegacalc_ub
     res = scipy.optimize.leastsq( f, self.p0, full_output=1)
     pfit, pcov, info, errmsg, ier = res
     ub = pfit.reshape(3,3)
     ubi = np.linalg.inv(ub)
     print indexing.ubitocellpars(ubi)
Exemplo n.º 3
0
    def do_fit_trans(self):
        f = self.fit_trans
        p0 = self.p0.copy()
        #        p0[:-3]=0.0
        #print p0,"call d0"
        #d0 = f(p0)
        if 0:
         for i in range(len(p0)):
            pt = p0.copy()
            pt[i] = p0[i]+0.001
            from matplotlib.pylab import clf, ion, title, plot, show
            print pt - p0, pt
            ion()
            clf()
            title("%d"%(i))
            plot(d0, f(pt) - d0, ",")
            show()
            if raw_input()[0] != " ": 
                break


        res = scipy.optimize.leastsq( f, p0, full_output=1)
        pfit, pcov, info, errmsg, ier = res
        if ier not in [1,2,3,4]:
            print s_sq, ier, errmsg
        else:
            residu = f(pfit) 
            s_sq = (residu**2).sum()/(len(residu)-len(p0))
        ubi = pfit[:9].reshape(3,3)
        print ("%.6f "*6)%(indexing.ubitocellpars(ubi))
        print pfit[9:12]
        self.g = grain( ubi, pfit[9:12].copy())
Exemplo n.º 4
0
def ferraris_and_ivaldi(ubi, tol=0.001):
    """
    Acta Cryst (1983) A39 595-596

    Determine the multiplicities of vectors in a computed powder pattern
    Match these to multiplicities according to lattice types
    ... appeals to powder person
    Tolerance is for grouping vector lengths.
    """
    cpar = ubitocellpars(ubi)
    cell = unitcell(cpar)
    dlim = cell.ds(np.array([7, 7, 7]))
    cell.makerings(dlim, tol)
    mult = [len(cell.ringhkls[d]) for d in cell.ringds]
    mx = max(mult)
    mn = min(mult)
    cases = {
        (2, 2): fi_triclinic,
        (4, 2): fi_monoclinic,
        #        (8,  2) : fi_orthorhombic,
        #        (12, 2) : fi_rhombohedral,
        #        (16, 2) : fi_tetragonal,
        #        (24, 2) : fi_hexagonal,
        #        (48, 2) : fi_cubic
    }
Exemplo n.º 5
0
def makehexagonal( ubi ):
    """ Finds a nearby hexagonal cell """
    cp = indexing.ubitocellpars( ubi )
    a = (cp[0]+cp[1])/2
    cell = unitcell( (a,a,cp[2],90,90,120),"P")
    u = indexing.ubitoU( ubi )
    ub = np.dot( u, cell.B )
    return np.linalg.inv( ub )
Exemplo n.º 6
0
Arquivo: latred.py Projeto: yns11/tst
def test_fft():
    gv = get_eu_gv()
    from ImageD11.fft_index_refac import grid
    from ImageD11.indexing import ubitocellpars, write_ubi_file,\
        refine
    g = grid( np = 128,
              mr = 1.0,
              nsig = 20,
              minlen = 3. )
    g.gv_to_grid_new(gv)
    g.fft()
    g.props()
    g.peaksearch(open("eu.patterson_pks","w"))
    g.read_peaks("eu.patterson_pks")
    vecs = g.UBIALL
    order = argsort( g.colfile.sum_intensity )[::-1]
    min_pks = 300
    try:
        for i in order:
            print vecs[i], g.colfile.sum_intensity[i]
            for j in order[i:]:
                for k in order[j:]:
                    print i,j,k
                    try:
                        l = lattice( vecs[i], vecs[j], vecs[k],
                                     space='real')
                        t = 0.1
                        ref = refine( l.vi, gv, t)
                        l = lattice( ref[0], ref[1], ref[2], space='real')
                        print "UBI:"
                        print l.vi
                        print ubitocellpars(l.vi)
                        s = l.score_recip( gv , t )
                        print "Indexes",s ,"at tolerance",t
                    
                    except:
                        import traceback
                        print traceback.print_exc()
                        raise Exception("error")
                    if s > min_pks:
                        write_ubi_file( "trial.ubi", [ l.vi ] )
                        raise Exception("Really bad control structure")
    except:
        import traceback
        print traceback.print_exc()
        print "Got something"
Exemplo n.º 7
0
def forwards_project( gr,
                      pars,
                      detector_size,
                      spatial,
                      dsmax,
                      gid):
    latt = "P"
    for k in pars.parameters.keys():
        if k.startswith("cell_lattice"):
            latt = pars.get(k)
    cell = unitcell.unitcell( indexing.ubitocellpars( gr.ubi ), latt )
    ds_hkl = cell.gethkls( dsmax )
    hkls = np.array( [ x[1] for x in ds_hkl] )
    gvecs = np.dot( gr.ub, hkls.T )
    wvln, wedge, chi = [ pars.get(x) for x in "wavelength", "wedge", "chi" ]
    tth, (eta1, eta2), (omega1, omega2) = transform.uncompute_g_vectors(
        gvecs, wvln, wedge=wedge, chi=chi)
    osign = float(pars.get("omegasign"))
    if osign != 1:
        print("# Flipping omegasign %f"%(osign))
        np.multiply( omega1, osign, omega1 )
        np.multiply( omega2, osign, omega2 )
    pars.set( "t_x", gr.translation[0] )
    pars.set( "t_y", gr.translation[1] )
    pars.set( "t_z", gr.translation[2] )
    fc1, sc1 = transform.compute_xyz_from_tth_eta(tth, eta1, omega1,
                                                  **pars.parameters)
    fc2, sc2 = transform.compute_xyz_from_tth_eta(tth, eta2, omega2,
                                                  **pars.parameters)
    # Now make a single list of output stuff:
    alltth = np.concatenate( (tth, tth))
    alleta = np.concatenate( (eta1, eta2) )
    allsc =  np.concatenate( (sc1, sc2) )
    allfc =  np.concatenate( (fc1, fc2) )
    sraw = np.zeros(allsc.shape)
    fraw = np.zeros(allsc.shape)
    for i,(s,f) in enumerate(zip( allsc, allfc )):
        sraw[i], fraw[i] = spatial.distort( s, f )
    allomega = np.concatenate( (omega1, omega2) )
    allhkls =  np.concatenate( (hkls, hkls) )
    order = np.argsort( allomega )
    # output ?
    # omega in range
    # peak in detector
    #  etc
    fmt = " % -4d % -3d % -3d % -3d % 8.4f % 7.2f % 8.2f % 8.2f % 8.2f % 8.2f % 8.2f"
    strs = []
    for i in order:
        s, f, o = sraw[i], fraw[i], allomega[i]
        if alltth[i] == 0:
            continue
        if inscan(  s, f, o, detector_size):
            line = fmt%(gid,allhkls[i][0],allhkls[i][1],allhkls[i][2],
                        alltth[i], alleta[i], allomega[i], allsc[i], allfc[i],
                        sraw[i], fraw[i] )
            strs.append( (allomega[i], line) ) # to be omega sortable
    return strs
Exemplo n.º 8
0
 def test_strain_ref(self):
     from xfab.tools import ubi_to_u_and_eps
     dzero_cell = indexing.ubitocellpars( self.ubi0 )
     u, eps_xfab_ref_e6 = ubi_to_u_and_eps( self.ubi, dzero_cell )
     dgt = finite_strain.DeformationGradientTensor( self.ubi, self.ub0 )
     eps_new = dgt.finite_strain_ref( m=0.5 )
     self.assertTrue( np.allclose( dgt.U, u ) )
     self.assertTrue( np.allclose( dgt.U, self.u ) )
     self.assertTrue( np.allclose( finite_strain.symm_to_e6(eps_new), eps_xfab_ref_e6 ) )
     self.assertTrue( np.allclose( finite_strain.e6_to_symm(eps_xfab_ref_e6), eps_new ) )
Exemplo n.º 9
0
 def test_strain_lab(self):
     from xfab.tools import ubi_to_u_and_eps
     dzero_cell = indexing.ubitocellpars( self.ubi0 )
     u, eps_xfab_ref_e6 = ubi_to_u_and_eps( self.ubi, dzero_cell )
     emat = finite_strain.e6_to_symm( eps_xfab_ref_e6 )
     Exfab = np.dot(np.dot( u, emat), u.T )
     dgt = finite_strain.DeformationGradientTensor( self.ubi, self.ub0 )
     eps_new = dgt.finite_strain_lab( m=0.5 )
     self.assertTrue( np.allclose( dgt.U, u ) )
     self.assertTrue( np.allclose( dgt.U, self.u ) )
     self.assertTrue( np.allclose( eps_new, Exfab ) )
Exemplo n.º 10
0
def test_fft():
    gv = get_eu_gv()
    from ImageD11.fft_index_refac import grid
    from ImageD11.indexing import ubitocellpars, write_ubi_file,\
        refine
    g = grid(np=128, mr=1.0, nsig=20)
    g.gv_to_grid_new(gv)
    g.fft()
    g.props()
    g.peaksearch(open("eu.patterson_pks", "w"))
    g.read_peaks("eu.patterson_pks")
    vecs = rc_array(g.UBIALL.T, direction='col')
    assert vecs.shape == (3, g.colfile.nrows)
    order = argsort(g.colfile.sum_intensity)[::-1]
    vecs = take(vecs, order, axis=1)
    min_pks = 300
    ntry = 0

    assert g.gv.shape[1] == 3
    tv = rc_array(g.gv, direction='row')
    print "Finding lattice l1 from patterson"
    l1 = find_lattice(vecs, min_vec2=9, test_vecs=tv, n_try=20)
    print "r2c == ubi matrix"
    print l1.r2c
    print "scores", l1.score(tv)
    print "cell", ubitocellpars(l1.r2c)
    l1.r2c = refine(l1.r2c, g.gv, tol=0.1)
    l1.c2r = inv(l1.r2c)
    print "With refine", l1.score(tv)
    print "cell", ubitocellpars(l1.r2c)
    print "Finding lattice l2 with gvectors to test"
    l2 = find_lattice(vecs, min_vec2=9, n_try=20, test_vecs=tv)
    print "r2c == ubi matrix"
    print l2.r2c
    print "scores", l2.score(tv)
    print "cell", ubitocellpars(l2.r2c)
    l2.r2c = refine(l2.r2c, g.gv, tol=0.1)
    l2.c2r = inv(l2.r2c)
    print "With refine", l2.score(tv)
    print "cell", ubitocellpars(l2.r2c)
    return
Exemplo n.º 11
0
 def makemap(self):
     """
     Generate a map fit versus position - no args?
     """
     for m in self.ubisread:
         g = grain(m)
         self.scandata=self.allscandata.copy()
         self.compute_gv(g)
         h=np.dot(g.ubi,np.transpose(self.gv))
         hint=np.floor(h+0.5).astype(np.int) # rounds down
         diff=h-hint
         drlv=np.sqrt(np.sum(diff*diff,0))
         indices = np.compress(drlv < 0.05,
                                    list(range(self.scandata.shape[0])))
         print(indices.shape,"hello")
         self.scandata = self.allscandata[indices]
         npts = 10
         for i in range(npts):
             for j in range(npts):
                 x=(i-npts*0.5)*1000/npts
                 y=(j-npts*0.5)*1000/npts
                 g.translation[0]=x
                 g.translation[1]=y
                 self.compute_gv(g)
                 for tol in [ 0.1]:
                     mat = g.ubi.copy()
                     npks = closest.score_and_refine(mat, self.gv, tol)
                     # 2nd time with refined
                     npks = closest.score_and_refine(mat, self.gv, tol)
                     h=np.dot(mat,np.transpose(self.gv))
                     hint=np.floor(h+0.5).astype(np.int)
                     # rounds down
                     diff=h-hint
                     drlv=np.sqrt(np.sum(diff*diff,0))
                     tthscore = np.sum(np.sum(hint*diff) *
                                       np.sum(hint*diff) /
                                       np.sum(h*h))
                     print(x,y, tol, "%5d"%(npks),sum(drlv)/drlv.shape[0],\
                     tthscore/drlv.shape[0],indexing.ubitocellpars(mat), end=' ')
                 print()
             sys.stdout.flush()
         print()
         print()
         print()
Exemplo n.º 12
0
def main():
    flt = columnfile.columnfile(sys.argv[1])
    grains = grain.read_grain_file(sys.argv[2])
    pars = parameters.read_par_file(sys.argv[3])
    newgrainfile = sys.argv[4]

    hkltol = 0.05  #  for first peak assignments
    nmedian = 5  #  for removing peak fit outliers
    omegastep = 1.0  #  for omega images
    ymin = -18  #  dty start (so -15 -> +15 in 0.25 steps)
    ystep = 0.25  #  step in dty from scan
    rcut = 0.2  #  cutoff for segmentation of reconstruction

    OMSLOP = omegastep / 2.0

    tth, eta, gve = update_cols(flt, pars, OMSLOP)
    assign_peaks(grains, gve, flt, pars, nmedian, hkltol)
    pl.ioff()
    print("\n\n")
    for i, g in enumerate(grains):
        print("# Grain:", i)
        fit_one_grain(g, flt, pars)
        y0, x, y = map_out_cell(g, flt)
        sinoangles, sino, recon = map_grain(g, flt, ymin, ystep, omegastep)
        if 0:
            pl.subplot(211)
            pl.imshow(sino)
            pl.subplot(212)
            pl.imshow(recon)
            pl.show()
        active = recon > recon.max() * rcut
        ii, jj = np.mgrid[0:recon.shape[0],
                          0:recon.shape[0]] - recon.shape[0] // 2
        for ix, iy in zip(ii[active], jj[active]):
            gf = fit_one_point(g, flt, pars, ix, iy, ystep)
            print(("%-4d  " * 4) % (i, ix, iy, gf.mask.astype(int).sum()),
                  end=" ")
            print(("%.6f  " * 6) % (indexing.ubitocellpars(gf.ubi)), end=" ")
            print(("%.6f  " * 3) % tuple(gf.Rod))
        g.translation = (x, y, 0)

    grain.write_grain_file(newgrainfile, grains)
Exemplo n.º 13
0
def lattice_powder(ubi, tol=0.01):
    a, b, c = np.asarray(ubi)
    nmax = 5
    vecs = []
    lens = []
    for ai in range(-nmax, nmax):
        for bi in range(-nmax, nmax):
            for ci in range(-nmax, nmax):
                vec = ai * a + bi * b + ci * c
                modv = np.sqrt(np.dot(vec, vec))
                lens.append(modv)
                vecs.append(vec)
    order = np.argsort(lens)
    lens = np.take(lens, order)
    vecs = np.take(vecs, order, axis=0)
    steps = (lens[1:] - lens[:-1]) / lens[1:]  # diff divided by upper
    gaps = steps > tol
    rings = np.cumsum(gaps)
    mults, bins = np.histogram(rings, bins=np.arange(-0.5, rings[-1] + 0.5, 1))
    print(rings)
    print(mults)
    nr = min(10, rings.max())
    for i in range(nr, 0, -1):
        # this ring:
        M = mults[i]
        print("Powder ring", i, "multiplicity", M)
        print("   Angles between vectors:")
        vl = vecs[1:][rings == i]
        vll = lens[1:][rings == i]
        for j in range(M):
            print("%2d:" % (j), vl[j], vll[j])
        print("  ", end="")
        for j in range(M - 1, 0, -1):
            print("%7d" % (j), end=" ")
        print()
        for j in range(M - 1):
            print(" %2d: " % (j), end="")
            for k in range(M - 1, j, -1):
                print("%7.3f" % (vecang(vl[j], vl[k])), end=" ")
            print()
    print("Cell pars before", ubitocellpars(ubi))
Exemplo n.º 14
0
    def add_voxel_to_field(self, voxel, field_recons, row, col, params):

        cell = indexing.ubitocellpars(voxel.ubi)
        field_recons['a'][row, col] = cell[0]
        field_recons['b'][row, col] = cell[1]
        field_recons['c'][row, col] = cell[2]
        field_recons['alpha'][row, col] = cell[3]
        field_recons['beta'][row, col] = cell[4]
        field_recons['gamma'][row, col] = cell[5]

        rod = voxel.Rod
        field_recons['rod1'][row, col] = rod[0]
        field_recons['rod2'][row, col] = rod[1]
        field_recons['rod3'][row, col] = rod[2]

        ubi = np.ravel(voxel.ubi, order='C')
        field_recons['UBI11'][row, col] = ubi[0]
        field_recons['UBI12'][row, col] = ubi[1]
        field_recons['UBI13'][row, col] = ubi[2]
        field_recons['UBI21'][row, col] = ubi[3]
        field_recons['UBI22'][row, col] = ubi[4]
        field_recons['UBI23'][row, col] = ubi[5]
        field_recons['UBI31'][row, col] = ubi[6]
        field_recons['UBI32'][row, col] = ubi[7]
        field_recons['UBI33'][row, col] = ubi[8]

        U, eps_cry = tools.ubi_to_u_and_eps(voxel.ubi,
                                            self.extract_cell(params))
        eps_cry_33 = np.array([[eps_cry[0], eps_cry[1], eps_cry[2]],
                               [eps_cry[1], eps_cry[3], eps_cry[4]],
                               [eps_cry[2], eps_cry[4], eps_cry[5]]])
        sample_strain = np.dot(U, np.dot(eps_cry_33, np.transpose(U)))

        field_recons['E11'][row, col] = sample_strain[0, 0]
        field_recons['E12'][row, col] = sample_strain[0, 1]
        field_recons['E13'][row, col] = sample_strain[0, 2]
        field_recons['E22'][row, col] = sample_strain[1, 1]
        field_recons['E23'][row, col] = sample_strain[1, 2]
        field_recons['E33'][row, col] = sample_strain[2, 2]
Exemplo n.º 15
0
def main():
    """
    A user interface
    """
    import sys, time, os, logging
    start = time.time()

    root = logging.getLogger('')
    root.setLevel(logging.WARNING)

    try:
        from optparse import OptionParser
        parser = OptionParser()
        parser = get_options(parser)
        options, args = parser.parse_args()
    except SystemExit:
        raise
    except:
        parser.print_help()
        print("\nProblem with your options:")
        raise

    if options.output is None:
        print("You must supply an output file (-o vol.h5)")
        sys.exit()

    if os.path.exists(options.output):
        print("I would overwrite your output file", options.output)
        print("If you really want that then delete it first and re-run")
        sys.exit()

    try:
        if options.pars is None:
            print("You must supply a parameter file, -p file.pars")
            sys.exit()
        pars = parameters.parameters()
        pars.loadparameters(options.pars)
        print("Got parameters from", options.pars)
        pd = pars.get_parameters()
        names = list(pd.keys())
        names.sort()
        for name in names:
            print("%30s   %s" % (name, pd[name]))
    except:
        print("Problem with parameters:", options.pars)
        raise

    try:
        if options.ubifile is None:
            print("You must supply an input ubifile")
        ubi = indexing.readubis(options.ubifile)[0]
        print("UBI:\n", ubi)
        print("Cell parameters:")
        print("%.5f %.5f %.5f %.4f %.4f %.4f" % \
              indexing.ubitocellpars(ubi))
    except:
        print("Problem with ubi file:", options.ubifile)
        raise

    if options.maskfilename is not None:
        from fabio.openimage import openimage
        try:
            mask = (openimage(options.maskfilename).data == 0)
        except:
            print("Problem with your mask image", options.maskfilename)
            raise
        print("Using a mask from", options.maskfilename)
        print("percent of image used %.3f" %
              (100.0 * mask.sum() / mask.shape[0] / mask.shape[1]))
    else:
        mask = None

    first_image = True
    nimage = 0

    imagefiles = ImageD11_file_series.get_series_from_options(options, args)

    print("Subslicing by", options.subslice)

    try:
        for fim in imagefiles:

            if first_image:  # allocate volume, compute k etc

                first_image = False

                mapper = rsv_mapper(fim.data.shape,
                                    pars,
                                    ubi,
                                    options.spline,
                                    np=options.npixels,
                                    border=options.border,
                                    maxpix=options.maxpix,
                                    mask=mask
                                    # FIXME omegarange
                                    )

                logging.info("Setting up time %.4f s" % (time.time() - start))

            ltp = time.time()
            om = float(fim.header['Omega'])
            oms = float(fim.header['OmegaStep'])
            for i in range(options.subslice):
                print(".", end=' ')
                omv = om + i * oms / options.subslice
                # ==1 : 0*s/1
                # ==2 : 0*s/2 , 1*s/2
                # ==3 : 0*s/3 , 1*s/3, 2*s/3 etc
                mapper.add_image(omv, fim.data)

            nimage = nimage + 1

            print("  %d %.3f %.4f s, %.4f s" %
                  (nimage, om, time.time() - ltp, time.time() - start))
            if options.images is not None:
                if nimage >= options.images:
                    break

    except KeyboardInterrupt:
        print("\nCaught a control-c")
        if nimage > 0:
            print("Problem, trying to save volume so far to:", options.output)
            mapper.writevol(options.output)
            print("Saved what I had")
        sys.exit()
    except:
        print("\nAn error occured")
        if nimage > 0:
            print("Problem, trying to save volume so far to:", options.output)
            mapper.writevol(options.output)
            print("Saved what I had")
        raise

    if nimage > 0:
        mapper.writevol(options.output)
Exemplo n.º 16
0
    def pairs(self, hkl1, hkl2, cos_tol=0.02, hkl_tol=0.1):
        """
        We only look for reflection pairs matching a single hkl pairing
        """
        import time
        start = time.time()
        w = self.transformpars.get("wavelength")
        tth1 = get_tth(self.unitcell.ds(hkl1), w)
        tth2 = get_tth(self.unitcell.ds(hkl2), w)
        tthtol = self.transformpars.get("fit_tolerance")
        allinds = np.arange(self.cf.nrows)
        ind1 = allinds[abs(self.cf.tth - tth1) < tthtol]
        ind2 = allinds[abs(self.cf.tth - tth2) < tthtol]
        angle, cosangle = self.unitcell.anglehkls(hkl1, hkl2)
        print("Angle, cosangle", angle, cosangle, hkl1, hkl2)
        assert angle > 1 and angle < 179, "hkls are parallel"
        g = np.array((self.cf.gx, self.cf.gy, self.cf.gz), np.float)
        n = g / self.cf.modg
        gvf = g.T.copy()
        n1 = n[:, ind1]
        n2 = n[:, ind2]
        pairs = []
        j = np.arange(n2.shape[1])
        # from unitcell.orient
        h1c = unit(np.dot(self.unitcell.B, hkl1))
        h2c = unit(np.dot(self.unitcell.B, hkl2))
        t1c = unit(h1c)
        t3c = unit(np.cross(h1c, h2c))
        t2c = unit(np.cross(h1c, t3c))
        T_c = np.array([t1c, t2c, t3c])
        T_g = np.zeros((3, 3))
        for i, this_n1 in enumerate(n1.T):
            cosa = np.dot(this_n1, n2)
            goodones = j[abs(cosa - cosangle) < cos_tol]
            # t1 is along g1
            # t2 is plane of both: g1x(g1xg2)
            # t3 is perpendicular to both
            #if i%100==0:
            #   print i,time.time()-start,len(n1.T)
            for k in goodones:
                this_n2 = n2[:, k]
                T_g[0] = this_n1
                T_g[2] = unit(np.cross(this_n1, this_n2))
                T_g[1] = unit(np.cross(this_n1, T_g[2]))
                U = np.dot(T_g.T, T_c)
                ub = np.dot(U, self.unitcell.B)
                ubi = np.linalg.inv(ub)
                ubio = ubi.copy()
                npks = cImageD11.score(ubi, gvf, hkl_tol)
                pairs.append((ind1[i], ind2[k], U, ubi))
                print(npks, end=' ')

                ubi, trans = self.refine(ubi,
                                         np.zeros(3, np.float),
                                         tol=hkl_tol)
                inds, hkls = self.assign(ubi, trans, hkl_tol)
                ubi, trans = self.refine(ubi,
                                         trans,
                                         inds=inds,
                                         hkls=hkls,
                                         tol=hkl_tol)
                print(npks, ubi)
                print("cell: ", 6 * "%.6f " % (indexing.ubitocellpars(ubi)))
                print("position: ", trans)
                print()
        self.pairscache = pairs
        print(time.time() - start, "for", len(pairs), n1.shape, n2.shape)
        return pairs
Exemplo n.º 17
0
                                      inds=inds,
                                      hkls=hkls,
                                      tol=tol)
                    g.translation = t
                    g.set_ubi(ubi)
            else:
                inds = np.compress(c.labels == k, inds)
                hkls = np.compress(c.labels == k, allhkls)
                for j in range(3):
                    ubi, t = i.refine(g.ubi,
                                      translation=g.translation,
                                      inds=inds,
                                      hkls=hkls,
                                      tol=tol)
                    g.translation = t
                    g.set_ubi(ubi)
            print(k, len(inds), 6 * "%.8f " % (indexing.ubitocellpars(ubi)))
            print("\t", t)
        ImageD11.grain.write_grain_file(sys.argv[5], gl)
    else:
        i.updatecolfile()
        i.tthcalc()
        print("Calling assign")
        i.assigntorings()
        hkl1 = [int(h) for h in sys.argv[3].split(",")]
        hkl2 = [int(h) for h in sys.argv[4].split(",")]
        print("Calling pairs")
        i.pairs(hkl1, hkl2)

# e.g. python indexer.py ../test/demo/eu3.pars ../test/demo/eu.flt 2,0,0 0,0,4
Exemplo n.º 18
0
def cpfromub( ubf ):
    ub = np.reshape( ubf, (3,3) )
    return np.array(indexing.ubitocellpars( np.linalg.inv( ub ) ))
Exemplo n.º 19
0
    gfl = []
    ng = 0
    # Take old peak assignments:
    if 1:
        print("Using existing peak assignments")
        inds = np.arange(o.colfile.nrows, dtype=int)
        for i, gref in enumerate(gl):
            gref.pks = np.compress(o.colfile.labels == i, inds)
        tols = [
            None,
        ] * 3
    else:
        tols = [0.05, 0.01, 0.0075]
    for gref in gl:
        print("BEFORE:            ", 3 * "% 7.3f " % tuple(gref.translation),
              6 * "%.6f " % (ubitocellpars(gref.ubi)))
        for ii, tol in enumerate(tols):
            #print gref.translation
            gref = o.refine(gref, tol=tol)
            #print i,gref.npks
#        gref.pks = None
# re-assign after convergence
#        gref = o.refine( gref, tol=0.0075)
        gfl.append(gref)
        ng += 1
        print(ng,
              ng * 100.0 / len(gl),
              "%.2f   " % (time.time() - start),
              gref.npks,
              end=' ')
        print((3 * "%.4f ") % tuple(gref.translation), end=' ')
Exemplo n.º 20
0
            #print l.score(all_gvecs[3:5], tol = options.tol)
            #print l.remainders( all_gvecs[3:5])

            all = len(all_gvecs)
            npks = l.score(all_gvecs, tol=options.tol)
            if (1.0 * npks / len(all_gvecs)) < options.fraction_indexed:
                break
            dr = indexing.calc_drlv2(l.r2c, all_gvecs)
            t2 = options.tol * options.tol
            # print "tol, dr",t2,dr.shape, [d for d in dr[:10]] # print it !!!
            n2 = np.sum(np.where(dr < t2, 1, 0))
            n3 = np.sum(np.where(dr > t2, 1, 0))
            assert npks == n2, "debug scoring"
            assert n3 == len(all_gvecs) - npks, "debug scoring"
            print l.r2c
            print "Unit cell:", (6 * "%.6f ") % indexing.ubitocellpars(l.r2c)

            # Put this grain in the output list
            ubis.append(l.r2c)

            # Remove from the gvectors
            drlv2 = indexing.calc_drlv2(l.r2c, cur_gvecs)
            # print drlv2[:20]
            # print cur_gvecs.shape
            # print drlv2.shape,drlv2[:10],options.tol*options.tol

            cur_gvecs = rc_array.rc_array(np.compress(
                drlv2 > options.tol * options.tol, cur_gvecs, axis=0),
                                          direction='row')
            print "Lattice found, indexes", npks, "from all", all
            print "Number of unindexed peaks remaining %d" % (len(cur_gvecs))
Exemplo n.º 21
0

for ubifile in sys.argv[1:]:
    print("Reading",ubifile, end=' ')
    try:
        ul = indexing.readubis(ubifile)
    except:
        print("error")
        continue
    print() 
    print("i    a       b       c     alpha    beta     gamma    volume")
    cell_all = []
    volume = []
    for u,i  in zip(ul,list(range(len(ul)))):
        print(i, end=' ') 
        cell = indexing.ubitocellpars(u)
        vol = cell[0]*cell[1]*cell[2]*numpy.sin(cell[3]*numpy.pi/180.)*numpy.sin(cell[4]*numpy.pi/180.)*numpy.sin(cell[5]*numpy.pi/180.)
        print("%.5f "*6 % cell + "%.5f" %vol)
        cell_all.append(cell)
        volume.append(vol)
        continue
        #print u
        red = try_to_reduce(u)
        #print red
        #print u
        if (red != u).any():
            print("Reduced ubi")
            print(red)
            print("%.5f "*6 % indexing.ubitocellpars(red))

    cell_all = numpy.asarray(cell_all)