本文整理汇总了Python中pymatgen.Element方法的典型用法代码示例。如果您正苦于以下问题:Python pymatgen.Element方法的具体用法?Python pymatgen.Element怎么用?Python pymatgen.Element使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymatgen
的用法示例。
在下文中一共展示了pymatgen.Element方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def test(self):
surfs=glob.glob("surf.al.fcc.01x01x01/00.place_ele/surf*")
surfs=[ii.split('/')[-1] for ii in surfs]
surfs.sort()
self.assertEqual(surfs,self.surfs)
poscars=glob.glob("surf.al.fcc.01x01x01/00.place_ele/surf*/sys*/POSCAR")
for poscar in poscars:
surf=poscar.split('/')[-3]
st1=Structure.from_file(surf+'.POSCAR')
st2=Structure.from_file(poscar)
vacuum_size=float(Element(self.jdata['elements'][0]).atomic_radius*2)
self.assertTrue(st1.lattice.c+vacuum_size-st2.lattice.c<0.01)
for surf in self.surfs:
elongs=glob.glob("surf.al.fcc.01x01x01/01.scale_pert/"+surf+"/sys-*/scale-1.000/el*")
elongs=[ii.split('/')[-1] for ii in elongs]
elongs.sort()
self.assertEqual(elongs,self.elongs)
示例2: mol_Oh
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def mol_Oh(central, ligand, scale):
"""
Return a perfect octahedra as a mg.Molecule object.
Args:
central: (string) Name of the central atom
ligand: (string) Name of ligand atoms
scale: (float) length of central-ligand distance
Returns
mg.Molecule object
"""
species = [mg.Element(central)] + 6 * [mg.Element(ligand)]
template = [[ 0., 0., 0.],
[ 1., 0., 0.],
[-1., 0., 0.],
[ 0., 1., 0.],
[ 0.,-1., 0.],
[ 0., 0., 1.],
[ 0., 0.,-1.]]
coords = [[scale * xi for xi in coord] for coord in template]
return mg.Molecule(species, coords)
示例3: test
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def test(self):
surfs=glob.glob("POSCAR.01x01x01/01.scale_pert/surf*")
surfs=[ii.split('/')[-1] for ii in surfs]
surfs.sort()
self.assertEqual(surfs,self.surfs)
poscars=glob.glob("POSCAR.01x01x01/00.place_ele/surf*/sys*/POSCAR")
for poscar in poscars:
surf=poscar.split('/')[-3]
st1=Structure.from_file(surf+'.POSCAR')
st2=Structure.from_file(poscar)
vacuum_size=float(Element(self.jdata['elements'][0]).atomic_radius*2)
self.assertTrue(st1.lattice.c+vacuum_size-st2.lattice.c<0.01)
for surf in self.surfs:
elongs=glob.glob("POSCAR.01x01x01/01.scale_pert/"+surf+"/sys-*/scale-1.000/el*")
elongs=[ii.split('/')[-1] for ii in elongs]
elongs.sort()
self.assertEqual(elongs,self.elongs)
示例4: compute_conrib_spd
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def compute_conrib_spd(bands, spin, name=None):
# get projected bands
if name:
pbands = bands.get_projections_on_elts_and_orbitals({name: ["s", "p", "d"]})
else:
raise NameError("Element name is not define")
# compute s, p, d normalized contributions
contrib = np.zeros((bands.nb_bands, len(bands.kpoints), 3))
for b in range(bands.nb_bands):
for k in range(len(bands.kpoints)):
sc = pbands[spin][b][k][name]["s"]**2
pc = pbands[spin][b][k][name]["p"]**2
dc = pbands[spin][b][k][name]["d"]**2
tot = sc + pc + dc
if tot != 0.0:
contrib[b, k, 0] = sc / tot
contrib[b, k, 1] = pc / tot
contrib[b, k, 2] = dc / tot
return contrib
示例5: setUp
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def setUp(self):
element_profile = {'Ni': {'r': 0.5, 'w': 1}}
describer1 = BispectrumCoefficients(rcutfac=4.1, twojmax=8,
element_profile=element_profile,
quadratic=False,
pot_fit=True)
model1 = LinearModel(describer=describer1)
model1.model.coef_ = coeff
model1.model.intercept_ = intercept
snap1 = SNAPotential(model=model1)
snap1.specie = Element('Ni')
self.ff_settings1 = snap1
describer2 = BispectrumCoefficients(rcutfac=4.1, twojmax=8,
element_profile=element_profile,
quadratic=True,
pot_fit=True)
model2 = LinearModel(describer=describer2)
model2.model.coef_ = coeff
model2.model.intercept_ = intercept
snap2 = SNAPotential(model=model2)
snap2.specie = Element('Ni')
self.ff_settings2 = snap2
self.struct = Structure.from_spacegroup('Fm-3m',
Lattice.cubic(3.506),
['Ni'], [[0, 0, 0]])
示例6: write_cfg
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def write_cfg(self, filename, cfg_pool):
"""
Write the formatted configuration file.
Args:
filename (str): The filename to be written.
cfg_pool (list): The configuration pool contains
structure and energy/forces properties.
"""
lines = []
for dataset in cfg_pool:
if isinstance(dataset['structure'], dict):
structure = Structure.from_dict(dataset['structure'])
else:
structure = dataset['structure']
energy = dataset['outputs']['energy']
forces = dataset['outputs']['forces']
virial_stress = dataset['outputs']['virial_stress']
virial_stress = [virial_stress[self.vasp_stress_order.index(n)]
for n in self.mtp_stress_order]
lines.append(self._line_up(structure, energy, forces, virial_stress))
self.specie = Element(structure.symbol_set[0])
with open(filename, 'w') as f:
f.write('\n'.join(lines))
return filename
示例7: write_cfgs
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def write_cfgs(self, filename, cfg_pool):
"""
Write the formatted configuration file.
Args:
filename (str): The filename to be written.
cfg_pool (list): The configuration pool contains
structure and energy/forces properties.
"""
if not filename.endswith('.xyz'):
raise RuntimeError('The extended xyz file should end with ".xyz"')
lines = []
for dataset in cfg_pool:
if isinstance(dataset['structure'], dict):
structure = Structure.from_dict(dataset['structure'])
else:
structure = dataset['structure']
energy = dataset['outputs']['energy']
forces = dataset['outputs']['forces']
virial_stress = dataset['outputs']['virial_stress']
lines.append(self._line_up(structure, energy, forces, virial_stress))
self.specie = Element(structure.symbol_set[0])
with open(filename, 'w') as f:
f.write('\n'.join(lines))
return filename
示例8: write_cfgs
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def write_cfgs(self, filename, cfg_pool):
"""
Write the formatted configuration file.
Args:
filename (str): The filename to be written.
cfg_pool (list): The configuration pool contains
structure and energy/forces properties.
"""
lines = []
for dataset in cfg_pool:
if isinstance(dataset['structure'], dict):
structure = Structure.from_dict(dataset['structure'])
else:
structure = dataset['structure']
energy = dataset['outputs']['energy']
forces = dataset['outputs']['forces']
virial_stress = dataset['outputs']['virial_stress']
lines.append(self._line_up(structure, energy, forces, virial_stress))
# dist = np.unique(structure.distance_matrix.ravel())[1]
# if self.shortest_distance > dist:
# self.shortest_distance = dist
self.specie = Element(structure.symbol_set[0])
with open(filename, 'w') as f:
f.write('\n'.join(lines))
return filename
示例9: _get_atomic_magpie_features
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def _get_atomic_magpie_features(self, composition, data_path):
# Get .table files containing feature values for each element, assign file names as feature names
magpie_feature_names = []
for f in os.listdir(data_path):
if '.table' in f:
magpie_feature_names.append(f[:-6])
composition = Composition(composition)
element_list, atoms_per_formula_unit = self._get_element_list(composition=composition)
element_dict = {}
for element in element_list:
element_dict[element] = Element(element).Z
magpiedata_atomic = {}
for k, v in element_dict.items():
atomic_values = {}
for feature_name in magpie_feature_names:
f = open(data_path + '/' + feature_name + '.table', 'r')
# Get Magpie data of relevant atomic numbers for this composition
for line, feature_value in enumerate(f.readlines()):
if line + 1 == v:
if "Missing" not in feature_value and "NA" not in feature_value:
if feature_name != "OxidationStates":
try:
atomic_values[feature_name] = float(feature_value.strip())
except ValueError:
atomic_values[feature_name] = 'NaN'
if "Missing" in feature_value:
atomic_values[feature_name] = 'NaN'
if "NA" in feature_value:
atomic_values[feature_name] = 'NaN'
f.close()
magpiedata_atomic[k] = atomic_values
return magpiedata_atomic
示例10: mol_D4h
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def mol_D4h(central, ligand, d1, d2):
"""
Return a D4h molecule as a mg.Molecule object.
Args:
central: (string) Name of the central atom
ligand: (string) Name of ligand atoms
d1: (float) length of central-ligand axial distance
d2: (float) length of central-ligand equatorial distance
Returns
mg.Molecule object
"""
species = [mg.Element(central)] + 6 * [mg.Element(ligand)]
template = [[ 0., 0., 0.],
[ 1., 0., 0.],
[-1., 0., 0.],
[ 0., 1., 0.],
[ 0.,-1., 0.],
[ 0., 0., 1.],
[ 0., 0.,-1.]]
coords = [template[0]] \
+ [[d1 * xi for xi in coord] for coord in template[1:5]] \
+ [[d2 * xi for xi in coord] for coord in template[5:]]
return mg.Molecule(species, coords)
#-----------------------------------------------------------------------------
# Distortion measurment
#-----------------------------------------------------------------------------
示例11: readStructures
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def readStructures(sfile, central, ligand, radius=3.):
"""
Read structure from file sfile and look for environments of all central
atoms in the structure. Only neighbors of type ligand are taken into
account.
Returns a list of mg.Molecule in which the first atom is the central atom
and the following atoms are the neighbors of type ligand of this central
atom.
"""
struct = mg.Structure.from_file(sfile)
central_sites = [site for site in struct
if site.specie == mg.Element(central)]
envs = list()
print("Identified sites:")
for site in central_sites:
mol = mg.Molecule([site.specie], [site.coords])
neighbors = struct.get_neighbors(site, radius)
for neighbor, d in neighbors:
if neighbor.specie == mg.Element(ligand):
mol.append(neighbor.specie, neighbor.coords)
envs.append(mol)
print("%2s[%2d] : #ligand = %d (%s)" %
(site.specie,
struct.index(site),
len(mol[1:]),
" ".join([at.specie.symbol for at in mol[1:]])))
return envs
示例12: write_param
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def write_param(self):
"""
Write parameter and coefficient file to perform lammps calculation.
"""
if not self.specie:
raise ValueError("No specie given!")
param_file = '{}.snapparam'.format(self.name)
coeff_file = '{}.snapcoeff'.format(self.name)
model = self.model
describer = self.model.describer
profile = describer.element_profile
elements = [element.symbol for element
in sorted([Element(e) for e in profile.keys()])]
ne = len(elements)
nbc = len(describer.subscripts)
if describer.quadratic:
nbc += int((1 + nbc) * nbc / 2)
coeff_lines = []
coeff_lines.append('{} {}'.format(ne, nbc + 1))
for element, coeff in zip(elements, np.split(model.coef, ne)):
coeff_lines.append('{} {} {}'.format(element,
profile[element]['r'],
profile[element]['w']))
coeff_lines.extend([str(c) for c in coeff])
with open(coeff_file, 'w') as f:
f.write('\n'.join(coeff_lines))
param_lines = []
keys = ['rcutfac', 'twojmax', 'rfac0', 'rmin0', 'diagonalstyle']
param_lines.extend(['{} {}'.format(k, getattr(describer, k))
for k in keys])
param_lines.append('quadraticflag {}'.format(int(describer.quadratic)))
param_lines.append('bzeroflag 0')
with open(param_file, 'w') as f:
f.write('\n'.join(param_lines))
pair_coeff = self.pair_coeff.format(elements=' '.join(elements),
specie=self.specie.name,
coeff_file=coeff_file,
param_file=param_file)
ff_settings = [self.pair_style, pair_coeff]
return ff_settings
示例13: from_config
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def from_config(param_file, coeff_file, **kwargs):
"""
Initialize potentials with parameters file and coefficient file.
Args:
param_file (str): The file storing the configuration of potentials.
coeff_file (str): The file storing the coefficients of potentials.
Return:
SNAPotential.
"""
with open(coeff_file) as f:
coeff_lines = f.readlines()
coeff_lines = [line for line in coeff_lines if not line.startswith('#')]
specie, r, w = coeff_lines[1].split()
r, w = float(r), int(w)
element_profile = {specie: {'r': r, 'w': w}}
rcut_pattern = re.compile(r'rcutfac (.*?)\n', re.S)
twojmax_pattern = re.compile(r'twojmax (\d*)\n', re.S)
rfac_pattern = re.compile(r'rfac0 (.*?)\n', re.S)
rmin_pattern = re.compile(r'rmin0 (.*?)\n', re.S)
diagonalstyle_pattern = re.compile(r'diagonalstyle (.*?)\n', re.S)
quadratic_pattern = re.compile(r'quadraticflag (.*?)(?=\n|$)', re.S)
with zopen(param_file, 'rt') as f:
param_lines = f.read()
rcut = float(rcut_pattern.findall(param_lines)[-1])
twojmax = int(twojmax_pattern.findall(param_lines)[-1])
rfac = float(rfac_pattern.findall(param_lines)[-1])
rmin = int(rmin_pattern.findall(param_lines)[-1])
diagonal = int(diagonalstyle_pattern.findall(param_lines)[-1])
if quadratic_pattern.findall(param_lines):
quadratic = bool(int(quadratic_pattern.findall(param_lines)[-1]))
else:
quadratic = False
describer = BispectrumCoefficients(rcutfac=rcut, twojmax=twojmax,
rfac0=rfac, element_profile=element_profile,
rmin0=rmin, diagonalstyle=diagonal, quadratic=quadratic,
pot_fit=True)
model = LinearModel(describer=describer, **kwargs)
model.model.coef_ = np.array(coeff_lines[2:], dtype=np.float)
model.model.intercept_ = 0
snap = SNAPotential(model=model)
snap.specie = Element(specie)
return snap
示例14: getAngles
# 需要导入模块: import pymatgen [as 别名]
# 或者: from pymatgen import Element [as 别名]
def getAngles(struct, sigma, npts, amin, amax, cutoff, centralAtom, ligandAtom):
""" compute all angles """
# info
print("\nBending angles analyses :")
print("-------------------------")
print("Central atom : %s" % centralAtom)
print("Ligand atom : %s" % ligandAtom)
print("cutoff : %f" % cutoff)
# central sites
central_sites = [site for site in struct
if site.specie == mg.Element(centralAtom)]
# x values for histogram
aval = np.linspace(amin, amax, npts)
# data
data = np.zeros(npts)
print("\nCoordinence")
for csite in central_sites:
neighbors = [(site, d) for site, d in struct.get_neighbors(csite, cutoff)
if site.specie == mg.Element(ligandAtom)]
iat = struct.index(csite)
print("%5s(%2d) : %d" % (csite.specie.symbol, iat, len(neighbors)))
#neighbors.append((distance, xij))
# compute bending angles and build histogram
for i in range(len(neighbors)):
isite, di = neighbors[i]
xic = isite.coords - csite.coords
for j in range(i + 1, len(neighbors)):
jsite, dj = neighbors[j]
xjc = jsite.coords - csite.coords
scal = np.dot(xic, xjc) / di / dj
if np.fabs(scal) > 1.:
print("Dot product error : %f" % scal)
raise ValueError
angle = np.degrees(np.arccos(scal))
# add a gaussian function
data += norm.pdf(aval, loc=angle, scale=sigma)
# print data
line = "# structural analysis\n"
line += "# column 1 : angle (degree)\n"
line += "# column 2 : histogram of angle %s-%s-%s\n" % (ligandAtom, centralAtom, ligandAtom)
for a, h in zip(aval, data):
line += "%12.4f %12.4f\n" % (a, h)
print("\n=> Print file anaAngles.dat\n")
open("anaAngles.dat", "w").write(line)
return aval, data