def make_generator(
        config: GenConfig) -> Union[PDFGenerator, DebyePDFGenerator]:
    """
    Build a generator according to the information in the GenConfig.

    Parameters
    ----------
    config : GenConfig
        A configuration instance for generator building.

    Returns
    -------
    generator: PDFGenerator or DebyePDFGenerator
        A generator built from GenConfig.

    """
    name = config.name
    stru: Structure = loadStructure(config.stru_file)
    ncpu = config.ncpu

    if config.debye:
        generator = DebyePDFGenerator(name)
    else:
        generator = PDFGenerator(name)

    generator.setStructure(stru, periodic=config.periodic)

    if ncpu:
        pool = multiprocessing.Pool(ncpu)
        generator.parallel(ncpu, mapfunc=pool.imap_unordered)
    else:
        pass

    return generator
 def test_discus(self):
     """check loading of discus file format
     """
     f = datafile('Ni-discus.stru')
     stru = loadStructure(f)
     self.assertTrue(type(stru) is PDFFitStructure)
     return
 def test_add_structure(self):
     """check PdfFit.add_structure()
     """
     ni = loadStructure(datafile('Ni.stru'))
     self.P.add_structure(ni)
     self.assertEqual(4, self.P.num_atoms())
     return
 def test_goodkwarg(self):
     """check loading of CIF file and passing of parser keyword argument.
     """
     f = datafile('graphite.cif')
     stru = loadStructure(f, eps=1e-10)
     self.assertEqual(8, len(stru))
     return
 def test_cif(self):
     """check loading of CIF file format
     """
     f = datafile('PbTe.cif')
     stru = loadStructure(f)
     self.assertTrue(isinstance(stru, Structure))
     self.assertFalse(isinstance(stru, PDFFitStructure))
     return
Exemple #6
0
def calc_fs_from_stru_files(*stru_files: str, qa=0) -> List[float]:
    """Calculate the compositional average scattering factor from the structure file."""
    fs = []
    for stru_file in stru_files:
        stru = loadStructure(stru_file)
        f = SFAverage.fromStructure(stru, XTB, qa).f1avg
        fs.append(f)
    return fs
Exemple #7
0
def nisph20():
    from diffpy.structure import Lattice, loadStructure
    from diffpy.structure.tests.testutils import datafile
    from diffpy.structure.expansion.makeellipsoid import makeSphere
    ni = loadStructure(datafile('Ni.stru'), 'pdffit')
    sph = makeSphere(ni, 20 / 2.0)
    sph.placeInLattice(Lattice())
    return sph
 def test_xcfg(self):
     """check loading of atomeye xcfg format
     """
     f = datafile('BubbleRaftShort.xcfg')
     stru = loadStructure(f)
     self.assertTrue(type(stru) is Structure)
     self.assertRaises(StructureFormatError,
             loadStructure, f, 'xyz')
     return
Exemple #9
0
def str_to_atoms(stru_str: str) -> Atoms:
    """Convert the cif files string to an ase.Atoms object."""
    with TemporaryDirectory() as temp_dir:
        cif_file = Path(temp_dir) / "temp.cif"
        cif_file.write_text(stru_str)
        stru = loadStructure(str(cif_file))
        stru.write(str(cif_file), format="cif")
        atoms = ase.io.read(str(cif_file))
    return atoms
Exemple #10
0
def calculate(pdfc, ciffile):
    from diffpy.structure import loadStructure
    lo = 0.5
    symeps = 0.001
    haszeropeak = lambda x: any(x[r < lo] > 0.01 * x.max())
    stru = loadStructure(ciffile, fmt='cif', eps=symeps)
    r, g = pdfc(stru)
    if haszeropeak(g):
        raise RuntimeError("contains near-zero peak")
    return r, g
 def test_uij(self):
     """check PdfFit.uij()
     """
     ni = loadStructure(datafile('Ni.stru'))
     ni[2].anisotropy = True
     ni[2].U11, ni[2].U22, ni[2].U33 = 1, 2, 3
     ni[2].U12, ni[2].U13, ni[2].U23 = 4, 5, 6
     pf = self.P
     pf.add_structure(ni)
     self.assertEqual(1, pf.getvar(pf.u11(3)))
     self.assertEqual(2, pf.getvar(pf.u22(3)))
     self.assertEqual(3, pf.getvar(pf.u33(3)))
     self.assertEqual(4, pf.getvar(pf.u12(3)))
     self.assertEqual(5, pf.getvar(pf.u13(3)))
     self.assertEqual(6, pf.getvar(pf.u23(3)))
     return
Exemple #12
0
 def test_pickling(self):
     "validate PDFContribution.residual() after pickling."
     from itertools import chain
     from diffpy.structure import loadStructure
     pc = self.pc
     pc.loadData(datafile("ni-q27r100-neutron.gr"))
     ni = loadStructure(datafile("ni.cif"))
     ni.Uisoequiv = 0.003
     pc.addStructure('ni', ni)
     pc.setCalculationRange(0, 10)
     pc2 = pickle.loads(pickle.dumps(pc))
     res0 = pc.residual()
     self.assertTrue(numpy.array_equal(res0, pc2.residual()))
     for p in chain(pc.iterPars('Uiso'), pc2.iterPars('Uiso')):
         p.value = 0.004
     res1 = pc.residual()
     self.assertFalse(numpy.allclose(res0, res1))
     self.assertTrue(numpy.array_equal(res1, pc2.residual()))
     return
Exemple #13
0
 def test_pickling(self):
     "validate PDFContribution.residual() after pickling."
     from itertools import chain
     from diffpy.structure import loadStructure
     pc = self.pc
     pc.loadData(datafile("ni-q27r100-neutron.gr"))
     ni = loadStructure(datafile("ni.cif"))
     ni.Uisoequiv = 0.003
     pc.addStructure('ni', ni)
     pc.setCalculationRange(0, 10)
     pc2 = pickle.loads(pickle.dumps(pc))
     res0 = pc.residual()
     self.assertTrue(numpy.array_equal(res0, pc2.residual()))
     for p in chain(pc.iterPars('Uiso'), pc2.iterPars('Uiso')):
         p.value = 0.004
     res1 = pc.residual()
     self.assertFalse(numpy.allclose(res0, res1))
     self.assertTrue(numpy.array_equal(res1, pc2.residual()))
     return
Exemple #14
0
 def test_bto_cubic(self):
     """check standard factory configuration on cubic BaTiO3.
     """
     crst = loadCrystal(self.cifbtoc)
     meta = dict(qmax=26, stype='N')
     recipe = self.factory.make(crst, self.r, self.g, meta=meta)
     self.assertEqual(1, recipe.cpdf.r.value[0])
     self.assertEqual(20, recipe.cpdf.r.value[-1])
     # check the effect of meta entries
     calc = recipe.cpdf.cif._calc
     self.assertEqual(26, calc.qmax)
     self.assertEqual('N', calc.scatteringfactortable.radiationType())
     # should have 4 parameters for B factors, 2 are isotropic
     bnames = [n for n in recipe.names if n.startswith('B')]
     self.assertEqual(4, len(bnames))
     self.assertEqual(2, len([n for n in bnames if n.startswith('Biso')]))
     # test type checking
     stru = loadStructure(self.cifbtoc)
     self.assertRaises(TypeError, self.factory.make,
                       stru, self.r, self.g, meta)
     return
atom_labels = set()

atomTypeSub = {"ALL":"AL","ASL":"AS","BAL":"BL","BIA":"BA",\
                "BIB":"BB","BIM":"BM","HHL":"BL","HHR":"HR",\
                "HWL":"HW","HWR":"HR","PBB":"PB","PBL":"PL",\
                "PBM":"PM","SBL":"SL","TIL":"TL","ZNI":"ZN"}

metals = ["CO", "CU", "FE", "MN", "MO", "NI", "V", "W", "ZN"]

with Bar('Processing', max=369) as bar:
    with open(finalData, "r") as f:
        for line in f.readlines():
            # print(line[:-1])
            fileName = line[:-1]
            if 'Blyth' not in fileName:
                cf = structure.loadStructure(os.path.join(finalDir, fileName))
                cf.assignUniqueLabels

                # print(cf[1].__sizeof__())
                # print(cf.label)
                for i in cf:
                    # print(i.label)
                    i.__setattr__('label',\
                        i.label.upper().replace('_',"").replace("-","").replace("OH","H").replace("(","").replace(")","").replace("WAT","OW").replace(",","").replace(".",""))
                    i.__setattr__('element', i.element.upper())
                    if i.label[0:4] == 'ZNII':
                        i.__setattr__('label', i.label.replace('ZNII', 'ZN'))
                    elif i.label[0:3] in atomTypeSub.keys():
                        i.__setattr__(
                            'label',
                            i.label.replace(i.label[0:3],
Exemple #16
0
NI_PONI = resource_filename('tests', 'test_data/Ni_poni_file.poni')
NI_GR = resource_filename('tests', 'test_data/Ni_gr_file.gr')
NI_CHI = resource_filename('tests', 'test_data/Ni_chi_file.chi')
NI_FGR = resource_filename('tests', 'test_data/Ni_fgr_file.fgr')
NI_IMG = resource_filename('tests', 'test_data/Ni_img_file.tiff')
NI_CIF = resource_filename('tests', 'test_data/Ni_cif_file.cif')
KAPTON_IMG = resource_filename('tests', 'test_data/Kapton_img_file.tiff')
BLACK_IMG = resource_filename('tests', 'test_data/black_img.tiff')
WHITE_IMG = resource_filename('tests', 'test_data/white_img.tiff')
NI_CONFIG = PDFConfig()
NI_CONFIG.readConfig(NI_GR)
NI_PDFGETTER = PDFGetter(NI_CONFIG)
ZRP_CIF = resource_filename('tests', 'test_data/ZrP.cif')
NI_CRYSTAL = loadCrystal(NI_CIF)
ZRP_CRYSTAL = loadCrystal(ZRP_CIF)
NI_DIFFPY = loadStructure(NI_CIF)

DB = {
    'Ni_img_file': NI_IMG,
    'Ni_img': load_img(NI_IMG),
    'Kapton_img_file': KAPTON_IMG,
    'Kapton_img': load_img(KAPTON_IMG),
    'Ni_poni_file': NI_PONI,
    'Ni_gr_file': NI_GR,
    'Ni_chi_file': NI_CHI,
    'Ni_fgr_file': NI_FGR,
    'ai': pyFAI.load(NI_PONI),
    'Ni_gr': load_data(NI_GR).T,
    'Ni_chi': load_data(NI_CHI).T,
    'Ni_fgr': load_data(NI_FGR).T,
    'black_img_file': BLACK_IMG,
import os
from shutil import copyfile

from diffpy.structure import loadStructure

PARENT_DIR = r"Z:\Jeffrey-Ede\crystal_structures\inorganic_no_H\\"
SAVE_LOC = r"Z:\Jeffrey-Ede\crystal_structures\standardized_inorganic_no_H\\"

base_files = os.listdir(PARENT_DIR)
files = [PARENT_DIR + f for f in base_files]

num_files = len(files)
for i, (file, base_file) in enumerate(zip(files, base_files)):
    print(f"File {i} of {num_files}")

    struct = loadStructure(file)
    struct.write(SAVE_LOC + base_file, "cif")
Exemple #18
0
NI_GR = load_array(NI_GR_FILE)
NI_CHI = load_array(NI_CHI_FILE)
NI_FGR = load_array(NI_FGR_FILE)
NI_CONFIG = PDFConfig()
NI_CONFIG.readConfig(NI_GR_FILE)
NI_PDFGETTER = PDFGetter(NI_CONFIG)
AI = pyFAI.load(NI_PONI_FILE)
MASK = numpy.load(MASK_FILE)
BLACK_IMG = load_img(BLACK_IMG_FILE)
WHITE_IMG = load_img(WHITE_IMG_FILE)
# model file
ZRP_CIF_FILE = resource_filename('tests', 'test_data/ZrP_cif_file.cif')
NI_CIF_FILE = resource_filename("tests", "test_data/Ni_cif_file.cif")
NI_CRYSTAL = loadCrystal(NI_CIF_FILE)
ZRP_CRYSTAL = loadCrystal(ZRP_CIF_FILE)
NI_DIFFPY = loadStructure(NI_CIF_FILE)
NI_MOLECULE = Molecule(NI_CRYSTAL)

DB = {
    'Ni_img_file': NI_IMG_FILE,
    'Ni_img': NI_IMG,
    'Kapton_img_file': KAPTON_IMG_FILE,
    'Kapton_img': KAPTON_IMG,
    'Ni_poni_file': NI_PONI_FILE,
    'Ni_gr_file': NI_GR_FILE,
    'Ni_chi_file': NI_CHI_FILE,
    'Ni_fgr_file': NI_FGR_FILE,
    'ai': AI,
    'Ni_gr': NI_GR,
    'Ni_chi': NI_CHI,
    'Ni_fgr': NI_FGR,
Exemple #19
0
def diff_read_cif(filename):

    from diffpy import structure
    # print(help(Structure))

    return (structure.loadStructure(filename))
# coding: utf-8

"Show SAS simulation for 20A diameter nickel sphere"

import numpy
from matplotlib import pyplot as plt

from sascalculator import SASCalculator
from diffpy.structure import Lattice, loadStructure
from diffpy.structure.tests.testutils import datafile
from diffpy.structure.expansion.makeellipsoid import makeSphere

ni = loadStructure(datafile('Ni.stru'), 'pdffit')
sph = makeSphere(ni, 20 / 2.0)
sph.placeInLattice(Lattice())

sc = SASCalculator(qstep=.01, rmax=20)
q, iqtot = sc(sph)

_, ax = plt.subplots()
ax.loglog(q, iqtot)
ax.set(title='SAS intensity from nickel sphere, d=20A',
       xlabel='Q (1/A)', ylabel='total intensity')
plt.show()
Exemple #21
0
def loadDiffPyStructure(filename):
    fullpath = datafile(filename)
    stru = mod_structure.loadStructure(fullpath)
    return stru
Exemple #22
0
def loadDiffPyStructure(filename):
    fullpath = datafile(filename)
    stru = mod_structure.loadStructure(fullpath)
    return stru