本文整理汇总了Python中pymatgen.io.vaspio.Poscar类的典型用法代码示例。如果您正苦于以下问题:Python Poscar类的具体用法?Python Poscar怎么用?Python Poscar使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Poscar类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _vasp_poscar_setup
def _vasp_poscar_setup(self):
"""Set up the POSCAR file for a single VASP run.
"""
name = self.keywords['name']
pospath = os.path.join(name, "POSCAR")
if os.path.isfile(pospath):
my_poscar = Poscar.from_file(pospath)
#parent should have given a structure
else: #this is an originating run; mast should give it a structure
my_poscar = Poscar(self.keywords['structure'])
workdir=os.path.dirname(name)
sdir=os.path.join(workdir,"structure_index_files")
if os.path.exists(sdir):
mystr=my_poscar.structure
manname="manifest___"
myatomindex=AtomIndex(structure_index_directory=sdir)
newstr=myatomindex.graft_new_coordinates_from_manifest(mystr, manname, "")
self.logger.info("Getting original coordinates from manifest.")
new_pos=Poscar(newstr)
my_poscar=new_pos
self.logger.info("No POSCAR found from a parent; base structure used for %s" % self.keywords['name'])
if 'mast_coordinates' in self.keywords['program_keys'].keys():
sxtend = StructureExtensions(struc_work1=my_poscar.structure, name=self.keywords['name'])
coordstrucs=self.get_coordinates_only_structure_from_input()
newstruc = sxtend.graft_coordinates_onto_structure(coordstrucs[0])
my_poscar.structure=newstruc.copy()
dirutil.lock_directory(name)
self.write_poscar_with_zero_velocities(my_poscar, pospath)
dirutil.unlock_directory(name)
return my_poscar
示例2: main
def main(api="", queryid=""):
"""Get VASP inputs for Materials Project structure
Args:
api <str>: Materials Project API key
queryid <str>: Materials Project ID of the structure
Returns:
creates a folder named with that mpid, and including
some VASP input files.
"""
if api == "":
print "Must have an API key from materialsproject.org"
return None
if queryid == "":
print "No MP structure ID given. Exiting."
return None
rest_adapter = MPRester(api)
entries=list()
proplist=list()
proplist.append('pretty_formula')
proplist.append('structure')
proplist.append('potcar')
proplist.append('material_id')
myentry = rest_adapter.mpquery(criteria={'material_id':queryid}, properties=proplist)
if len(myentry) == 0:
print "Could not find entry for %s as material_id. Trying entry_id." % queryid
myentry = rest_adapter.mpquery(criteria={'entry_id':queryid}, properties=proplist)
if len(myentry) == 0:
print "Could not find entry for %s" % queryid
return None
entries.extend(myentry)
workdir = os.getcwd()
from pymatgen.io.vaspio_set import MITVaspInputSet, MPVaspInputSet
for entry in entries:
mpvis = MPVaspInputSet()
myname = str(entry['pretty_formula'])
#print entry['structure'].composition
#print entry['structure'].formula
#myname = entry['pretty_formula']
myname = myname.replace("(","_").replace(")","_")
myname = myname + "_" + entry['material_id']
os.mkdir(myname)
os.chdir(myname)
mystructure = entry['structure']
if mystructure.num_sites <= 10:
mystructure.make_supercell([2,2,2])
#mystructure.perturb(0.01)
incar = mpvis.get_incar(mystructure)
incar.write_file("INCAR")
potcar = mpvis.get_potcar(mystructure)
potcar.write_file("POTCAR")
#potcar_symbols = mpvis.get_potcar_symbols(mystructure)
myposcar=Poscar(mystructure)
mykpoints=mpvis.get_kpoints(mystructure)
mykpoints.write_file("KPOINTS")
myposcar.write_file("POSCAR")
os.chdir(workdir)
示例3: forward_final_structure_file
def forward_final_structure_file(self, childpath, newname="POSCAR"):
"""Forward the final structure.
For VASP, this is the CONTCAR.
Args:
childpath <str>: Path of child ingredient
newname <str>: new name (default 'POSCAR')
"""
proceed=False
workdir=os.path.dirname(self.keywords['name'])
sdir=os.path.join(workdir,"structure_index_files")
if os.path.exists(sdir):
proceed=True
if not proceed:
return self.copy_a_file(childpath, "CONTCAR", newname)
childmeta=Metadata(metafile="%s/metadata.txt" % childpath)
child_program=childmeta.read_data("program")
if not "vasp" in child_program: #madelung utility or another folder
return self.copy_a_file(childpath, "CONTCAR", newname)
child_scaling_label=childmeta.read_data("scaling_label")
child_defect_label=childmeta.read_data("defect_label")
child_neb_label=childmeta.read_data("neb_label")
child_phonon_label=childmeta.read_data("phonon_label")
if child_scaling_label == None:
child_scaling_label = ""
if child_defect_label == None:
child_defect_label = ""
if child_neb_label == None:
child_neb_label = ""
if child_phonon_label == None:
child_phonon_label = ""
parentmeta=Metadata(metafile="%s/metadata.txt" % self.keywords['name'])
parent_defect_label=parentmeta.read_data("defect_label")
parent_neb_label=parentmeta.read_data("neb_label")
if parent_defect_label == None:
parent_defect_label = ""
if parent_neb_label == None:
parent_neb_label = ""
if (not (child_neb_label == "")) and (not (parent_defect_label == "")):
child_defect_label = parent_defect_label
if (not (child_phonon_label == "")):
if (not (parent_defect_label == "")):
child_defect_label = parent_defect_label
if (not (parent_neb_label == "")):
child_neb_label = parent_neb_label
child_defect_label = parent_neb_label.split('-')[0].strip() # always define phonons from first endpoint
#get child manifest
childmanifest="manifest_%s_%s_%s" % (child_scaling_label, child_defect_label, child_neb_label)
#build structure from atom indices using parent name_frac_coords
ing_label=os.path.basename(self.keywords['name'])
childmeta.write_data("parent",ing_label)
mystr=Poscar.from_file("%s/CONTCAR" % self.keywords['name']).structure
myatomindex=AtomIndex(structure_index_directory=sdir)
if "inducescaling" in childpath: #initial scaled coords have no parent
ing_label="original"
newstr=myatomindex.graft_new_coordinates_from_manifest(mystr, childmanifest,ing_label)
newposcar=Poscar(newstr)
newposcar.write_file(os.path.join(childpath,newname))
return
示例4: run_aconvasp_command
def run_aconvasp_command(command, structure):
"""
Helper function for calling aconvasp with different arguments
"""
from pymatgen.io.vaspio import Poscar
poscar = Poscar(structure)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
output = p.communicate(input=poscar.get_string())
return output
示例5: refined
def refined(src="POSCAR"):
"""
refined poscar を 作成する
"""
srcpos = Poscar.from_file(src)
finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-1, angle_tolerance=8)
std = finder.get_refined_structure()
dstpos = Poscar(std)
dst = "POSCAR_refined"
Cabinet.reserve_file(dst)
dstpos.write_file(dst)
示例6: standard
def standard(src="POSCAR"):
"""
standardに変換
"""
srcpos = Poscar.from_file(src)
finder = SpacegroupAnalyzer(srcpos.structure)
std = finder.get_conventional_standard_structure()
dstpos = Poscar(std)
dst = "POSCAR_std"
Cabinet.reserve_file(dst)
dstpos.write_file(dst)
示例7: ConvertCifFileToPoscarFile
def ConvertCifFileToPoscarFile(cifFilename,poscarFilename):
parser = CifParser(cifFilename)
structure = parser.get_structures()[0]
structure_name = cif_file.split('.')[0]
poscar_obj = Poscar(structure=structure,comment=structure_name)
poscar_string = poscar_obj.to_string()
poscar_filename = '{}/{}.poscar'.format(poscar_directory_name,structure_name)
with open(poscar_filename,'w') as f:
f.write(poscar_string)
示例8: primitive
def primitive(src="POSCAR"):
"""
primitiveに変換
"""
srcpos = Poscar.from_file(src)
finder = SpacegroupAnalyzer(srcpos.structure)
prim = finder.get_primitive_standard_structure()
dstpos = Poscar(prim)
dst = "POSCAR_prim"
Cabinet.reserve_file(dst)
dstpos.write_file(dst)
示例9: convert_fmt
def convert_fmt(args):
iformat = args.input_format[0]
oformat = args.output_format[0]
filename = args.input_filename[0]
out_filename = args.output_filename[0]
try:
if iformat == "smart":
structure = read_structure(filename)
if iformat == "POSCAR":
p = Poscar.from_file(filename)
structure = p.structure
elif iformat == "CIF":
r = CifParser(filename)
structure = r.get_structures()[0]
elif iformat == "CSSR":
structure = Cssr.from_file(filename).structure
if oformat == "smart":
write_structure(structure, out_filename)
elif oformat == "POSCAR":
p = Poscar(structure)
p.write_file(out_filename)
elif oformat == "CIF":
w = CifWriter(structure)
w.write_file(out_filename)
elif oformat == "CSSR":
c = Cssr(structure)
c.write_file(out_filename)
elif oformat == "VASP":
input_set = MPVaspInputSet()
ts = TransformedStructure(
structure,
[],
history=[
{"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()}
],
)
ts.write_vasp_input(input_set, output_dir=out_filename)
elif oformat == "MITVASP":
input_set = MITVaspInputSet()
ts = TransformedStructure(
structure,
[],
history=[
{"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()}
],
)
ts.write_vasp_input(input_set, output_dir=out_filename)
except Exception as ex:
print "Error converting file. Are they in the right format?"
print str(ex)
示例10: checkrelax_single
def checkrelax_single(path, src_ini="posfinal", src_fin="posfinal3"):
dirc = path
initial = Poscar.from_file(os.path.join(dirc, src_ini)).structure.as_dict()["lattice"]
final = Poscar.from_file(os.path.join(dirc, src_fin)).structure.as_dict()["lattice"]
length_a = final[u"a"] / initial[u"a"]
length_b = final[u"b"] / initial[u"b"]
length_c = final[u"c"] / initial[u"c"]
delta_length = ((length_b / length_a - 1) ** 2 + (length_c / length_a - 1) ** 2) ** 0.5
# print(delta_length)
angle_a = final["alpha"] / initial["alpha"] - 1
angle_b = final["beta"] / initial["beta"] - 1
angle_c = final["gamma"] / initial["gamma"] - 1
delta_angle = (angle_a ** 2 + angle_b ** 2 + angle_c ** 2) ** 0.5
# print(delta_angle)
return delta_length, delta_angle
示例11: supercell
def supercell(poscar,scale,outFile=None,replace=False):
'''Reads in a structure in VASP POSCAR format and returns one with a supercell
of that structure
Args:
-------------------------------------
poscar: location of POSCAR file to find supercell of
scale: iterable of integer scaling factors with length 3.
kwargs:
-------------------------------------
outFile: location for new poscar file with
modifies:
-------------------------------------
outFile: if replace=True
poscar: if replace=False
'''
assert os.path.isfile(poscar)
assert replace==True or not outFile is None
p = Poscar.from_file(poscar,False)
# with open(poscar) as f:
# poscomment = f.readline().strip()
#
# p.comment = poscomment
p.structure.make_supercell(scale)
if replace==True:
p.write_file(poscar,vasp4_compatible=True)
else:
p.write_file(outFile,vasp4_compatible=True)
示例12: strout2poscar
def strout2poscar(src='str.out'):
"""
str.outをposcarの記述に変換し, Poscar objをreturn
"""
with open(src, 'r') as rfile:
lines = rfile.readlines()
latt_tmp = [[float(x) for x in y.split()] for y in lines[0:3]]
trans = [[float(x) for x in y.split()] for y in lines[3:6]]
sites_tmp = [[float(x) for x in y.split()[0:3]] for y in lines[6:]]
elements = [x.split()[3].split('+')[0].split('-')[0] for x in lines[6:]]
num_atoms = [elements.count(e)
for e in sorted(set(elements), key=elements.index)]
latt = np.dot(np.array(trans), np.array(latt_tmp))
sites = np.dot(np.array(sites_tmp), np.array(latt_tmp))
posc_str = "posc_orig\n"
posc_str += "1.00\n"
posc_str += "\n".join([" ".join([str(f) for f in l]) for l in latt])
posc_str += "\n"
posc_str += " ".join(sorted(set(elements), key=elements.index)) + "\n"
posc_str += " ".join([str(d) for d in num_atoms]) + "\n"
posc_str += "Cartesian\n"
posc_str += "\n".join([" ".join([str(f) for f in s]) for s in sites])
return Poscar.from_string(posc_str)
示例13: print_spg
def print_spg(src="POSCAR"):
srcpos = Poscar.from_file(src)
finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-2, angle_tolerance=8)
spg = finder.get_spacegroup_symbol()
spg_num = finder.get_spacegroup_number()
print(spg)
print(spg_num)
示例14: test_init_from_structure
def test_init_from_structure(self):
filepath = os.path.join(test_dir, "POSCAR")
poscar = Poscar.from_file(filepath)
struct = poscar.struct
xyz = XYZ(struct)
ans = """24
Fe4 P4 O16
Fe 2.277347 4.550379 2.260125
Fe 2.928536 1.516793 4.639870
Fe 7.483231 4.550379 0.119620
Fe 8.134420 1.516793 2.499364
P 0.985089 1.516793 1.990624
P 4.220794 4.550379 4.370369
P 6.190973 1.516793 0.389120
P 9.426677 4.550379 2.768865
O 0.451582 4.550379 3.365614
O 1.006219 1.516793 3.528306
O 1.725331 0.279529 1.358282
O 1.725331 2.754057 1.358282
O 3.480552 3.313115 3.738027
O 3.480552 5.787643 3.738027
O 4.199665 4.550379 1.148562
O 4.754301 1.516793 0.985870
O 5.657466 4.550379 3.773620
O 6.212102 1.516793 3.610928
O 6.931215 0.279529 1.021463
O 6.931215 2.754057 1.021463
O 8.686436 3.313115 3.401208
O 8.686436 5.787643 3.401208
O 9.405548 4.550379 1.231183
O 9.960184 1.516793 1.393875"""
self.assertEqual(str(xyz), ans)
示例15: read_structure
def read_structure(filename):
"""
Reads a structure based on file extension. For example, anything ending in
a "cif" is assumed to be a Crystallographic Information Format file.
Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
vasprun.xml, CSSR and pymatgen's JSON serialized structures.
Args:
filename (str): A filename to read from.
Returns:
A Structure object.
"""
fname = os.path.basename(filename)
if fnmatch(fname.lower(), "*.cif*"):
parser = CifParser(filename)
return parser.get_structures(True)[0]
elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
return Poscar.from_file(filename, False).structure
elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
return Chgcar.from_file(filename).structure
elif fnmatch(fname, "vasprun*.xml*"):
return Vasprun(filename).final_structure
elif fnmatch(fname.lower(), "*.cssr*"):
cssr = Cssr.from_file(filename)
return cssr.structure
elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
with zopen(filename) as f:
s = json.load(f, cls=PMGJSONDecoder)
if type(s) != Structure:
raise IOError("File does not contain a valid serialized "
"structure")
return s
raise ValueError("Unrecognized file extension!")