Example #1
0
 def test_getParser(self):
     """Test passing of eps keyword argument by getParser function.
     """
     pcif = getParser('cif', eps=1e-6)
     grph = pcif.parseFile(self.graphiteciffile)
     self.assertEqual(8, len(grph))
     self.assertTrue(all(a.label.startswith('C1') for a in grph[:2]))
     self.assertTrue(all(a.label.startswith('C2') for a in grph[2:]))
     pcif2 = getParser('cif')
     grph2 = pcif2.parseFile(self.graphiteciffile)
     self.assertEqual(4, len(grph2))
     return
Example #2
0
    def _wrapParseMethod(self, method, *args, **kwargs):
        """A helper evaluator method.  Try the specified parse method with
        each registered structure parser and return the first successful
        resul.  Structure parsers that match structure file extension are
        tried first.

        Set format attribute to the detected file format.
        Return Structure instance, or raise StructureFormatError.
        """
        from diffpy.Structure.Parsers import getParser
        ofmts = self._getOrderedFormats()
        stru = None
        # try all parsers in sequence
        parsers_emsgs = []
        for fmt in ofmts:
            p = getParser(fmt)
            try:
                pmethod = getattr(p, method)
                stru = pmethod(*args, **kwargs)
                self.format = fmt
                break
            except StructureFormatError, err:
                parsers_emsgs.append("%s: %s" % (fmt, err))
            except NotImplementedError:
                pass
Example #3
0
    def read(self, filename, format='auto'):
        """Load structure from a file, any original data become lost.

        filename -- file to be loaded
        format   -- all structure formats are defined in Parsers submodule,
                    when format == 'auto' all Parsers are tried one by one

        Return instance of data Parser used to process file.  This
        can be inspected for information related to particular format.
        """
        import diffpy.Structure
        import diffpy.Structure.Parsers
        getParser = diffpy.Structure.Parsers.getParser
        p = getParser(format)
        new_structure = p.parseFile(filename)
        # reinitialize data after successful parsing
        # avoid calling __init__ from a derived class
        Structure.__init__(self)
        if new_structure is not None:
            self.__dict__.update(new_structure.__dict__)
            self[:] = new_structure
        if not self.title:
            import os.path
            tailname = os.path.basename(filename)
            tailbase = os.path.splitext(tailname)[0]
            self.title = tailbase
        return p
Example #4
0
    def read(self, filename, format='auto'):
        """Load structure from a file, any original data become lost.

        filename -- file to be loaded
        format   -- all structure formats are defined in Parsers submodule,
                    when format == 'auto' all Parsers are tried one by one

        Return instance of data Parser used to process file.  This
        can be inspected for information related to particular format.
        """
        import diffpy.Structure
        import diffpy.Structure.Parsers
        getParser = diffpy.Structure.Parsers.getParser
        p = getParser(format)
        new_structure = p.parseFile(filename)
        # reinitialize data after successful parsing
        # avoid calling __init__ from a derived class
        Structure.__init__(self)
        if new_structure is not None:
            self.__dict__.update(new_structure.__dict__)
            self[:] = new_structure
        if not self.title:
            import os.path
            tailname = os.path.basename(filename)
            tailbase = os.path.splitext(tailname)[0]
            self.title = tailbase
        return p
Example #5
0
    def _wrapParseMethod(self, method, *args, **kwargs):
        """A helper evaluator method.  Try the specified parse method with
        each registered structure parser and return the first successful
        resul.  Structure parsers that match structure file extension are
        tried first.

        Set format attribute to the detected file format.
        Return Structure instance, or raise StructureFormatError.
        """
        from diffpy.Structure.Parsers import getParser
        ofmts = self._getOrderedFormats()
        stru = None
        # try all parsers in sequence
        parsers_emsgs = []
        for fmt in ofmts:
            p = getParser(fmt)
            try:
                pmethod = getattr(p, method)
                stru = pmethod(*args, **kwargs)
                self.format = fmt
                break
            except StructureFormatError, err:
                parsers_emsgs.append("%s: %s" % (fmt, err))
            except NotImplementedError:
                pass
Example #6
0
def parse_cif_upload(content):
    content_type, content_string = content.split(',')
    decoded = base64.b64decode(content_string)

    cif_s = decoded.decode('utf-8')
    p = getParser('cif')
    struc = p.parse(cif_s)
    struc.sg = p.spacegroup
    return struc
Example #7
0
    def writeStr(self, format):
        """return string representation of the structure in specified format

        Note: available structure formats can be obtained by:
            from Parsers import formats
        """
        from diffpy.Structure.Parsers import getParser
        p = getParser(format)
        s = p.tostring(self)
        return s
Example #8
0
    def writeStr(self, format):
        """return string representation of the structure in specified format

        Note: available structure formats can be obtained by:
            from Parsers import formats
        """
        from diffpy.Structure.Parsers import getParser
        p = getParser(format)
        s = p.tostring(self)
        return s
Example #9
0
def loadCif(path):
    """load CIF file from given path to create a Structure instance
    """
    if sys.version_info[0] < 3:
        from diffpy.Structure.Parsers import getParser
    else:
        from diffpy.structure.parsers import getParser
    p = getParser('cif')
    nacl = p.parseFile(path)
    nacl.sg = p.spacegroup
    return nacl
Example #10
0
def loadStructure(filename, fmt='auto'):
    """Load a new structure from a specified file.

    filename -- file to be loaded
    fmt      -- format of the structure file.  Must be one of the formats
                defined in the Parsers subpackage.  When 'auto', all
                Parsers are tried in sequence.

    Return a new Structure object.
    Return PDFFitStructure object for 'pdffit' or 'discus' formats.
    """
    from diffpy.Structure.Parsers import getParser
    p = getParser(fmt)
    rv = p.parseFile(filename)
    return rv
Example #11
0
def loadStructure(filename, fmt='auto'):
    """Load a new structure from a specified file.

    filename -- file to be loaded
    fmt      -- format of the structure file.  Must be one of the formats
                defined in the Parsers subpackage.  When 'auto', all
                Parsers are tried in sequence.

    Return a new Structure object. 
    Return PDFFitStructure object for 'pdffit' or 'discus' formats.
    """
    from diffpy.Structure.Parsers import getParser
    p = getParser(fmt)
    rv = p.parseFile(filename)
    return rv
Example #12
0
    def write(self, filename, format):
        """Save structure to file in the specified format

        No return value.

        Note: available structure formats can be obtained by:
            from Parsers import formats
        """
        from diffpy.Structure.Parsers import getParser
        p = getParser(format)
        p.filename = filename
        s = p.tostring(self)
        f = open(filename, 'wb')
        f.write(s)
        f.close()
        return
Example #13
0
    def write(self, filename, format):
        """Save structure to file in the specified format

        No return value.

        Note: available structure formats can be obtained by:
            from Parsers import formats
        """
        from diffpy.Structure.Parsers import getParser
        p = getParser(format)
        p.filename = filename
        s = p.tostring(self)
        f = open(filename, 'wb')
        f.write(s)
        f.close()
        return
Example #14
0
def _loadStructure(path, sample):
    "load crystal structure from path and save info in `sample`"
    ext = os.path.splitext(path)[-1][1:]
    from diffpy.Structure.Parsers import getParser
    p = getParser(ext)
    sample.atomic_structure = structure = p.parseFile(path)
    assert not hasattr(sample, 'chemical_formula')
    assert not hasattr(sample, 'lattice')
    atoms = [atom.element for atom in structure]
    from collections import Counter
    atoms_counter = Counter(atoms)
    sample.chemical_formula = ''.join('%s%s' % (a, n) for a,n in atoms_counter.items())
    class Lattice: pass
    lattice = sample.lattice = Lattice()
    sl = structure.lattice
    lattice.constants = sl.a, sl.b, sl.c, sl.alpha, sl.beta, sl.gamma
    lattice.basis_vectors = sl.base
    return sample
Example #15
0
    def readStr(self, s, format='auto'):
        """Load structure from a string, any original data become lost.

        s        -- string with structure definition
        format   -- all structure formats are defined in Parsers submodule,
                    when format == 'auto' all Parsers are tried one by one

        Return instance of data Parser used to process input string.  This
        can be inspected for information related to particular format.
        """
        from diffpy.Structure.Parsers import getParser
        p = getParser(format)
        new_structure = p.parse(s)
        # reinitialize data after successful parsing
        # avoid calling __init__ from a derived class
        Structure.__init__(self)
        if new_structure is not None:
            self.__dict__.update(new_structure.__dict__)
            self[:] = new_structure
        return p
Example #16
0
    def readStr(self, s, format='auto'):
        """Load structure from a string, any original data become lost.

        s        -- string with structure definition
        format   -- all structure formats are defined in Parsers submodule,
                    when format == 'auto' all Parsers are tried one by one

        Return instance of data Parser used to process input string.  This
        can be inspected for information related to particular format.
        """
        from diffpy.Structure.Parsers import getParser
        p = getParser(format)
        new_structure = p.parse(s)
        # reinitialize data after successful parsing
        # avoid calling __init__ from a derived class
        Structure.__init__(self)
        if new_structure is not None:
            self.__dict__.update(new_structure.__dict__)
            self[:] = new_structure
        return p
Example #17
0
    def exportStru(self, filename, format='cif', stype='diffpy'):
        '''
        Save structure to file in the specified format
        
        :param filename: str, name of the file
        :param stype: str, the type of stru file to export
        
        :return: None

        Note: available structure formats can be obtained by:
            from Parsers import formats
        '''
        from diffpy.Structure.Parsers import getParser
        p = getParser(format)
        p.filename = filename
        stru = self.convertStru(stype)
        s = p.tostring(stru)
        f = open(filename, 'wb')
        f.write(s)
        f.close()
        return
Example #18
0
def slice(crystal, phonon, start, end, npts, cartesian, outhist, eaxis):
    "Given phonon data in IDF format, compute slice of SQE data along a specific reciprocal space direction"
    # phonon is the path to a directory with IDF phonon data

    # read phonon data
    from mccomponents.sample.phonon import periodicdispersion_fromidf as pd
    import mcni, numpy as np
    disp = pd(phonon)
    # and construct a proxy to the c++ data object
    import mccomponents.homogeneous_scatterer as mh
    cdisp = mh.scattererEngine(disp)
    # create Q array
    start = np.array(start)
    end = np.array(end)
    step = (end - start) / npts
    Qs = start + step * np.arange(0, npts, 1.)[:, np.newaxis]
    # Qs: cartesian, hkls: miller indexes
    import os
    reci_basis = recibasis_fromQgridinfo(os.path.join(phonon, 'Qgridinfo'))
    inv_reci_basis = np.linalg.inv(reci_basis)
    if cartesian:
        hkls = np.dot(Qs, inv_reci_basis)
        # these vectors will be used later in method Qtox
        start = np.dot(start, inv_reci_basis)
        step = np.dot(step, inv_reci_basis)
        end = np.dot(end, inv_reci_basis)
    else:
        hkls = Qs
        Qs = np.dot(hkls, reci_basis)
    # gather energies and polarizations
    nQ = len(Qs)
    nbr = disp.dispersion.nBranches
    natoms = disp.dispersion.nAtoms
    # energies
    Es = [cdisp.energy(br, mcni.vector3(*Q)) for Q in Qs for br in range(nbr)]
    Es = np.array(Es)
    Es.shape = nQ, nbr
    # polarizations
    pols = [
        np.array(cdisp.polarization(br, atom, mcni.vector3(*Q))) for Q in Qs
        for br in range(nbr) for atom in range(natoms)
    ]
    pols = np.array(pols)
    pols.shape = nQ, nbr, natoms, 3

    # get atom positions from crystal structure file
    from diffpy.Structure.Parsers import getParser
    parser = getParser(os.path.splitext(crystal)[-1][1:])
    structure = parser.parseFile(crystal)
    atom_positions = [atom.xyz for atom in structure]
    # create "events" for later histogramming process to construct slice
    events = computeEvents(hkls, Es, pols, atom_positions, reci_basis)
    # for x axis of the histogram (along Q)
    maxx = np.linalg.norm(end - start)
    xaxis = 0, maxx, maxx / npts
    # Eaxis = 0, np.max(Es) * 1.1, 1.
    Eaxis = eaxis
    # functor to convert hkl to "x" value
    from distutils.version import LooseVersion

    def Qtox(hkl):
        if LooseVersion(np.__version__) >= LooseVersion("1.8"):
            x = np.linalg.norm(hkl - start, axis=-1)
        else:
            x = np.array(map(np.linalg.norm, hkl - start))
        mask = x == x
        return x, mask

    # histogramming
    h = makeSlice(events, xaxis, Eaxis, Qtox)
    # output
    import histogram.hdf as hh
    hh.dump(h, outhist)
    return
Example #19
0
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

from diffpy.mpdf import *
from diffpy.Structure.Parsers import getParser
from diffpy.srfit.pdf import PDFGenerator, PDFParser
from diffpy.srfit.fitbase import FitRecipe, FitResults
from diffpy.srfit.fitbase import Profile, FitContribution

# Files containing our experimental data and structure file
dataFile = "npdf_07334.gr"
structureFile = "MnO_R-3m.cif"

# load structure and space group from the CIF file
pcif = getParser('cif')
mno = pcif.parseFile(structureFile)

# prepare profile object with experimental data
profile = Profile()
parser = PDFParser()
parser.parseFile(dataFile)
profile.loadParsedData(parser)

# define range for pdf calculation
rmin = 0.01
rmax = 20
rstep = 0.01

# setup calculation range for the PDF simulation
profile.setCalculationRange(xmin=rmin, xmax=rmax, dx=rstep)
def ciffile2unitcell(filename):
    from diffpy.Structure.Parsers import getParser
    p = getParser('cif')
    return p.parseFile(filename)
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize.minpack import leastsq

from diffpy.magpdf import *
from diffpy.Structure.Parsers import getParser
from diffpy.srfit.pdf import PDFGenerator, PDFParser
from diffpy.srfit.fitbase import FitRecipe, FitResults
from diffpy.srfit.fitbase import Profile, FitContribution

# Files containing our experimental data and structure file
dataFile = "npdf_07334.gr"
structureFile = "MnO_R-3m.cif"

# load structure and space group from the CIF file
pcif = getParser('cif')
mno = pcif.parseFile(structureFile)

# prepare profile object with experimental data
profile = Profile()
parser = PDFParser()
parser.parseFile(dataFile)
profile.loadParsedData(parser)

# define range for pdf calculation
rmin = 0.01
rmax = 20
rstep = 0.01

# setup calculation range for the PDF simulation
profile.setCalculationRange(xmin=rmin, xmax=rmax, dx=rstep)
Example #22
0
def ciffile2unitcell(filename):
    from diffpy.Structure.Parsers import getParser
    p = getParser('cif')
    return p.parseFile(filename)