Example #1
0
def main():
    import sys, time
    c = columnfile(sys.argv[1])
    p = read_par_file(sys.argv[2])
    u = unitcell_from_parameters(p)
    gl = read_grain_file(sys.argv[3])
    if gl[0].translation is None:
        gl[0].translation = np.array((0., 0., 0.))
    start = time.time()
    # Setup and assign hkls
    w = p.get("wavelength")
    peaks_Cxyz, beam_Cxyz = getCxyz(c, p)
    t = gl[0].translation.copy()
    ub = gl[0].ub.copy()
    ubi = gl[0].ubi.copy()
    gve = compute_Cgve(t, peaks_Cxyz, beam_Cxyz, w)
    hi = np.round(np.dot(ubi, gve))
    lastgof = 1e9
    ubn, tn = fit_ub_t(ub, t, hi, peaks_Cxyz, beam_Cxyz, w)
    print("Before\nt=", gl[0].translation)
    print("UB=", gl[0].ub)
    gl[0].set_ubi(np.linalg.inv(ubn))
    gl[0].translation = tn
    dt = time.time() - start
    print("time calculating", dt, "gps", 1 / dt)
    print("After\nt=", gl[0].translation)
    print("UB=", gl[0].ub)
    write_grain_file(sys.argv[4], gl)
Example #2
0
 def loadmap(self,filename):
     try:
         self.map=read_grain_file(filename)
         self.ubis=[x.ubi for x in self.map]
     except:
         print "error when reading %s\n",filename
         raise
Example #3
0
    def recon_slice(self, flt_file, grain_file, label):

        print("\n \nStarting reconstruction of slice: " + label)
        print(flt_file)
        flt = columnfile.columnfile(flt_file)

        #---------------------------------------------------------------------------
        # Fix the dty column of the flt such that it scanns across 0 anddty is in microns.
        flt.dty[:] = ((flt.dty - self.ymin_flt) * self.unit /
                      (10**(-6))) - self.ystep * (self.number_y_scans // 2)
        print(
            '\nFixed the dty column, existing dtys are now (in units of microns):'
        )
        print(np.unique(flt.dty))
        print('')
        #---------------------------------------------------------------------------

        grains = grain.read_grain_file(grain_file)

        grain_topology_masks = self.recon_topology(flt, grains)

        g, s = self.select_grains(grains, grain_topology_masks)


        recons = self.reconstructor.reconstruct( flt, g, self.number_y_scans,\
                                                 self.ymin, self.ystep, s )

        print("Recon shape: ", recons['E11'].shape)
        print("\n Finished reconstruction of slice: " + label)
        print("Saving results..")
        self.slices[label] = recons
        self.slice_masks[label] = sum(grain_topology_masks)
        self.save_slice_as_npy(recons, label)

        return recons
Example #4
0
def setup():
    try:
        c = columnfile( sys.argv[1] )
        g = read_grain_file( sys.argv[2] )
        parfile = sys.argv[3]
        cmds = []
    except:
        print( "Usage: %s colfile.flt.new grains.map parameters.par  --omega_slop=1 etc"%(sys.argv[0]))
        sys.exit()
    
    if platform.system() != "Windows":
        fmt = "%s %s"
    else:
        fmt = '%s "%s"'

    cmd0 = fmt%( sys.executable,
                     os.path.join( os.path.split(__file__)[0],
                                   "fitgrain.py" ) )

    for i in range(len(g)):
        #g[i].translation[2] = 0.0
        write_grain_file("%d.ubi"%(i),[g[i]])
        d = c.copy()
        d.filter( d.labels == i )
        d.writefile("%d.flt"%(i))
        cmd = cmd0 + " -p %s -u %d.ubi -U %d.ubi -P %d.par -f %d.flt -x t_z"%(
            parfile,i,i,i,i)
        for extra_arg in sys.argv[4:]:
            cmd += " "+extra_arg
        cmds.append( cmd )
    return cmds
Example #5
0
 def setUp(self):
     pth = os.path.split(__file__)[0]
     self.testdata = np.loadtxt(os.path.join(pth,"test.out"), skiprows = 30)
     self.titles = list( 
         "cell__a cell__b cell__c cell_alpha cell_beta cell_gamma u11 u12 u13 u21 u22 u23 u31 u32 u33".split() + 
         "eps11_c eps22_c eps33_c eps12_c eps13_c eps23_c eps11_s eps22_s eps33_s eps12_s eps13_s eps23_s".split() + 
         "sig11_c sig22_c sig33_c sig12_c sig13_c sig23_c sig11_s sig22_s sig33_s sig12_s sig13_s sig23_s".split() 
         )
     self.grains = read_grain_file(os.path.join(pth,"CuAlBe_scan10.map"))
     a = 5.77
     self.dzero = ( a, a, a, 90., 90., 90. )
Example #6
0
def main2():
    import sys
    c = columnfile(sys.argv[1])
    p = read_par_file(sys.argv[2])
    gl = read_grain_file(sys.argv[3])
    for i, g in enumerate(gl):
        mask = c.labels == i
        g.sc = np.compress(mask, c.sc)
        g.fc = np.compress(mask, c.fc)
        g.omega = np.compress(mask, c.omega)
        ubnew, tnew = fitagrain(g, p)
        g.set_ubi(np.linalg.inv(ubnew))
        g.translation[:] = tnew
        print(i, len(g.sc), tnew)
    write_grain_file(sys.argv[4], gl)
Example #7
0
 def readubis(self, filename):
     """
     Read ubi matrices from a text file
     """
     try:
         ul = grain.read_grain_file(filename)
     except:
         print(filename, type(filename))
         raise
     for i, g in enumerate(ul):
         # name = filename + "_" + str(i)
         # Hmmm .... multiple grain files?
         name = i
         self.grainnames.append(i)
         self.ubisread[name] = g.ubi
         self.translationsread[name] = g.translation
Example #8
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 = 13.5      #  dty start (so -15 -> +15 in 0.25 steps)
    ystep = 0.02     #  step in dty from scan
    rcut  = 0.2      #  cutoff for segmentation of reconstruction
    
    flt.filter( flt.dty >= ymin )
    flt.idty = np.round((flt.dty - ymin)/ystep).astype(np.int32) - 35
    flt.NY = 71 # flt.idty.max()+1
    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")
    out = open( newgrainfile, "w" )
    out.write("#  grain  ix  iy   npks   ubi00  ubi01  ubi02  ubi10  ubi11  ubi12  ubi20  ubi21  ubi22\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 )
            r = ("%-4d  "*4)%(i,ix,iy,gf.mask.astype(int).sum())
            print(r)
            u = ("%.7f  "*9)%tuple(gf.ubi.ravel())
            out.write(r)
            out.write(u+"\n")
        g.translation = (x,y,0)
Example #9
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)
Example #10
0
def test_eu():
    from ImageD11.grain import read_grain_file
    from ImageD11.columnfile import columnfile
    from ImageD11.parameters import read_par_file
    gr  = read_grain_file("./eu3.map")[0]
    par = read_par_file("./0.par")
    flt = columnfile( "../demo/eu.flt" )
    flt.updateGeometry(par)
    gve = np.array( [flt.gx, flt.gy, flt.gz], np.float)
    e0,e1,e2 = pkfom( gr, gve )
    flt.addcolumn( e0, "e0" )
    flt.addcolumn( e1, "e1" )
    flt.addcolumn( e2, "e2" )
    pl.subplot(131)
    pl.scatter( flt.tth, flt.e0, c=flt.eta, edgecolor='none')
    pl.subplot(132)
    pl.scatter( flt.tth, flt.e1, c=flt.eta, edgecolor='none')
    pl.subplot(133)
    pl.scatter( flt.tth, flt.e2, c=flt.eta, edgecolor='none')
    pl.show()
    return gr, flt, par
Example #11
0
    def recon_slice(self, flt_file, grain_file, label):

        print("\n \nStarting reconstruction of slice: " + label)
        flt = columnfile.columnfile(flt_file)
        grains = grain.read_grain_file(grain_file)

        self.ymin, self.ystep, self.number_y_scans = self.extract_scan_geometry(
            flt)
        grain_topology_masks = self.recon_topology(flt, grains)

        g, s = self.select_grains(grains, grain_topology_masks)

        recons = self.reconstructor.reconstruct( flt, g, self.number_y_scans,\
                                                 self.ymin, self.ystep, s )

        print("Recon shape: ", recons['E11'].shape)
        print("\n Finished reconstruction of slice: " + label)
        print("Saving results..")
        self.slices[label] = recons
        self.save_slice_as_npy(recons, label)

        return recons
Example #12
0
        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())

if __name__=="__main__":
    h = h5py.File(sys.argv[1],"r")
    assert sys.argv[2] in h.keys(), h.keys()
    c = h[sys.argv[2]]
    p = read_par_file(sys.argv[3])
    gf = read_grain_file(sys.argv[4])
    tol = float(sys.argv[5])

    sc = c['sc'][:]
    fc = c['fc'][:]
    omega = c['omega'][:]

    cyf = cyfit( p )
    cyf.setscfc( sc, fc )
    hkl = np.zeros( cyf.XL.shape, np.float)
    drlv = np.zeros( cyf.XL.shape[0], np.float)
    kcalc = np.zeros( cyf.XL.shape, np.float)
    rs = []
    r_omega  = np.array(omega*np.pi/180.0,np.float)
    start = time.clock()
    for i in range(5):#len(gf)):
Example #13
0
def ubi_to_gff(ubi,par):
    from ImageD11 import grain as ig
    from ImageD11 import parameters as ip
    from string import split
    from xfab import tools
    from six.moves import range
    
    list_of_grains = ig.read_grain_file(ubi)
    p = ip.parameters()
    p.loadparameters(par)
    uc = [p.parameters['cell__a'],p.parameters['cell__b'],p.parameters['cell__c'],p.parameters['cell_alpha'],p.parameters['cell_beta'],p.parameters['cell_gamma']]
    #print(uc)
    
    grainno = []
    x = []
    y = []
    z = []
    rodx = []
    rody = []
    rodz = []
    unitcell_a = []
    unitcell_b = []
    unitcell_c = []
    unitcell_alpha = []
    unitcell_beta = []
    unitcell_gamma = []
    U11 = []
    U12 = []
    U13 = []
    U21 = []
    U22 = []
    U23 = []
    U31 = []
    U32 = []
    U33 = []
    eps11 = []
    eps22 = []
    eps33 = []
    eps23 = []
    eps13 = []
    eps12 = []
    titles = ["grainno","x","y","z","rodx","rody","rodz","U11","U12","U13","U21","U22","U23","U31","U32","U33","unitcell_a","unitcell_b","unitcell_c","unitcell_alpha","unitcell_beta","unitcell_gamma","eps11","eps22","eps33","eps23","eps13","eps12"]
    for i in range(len(list_of_grains)):
        if hasattr(list_of_grains,'name') == False:
            grainno.append(i)
        elif hasattr(list_of_grains,'name') == True:
            grainno.append(eval(split(list_of_grains[i].name,':')[0]))
        x.append(list_of_grains[i].translation[0]/1000.)
        y.append(list_of_grains[i].translation[1]/1000.)
        z.append(list_of_grains[i].translation[2]/1000.)
        ubi = list_of_grains[i].ubi
        (U,eps) = tools.ubi_to_u_and_eps(ubi,uc)
        uc_a, uc_b, uc_c, uc_alpha, uc_beta, uc_gamma = tools.ubi_to_cell(ubi)
        unitcell_a.append(uc_a)
        unitcell_b.append(uc_b)
        unitcell_c.append(uc_c)
        unitcell_alpha.append(uc_alpha)
        unitcell_beta.append(uc_beta)
        unitcell_gamma.append(uc_gamma)
        rod = tools.u_to_rod(U)
        rodx.append(rod[0])
        rody.append(rod[1])
        rodz.append(rod[2])
        U11.append(U[0,0])
        U12.append(U[0,1])
        U13.append(U[0,2])
        U21.append(U[1,0])
        U22.append(U[1,1])
        U23.append(U[1,2])
        U31.append(U[2,0])
        U32.append(U[2,1])
        U33.append(U[2,2])
        eps11.append(eps[0])
        eps12.append(eps[1])
        eps13.append(eps[2])
        eps22.append(eps[3])
        eps23.append(eps[4])
        eps33.append(eps[5])
    
    gff = cl.newcolumnfile(titles)
    gff.ncols = len(titles)
    gff.nrows = len(grainno)
    gff.bigarray = np.zeros((gff.ncols,gff.nrows))
    gff.set_attributes()
    gff.addcolumn(grainno,"grainno")
    gff.addcolumn(x,"x")
    gff.addcolumn(y,"y")
    gff.addcolumn(z,"z")
    gff.addcolumn(rodx,"rodx")
    gff.addcolumn(rody,"rody")
    gff.addcolumn(rodz,"rodz")
    gff.addcolumn(U11,"U11")
    gff.addcolumn(U12,"U12")
    gff.addcolumn(U13,"U13")
    gff.addcolumn(U21,"U21")
    gff.addcolumn(U22,"U22")
    gff.addcolumn(U23,"U23")
    gff.addcolumn(U31,"U31")
    gff.addcolumn(U32,"U32")
    gff.addcolumn(U33,"U33")
    gff.addcolumn(unitcell_a,"unitcell_a")
    gff.addcolumn(unitcell_b,"unitcell_b")
    gff.addcolumn(unitcell_c,"unitcell_c")
    gff.addcolumn(unitcell_alpha,"unitcell_alpha")
    gff.addcolumn(unitcell_beta,"unitcell_beta")
    gff.addcolumn(unitcell_gamma,"unitcell_gamma")    
    gff.addcolumn(eps11,"eps11")
    gff.addcolumn(eps22,"eps22")
    gff.addcolumn(eps33,"eps33")
    gff.addcolumn(eps23,"eps23")
    gff.addcolumn(eps13,"eps13")
    gff.addcolumn(eps12,"eps12")
    return gff, uc
Example #14
0
from __future__ import print_function

from ImageD11 import sym_u
from ImageD11.grain import read_grain_file

c = sym_u.cubic()
c.makegroup()

import glob

fl = glob.glob("x*.ubi")

for f in fl:
    gl = read_grain_file(f)
    x = int(f.split("_")[0][1:])
    y = int(f.split("_")[1].split(".")[0][1:])
    for g in gl:
        ubi = sym_u.find_uniq_u(g.ubi, c)
        g.set_ubi(ubi)
        print(x, y, end=' ')
        for i in range(3):
            for j in range(3):
                print(g.u[i][j], end=' ')
        print()
Example #15
0
     just copies all the data for the peak it is interested in""")
     sys.exit()

    omega_axis = axis( [ 0, 0, 1] ) # z
    chi_axis   = axis( [ 1, 0, 0] ) # x
    wedge_axis = axis( [ 0, 1, 0] ) # y
    


    # Data object
    peakdata = columnfile.colfile_from_hdf( sys.argv[1] )
    if not hasattr( peakdata, 'sum_intensity'):
        peakdata.sum_intensity = peakdata.npixels * peakdata.avg_intensity

    # Grain collection object
    grainlist = grain.read_grain_file( sys.argv[2] )

    if sys.argv[2][0:2] == "x_":
        items = sys.argv[2].split("_")
        tx = float( items[1] )*1500 - 4500
        ty = float( items[3] )*1500 - 4500
        tz = float( items[5].split(".")[0] )*500 -750
        for g in grainlist:
            #print tx,ty,tz,g.translation
            g.translation += [tx,ty,tz]
            #print tx,ty,tz,g.translation
        print("Sand translations added")
    # Detector parameters
    pars = parameters.parameters()
    pars.loadparameters( sys.argv[3] )
Example #16
0
#!/usr/bin/python

from ImageD11.columnfile  import columnfile
from ImageD11.grain import read_grain_file, write_grain_file
import sys, os

c = columnfile( sys.argv[1] )
g = read_grain_file( sys.argv[2] )

for i in range(len(g)):
    #g[i].translation[2] = 0.0
    write_grain_file("%d.ubi"%(i),[g[i]])
    d = c.copy()
    d.filter( d.labels == i )
    d.writefile("%d.flt"%(i))

    os.system( "fitgrain.py -p %s -u %d.ubi -U %d.ubi -P %d.par -f %d.flt -x t_z"%(sys.argv[3],i,i,i,i))

#    for j in range(3):
#            os.system( "fitgrain.py -u %d.ubi -U %d.ubi -p %d.par -P %d.par -f %d.flt"%(i,i,i,i,i))
Example #17
0
import numpy as np
import pylab
import sys


energy = float(sys.argv[1])
pks  = sys.argv[2] 
ubi = sys.argv[3]
tilt = float(sys.argv[4])
TOLERANCE=float(sys.argv[5])

c=WWMcrystal()
c.set_wvln( 12.3985/ energy )
c.dmin = 0.6
u0 = grain.read_grain_file(ubi)[0].u # np.eye(3)
#print u0
rx, ry, rz = getrxryrz( u0 )
c.set_orientation(u0)
c.generate_hkls()
c.generate_gve()
d = WWMdiffractometer(c, pks)
d.axistilt = tilt
d.computek()
d.computeomegas()
print d.omega.shape


def getom(d, hkl, fri):
    c = d.crystal
    ub = np.dot( c.umatrix, c.bmatrix )
Example #18
0

from ImageD11.grain import read_grain_file, write_grain_file
from ImageD11.columnfile import columnfile
import numpy as np

ideal = read_grain_file("ideal.map")

fnames = "allgrid_fittrans.map allgrid_indexer.map allgrid_makemap.map allgrid_teo.map".split()
#fnames = "teo.map",

def check(gl1, gl2):
    dTs = 0
    dVs = 0
    mxT = 0
    mxTi = 0
    mxV = 0
    mxVi = 0
    for i, (g1, g2) in enumerate(zip( gl1, gl2)):
        dT = g1.translation - g2.translation
        dvol = np.linalg.det(g1.ubi) - np.linalg.det(g2.ubi)
        t = abs(dT).max()
        dTs += t
        dVs += abs(dvol)
        if t > mxT:
            mxTi, mxT = i, t
        if abs(dvol) > mxV:
            mxVi, mxV = i, abs(dvol)
    print dTs/i, dVs/i, mxT, mxTi, mxV, mxVi
    
Example #19
0
    wedge = np.radians(float(pars.get("wedge")))
    chi = np.radians(float(pars.get("chi")))
    wvln = float(pars.get("wavelength"))

    c = columnfile(colfile)
    c.nrows = 2
    c.bigarray = c.bigarray[:, :2]
    print c.bigarray.shape
    c.set_attributes()

    XL = flatfloat(compute_xyz_lab([c.sc, c.fc], **pars.parameters).T)
    om = flatfloat(np.radians(c.omega))

    #    XL[0,:]=[41,42,43]

    grains = read_grain_file(grainfile)
    UBIs = flatfloat([g.ubi for g in grains], shape=(len(grains), 3, 3))
    UBs = flatfloat([np.linalg.inv(g.ubi) for g in grains],
                    shape=(len(grains), 3, 3))
    Ts = flatfloat([g.translation for g in grains], shape=(len(grains), 3))

    labels = np.zeros(c.nrows, np.int32)
    hkls = np.zeros((c.nrows, 3), NPREAL)

    print XL.shape
    print om.shape
    print UBs.shape
    print UBIs.shape
    print Ts.shape
    print labels.shape
    print hkls.shape
Example #20
0
 def loadgrains(self, fname):
     self.grains = grain.read_grain_file(fname)
     if len(self.grains) > 0:
         self.resetlabels()
         self.assignlabels()
Example #21
0
#!/usr/bin/python

from ImageD11.grain import read_grain_file
import sys, os

gf = read_grain_file(sys.argv[1])
mapfile = open(sys.argv[2], "w")


def dodot(xyz, k):
    mapfile.write("%f %f %f %d\n" % (xyz[0], xyz[1], xyz[2], k))


def getmedian(s):
    items = s.split()
    j = -1
    for i in range(len(items)):
        if items[i] == "median":
            j = i
    if j == -1:
        return 0
    return abs(float(items[j + 2]))


try:
    outersf = float(sys.argv[3])
except:
    outersf = 1.0

print("Scale factor is", outersf)
for g in gf:
Example #22
0
                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


# TODO:
#
# DONE : Least squares as SVD problem
# - Allow a constraint matrix to be used
# - Compute weights from experimental data (sig/cov etc)
# DONE (but not weighted or printed) : Compute error estimates
# - Allow fitting of other geometrical parameters
# - Allow refinement in terms of other parameterisation of UB (e.g. U, B)
# - Documentation

if __name__ == "__main__":
    colfile, parfile, grainsfile, newgrainsfile = sys.argv[1:5]
    c = columnfile.columnfile(colfile)
    p = parameters.read_par_file(parfile)
    g = grain.read_grain_file(grainsfile)
    grain.write_grain_file(newgrainsfile, refit_makemap(c, p, g))

    # python teo.py ../test/simul_1000_grains/g187.flt ../test/simul_1000_grains/Al1000/Al1000.par ../test/simul_1000_grains/g187.map teo187fitted.map
Example #23
0
#!/usr/bin/env python
from __future__ import print_function


"""
Removes grains from a grain file if they have less than
npks peaks

Usage : cutgrains.py   ubi_in  ubi_out  npks
"""

from ImageD11.grain import read_grain_file, write_grain_file
import sys
try:
    GRAINS = read_grain_file(sys.argv[1])
    NPKS = int(sys.argv[3])
    KEEP = []
    for g in GRAINS:
        if int(g.npks) >= NPKS:
            KEEP.append(g)
    write_grain_file( sys.argv[2], KEEP)
except:
    print(__doc__)
    raise
            
Example #24
0
            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))


def katayama(ubi):
    """
    J. Appl. Cryst (1986) 19 69-72
    
    Take four vectors a,b,c and d=-(a+b+c)
    Compute the 6 pairwise dot products (ab, ac, ad, bc, bd, cd)
    Apply transformations (up to 12) and recompute
    
    etc
    """
    pass


if __name__ == "__main__":
    for grain in read_grain_file(sys.argv[1]):
        print("ubi:\n", grain.ubi)
        lattice_powder(grain.ubi)
Example #25
0
        chi = float(self.colfile.parameters.get('chi'))
        self.chiwedge = gv_general.chiwedge(chi, wedge)
        omega = np.radians(self.colfile.omega)
        cosomega = np.cos(omega)
        sinomega = np.sin(omega)
        beam = np.zeros((3, len(omega)), float)
        beam[0, :] = 1.
        self.XB = k_to_g(beam, cosomega, sinomega, self.chiwedge)
        self.XS = k_to_g(self.peaks_xyz, cosomega, sinomega, self.chiwedge)


if __name__ == "__main__":
    import sys
    from ImageD11.indexing import ubitocellpars
    o = fittrans(sys.argv[1], sys.argv[2])
    gl = grain.read_grain_file(sys.argv[3])
    gref = gl[0]
    import time
    start = time.time()
    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:
Example #26
0
    def sinogram(self, grain_no, flt_file, grain_file):

        flt = columnfile.columnfile(flt_file)
        grains = grain.read_grain_file(grain_file)
        g = grains[grain_no]

        params = self.reconstructor.params
        self.peak_mapper.map_peaks(flt, grains, params, \
                self.omslop, self.hkltol, self.nmedian, self.rcut,\
                self.ymin, self.ystep, self.number_y_scans)

        distance = params.get('distance')
        pixelsize = (params.get('y_size') + params.get('z_size')) / 2.0
        wavelength = params.get('wavelength')
        cell_original = [
            params.get('cell__a'),
            params.get('cell__b'),
            params.get('cell__c'),
            params.get('cell_alpha'),
            params.get('cell_beta'),
            params.get('cell_gamma')
        ]

        strains, directions, omegas, dtys, weights, tths, etas, intensity, sc, G_omegas, hkl = mc.extract_strain_and_directions(
            cell_original, wavelength, distance, pixelsize, g, flt, self.ymin,
            self.ystep, self.omegastep, self.number_y_scans)

        hkl_eta = np.zeros((hkl.shape[0], 4))
        hkl_eta[:, 0:3] = hkl[:, :]
        hkl_eta[:, 3] = np.sign(etas[:])

        sinogram_strain = np.zeros(
            (int(-2 * (self.ymin / self.ystep)), len(np.unique(hkl_eta,
                                                               axis=0))))
        sinogram_tth = np.zeros(
            (int(-2 * (self.ymin / self.ystep)), len(np.unique(hkl_eta,
                                                               axis=0))))
        sinogram_eta = np.zeros(
            (int(-2 * (self.ymin / self.ystep)), len(np.unique(hkl_eta,
                                                               axis=0))))
        sinogram_int = np.zeros(
            (int(-2 * (self.ymin / self.ystep)), len(np.unique(hkl_eta,
                                                               axis=0))))
        indx = np.argsort(omegas)
        hkl_sorted = hkl_eta[indx, :]
        _, ind = np.unique(hkl_sorted, axis=0, return_index=True)
        miller = hkl_sorted[np.sort(ind), :]

        for (s, o, y, w, I, m, t,
             e) in zip(strains[indx], omegas[indx], dtys[indx], weights[indx],
                       intensity[indx], hkl_sorted, tths[indx], etas[indx]):
            i = int((y + self.ymin) / self.ystep)
            #j = (np.min( np.abs(omega_range-o) )==np.abs(omega_range-o))
            j = np.where((miller == m).all(axis=1))[0]
            assert len(j) == 1
            #print( np.unique(hkl[indx,:],axis=0) )
            #print(o,j,miller)

            sinogram_int[i, j] = I
            sinogram_strain[i, j] = s * w
            sinogram_tth[i, j] = t
            print(t)
            sinogram_eta[i, j] = e

        #TODO: Morivate why we do this.. ask Jon...
        #      make sinograms for tth shifts, eta shifts and strain
        #      make script to generate data of reconstructed slice.
        #      put all resulting nine sinograms in the paper.

        sinogram_int = sinogram_int / np.max(sinogram_int, axis=0)
        sino_mask = sinogram_int > 0.2
        sinogram_strain = sinogram_strain * sino_mask
        sinogram_tth = sinogram_tth * sino_mask
        sinogram_eta = sinogram_eta * sino_mask

        #Relative deviation from reflection mean value
        m = np.sum(sinogram_tth, axis=0) / np.sum(sino_mask, axis=0)
        mean_tth = np.tile(m, (sinogram_tth.shape[0], 1))
        print(mean_tth)
        sinogram_tth = sinogram_tth - mean_tth

        m = np.sum(sinogram_eta, axis=0) / np.sum(sino_mask, axis=0)
        mean_eta = np.tile(m, (sinogram_eta.shape[0], 1))
        sinogram_eta = sinogram_eta - mean_eta

        m = np.sum(sinogram_strain, axis=0) / np.sum(sino_mask, axis=0)
        mean_strain = np.tile(m, (sinogram_strain.shape[0], 1))
        sinogram_strain = sinogram_strain - mean_strain

        sinogram_tth[~sino_mask] = np.nan
        sinogram_eta[~sino_mask] = np.nan
        sinogram_strain[~sino_mask] = np.nan

        s = 20
        t = 15
        plt.figure(1)
        plt.imshow(sinogram_int.T)
        plt.xlabel(r'sample y-translation', size=s)
        plt.ylabel(r'Miller reflections (sorted by $\omega$)', size=s)
        plt.title(r'Intensity', size=s)
        c1 = plt.colorbar()
        c1.ax.tick_params(labelsize=t)
        plt.tick_params(labelsize=t)

        plt.figure(2)
        plt.imshow(sinogram_strain.T)
        plt.xlabel(r'sample y-translation', size=s)
        plt.ylabel(r'Miller reflections (sorted by $\omega$)', size=s)
        plt.title(r'Shift in strain $\varepsilon_m$', size=s)
        c2 = plt.colorbar()
        c2.ax.tick_params(labelsize=t)
        plt.tick_params(labelsize=t)

        plt.figure(3)
        plt.imshow(sinogram_tth.T)
        plt.xlabel(r'sample y-translation', size=s)
        plt.ylabel(r'Miller reflections (sorted by $\omega$)', size=s)
        plt.title(r'Shift in $2\theta$', size=s)
        c3 = plt.colorbar()
        c3.ax.tick_params(labelsize=t)
        plt.tick_params(labelsize=t)

        plt.figure(4)
        plt.imshow(sinogram_eta.T)
        plt.xlabel(r'sample y-translation', size=s)
        plt.ylabel(r'Miller reflections (sorted by $\omega$)', size=s)
        plt.title(r'Shift in $\eta$', size=s)
        c4 = plt.colorbar()
        c4.ax.tick_params(labelsize=t)
        plt.tick_params(labelsize=t)

        plt.show()
Example #27
0
symmetry = sys.argv[1]
grp = getattr(sym_u, symmetry)()
ubifile = sys.argv[2]
uniqfile = sys.argv[3]

if ubifile[-3:] == "flt":
    c = columnfile.columnfile(ubifile)
    print("Got c.nrows", c.nrows)
    ubis = np.zeros((c.nrows, 3, 3), np.float)
    for i in range(3):
        for j in range(3):
            ubis[:, i, j] = c.getcolumn("UBI%d%d" % (i, j))
    del c
else:
    c = grain.read_grain_file(ubifile)
    ubis = np.array([g.ubi for g in c])
    del c

ubis.shape = len(ubis), 9

# First is to cluster without symmetry


def removeone(ubis, testubi, tol=None):
    diffs = abs(ubis - testubi).sum(axis=1)
    if tol is None:
        pl.hist(diffs, bins=1024)
        pl.show()
        tol = float(input("Tolerance?"))
    matching = diffs < tol
def fitallgrains( gfile, pfile, cfile, ngrains = None):
    colfile = loadcolfile( cfile )
    grains = read_grain_file( gfile )
    pars = read_par_file( pfile )

    variables = [ 't_x','t_y', 't_z', 'y_center',  'tilt_y', 'tilt_z',
                       'tilt_x',  'distance', 'wedge']
    pfitted = []
    grs = []
    cfs = []
    if ngrains is None:
        ng = len(grains)
    else:
        ng = ngrains
    
    for i in range(ng):
        print "***",i,
        gr = grains[i]
        cf = assignpeaks( gr, pars, colfile, tol = 0.02 )
        cfs.append(cf)
        grs.append(gr)
    pi = parameters( **pars.parameters )
    refpars = fitmanygrains( cfs, grs, pi, variables )
    for i in range(3):
        refpars = fitmanygrains( cfs, grs, refpars, variables )

    if 0:
        pi = parameters( **pars.parameters )
        pi.set('t_x', gr.translation[0])
        pi.set('t_y', gr.translation[1])
        pi.set('t_z', gr.translation[2])
        diff, Ddiff = fitgrainfunc( cf, gr, pi, variables )
        print "%.5g"%((diff*diff).ravel().sum()),
        gr, pfit = fitgrain( cf, gr, pi, variables, quiet=True )
        grains[i] = gr
        pfitted.append( pfit )
        diff, Ddiff = fitgrainfunc( cf, gr, pfit, variables )
        print "%.5g"%((diff*diff).ravel().sum())

        if 0:
            v = Ddiff.keys()
            for v in ['y_center', 'distance']:
                pylab.figure(1)
                pylab.title("Versus omega")
                pylab.plot( cf.omega, project_diff_on_variable( diff, v, Ddiff) , ",", label=v) 
                pylab.figure(2)
                pylab.title("Versus fc")
                pylab.plot( cf.fc, project_diff_on_variable( diff, v, Ddiff) , ",", label=v) 
                pylab.figure(3)
                pylab.title("Versus sc")
                pylab.plot( cf.sc, project_diff_on_variable( diff, v, Ddiff) , ",", label=v) 
                pylab.figure(4)
                pylab.title("Versus sigo")
                pylab.plot( cf.sigo, project_diff_on_variable( diff, v, Ddiff) , ",", label=v)    
                pylab.legend()
                pylab.show()
                raw_input()



    write_grain_file( gfile+".fit", grains)
Example #29
0
from ImageD11 import parameters as ip
import sys
import numpy as n
from string import split
from xfab import tools
from six.moves import range

if len(sys.argv) < 4:
    print("\n")
    print("########################################################")
    print("Usage:")
    print("ubi_to_gff.py input.ubi detector.par output.gff")
    print("########################################################")
    print("\n")

list_of_grains = ig.read_grain_file(sys.argv[1])
p = ip.parameters()
p.loadparameters(sys.argv[2])
uc = [
    p.parameters['cell__a'], p.parameters['cell__b'], p.parameters['cell__c'],
    p.parameters['cell_alpha'], p.parameters['cell_beta'],
    p.parameters['cell_gamma']
]
print(uc)

grainno = []
x = []
y = []
z = []
rodx = []
rody = []
Example #30
0
symmetry = sys.argv[2]
angtol = float(sys.argv[3])

symnum = {
    "triclinic": 1,
    "monoclinic": 2,
    "orthorhombic": 3,
    "tetragonal": 4,
    "trigonal": 5,
    "hexagonal": 6,
    "cubic": 7
}[symmetry]

h = getattr(sym_u, symmetry)()  # cubic()

gl = grain.read_grain_file(ubifl)

pks = list(
    set([
        tuple(np.dot(o, hkl)) for o in h.group for hkl in [
            (1, 0, 0),
            (1, 1, 0),
            (1, 1, 1),
            (2, 1, 0),
            (2, 1, 1),
            (3, 2, 1),
        ]
    ]))
frids = []
for h, k, l in pks:
    if (h <= 0) and (k <= 0) and (l <= 0) and (-h, -k, -l) in pks:
Example #31
0
from __future__ import print_function

from ImageD11 import sym_u
from ImageD11 import grain
import sys, numpy as np, xfab.tools

print("# Usage: %s grains1.map grains2.map group angletol  distancetol" %
      (sys.argv[0]))
print("# Matches grains using symmetry group from:  ")
print(
    "#  [cubic|hexagonal|trigonal|rhombohedralP|tetragonal|orthorhombic|monoclinic_[a|b|c]|triclinic]"
)

g1l = grain.read_grain_file(sys.argv[1])
g2l = grain.read_grain_file(sys.argv[2])
for g in g1l + g2l:
    if g.translation is None:
        g.translation = np.zeros(3)
try:
    h = getattr(sym_u, sys.argv[3])()
except:
    print("# No group!")
    print("#Using cubic")
    h = sym_u.cubic()
print("# Symmetry considered")
for o in h.group:
    print(o)

try:
    tolangle = float(sys.argv[4])
except:
    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


if __name__ == "__main__":
    grains = grain.read_grain_file(sys.argv[1])
    pars = parameters.read_par_file(sys.argv[2])
    detector_size = (2048, 2048)
    spline = sys.argv[3]
    if spline == "perfect":
        spatial = blobcorrector.perfect()
    else:
        spatial = blobcorrector.correctorclass(spline)
    outfile = sys.argv[4]
    tthmax, dsmax = tth_ds_max(pars, detector_size)
    print(
        "# id   h   k   l    tth       eta      omega     sc       fc     s_raw    f_raw"
    )
    peaks = []
    for gid, gr in enumerate(grains):
        newpeaks = forwards_project(gr, pars, detector_size, spatial, dsmax,