本文整理汇总了Python中diffpy.Structure.Structure类的典型用法代码示例。如果您正苦于以下问题:Python Structure类的具体用法?Python Structure怎么用?Python Structure使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Structure类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rwStr_pdb_CdSe
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)
示例2: crystalToDiffpyStructure
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
示例3: makeRecipe
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
示例4: test_nometa
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
示例5: test_nometa
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
示例6: convertDiffpyStru
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)
示例7: test_angle
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
示例8: supercell
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
示例9: parseLines
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
示例10: main
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))
示例11: makeC60
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
示例12: test_label
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
示例13: test_huge_occupancy
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
示例14: loadStructureFile
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)
示例15: makeData
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