def convertDiffpyStru(self, mode='xyz'): ''' convert self.xxx to diffpy :param mode: 'xyz' or 'xyz_c', 'xyz': pass fractional xyz 'xyz_c': pass Cartesian xyz directly ''' rv = Structure() if mode == 'xyz': rv.lattice.setLatPar(*self.lat) aa = Atom() for i in range(self.n): rv.append(aa, copy=True) rv.element = self.element rv.occupancy = self.occ rv.anisotropy = self.anisotropy rv.U = self.uij_c if mode == 'xyz': rv.xyz = self.xyz elif mode == 'xyz_c': rv.xyz_cartn = self.xyz_c rv.title = self.name return self.addProp(rv)
def test_rwStr_pdb_CdSe(self): """check conversion to PDB file format""" stru = self.stru stru.read(datafile('CdSe_bulk.stru'), 'pdffit') s = stru.writeStr(self.format) # all lines should be 80 characters long linelens = [len(l) for l in s.split('\n') if l != ""] self.assertEqual(linelens, len(linelens) * [80]) # now clean and re-read structure stru = Structure() stru.readStr(s, self.format) s_els = [a.element for a in stru] f_els = ['Cd', 'Cd', 'Se', 'Se'] self.assertEqual(s_els, f_els) s_lat = [ stru.lattice.a, stru.lattice.b, stru.lattice.c, stru.lattice.alpha, stru.lattice.beta, stru.lattice.gamma ] f_lat = [4.235204, 4.235204, 6.906027, 90.0, 90.0, 120.0] self.assertListAlmostEqual(s_lat, f_lat) a0 = stru[0] s_Uii = [a0.U[i, i] for i in range(3)] f_Uii = [0.01303035, 0.01303035, 0.01401959] self.assertListAlmostEqual(s_Uii, f_Uii) s_sigUii = [a0.sigU[i, i] for i in range(3)] f_sigUii = [0.00011127, 0.00011127, 0.00019575] self.assertListAlmostEqual(s_sigUii, f_sigUii) s_title = stru.title f_title = "Cell structure file of CdSe #186" self.assertEqual(s_title, f_title)
def test___getitem__(self): """check Structure.__getitem__() """ stru = self.stru self.assertTrue(stru[0] is stru.tolist()[0]) intidx = range(len(stru))[::-1] self.assertEqual(stru[intidx].tolist(), stru.tolist()[::-1]) flagidx = (numpy.arange(len(stru)) > 0) self.assertEqual(stru[flagidx].tolist(), stru.tolist()[1:]) cdse = Structure(self.cdse) self.assertEqual([cdse[0], cdse[-2]], cdse[0, -2].tolist()) cdse013 = cdse.tolist() cdse013.pop(2) self.assertEqual(cdse013, cdse[:2, 3].tolist()) self.assertRaises(IndexError, cdse.__getitem__, 'Cd1') cdse.assignUniqueLabels() self.assertTrue(cdse[0] is cdse['Cd1']) cdse[0].label = 'Hohenzollern' self.assertRaises(IndexError, cdse.__getitem__, 'Cd1') self.assertTrue(cdse[0] is cdse['Hohenzollern']) self.assertEqual([cdse[0], cdse[3], cdse[1]], cdse['Hohenzollern', 3:0:-2].tolist()) stru.label = ['A', 'B'] self.assertTrue(stru[0] is stru['A']) self.assertTrue(stru[1] is stru['B']) stru[1].label = 'A' self.assertRaises(IndexError, stru.__getitem__, 'A') return
def makeRecipe(ciffile, datname): """Create a fitting recipe for crystalline PDF data.""" # Work directly with a custom PDFContribution to load the data contribution = PDFContribution("nickel") contribution.loadData(datname) contribution.setCalculationRange(xmin = 1, xmax = 20, dx = 0.1) # and the phase stru = Structure() stru.read(ciffile) contribution.addStructure("nickel", stru) ## Make the FitRecipe and add the FitContribution. recipe = FitRecipe() recipe.addContribution(contribution) ## Configure the fit variables phase = contribution.nickel.phase from diffpy.srfit.structure import constrainAsSpaceGroup sgpars = constrainAsSpaceGroup(phase, "Fm-3m") for par in sgpars.latpars: recipe.addVar(par) for par in sgpars.adppars: recipe.addVar(par, 0.005) recipe.addVar(contribution.scale, 1) recipe.addVar(contribution.qdamp, 0.03, fixed = True) recipe.addVar(contribution.nickel.delta2, 5) # Give the recipe away so it can be used! return recipe
def makeRecipe(ciffile, datname): """Create a fitting recipe for crystalline PDF data.""" # Work directly with a custom PDFContribution to load the data contribution = PDFContribution("nickel") contribution.loadData(datname) contribution.setCalculationRange(xmin=1, xmax=20, dx=0.1) # and the phase stru = Structure() stru.read(ciffile) contribution.addStructure("nickel", stru) ## Make the FitRecipe and add the FitContribution. recipe = FitRecipe() recipe.addContribution(contribution) ## Configure the fit variables phase = contribution.nickel.phase from diffpy.srfit.structure import constrainAsSpaceGroup sgpars = constrainAsSpaceGroup(phase, "Fm-3m") for par in sgpars.latpars: recipe.addVar(par) for par in sgpars.adppars: recipe.addVar(par, 0.005) recipe.addVar(contribution.scale, 1) recipe.addVar(contribution.qdamp, 0.03, fixed=True) recipe.addVar(contribution.nickel.delta2, 5) # Give the recipe away so it can be used! return recipe
def test_rwStr_pdb_CdSe(self): """check conversion to PDB file format""" stru = self.stru stru.read(datafile('CdSe_bulk.stru'), 'pdffit') s = stru.writeStr(self.format) # all lines should be 80 characters long linelens = [ len(l) for l in s.split('\n') if l != "" ] self.assertEqual(linelens, len(linelens)*[80]) # now clean and re-read structure stru = Structure() stru.readStr(s, self.format) s_els = [a.element for a in stru] f_els = ['Cd', 'Cd', 'Se', 'Se'] self.assertEqual(s_els, f_els) s_lat = [ stru.lattice.a, stru.lattice.b, stru.lattice.c, stru.lattice.alpha, stru.lattice.beta, stru.lattice.gamma ] f_lat = [ 4.235204, 4.235204, 6.906027, 90.0, 90.0, 120.0 ] self.assertListAlmostEqual(s_lat, f_lat) a0 = stru[0] s_Uii = [ a0.U[i,i] for i in range(3) ] f_Uii = [ 0.01303035, 0.01303035, 0.01401959 ] self.assertListAlmostEqual(s_Uii, f_Uii) s_sigUii = [ a0.sigU[i,i] for i in range(3) ] f_sigUii = [ 0.00011127, 0.00011127, 0.00019575 ] self.assertListAlmostEqual(s_sigUii, f_sigUii) s_title = stru.title f_title = "Cell structure file of CdSe #186" self.assertEqual(s_title, f_title)
def test_nometa(self): """check NoMetaStructureAdapter. """ r0, g0 = PDFCalculator()(nickel) ni1 = Structure(nickel) ni1.pdffit["scale"] = 2.0 r1, g1 = PDFCalculator()(ni1) self.failUnless(numpy.array_equal(r0, r1)) self.failUnless(numpy.allclose(2 * g0, g1)) ni1nm = nometa(ni1) self.failUnless(ni1nm is nometa(ni1nm)) r1nm, g1nm = PDFCalculator()(ni1nm) self.failUnless(numpy.array_equal(r0, r1nm)) self.failUnless(numpy.allclose(g0, g1nm)) ni2 = Structure(nickel) ni2.pdffit["delta2"] = 4 r2, g2 = PDFCalculator()(ni2) r2, g2nm = PDFCalculator()(nometa(ni2)) self.failIf(numpy.allclose(g0, g2)) self.failUnless(numpy.allclose(g0, g2nm)) adpt2 = createStructureAdapter(ni2) ra2, ga2 = PDFCalculator()(adpt2) ra2, ga2nm = PDFCalculator()(nometa(adpt2)) self.failUnless(numpy.allclose(g2, ga2)) self.failUnless(numpy.allclose(g0, ga2nm)) return
def test_nometa(self): '''check NoMetaStructureAdapter. ''' r0, g0 = PDFCalculator()(self.nickel) ni1 = Structure(self.nickel) ni1.pdffit['scale'] = 2.0 r1, g1 = PDFCalculator()(ni1) self.assertTrue(numpy.array_equal(r0, r1)) self.assertTrue(numpy.allclose(2 * g0, g1)) ni1nm = nometa(ni1) self.assertTrue(ni1nm is nometa(ni1nm)) r1nm, g1nm = PDFCalculator()(ni1nm) self.assertTrue(numpy.array_equal(r0, r1nm)) self.assertTrue(numpy.allclose(g0, g1nm)) ni2 = Structure(self.nickel) ni2.pdffit['delta2'] = 4 r2, g2 = PDFCalculator()(ni2) r2, g2nm = PDFCalculator()(nometa(ni2)) self.assertFalse(numpy.allclose(g0, g2)) self.assertTrue(numpy.allclose(g0, g2nm)) adpt2 = createStructureAdapter(ni2) ra2, ga2 = PDFCalculator()(adpt2) ra2, ga2nm = PDFCalculator()(nometa(adpt2)) self.assertTrue(numpy.allclose(g2, ga2)) self.assertTrue(numpy.allclose(g0, ga2nm)) return
def crystalToDiffpyStructure(crystal): """Create a diffpy.Structure.Structure from a crystal. This requires diffpy.Structure to be installed. This uses file IO transfer data, so there is some inherent precision loss. Note that the resulting structure will be in P1 symmetry. """ # Write the crystal to string and load it into a diffpy Structure from cStringIO import StringIO buf = StringIO() crystal.CIFOutput(buf) from diffpy.Structure import Structure stru = Structure() s = buf.getvalue() stru.readStr(s) buf.close() return stru
def test_angle(self): """check Structure.angle() """ cdse = Structure(filename=cdsefile) cdse.assignUniqueLabels() self.assertEqual(109, round(cdse.angle(0, 2, 1))) self.assertEqual(109, round(cdse.angle("Cd1", "Se1", "Cd2"))) return
def parseLines(self, lines): """Parse list of lines in RAWXYZ format. Return Structure object or raise StructureFormatError. """ linefields = [l.split() for l in lines] # prepare output structure stru = Structure() # find first valid record start = 0 for field in linefields: if len(field) == 0 or field[0] == "#": start += 1 else: break # find the last valid record stop = len(lines) while stop > start and len(linefields[stop-1]) == 0: stop -= 1 # get out for empty structure if start >= stop: return stru # here we have at least one valid record line # figure out xyz layout from the first line for plain and raw formats floatfields = [ isfloat(f) for f in linefields[start] ] nfields = len(linefields[start]) if nfields not in (3, 4): emsg = ("%d: invalid RAWXYZ format, expected 3 or 4 columns" % (start + 1)) raise StructureFormatError(emsg) if floatfields[:3] == [True, True, True]: el_idx, x_idx = (None, 0) elif floatfields[:4] == [False, True, True, True]: el_idx, x_idx = (0, 1) else: emsg = "%d: invalid RAWXYZ format" % (start + 1) raise StructureFormatError(emsg) # now try to read all record lines try: p_nl = start for fields in linefields[start:] : p_nl += 1 if fields == []: continue elif len(fields) != nfields: emsg = ('%d: all lines must have ' + 'the same number of columns') % p_nl raise StructureFormatError, emsg element = el_idx is not None and fields[el_idx] or "" xyz = [ float(f) for f in fields[x_idx:x_idx+3] ] if len(xyz) == 2: xyz.append(0.0) stru.addNewAtom(element, xyz=xyz) except ValueError: emsg = "%d: invalid number" % p_nl exc_type, exc_value, exc_traceback = sys.exc_info() raise StructureFormatError, emsg, exc_traceback return stru
def supercell(S, mno): """Perform supercell expansion for a structure. New lattice parameters are multiplied and fractional coordinates divided by corresponding multiplier. New atoms are grouped with their source in the original cell. S -- an instance of Structure from diffpy.Structure. mno -- sequence of 3 integers for cell multipliers along the a, b and c axes. Return a new expanded structure instance. Raise TypeError when S is not Structure instance. Raise ValueError for invalid mno argument. """ # check arguments if len(mno) != 3: emsg = "Argument mno must contain 3 numbers." raise ValueError, emsg elif min(mno) < 1: emsg = "Multipliers must be greater or equal 1" raise ValueError, emsg if not isinstance(S, Structure): emsg = "The first argument must be a Structure instance." raise TypeError, emsg # convert mno to a tuple of integers so it can be used as range limit. mno = (int(mno[0]), int(mno[1]), int(mno[2])) # create return instance newS = Structure(S) if mno == (1, 1, 1): return newS # back to business ijklist = [(i,j,k) for i in range(mno[0]) for j in range(mno[1]) for k in range(mno[2])] # numpy.floor returns float array mnofloats = numpy.array(mno, dtype=float) # build a list of new atoms newAtoms = [] for a in S: for ijk in ijklist: adup = Atom(a) adup.xyz = (a.xyz + ijk)/mnofloats newAtoms.append(adup) # newS can own references in newAtoms, no need to make copies newS.__setslice__(0, len(newS), newAtoms, copy=False) # take care of lattice parameters newS.lattice.setLatPar( a=mno[0]*S.lattice.a, b=mno[1]*S.lattice.b, c=mno[2]*S.lattice.c ) return newS
def makeC60(): """Make the C60 molecule using diffpy.Structure.""" from diffpy.Structure import Structure stru = Structure() for line in c60xyz.splitlines(): if not line: continue xyz = map(float, line.split()) stru.addNewAtom("C", xyz) return stru
def main(): # load structure from a specified file, by default "lj50.xyz" filename = len(sys.argv) > 1 and sys.argv[1] or "lj50.xyz" stru = Structure() stru.read(filename) # create an instance of LennardJonesCalculator ljcalc = LennardJonesCalculator() # calculate and print the LJ potential. print "LJ potential of %s is %g" % (filename, ljcalc(stru))
def test__get_lattice(self): """check Structure._get_lattice() """ lat = Lattice() stru = Structure() self.assertEqual((1, 1, 1, 90, 90, 90), stru.lattice.abcABG()) stru2 = Structure(lattice=lat) self.failUnless(lat is stru2.lattice) return
def test_huge_occupancy(self): """check structure with huge occupancy can be read. """ self.stru.read(datafile('Ni.stru'), self.format) self.stru[0].occupancy = 16e16 s_s = self.stru.writeStr(self.format) stru1 = Structure() stru1.readStr(s_s, self.format) self.assertEqual(16e16, stru1[0].occupancy) return
def loadStructureFile(filename, format="auto"): """Load structure from specified file. Return a tuple of (Structure, fileformat). """ from diffpy.Structure import Structure stru = Structure() p = stru.read(filename, format) fileformat = p.format return (stru, fileformat)
def test_label(self): """check Structure.label """ cdse = Structure(self.cdse) self.assertEqual(4 * [''], cdse.label.tolist()) cdse.assignUniqueLabels() self.assertEqual('Cd1 Cd2 Se1 Se2'.split(), cdse.label.tolist()) cdse.label = cdse.label.lower() self.assertEqual('cd1 cd2 se1 se2'.split(), cdse.label.tolist()) return
def test_write_and_read(self): """high-level check of P_cif.tostring() """ # high-level check stru_check = Structure() stru_check.read(self.cdsebulkpdffitfile) s_s = stru_check.writeStr('cif') stru = Structure() stru.readStr(s_s, 'cif') self.assertAlmostEqual(4.2352, stru.lattice.a, self.places) self.assertAlmostEqual(4.2352, stru.lattice.b, self.places) self.assertAlmostEqual(6.90603, stru.lattice.c, self.places) self.assertEqual(4, len(stru)) a0 = stru[0] self.assertEqual('Cd', a0.element) self.assertListAlmostEqual([0.3334, 0.6667, 0.0], a0.xyz) self.failUnless(a0.anisotropy) self.assertAlmostEqual(0.01303, a0.U[0,0]) self.assertAlmostEqual(0.01303, a0.U[1,1]) self.assertAlmostEqual(0.01402, a0.U[2,2]) a3 = stru[3] self.assertEqual('Se', a3.element) self.assertListAlmostEqual([0.6666, 0.333300, 0.87667], a3.xyz) self.assertAlmostEqual(0.015673, a3.U[0,0]) self.assertAlmostEqual(0.015673, a3.U[1,1]) self.assertAlmostEqual(0.046164, a3.U[2,2]) return
def makeData(strufile, q, datname, scale, a, Uiso, sig, bkgc, nl=1): """Make some fake data and save it to file. Make some data to fit. This uses iofq to calculate an intensity curve, and adds to it a background, broadens the peaks, and noise. strufile-- A filename holding the sample structure q -- The q-range to calculate over. datname -- The name of the file we're saving to. scale -- The scale factor a -- The lattice constant to use Uiso -- The thermal factor for all atoms sig -- The broadening factor bkgc -- A parameter that gives minor control of the background. nl -- Noise level (0, inf), default 1, larger -> less noise. """ from diffpy.Structure import Structure S = Structure() S.read(strufile) # Set the lattice parameters S.lattice.setLatPar(a, a, a) # Set a DW factor for a in S: a.Uisoequiv = Uiso y = iofq(S, q) # We want to broaden the peaks as well. This simulates instrument effects. q0 = q[len(q) / 2] g = numpy.exp(-0.5 * ((q - q0) / sig) ** 2) y = numpy.convolve(y, g, mode="same") / sum(g) # Add a polynomial background. bkgd = (q + bkgc) ** 2 * (1.5 * max(q) - q) ** 5 bkgd *= 0.2 * max(y) / max(bkgd) y += bkgd # Multipy by a scale factor y *= scale # Calculate the uncertainty u = (y / nl) ** 0.5 # And apply the noise if nl > 0: y = numpy.random.poisson(y * nl) / nl # Now save it numpy.savetxt(datname, zip(q, y, u)) return
def supercell(S, mno): """Perform supercell expansion for a structure. New lattice parameters are multiplied and fractional coordinates divided by corresponding multiplier. New atoms are grouped with their source in the original cell. S -- an instance of Structure from diffpy.Structure. mno -- sequence of 3 integers for cell multipliers along the a, b and c axes. Return a new expanded structure instance. Raise TypeError when S is not Structure instance. Raise ValueError for invalid mno argument. """ # check arguments if len(mno) != 3: emsg = "Argument mno must contain 3 numbers." raise ValueError, emsg elif min(mno) < 1: emsg = "Multipliers must be greater or equal 1" raise ValueError, emsg if not isinstance(S, Structure): emsg = "The first argument must be a Structure instance." raise TypeError, emsg # convert mno to a tuple of integers so it can be used as range limit. mno = (int(mno[0]), int(mno[1]), int(mno[2])) # create return instance newS = Structure(S) if mno == (1, 1, 1): return newS # back to business ijklist = [(i, j, k) for i in range(mno[0]) for j in range(mno[1]) for k in range(mno[2])] # numpy.floor returns float array mnofloats = numpy.array(mno, dtype=float) # build a list of new atoms newAtoms = [] for a in S: for ijk in ijklist: adup = Atom(a) adup.xyz = (a.xyz + ijk) / mnofloats newAtoms.append(adup) # newS can own references in newAtoms, no need to make copies newS.__setslice__(0, len(newS), newAtoms, copy=False) # take care of lattice parameters newS.lattice.setLatPar(a=mno[0] * S.lattice.a, b=mno[1] * S.lattice.b, c=mno[2] * S.lattice.c) return newS
def makeData(strufile, q, datname, scale, a, Uiso, sig, bkgc, nl = 1): """Make some fake data and save it to file. Make some data to fit. This uses iofq to calculate an intensity curve, and adds to it a background, broadens the peaks, and noise. strufile-- A filename holding the sample structure q -- The q-range to calculate over. datname -- The name of the file we're saving to. scale -- The scale factor a -- The lattice constant to use Uiso -- The thermal factor for all atoms sig -- The broadening factor bkgc -- A parameter that gives minor control of the background. nl -- Noise level (0, inf), default 1, larger -> less noise. """ from diffpy.Structure import Structure S = Structure() S.read(strufile) # Set the lattice parameters S.lattice.setLatPar(a, a, a) # Set a DW factor for a in S: a.Uisoequiv = Uiso y = iofq(S, q) # We want to broaden the peaks as well. This simulates instrument effects. q0 = q[len(q)/2] g = numpy.exp(-0.5*((q-q0)/sig)**2) y = numpy.convolve(y, g, mode='same')/sum(g) # Add a polynomial background. bkgd = (q + bkgc)**2 * (1.5*max(q) - q)**5 bkgd *= 0.2 * max(y) / max(bkgd) y += bkgd # Multipy by a scale factor y *= scale # Calculate the uncertainty u = (y/nl)**0.5 # And apply the noise if nl > 0: y = numpy.random.poisson(y*nl) / nl # Now save it numpy.savetxt(datname, zip(q, y, u)) return
def test___copy__(self): """check Structure.__copy__() """ cdse = Structure(filename=cdsefile) cdse_str = cdse.writeStr('pdffit') cdse2 = copy.copy(cdse) self.assertEqual(cdse_str, cdse2.writeStr('pdffit')) self.failIf(cdse.lattice is cdse2.lattice) sameatoms = set(cdse).intersection(cdse2) self.failIf(sameatoms) return
def test_nometa_pickling(self): '''check pickling of the NoMetaStructureAdapter wrapper. ''' r0, g0 = PDFCalculator()(self.nickel) ni1 = Structure(self.nickel) ni1.pdffit['scale'] = 2.0 ni1nm = cPickle.loads(cPickle.dumps(nometa(ni1))) self.assertFalse(ni1nm is ni1) r1nm, g1nm = PDFCalculator()(ni1nm) self.assertTrue(numpy.array_equal(r0, r1nm)) self.assertTrue(numpy.array_equal(g0, g1nm)) return
def setUp(self): self.stru = Structure( [ Atom('C', [0,0,0]), Atom('C', [1,1,1]) ], lattice=Lattice(1, 1, 1, 90, 90, 120) ) if not self._loaded_structures: self._loaded_structures.update([ ('cdse', Structure(filename=cdsefile)), ('tei', Structure(filename=teifile)), ('pbte', Structure(filename=pbtefile)), ]) self.__dict__.update(self._loaded_structures) self.places = 12 return
def setUp(self): # load test structures once if TestSuperCell.stru_cdse is None: cdsefile = datafile("CdSe_bulk.stru") TestSuperCell.stru_cdse = Structure(filename=cdsefile) if TestSuperCell.stru_ni is None: nifile = datafile("Ni.stru") TestSuperCell.stru_ni = Structure(filename=nifile) # bring them to the instance self.stru_cdse = TestSuperCell.stru_cdse self.stru_ni = TestSuperCell.stru_ni return
def test_nometa_pickling(self): '''check pickling of the NoMetaStructureAdapter wrapper. ''' r0, g0 = PDFCalculator()(nickel) ni1 = Structure(nickel) ni1.pdffit['scale'] = 2.0 ni1nm = cPickle.loads(cPickle.dumps(nometa(ni1))) self.failIf(ni1nm is ni1) r1nm, g1nm = PDFCalculator()(ni1nm) self.failUnless(numpy.array_equal(r0, r1nm)) self.failUnless(numpy.array_equal(g0, g1nm)) return
def test_nometa_pickling(self): """check pickling of the NoMetaStructureAdapter wrapper. """ r0, g0 = PDFCalculator()(nickel) ni1 = Structure(nickel) ni1.pdffit["scale"] = 2.0 ni1nm = cPickle.loads(cPickle.dumps(nometa(ni1))) self.failIf(ni1nm is ni1) r1nm, g1nm = PDFCalculator()(ni1nm) self.failUnless(numpy.array_equal(r0, r1nm)) self.failUnless(numpy.array_equal(g0, g1nm)) return
def test___isub__(self): """check Structure.__isub__() """ cdse = Structure(filename=cdsefile) lat = cdse.lattice lst = cdse.tolist() cdse -= cdse[2:] self.assertEqual(2, len(cdse)) self.assertEqual(4, len(lst)) self.assertEqual('Cd', cdse[0].element) self.assertEqual('Cd', cdse[1].element) self.assertEqual(lat, cdse.lattice) self.assertEqual(lst[:2], cdse.tolist()) return
def test___imul__(self): """check Structure.__imul__() """ cdse = Structure(filename=cdsefile) lat = cdse.lattice els = cdse.element xyz = cdse.xyz lst = cdse.tolist() cdse *= 2 self.assertEqual(8, len(cdse)) self.assertEqual(lst, cdse[:4].tolist()) self.assertEqual(numpy.tile(els, 2).tolist(), cdse.element.tolist()) self.failUnless(numpy.array_equal(numpy.tile(xyz, (2, 1)), cdse.xyz)) self.assertEqual(8, len(set(cdse))) self.assertEqual(8 * [lat], [a.lattice for a in cdse]) return
def main(): s = raw_input('Enter rmin: ') if s.strip(): distprint.rmin = float(s) print "rmin =", distprint.rmin s = raw_input('Enter rmax: ') if s.strip(): distprint.rmax = float(s) print "rmax =", distprint.rmax print linesep = 78 * '-' # C60bucky print linesep raw_input('Press enter for distances in C60 molecule.') distprint.eval(bucky) # nickel print linesep raw_input('Press enter for distances in a nickel crystal.') distprint.eval(nickel) # objcryst sphalerite print linesep raw_input('Press enter for distances in objcryst loaded sphalerite.cif.') crst = get_pyobjcryst_sphalerite() distprint.eval(crst) print linesep raw_input('Press enter for distances in diffpy.Structure sphalerite.cif.') crst = Structure(filename='datafiles/sphalerite.cif') distprint.eval(crst) return
def test_write_and_read(self): """high-level check of P_cif.tostring() """ # high-level check stru_check = Structure() stru_check.read(self.cdsebulkpdffitfile) s_s = stru_check.writeStr('cif') stru = Structure() stru.readStr(s_s, 'cif') self.assertAlmostEqual(4.2352, stru.lattice.a, self.places) self.assertAlmostEqual(4.2352, stru.lattice.b, self.places) self.assertAlmostEqual(6.90603, stru.lattice.c, self.places) self.assertEqual(4, len(stru)) a0 = stru[0] self.assertEqual('Cd', a0.element) self.assertListAlmostEqual([0.3334, 0.6667, 0.0], a0.xyz) self.assertAlmostEqual(0.01303, a0.U[0,0]) self.assertAlmostEqual(0.01303, a0.U[1,1]) self.assertAlmostEqual(0.01402, a0.U[2,2]) a3 = stru[3] self.assertEqual('Se', a3.element) self.assertListAlmostEqual([0.6666, 0.333300, 0.87667], a3.xyz) self.assertAlmostEqual(0.015673, a3.U[0,0]) self.assertAlmostEqual(0.015673, a3.U[1,1]) self.assertAlmostEqual(0.046164, a3.U[2,2]) return
def test_rwStr_xcfg_CdSe(self): """check conversion to XCFG file format""" stru = self.stru stru.read(datafile('CdSe_bulk.stru'), 'pdffit') s = stru.writeStr(self.format) stru = Structure() stru.readStr(s, self.format) s_els = [a.element for a in stru] f_els = ['Cd', 'Cd', 'Se', 'Se'] self.assertEqual(s_els, f_els) s_lat = [ stru.lattice.a, stru.lattice.b, stru.lattice.c, stru.lattice.alpha, stru.lattice.beta, stru.lattice.gamma ] f_lat = [ 4.235204, 4.235204, 6.906027, 90.0, 90.0, 120.0 ] self.assertListAlmostEqual(s_lat, f_lat) a0 = stru[0] s_Uii = [ a0.U[i,i] for i in range(3) ] f_Uii = [ 0.01303035, 0.01303035, 0.01401959 ] self.assertListAlmostEqual(s_Uii, f_Uii)
def test___call__(self): """Check PDFCalculator.__call__() """ from diffpy.Structure import Structure r0, g0 = self.pdfcalc(self.tio2rutile, rmin=2) self.assertEqual(2.0, r0[0]) r1, g1 = self.pdfcalc(self.tio2rutile, scale=7) self.assertAlmostEqual(7.0, g1[0] / g0[0]) # check application of spdiameter rutile2 = Structure(self.tio2rutile) # work around Structure bug of shared pdffit dictionary rutile2.pdffit = dict(self.tio2rutile.pdffit) rutile2.pdffit['spdiameter'] = 5.0 r3, g3 = self.pdfcalc(rutile2) self.assertEqual(0.0, sum(g3[r3 >= 5]**2)) r4, g4 = self.pdfcalc(rutile2, scale=1, spdiameter=0) self.failUnless(numpy.all(r4 == r0)) self.failUnless(numpy.all(g4 == g0)) return
def test_bvrmsdiff(self): """check BVSCalculator.bvrmsdiff """ from math import sqrt self.assertEqual(0, self.bvc.bvrmsdiff) self.bvc(self.rutile) self.failUnless(self.bvc.bvrmsdiff > 0) self.assertAlmostEqual(sqrt(self.bvc.bvmsdiff), self.bvc.bvrmsdiff, 12) bvrmsd0 = self.bvc.bvrmsdiff # check mixed occupancy rutilemix = Structure(self.rutile) for a in self.rutile: rutilemix.addNewAtom(a) for a in rutilemix: a.occupancy = 0.5 self.bvc(rutilemix) self.assertEqual(12, len(self.bvc.value)) self.assertAlmostEqual(bvrmsd0, self.bvc.bvrmsdiff, 12) return
def test_pickling(self): """Test pickling of DiffpyStructureParSet. """ stru = Structure([Atom("C", [0, 0.2, 0.5])]) dsps = DiffpyStructureParSet("dsps", stru) data = pickle.dumps(dsps) dsps2 = pickle.loads(data) self.assertEqual(1, len(dsps2.atoms)) self.assertEqual(0.2, dsps2.atoms[0].y.value) return
def test___call__(self): """Check PDFCalculator.__call__() """ from diffpy.Structure import Structure r0, g0 = self.pdfcalc(self.tio2rutile, rmin=2) self.assertEqual(2.0, r0[0]) r1, g1 = self.pdfcalc(self.tio2rutile, scale=7) self.assertAlmostEqual(7.0, g1[0] / g0[0]) # check application of spdiameter rutile2 = Structure(self.tio2rutile) # work around Structure bug of shared pdffit dictionary rutile2.pdffit = dict(self.tio2rutile.pdffit) rutile2.pdffit['spdiameter'] = 5.0 r3, g3 = self.pdfcalc(rutile2) self.assertEqual(0.0, sum(g3[r3 >= 5] ** 2)) r4, g4 = self.pdfcalc(rutile2, scale=1, spdiameter=0) self.failUnless(numpy.all(r4 == r0)) self.failUnless(numpy.all(g4 == g0)) return
def test_bvrmsdiff(self): """check BVSCalculator.bvrmsdiff """ from math import sqrt self.assertEqual(0, self.bvc.bvrmsdiff) self.bvc(self.rutile) self.assertTrue(self.bvc.bvrmsdiff > 0) self.assertAlmostEqual(sqrt(self.bvc.bvmsdiff), self.bvc.bvrmsdiff, 12) bvrmsd0 = self.bvc.bvrmsdiff # check mixed occupancy rutilemix = Structure(self.rutile) for a in self.rutile: rutilemix.addNewAtom(a) for a in rutilemix: a.occupancy = 0.5 self.bvc(rutilemix) self.assertEqual(12, len(self.bvc.value)) self.assertAlmostEqual(bvrmsd0, self.bvc.bvrmsdiff, 12) return
def test___repr__(self): """Test representation of DiffpyStructureParSet objects. """ lat = Lattice(3, 3, 2, 90, 90, 90) atom = Atom("C", [0, 0.2, 0.5]) stru = Structure([atom], lattice=lat) dsps = DiffpyStructureParSet("dsps", stru) self.assertEqual(repr(stru), repr(dsps)) self.assertEqual(repr(lat), repr(dsps.lattice)) self.assertEqual(repr(atom), repr(dsps.atoms[0])) return
def test_rwStr_xcfg_CdSe(self): """check conversion to XCFG file format""" stru = self.stru stru.read(datafile('CdSe_bulk.stru'), 'pdffit') s = stru.writeStr(self.format) stru = Structure() stru.readStr(s, self.format) s_els = [a.element for a in stru] f_els = ['Cd', 'Cd', 'Se', 'Se'] self.assertEqual(s_els, f_els) s_lat = [ stru.lattice.a, stru.lattice.b, stru.lattice.c, stru.lattice.alpha, stru.lattice.beta, stru.lattice.gamma ] f_lat = [4.235204, 4.235204, 6.906027, 90.0, 90.0, 120.0] self.assertListAlmostEqual(s_lat, f_lat) a0 = stru[0] s_Uii = [a0.U[i, i] for i in range(3)] f_Uii = [0.01303035, 0.01303035, 0.01401959] self.assertListAlmostEqual(s_Uii, f_Uii)
def test_stepcut_parsing(self): """check parsing of stepcut record from a file. """ stru = self.stru stru.read(datafile("Ni.stru"), self.format) self.assertEqual(0, stru.pdffit["stepcut"]) snoshape = stru.writeStr(format=self.format) self.failUnless(not re.search("(?m)^shape", snoshape)) # produce a string with non-zero stepcut stru.pdffit["stepcut"] = 13 s13 = stru.writeStr(format=self.format) self.failUnless(re.search("(?m)^shape +stepcut, ", s13)) stru13 = Structure() stru13.readStr(s13) self.assertEqual(13, stru13.pdffit["stepcut"]) ni_lines = open(datafile("Ni.stru")).readlines() ni_lines.insert(3, "shape invalid, 7\n") sbad = "".join(ni_lines) self.assertRaises(StructureFormatError, self.stru.readStr, sbad, format=self.format) return
def test_extend(self): """check Structure.extend() """ stru = self.stru cdse = Structure(filename=cdsefile) lst = stru.tolist() stru.extend(cdse) self.assertEqual(6, len(stru)) self.assertTrue(all(a.lattice is stru.lattice for a in stru)) self.assertEqual(lst, stru.tolist()[:2]) self.assertNotEqual(stru[-1], cdse[-1]) return
def test_stepcut_parsing(self): """check parsing of stepcut record from a file. """ stru = self.stru stru.read(datafile('Ni-discus.stru'), self.format) self.assertEqual(0, stru.pdffit['stepcut']) snoshape = stru.writeStr(format=self.format) self.assertTrue(not re.search('(?m)^shape', snoshape)) # produce a string with non-zero stepcut stru.pdffit['stepcut'] = 13 s13 = stru.writeStr(format=self.format) self.assertTrue(re.search('(?m)^shape +stepcut, ', s13)) stru13 = Structure() stru13.readStr(s13) self.assertEqual(13, stru13.pdffit['stepcut']) ni_lines = open(datafile('Ni.stru')).readlines() ni_lines.insert(3, 'shape invalid, 7\n') sbad = ''.join(ni_lines) self.assertRaises(StructureFormatError, self.stru.readStr, sbad, format=self.format) return
def test_spdiameter_parsing(self): """check parsing of spdiameter record from a file. """ stru = self.stru stru.read(datafile('Ni.stru'), self.format) self.assertEqual(0, stru.pdffit['spdiameter']) snoshape = stru.writeStr(format=self.format) self.failUnless(not re.search('(?m)^shape', snoshape)) # produce a string with non-zero spdiameter stru.pdffit['spdiameter'] = 13 s13 = stru.writeStr(format=self.format) self.failUnless(re.search('(?m)^shape +sphere, ', s13)) stru13 = Structure() stru13.readStr(s13) self.assertEqual(13, stru13.pdffit['spdiameter']) ni_lines = open(datafile('Ni.stru')).readlines() ni_lines.insert(3, 'shape invalid, 7\n') sbad = ''.join(ni_lines) self.assertRaises(StructureFormatError, self.stru.readStr, sbad, format=self.format) return
def test_setQmax(self): """check PDFContribution.setQmax() """ from diffpy.Structure import Structure pc = self.pc pc.setQmax(21) pc.addStructure('empty', Structure()) self.assertEqual(21, pc.empty.getQmax()) pc.setQmax(22) self.assertEqual(22, pc.getQmax()) self.assertEqual(22, pc.empty.getQmax()) return
def test_nometa(self): '''check NoMetaStructureAdapter. ''' r0, g0 = PDFCalculator()(nickel) ni1 = Structure(nickel) ni1.pdffit['scale'] = 2.0 r1, g1 = PDFCalculator()(ni1) self.failUnless(numpy.array_equal(r0, r1)) self.failUnless(numpy.allclose(2 * g0, g1)) ni1nm = nometa(ni1) self.failUnless(ni1nm is nometa(ni1nm)) r1nm, g1nm = PDFCalculator()(ni1nm) self.failUnless(numpy.array_equal(r0, r1nm)) self.failUnless(numpy.allclose(g0, g1nm)) ni2 = Structure(nickel) ni2.pdffit['delta2'] = 4 r2, g2 = PDFCalculator()(ni2) r2, g2nm = PDFCalculator()(nometa(ni2)) self.failIf(numpy.allclose(g0, g2)) self.failUnless(numpy.allclose(g0, g2nm)) adpt2 = createStructureAdapter(ni2) ra2, ga2 = PDFCalculator()(adpt2) ra2, ga2nm = PDFCalculator()(nometa(adpt2)) self.failUnless(numpy.allclose(g2, ga2)) self.failUnless(numpy.allclose(g0, ga2nm)) return
def test___sub__(self): """check Structure.__sub__() """ cdse = Structure(filename=cdsefile) cadmiums = cdse - cdse[2:] self.assertEqual(2, len(cadmiums)) self.assertEqual('Cd', cadmiums[0].element) self.assertEqual('Cd', cadmiums[1].element) self.failUnless(numpy.array_equal(cdse[0].xyz, cadmiums[0].xyz)) self.failUnless(numpy.array_equal(cdse[1].xyz, cadmiums[1].xyz)) self.failIf(cdse[0] is cadmiums[0]) self.failIf(cdse.lattice is cadmiums.lattice) return
def test___getitem__(self): """check Structure.__getitem__() """ stru = self.stru self.failUnless(stru[0] is stru.tolist()[0]) intidx = range(len(stru))[::-1] self.assertEqual(stru[intidx].tolist(), stru.tolist()[::-1]) flagidx = (numpy.arange(len(stru)) > 0) self.assertEqual(stru[flagidx].tolist(), stru.tolist()[1:]) cdse = Structure(self.cdse) self.assertEqual([cdse[0], cdse[-2]], cdse[0, -2].tolist()) cdse013 = cdse.tolist() cdse013.pop(2) self.assertEqual(cdse013, cdse[:2,3].tolist()) self.assertRaises(IndexError, cdse.__getitem__, 'Cd1') cdse.assignUniqueLabels() self.failUnless(cdse[0] is cdse['Cd1']) cdse[0].label = 'Hohenzollern' self.assertRaises(IndexError, cdse.__getitem__, 'Cd1') self.failUnless(cdse[0] is cdse['Hohenzollern']) self.assertEqual([cdse[0], cdse[3], cdse[1]], cdse['Hohenzollern', 3:0:-2].tolist()) return
def parseLines(self, lines): """Parse list of lines in PDB format. Return Structure instance or raise StructureFormatError. """ try: stru = Structure() scale = numpy.identity(3, dtype=float) scaleU = numpy.zeros(3, dtype=float) p_nl = 0 for line in lines: p_nl += 1 # skip blank lines if not line.strip(): continue # make sure line has 80 characters if len(line) < 80: line = "%-80s" % line words = line.split() record = words[0] if record == "TITLE": continuation = line[8:10] if continuation.strip(): stru.title += line[10:].rstrip() else: stru.title = line[10:].rstrip() elif record == "CRYST1": a = float(line[7:15]) b = float(line[15:24]) c = float(line[24:33]) alpha = float(line[33:40]) beta = float(line[40:47]) gamma = float(line[47:54]) stru.lattice.setLatPar(a, b, c, alpha, beta, gamma) scale = numpy.transpose(stru.lattice.recbase) elif record == "SCALE1": sc = numpy.zeros((3,3), dtype=float) sc[0,:] = [float(x) for x in line[10:40].split()] scaleU[0] = float(line[45:55]) elif record == "SCALE2": sc[1,:] = [float(x) for x in line[10:40].split()] scaleU[1] = float(line[45:55]) elif record == "SCALE3": sc[2,:] = [float(x) for x in line[10:40].split()] scaleU[2] = float(line[45:55]) base = numpy.transpose(numpy.linalg.inv(sc)) abcABGcryst = numpy.array(stru.lattice.abcABG()) stru.lattice.setLatBase(base) abcABGscale = numpy.array(stru.lattice.abcABG()) reldiff = numpy.fabs(1.0 - abcABGscale/abcABGcryst) if not numpy.all(reldiff < 1.0e-4): emsg = "%d: " % p_nl + \ "SCALE and CRYST1 are not consistent." raise StructureFormatError(emsg) if numpy.any(scaleU != 0.0): emsg = "Origin offset not yet implemented." raise NotImplementedError(emsg) elif record in ("ATOM", "HETATM"): name = line[12:16].strip() rc = [float(x) for x in line[30:54].split()] xyz = numpy.dot(scale, rc) + scaleU try: occupancy = float(line[54:60]) except ValueError: occupancy = 1.0 try: B = float(line[60:66]) U = numpy.identity(3)*B/(8*pi**2) except ValueError: U = numpy.zeros((3,3), dtype=float) element = line[76:78].strip() if element == "": # get element from the first 2 characters of name element = line[12:14].strip() element = element[0].upper() + element[1:].lower() stru.addNewAtom(element, occupancy=occupancy, label=name, U=U) last_atom = stru.getLastAtom() last_atom.xyz_cartn = rc elif record == "SIGATM": sigrc = [float(x) for x in line[30:54].split()] sigxyz = numpy.dot(scale, sigrc) try: sigo = float(line[54:60]) except ValueError: sigo = 0.0 try: sigB = float(line[60:66]) sigU = numpy.identity(3)*sigB/(8*pi**2) except ValueError: sigU = numpy.zeros((3,3), dtype=float) last_atom.sigxyz = sigxyz last_atom.sigo = sigo last_atom.sigU = sigU elif record == "ANISOU": Uij = [ float(x)*1.0e-4 for x in line[28:70].split() ] for i in range(3): last_atom.U[i,i] = Uij[i] last_atom.U[0,1] = last_atom.U[1,0] = Uij[3] last_atom.U[0,2] = last_atom.U[2,0] = Uij[4] last_atom.U[1,2] = last_atom.U[2,1] = Uij[5] elif record == "SIGUIJ": sigUij = [ float(x)*1.0e-4 for x in line[28:70].split() ] for i in range(3): last_atom.sigU[i,i] = sigUij[i] last_atom.sigU[0,1] = last_atom.sigU[1,0] = sigUij[3] last_atom.sigU[0,2] = last_atom.sigU[2,0] = sigUij[4] last_atom.sigU[1,2] = last_atom.sigU[2,1] = sigUij[5] elif record in P_pdb.validRecords: pass else: emsg = "%d: invalid record name '%r'" % (p_nl, record) raise StructureFormatError(emsg) except (ValueError, IndexError): emsg = "%d: invalid PDB record" % p_nl exc_type, exc_value, exc_traceback = sys.exc_info() raise StructureFormatError, emsg, exc_traceback return stru
try: infmt, outfmt = args[0].split('..', 1) if infmt not in inputFormats(): print >> sys.stderr, "'%s' is not valid input format" % infmt sys.exit(2) if outfmt not in outputFormats(): print >> sys.stderr, "'%s' is not valid output format" % outfmt sys.exit(2) except ValueError: print >> sys.stderr, \ "invalid format specification '%s' does not contain .." % args[0] sys.exit(2) # ready to do some real work try: strufile = args[1] stru = Structure() if args[1] == "-": stru.readStr(sys.stdin.read(), infmt) else: stru.read(strufile, infmt) sys.stdout.write( stru.writeStr(outfmt) ) except IndexError: print >> sys.stderr, "strufile not specified" sys.exit(2) except IOError, (errno, errmsg): print >> sys.stderr, "%s: %s" % (strufile, errmsg) sys.exit(1) except StructureFormatError, errmsg: print >> sys.stderr, "%s: %s" % (strufile, errmsg) sys.exit(1)