Beispiel #1
0
 def __init__(self, filename=None, new=False):
     self.filename = filename
     self.bigarray = None
     self.titles = []
     if filename is not None:
         self.parameters = parameters.parameters(filename=filename)
     else:
         self.parameters = parameters.parameters()
     self.ncols = 0
     self.nrows = 0
     if not new:
         self.readfile(filename)
Beispiel #2
0
    def __init__(self,
                 unitcell=None,
                 gv=None,
                 cosine_tol=0.002,
                 minpks=10,
                 hkl_tol=0.01,
                 ring_1=1,
                 ring_2=2,
                 ds_tol=0.005,
                 wavelength=-1,
                 uniqueness=0.5,
                 eta_range=0.,
                 max_grains=100):
        """
        Unitcell would be a unitcell object for generating hkls peaks
        gv would be a 3*n array of points in reciprocal space
        The rest of the arguments are parameters.
        """
        self.unitcell = unitcell
        self.gv = gv
        if gv is not None:  # do init
            print('gv:', gv, gv.shape, gv.dtype)
            assert gv.shape[1] == 3
            self.gv = gv.astype(np.float)
            self.ds = np.sqrt((gv * gv).sum(axis=1))
            self.ga = np.zeros(len(self.ds), np.int32) - 1  # Grain assignments
            self.gvflat = np.ascontiguousarray(gv, np.float)
            self.wedge = 0.0  # Default

        self.cosine_tol = cosine_tol
        self.wavelength = wavelength
        self.hkl_tol = hkl_tol
        self.ring_1 = ring_1
        self.ring_2 = ring_2
        self.uniqueness = uniqueness
        self.minpks = minpks
        self.ds_tol = ds_tol
        self.max_grains = max_grains
        self.eta_range = eta_range
        self.ubis = []
        self.scores = []

        # it would make more sense to inherit the parameter object - will
        # have to think about this some more - how general is it?
        from ImageD11 import parameters
        self.parameterobj = parameters.parameters(cosine_tol=self.cosine_tol,
                                                  hkl_tol=self.hkl_tol,
                                                  ring_1=self.ring_1,
                                                  ring_2=self.ring_2,
                                                  minpks=self.minpks,
                                                  uniqueness=self.uniqueness,
                                                  ds_tol=self.ds_tol,
                                                  wavelength=self.wavelength,
                                                  eta_range=self.eta_range,
                                                  max_grains=self.max_grains)

        # Add a resetting functionality, adapted from
        # stackoverflow.com/questions/4866587/pythonic-way-to-reset-an-objects-variables
        import copy
        self.__pristine_dict = copy.deepcopy(self.__dict__)
Beispiel #3
0
    def __init__(self,
                 tolerance=0.01,
                 intensity_tth_range=(6.1, 6.3),
                 latticesymmetry=triclinic,
                 OmFloat=True,
                 OmSlop=0.25):
        """

        """
        self.OMEGA_FLOAT = OmFloat
        self.slop = OmSlop
        if self.OMEGA_FLOAT:
            print("Using", self.slop, "degree slop")
        else:
            print("Omega is used as observed")
        self.tolerance = tolerance
        # list of ubi matrices (1 for each grain in each scan)
        self.grainnames = []
        self.ubisread = {}
        self.translationsread = {}
        # list of scans and corresponding data
        self.scannames = []
        self.scantitles = {}
        self.scandata = {}
        # grains in each scan
        self.grains = {}
        self.grains_to_refine = []
        self.latticesymmetry = latticesymmetry
        # ?
        self.drlv = None
        self.parameterobj = parameters.parameters(**self.pars)
        self.intensity_tth_range = intensity_tth_range
        self.recompute_xlylzl = False
        for k, s in list(self.stepsizes.items()):
            self.parameterobj.stepsizes[k] = s
Beispiel #4
0
 def rdpars(self, parfile=None):
     if parfile == None:
         parfile = tkFileDialog.askopenfilename(initialdir=os.getcwd())
     from ImageD11 import parameters
     o = parameters.parameters()
     o.loadparameters(parfile)
     self.parameters = o.parameters
Beispiel #5
0
def make_powder_mask( parfile,
                      ndeg = 1,
                      splinefile=None,
                      dims=(2048, 2048) ):
    """
    Compute a two theta and azimuth image
    """
    pars = parameters.parameters()
    pars.loadparameters( parfile )
    if splinefile is None:
        spatial = blobcorrector.perfect()
    else:
        spatial = blobcorrector.correctorclass( splinefile )
    xim, yim = spatial.make_pixel_lut ( dims )
    peaks = [ np.ravel( xim ) , np.ravel( yim ) ]
    tth , eta = transform.compute_tth_eta( peaks , **pars.get_parameters() )
    tth.shape = dims
    eta.shape = dims
    # Assume a circle geometry for now
    # tth * eta ~ length on detector
    # lim = tth * eta
    # need some idea how to cut it up...
    #  degree bins
    m =  (eta.astype(np.int) % 2)==0
    return m
Beispiel #6
0
 def setUp(self):
     npk = 10240
     self.sc = np.random.random(npk) * 2048
     self.fc = np.random.random(npk) * 2048
     self.pars = parameters.parameters()
     self.pars.set('z_center', 980.)
     self.pars.set('y_center', 1010.)
     self.pars.set('z_size', 48.)
     self.pars.set('y_size', 49.)
     self.pars.set('distance', 100100.)
Beispiel #7
0
 def copy(self):
     """
     Returns a (deep) copy of the columnfile
     """
     cnw = columnfile(self.filename, new=True)
     self.chkarray()
     cnw.titles = [t for t in self.titles]
     cnw.parameters = parameters.parameters(**self.parameters.parameters)
     cnw.bigarray = [col.copy() for col in self.__data]
     cnw.set_attributes()
     return cnw
Beispiel #8
0
 def readfile(self, filename):
     """
     Reads in an ascii columned file
     """
     self.titles = []
     self.bigarray = None
     self.parameters = parameters.parameters(filename=filename)
     self.ncols = 0
     self.nrows = 0
     i = 0
     # Check if this is a hdf file: magic number
     with open(filename, "rb") as f:
         magic = f.read(4)
     #              1 2 3 4 bytes
     if magic == b'\x89HDF':
         print("Reading your columnfile in hdf format")
         colfile_from_hdf(filename, obj=self)
         return
     with open(filename, "r") as f:
         raw = f.readlines()
     header = True
     while header and i < len(raw):
         if len(raw[i].lstrip()) == 0:
             # skip blank lines
             i += 1
             continue
         if raw[i][0] == "#":
             # title line
             if raw[i].find("=") > -1:
                 # key = value line
                 name, value = clean(raw[i][1:].split("="))
                 self.parameters.addpar(parameters.par(name, value))
             else:
                 self.titles = raw[i][1:].split()
             i += 1
         else:
             header = False
     try:
         row0 = [float(v) for v in raw[i].split()]
         lastrow = [float(v) for v in raw[-1].split()]
         if len(row0) == len(lastrow):
             nrows = len(raw) - i
             last = None
         else:
             nrows = len(raw) - i - 1  # skip the last row
             last = -1
         self.bigarray = np.zeros((len(row0), nrows), np.float)
         for i, line in enumerate(raw[i:last]):
             self.bigarray[:, i] = [float(v) for v in line.split()]
     except:
         raise Exception("Problem interpreting your colfile")
     (self.ncols, self.nrows) = self.bigarray.shape
     self.parameters.dumbtypecheck()
     self.set_attributes()
Beispiel #9
0
    def __init__(self,
                 unitcell=None,
                 gv=None,
                 cosine_tol=0.002,
                 minpks=10,
                 hkl_tol=0.01,
                 ring_1=1,
                 ring_2=2,
                 ds_tol=0.005,
                 wavelength=-1,
                 uniqueness=0.5,
                 eta_range=0.,
                 max_grains=100):
        """
        Unitcell would be a unitcell object for generating hkls peaks
        gv would be a 3*n array of points in reciprocal space
        The rest of the arguments are parameters.
        """
        self.unitcell = unitcell
        self.gv = gv
        if gv is not None:
            print 'gv:', gv, gv.shape, gv.dtype
        self.wedge = 0.0  # Default
        if gv != None:
            self.gvflat = np.ascontiguousarray(gv, 'd')
            # Makes it contiguous in memory, hkl fast index

        self.cosine_tol = cosine_tol
        self.wavelength = wavelength
        self.hkl_tol = hkl_tol
        self.ring_1 = ring_1
        self.ring_2 = ring_2
        self.uniqueness = uniqueness
        self.minpks = minpks
        self.ds_tol = ds_tol
        self.max_grains = max_grains
        self.eta_range = eta_range
        self.ubis = []
        self.scores = []

        # it would make more sense to inherit the parameter object - will
        # have to think about this some more - how general is it?
        from ImageD11 import parameters
        self.parameterobj = parameters.parameters(cosine_tol=self.cosine_tol,
                                                  hkl_tol=self.hkl_tol,
                                                  ring_1=self.ring_1,
                                                  ring_2=self.ring_2,
                                                  minpks=self.minpks,
                                                  uniqueness=self.uniqueness,
                                                  ds_tol=self.ds_tol,
                                                  wavelength=self.wavelength,
                                                  eta_range=self.eta_range,
                                                  max_grains=self.max_grains)
Beispiel #10
0
def gridgrains(
    ul,
    flt,
    pars,
    minx=-750,
    maxx=750,
    stepx=25,
    miny=-750,
    maxy=750,
    stepy=25,
    tol=0.05,
):
    trn = transformer.transformer()
    trn.loadfiltered(flt)
    trn.parameterobj = parameters.parameters(**pars)

    peaks = [trn.getcolumn(trn.xname), trn.getcolumn(trn.yname)]
    peaks_xyz = transform.compute_xyz_lab(peaks,
                                          **trn.parameterobj.get_parameters())

    omega = trn.getcolumn(trn.omeganame)
    trn.updateparameters()
    tx = minx - stepx
    n = 0
    sys.stderr.write("Using tol = %f\n" % (tol))
    while tx <= maxx:
        tx = tx + stepx
        ty = miny - stepy
        while ty <= maxy:
            ty = ty + stepy
            trn.parameterobj.set_parameters({'t_x': tx, 't_y': ty})
            pars = trn.parameterobj.get_parameters()
            tth, eta = transform.compute_tth_eta_from_xyz(
                peaks_xyz, omega, **pars)
            if 'omegasign' in pars:
                om_sgn = float(pars["omegasign"])
            else:
                om_sgn = 1.0

            gv = transform.compute_g_vectors(tth, eta, omega * om_sgn, **pars)
            print(tx, ty, end=' ')
            for ubi in ul:
                ns = score(ubi, gv.T, tol)
                print(ns, end=' ')
                n += ns
            print()
    return n
Beispiel #11
0
 def __init__(self, parfile=None, fltfile=None):
     """
     Nothing is passed in
     ...will need to loadfileparameters and also peaks
     """
     self.unitcell = None
     # this sets defaults according to class dict.
     self.parameterobj = parameters()
     for p in PARAMETERS:
         self.parameterobj.addpar(p)
     # Interesting - is this an alias for the dict?
     self.pars = self.parameterobj.get_parameters()
     self.colfile = None
     self.xname = None
     self.yname = None
     self.omeganame = None
     self.theoryds = None
     if parfile is not None:
         self.loadfileparameters(parfile)
     if fltfile is not None:
         self.loadfiltered(fltfile)
Beispiel #12
0
def make_pars(parfile):
    from ImageD11.parameters import parameters
    from ImageD11 import transform
    p = parameters()
    p.loadparameters(parfile)
    rmat = transform.detector_rotation_matrix(float(p.parameters["tilt_x"]),
                                              float(p.parameters["tilt_y"]),
                                              float(p.parameters["tilt_z"]))
    fmat = np.array(
        [[1, 0, 0], [
            0, float(p.parameters['o11']),
            float(p.parameters['o12'])
        ], [0, float(p.parameters['o21']),
            float(p.parameters['o22'])]], np.float32)
    pars = np.array([
        float(p.parameters["y_center"]),
        float(p.parameters["y_size"]),
        float(p.parameters["z_center"]),
        float(p.parameters["z_size"]),
        float(p.parameters["distance"])
    ] + list(np.dot(rmat, fmat).ravel()), np.float32)
    return pars
Beispiel #13
0
    def __init__(self, splinefile=None, parfile=None):
        """
        splinefile = fit2d spline file, or None for images
        that are already corrected

        parfile = ImageD11 parameter file. Can be fitted
        using old ImageD11_gui.py or newer fable.transform
        plugin.
        """
        self.splinefile = splinefile

        if self.splinefile is None:
            self.spatial = blobcorrector.perfect()
        else:
            self.spatial = blobcorrector.correctorclass(splinefile)

        self.parfile = parfile
        self.pars = parameters.parameters()
        self.pars.loadparameters(parfile)
        for key in self.required_pars:

            if key not in self.pars.parameters:
                raise Exception("Missing parameter " + str(par))
Beispiel #14
0
import sys
from ImageD11.columnfile import columnfile
from ImageD11.parameters import parameters
from ImageD11.transform import compute_xyz_lab, detector_rotation_matrix
import cImageD11_wrap

import numpy as np, time

start = time.time()
c = columnfile(sys.argv[1])
p = parameters()
p.loadparameters(sys.argv[2])

try:
    pks = [c.sc, c.fc]
except:
    pks = [c.xc, c.yc]

testtilts = [-0.5, 0., 0.24]

tilts = [(x, y, z) for x in testtilts for y in testtilts for z in testtilts]
pars = np.array(
    (p.get("z_center"), p.get("y_center"), p.get("z_size"), p.get("y_size")))
dist = np.array((p.get("distance"), 0., 0.))

for o11, o12, o21, o22 in [[1, 0, 0, 1], [-1, 0, 0, 1], [-1, 0, 0, -1],
                           [1, 0, 0, -1], [0, 1, 1, 0], [0, -1, 1, 0],
                           [0, -1, -1, 0], [0, 1, -1, 0]]:
    for tx, ty, tz in tilts:
        p.parameters['tilt_x'] = tx
        p.parameters['tilt_y'] = ty
Beispiel #15
0
            for ubi in ul:
                ns = score(ubi, gv.T, tol)
                print(ns, end=' ')
                n += ns
            print()
    return n


if __name__ == "__main__":
    flt = sys.argv[1]
    par = sys.argv[2]
    grains = sys.argv[3]

    ul = indexing.readubis(grains)

    po = parameters.parameters()
    po.loadparameters(par)
    pars = po.get_parameters()

    dcen = float(pars["distance"])
    zcen = float(pars["z_center"])
    ycen = float(pars["y_center"])
    f = open("parmap", "a")
    for dist in [dcen * 0.99, dcen, dcen * 1.01]:
        pars["distance"] = dist
        for yc in [ycen - 1, ycen, ycen + 1]:
            pars["y_center"] = yc
            for zc in [zcen - 1, zcen, zcen + 1]:
                pars["z_center"] = zc
                print("\n\n# %f %f %f" % (dist, yc, zc))
                npk = gridgrains(ul, flt, pars)
Beispiel #16
0
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 = []
rodz = []
Beispiel #17
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)
Beispiel #18
0
    def readfile(self, filename):
        """
        Reads in an ascii columned file
        """
        self.titles = []
        self.bigarray = None
        self.parameters = parameters.parameters(filename=filename)
        self.ncols = 0
        self.nrows = 0
        i = 0

        try:
            raw = open(filename, "r").readlines()
        except:
            raise Exception("Cannot open %s for reading" % (filename))
        header = True
        while header and i < len(raw):
            if len(raw[i].lstrip()) == 0:
                # skip blank lines
                i += 1
                continue
            if raw[i][0] == "#":
                # title line
                if raw[i].find("=") > -1:
                    # key = value line
                    name, value = clean(raw[i][1:].split("="))
                    self.parameters.addpar(parameters.par(name, value))
                else:
                    self.titles = raw[i][1:].split()
                i += 1
            else:
                header = False
        try:
            cc = [numpy.fromstring(v, sep=' ') for v in raw[i:]]
            self.bigarray = numpy.array(cc).transpose()
        except:
            raise Exception("Non numeric data on all lines\n")
        (self.ncols, self.nrows) = self.bigarray.shape

        #         data = []
        #         try:
        #             fileobj = open(filename,"r").readlines()
        #         except:
        #             raise Exception("Cannot open %s for reading"%(filename))
        #         for line in fileobj:
        #             i += 1
        #             if len(line.lstrip())==0:
        #                 # skip blank lines
        #                 continue
        #             if line[0] == "#":
        #                 # title line
        #                 if line.find("=") > -1:
        #                     # key = value line
        #                     name, value = clean(line[1:].split("="))
        #                     self.parameters.addpar(
        #                         parameters.par( name, value ) )
        #                 else:
        #                     self.titles = clean(line[1:].split())
        #                     self.ncols = len(self.titles)
        #                 continue
        #             # Assume a data line
        #             try:
        #                 vals = [ float(v) for v in line.split() ]
        #             except:
        #                 raise Exception("Non numeric data on line\n"+line)
        #             if len(vals) != self.ncols:
        #                 raise Exception("Badly formatted column file\n"\
        #                                     "expecting %d columns, got %d\n"\
        #                                     " line %d in file %s"%
        #                                 (self.ncols, len(vals),
        #                                  i, self.filename))
        #             self.nrows += 1
        #             data.append(vals)
        #         self.bigarray = numpy.transpose(numpy.array(data))
        #         if self.nrows > 0:
        #             assert self.bigarray.shape == (self.ncols, self.nrows)
        self.set_attributes()
Beispiel #19
0
##########################################################################
# IMPORT PYTHON PACKAGES
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import math
from xfab import tools
from ImageD11 import parameters
import os
import argparse

import textwrap
from six.moves import range
##########################################################################
myparms = parameters.parameters()

def readparfile(filename):

    myparms.loadparameters(filename)
    omat = np.zeros((2,2))
    if 'cell__a' in myparms.get_parameters().keys():
        a0 = float(myparms.get('cell__a'))
    if 'cell__b' in myparms.get_parameters().keys():
        b0 = float(myparms.get('cell__b'))
    if 'cell__c' in myparms.get_parameters().keys():
        c0 = float(myparms.get('cell__c'))
    if 'cell_alpha' in myparms.get_parameters().keys():
        alpha0 = float(myparms.get('cell_alpha'))
    if 'cell_beta' in myparms.get_parameters().keys():
        beta0 = float(myparms.get('cell_beta'))
Beispiel #20
0
 def readprms(self,prms):
     from ImageD11 import parameters
     o = parameters.parameters()
     o.loadparameters(prms)
     self.pars=o.get_parameters()
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)
Beispiel #22
0
    return flat


if __name__ == "__main__":
    import sys, numpy as np

    from ImageD11.grain import read_grain_file
    from ImageD11.columnfile import columnfile
    from ImageD11.parameters import parameters
    from ImageD11.transform import compute_xyz_lab

    colfile = sys.argv[1]
    grainfile = sys.argv[2]
    parfile = sys.argv[3]

    pars = parameters()
    pars.loadparameters(parfile)

    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))
Beispiel #23
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
Beispiel #24
0
 def __init__(self,
         unitcell=None,
         ubis=None,
         crystal_symmetry=None,
         c11=None,c12=None,c13=None,c14=None,c15=None,c16=None,
         c22=None,c23=None,c24=None,c25=None,c26=None,
         c33=None,c34=None,c35=None,c36=None,
         c44=None,c45=None,c46=None,
         c55=None,c56=None,
         c66=None):
     """
     unitcell would be a list of six elements [a, b, c, alpha, beta, gamma]
     ubis would be a list of orientation matrices as by ImageD11 convention
     symmetry would be isotropic, cubic, tetragonal_high... (see FitAllB.conversion) to form the stiffness tensor C
     The rest of the arguments are parameters.
     """
     
     self.cell__a = None
     self.cell__b = None
     self.cell__c = None
     self.cell_alpha = None
     self.cell_beta = None
     self.cell_gamma = None
     if unitcell is not None:
         if len(unitcell)==6:
             self.cell__a = unitcell[0]
             self.cell__b = unitcell[1]
             self.cell__c = unitcell[2]
             self.cell_alpha = unitcell[3]
             self.cell_beta = unitcell[4]
             self.cell_gamma = unitcell[5]
         else:
             raise Exception("The unit cell must be defined by six parameters!")
     self.ubis=ubis
     self.crystal_symmetry=crystal_symmetry
     self.c11=c11
     self.c12=c12
     self.c13=c13
     self.c14=c14
     self.c15=c15
     self.c16=c16
     self.c22=c22
     self.c23=c23
     self.c24=c24
     self.c25=c25
     self.c26=c26
     self.c33=c33
     self.c34=c34
     self.c35=c35
     self.c36=c36
     self.c44=c44
     self.c45=c45
     self.c46=c46
     self.c55=c55
     self.c56=c56
     self.c66=c66
     self.parameterobj = parameters(cell__a=self.cell__a,
                                    cell__b=self.cell__b,
                                    cell__c=self.cell__c,
                                    cell_alpha=self.cell_alpha,
                                    cell_beta=self.cell_beta,
                                    cell_gamma=self.cell_gamma,                                                 
                                    crystal_symmetry=self.crystal_symmetry,
                                    c11=self.c11,c12=self.c12,c13=self.c13,c14=self.c14,c15=self.c15,c16=self.c16,
                                    c22=self.c22,c23=self.c23,c24=self.c24,c25=self.c25,c26=self.c26,
                                    c33=self.c33,c34=self.c34,c35=self.c35,c36=self.c36,
                                    c44=self.c44,c45=self.c45,c46=self.c46,
                                    c55=self.c55,c56=self.c56,
                                    c66=self.c66)
     self.epsilon=[]
     self.sigma=[]