Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def run_hse_calculations(directories, submit=True):
"""
Setup and submit HSE06 calculations for accurate band structures.
Requires a previous WAVECAR and IBZKPT from a PBE run. See
http://cms.mpi.univie.ac.at/wiki/index.php/Si_bandstructure for more
details.
"""
for directory in directories:
os.chdir(directory)
vasprun = Vasprun('vasprun.xml')
band_gap = vasprun.get_band_structure().get_band_gap()
kpath = []
if band_gap['energy']:
transition = band_gap['transition'].split('-')
# Amount to increment along the kpath to result in 10
# points total.
increment = ((transition[1][0] - transition[0][0]) / 9,
(transition[1][1] - transition[0][1]) / 9,
(transition[1][2] - transition[0][2] / 9))
for i in range(10):
kpath.append((transition[0] + increment[0] * i),
(transition[1] + increment[1] * i),
(transition[2] + increment[2] * i))
def __init__(self, filenames=".", vasprun='vasprun.xml', Kpointsfile='KPOINTS'):
"""
Args:
filenames (list or string): can be a list of file names or a path to a folder folder from which all
"FATBAND_*" files will be read
vasprun: corresponding vasprun file
Kpointsfile: KPOINTS file for bandstructure calculation, typically "KPOINTS"
"""
warnings.warn('Make sure all relevant FATBAND files were generated and read in!')
warnings.warn('Use Lobster 3.2.0 or newer for fatband calculations!')
VASPRUN = Vasprun(filename=vasprun, ionic_step_skip=None,
ionic_step_offset=0, parse_dos=True,
parse_eigen=False, parse_projected_eigen=False,
parse_potcar_file=False, occu_tol=1e-8,
exception_on_bad_xml=True)
self.structure = VASPRUN.final_structure
self.lattice = self.structure.lattice.reciprocal_lattice
self.efermi = VASPRUN.efermi
kpoints_object = Kpoints.from_file(Kpointsfile)
atomtype = []
atomnames = []
orbital_names = []
if not isinstance(filenames, list) or filenames is None:
filenames_new = []
if filenames is None:
def run_task(self, fw_spec):
from mpmorph.workflows.converge import get_converge_wf
vr = Vasprun('vasprun.xml.gz')
fws = []
for t in self['temperatures']:
fws.extend(get_converge_wf(s, int(t), max_steps=self['max_steps'],
target_steps=self['target_steps'],
trajectory_to_db=self['trajectory_to_db'],
notes=self['notes']))
wf = Workflow(fws)
return FWAction(detours=wf)
for dir_name in sorted_branch_dir_names:
xml_file = os.path.join(dir_name, "vasprun.xml")
if os.path.exists(xml_file):
run = Vasprun(xml_file, parse_projected_eigen=projections)
branches.append(run.get_band_structure(efermi=efermi))
else:
# It might be better to throw an exception
warnings.warn("Skipping {}. Unable to find {}"
.format(d=dir_name, f=xml_file))
return get_reconstructed_band_structure(branches, efermi)
else:
xml_file = os.path.join(dir_name, "vasprun.xml")
# Better handling of Errors
if os.path.exists(xml_file):
return Vasprun(xml_file, parse_projected_eigen=projections)\
.get_band_structure(kpoints_filename=None, efermi=efermi)
else:
return None
def from_files(struct="CONTCAR", pwf="WAVECAR", cr="POTCAR",
vr="vasprun.xml", outcar="OUTCAR", setup_projectors=False):
"""
Construct a Wavefunction object from file paths.
Arguments:
struct (str): VASP POSCAR or CONTCAR file path
pwf (str): VASP WAVECAR file path
cr (str): VASP POTCAR file path
vr (str): VASP vasprun file path
outcar (str): VASP OUTCAR file path
Returns:
Wavefunction object
"""
vr = Vasprun(vr)
symprec = vr.parameters["SYMPREC"]
return Wavefunction(Poscar.from_file(struct).structure,
PseudoWavefunction(pwf, vr),
CoreRegion(Potcar.from_file(cr)),
Outcar(outcar), symprec, setup_projectors)
def check_vasprun(vasprun: Union[str, Vasprun], vasprun_kwargs: dict = {}) -> \
Vasprun:
"""
Helper utility to take a vasprun file name or Vasprun object
and return a vasprun object.
:param vasprun: vasprun filename or object
"""
if type(vasprun) == str:
return Vasprun(vasprun, **vasprun_kwargs)
elif type(vasprun) == Vasprun:
return vasprun
else:
raise ValueError('Vasprun argument is not a string or '
'Vasprun instance!')
def get_mu_vs_F_N(basin_dir):
"""
Essentially the same function as plotting, but without the plot.
Returns {'F_N': F_N, 'mu': mu}. F_N is in units of nN.
"""
os.chdir('friction/normal')
spacings = [float(dir) for dir in os.listdir(os.getcwd()) if
os.path.isdir(dir)]
spacings.sort()
abs_E = [
Vasprun('{}/{}/vasprun.xml'.format(spacing, basin_dir)).final_energy
for spacing in spacings
]
E = [energy - abs_E[-1] for energy in abs_E]
spline = interpolate.splrep(spacings, E, s=0)
xnew = np.arange(spacings[0], spacings[-1], 0.001)
ynew = interpolate.splev(xnew, spline, der=0)
ynew_slope = interpolate.splev(spacings, spline, der=1)
F_N = [-y * 1.602 for y in ynew_slope]
os.chdir('../../friction/normal')
F_f = []
for spacing in sorted([float(spc) for spc in os.listdir(os.getcwd()) if
os.path.isdir(spc)]):
# framework and store them in a dictionary ({formula: entry}).
if os.path.isdir(competing_phase_directory):
os.chdir(competing_phase_directory)
for comp_dir in [dir for dir in os.listdir(os.getcwd())
if os.path.isdir(dir) and is_converged(dir)]:
vasprun = Vasprun('{}/vasprun.xml'.format(comp_dir))
composition = vasprun.final_structure.composition
energy = vasprun.final_energy
finished_competitors[comp_dir] = ComputedEntry(composition, energy)
os.chdir(original_directory)
else:
raise ValueError('Competing phase directory does not exist.')
composition = Structure.from_file('POSCAR').composition
try:
energy = Vasprun('vasprun.xml').final_energy
except:
raise ValueError('This directory does not have a converged vasprun.xml')
my_entry = ComputedEntry(composition, energy) # 2D material
entries = MPR.get_entries_in_chemsys([elt.symbol for elt in composition])
# If the energies of competing phases have been calculated in
# the current framework, put them in the phase diagram instead
# of the MP energies.
for i in range(len(entries)):
formula = entries[i].composition.reduced_formula
if formula in finished_competitors:
entries[i] = finished_competitors[formula]
else:
entries[i] = ComputedEntry(entries[i].composition, 100)
entries.append(my_entry) # 2D material
def plot_color_projected_bands(ylim=(-5, 5), fmt='pdf'):
"""
Plot a single band structure where the color of the band indicates
the elemental character of the eigenvalue.
Args:
ylim (tuple): minimum and maximum energies for the plot's
y-axis.
fmt (str): matplotlib format style. Check the matplotlib
docs for options.
"""
vasprun = Vasprun('vasprun.xml', parse_projected_eigen=True)
bs = vasprun.get_band_structure('KPOINTS', line_mode=True)
bspp = BSPlotterProjected(bs)
plot = bspp.get_elt_projected_plots_color()
fig = plot.gcf()
ax = fig.gca()
ax.set_xticklabels([r'$\mathrm{%s}$' % t for t in ax.get_xticklabels()])
ax.set_ylim(ylim)
fig.savefig('color_projected_bands.{}'.format(fmt))
plt.close()