Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def create_random_reader(num_atoms):
lattice = pmg.Lattice.from_parameters(1, 1, 1, 90, 90, 90)
positions = np.array([(_, _, _) for _ in np.linspace(0, 1, num_atoms)])
symbols = ['H'] * num_atoms
return MDReader(
energy=random.random(),
stress=np.random.random((3, 3)),
forces=np.random.random((num_atoms, 3)),
structure=pmg.Structure(lattice, symbols, positions))
def test_make_confs_0(self):
if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
with self.assertRaises(RuntimeError):
self.elastic.make_confs(self.target_path, self.equi_path)
shutil.copy(os.path.join(self.source_path, 'CONTCAR'), os.path.join(self.equi_path, 'CONTCAR'))
task_list = self.elastic.make_confs(self.target_path, self.equi_path)
dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))
incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
incar0['ISIF'] = 4
self.assertEqual(os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')),
os.path.realpath(os.path.join(self.target_path, 'POSCAR')))
ref_st = Structure.from_file(os.path.join(self.target_path, 'POSCAR'))
dfm_dirs.sort()
for ii in dfm_dirs:
st_file = os.path.join(ii, 'POSCAR')
self.assertTrue(os.path.isfile(st_file))
strain_json_file = os.path.join(ii, 'strain.json')
self.assertTrue(os.path.isfile(strain_json_file))
strain_json = loadfn(strain_json_file)
def parse_view(args):
from pymatgen.vis.structure_vtk import StructureVis
excluded_bonding_elements = args.exclude_bonding[0].split(",") \
if args.exclude_bonding else []
s = Structure.from_file(args.filename[0])
vis = StructureVis(excluded_bonding_elements=excluded_bonding_elements)
vis.set_structure(s)
vis.show()
def compare_structures(args):
filenames = args.filenames
if len(filenames) < 2:
print("You need more than one structure to compare!")
sys.exit(-1)
try:
structures = [Structure.from_file(fn) for fn in filenames]
except Exception as ex:
print("Error converting file. Are they in the right format?")
print(str(ex))
sys.exit(-1)
m = StructureMatcher() if args.group == "species" \
else StructureMatcher(comparator=ElementComparator())
for i, grp in enumerate(m.group_structures(structures)):
print("Group {}: ".format(i))
for s in grp:
print("- {} ({})".format(filenames[structures.index(s)],
s.formula))
print()
if None in symbols:
raise ValueError('Symbols needed for all atypes')
# Convert short symbols list to full species list
atype = system.atoms.atype
species = symbols[atype-1]
# Get atomic information
sites = system.atoms_prop(key='pos', scale=True)
prop = {}
for p in system.atoms_prop():
if p != 'atype' and p != 'pos':
prop[p] = system.atoms_prop(key=p)
# Build structure
structure = pmg.Structure(lattice, species, sites, site_properties=prop)
return structure
elif os.path.exists("CONTCAR"):
_poscar = Poscar.from_file("CONTCAR")
structure = _poscar.structure
adsorb_finder = AdsorbateSiteFinder(slab=structure, selective_dynamics=True)
ad_structs = adsorb_finder.generate_adsorption_structures(molecule=molecule, **adsorbate_gen_args)
opt_fws = []
stat_fws = []
for ad_struct in ad_structs:
_struct_dict = ad_struct.as_dict()
for site in _struct_dict["sites"]:
if "velocities" in site["properties"].keys():
del site["properties"]["velocities"]
_ad_struct = Structure.from_dict(_struct_dict)
opt_fws.append(
OptimizeFW(structure=_ad_struct, name=structure.composition.reduced_formula + "_slab_optimize",
**run_specs))
stat_fw = StaticFW(structure=_ad_struct, name=structure.composition.reduced_formula + "_slab_static",
prev_calc_loc=True, **run_specs, parents=[opt_fws[-1]])
stat_fw.tasks.append(SpawnVibrationalFWTask(run_specs=run_specs))
stat_fws.append(stat_fw)
fws = opt_fws
fws.extend(stat_fws)
wf = Workflow(fws)
return FWAction(additions=wf)
def MAST2Structure(lattice=None, coordinates=None, atom_list=None, coord_type='fractional'):
"""Helper function for converting input options into a pymatgen Structure object"""
if (coord_type.lower() == 'fractional'):
return pmg.Structure(lattice, atom_list, coordinates)
elif (coord_type.lower() == 'cartesian'):
return pmg.Structure(lattice, atom_list, coordinates,
coords_are_cartesian=True)
def _parse_structure(self, structure_schema):
data = structure_schema['data']
format = structure_schema['format']
if format == 'cif':
# cif lattice can be weird non standard shape
structure = (CifParser.from_string(data)).get_structures()[0]
lattice = pmg.Lattice.from_parameters(*structure.lattice.abc, *structure.lattice.angles)
structure = pmg.Structure(lattice, structure.species, structure.frac_coords, coords_are_cartesian=False)
elif format == 'POSCAR':
structure = (Poscar.from_string(data)).structure
return structure
# ------ strain matrix
strain_matrix = np.empty([3, 3])
for i in range(3):
for j in range(3):
if i <= j:
if i == j:
strain_matrix[i][j] = 1.0 + np.random.normal(
loc=0.0, scale=self.sigma)
else:
strain_matrix[i][j] = np.random.normal(
loc=0.0, scale=self.sigma)/2.0
strain_matrix[j][i] = strain_matrix[i][j]
# ------ strained lattice
strained_lattice = np.dot(strain_matrix, lat_mat).T
# ------ child
self.child = Structure(strained_lattice, struc.species,
struc.frac_coords)
# ------ scale lattice
self.child.scale_lattice(struc.volume)
# ------ check distance
if check_distance(self.child, self.atype, self.mindist):
# -- success
self.child = sort_by_atype(self.child, self.atype)
return self.child
else:
# -- failure
cnt += 1
if cnt >= self.maxcnt_ea:
self.child = None
return None # change parent
def run(self):
logger.info("MaterialsDescriptorBuilder starting...")
self._build_indexes()
q = {}
if not self.update_all:
q["descriptors.density"] = {"$exists": False}
mats = [m for m in self._materials.find(q, {"structure": 1, "material_id": 1})]
pbar = tqdm(mats)
for m in pbar:
pbar.set_description("Processing materials_id: {}".format(m['material_id']))
struct = Structure.from_dict(m["structure"])
d = {"descriptors": {}}
d["descriptors"]["dimensionality"] = get_dimensionality(struct)
d["descriptors"]["density"] = struct.density
d["descriptors"]["nsites"] = len(struct)
d["descriptors"]["volume"] = struct.volume
self._materials.update_one({"material_id": m["material_id"]}, {"$set": d})