def xyz_to_sbu(path: str) -> Dict[str, Fragment]: """ [summary] Parameters ---------- path : str [description] Returns ------- Fragment [description] """ xyz = XYZ.from_file(path) names = get_xyz_names(path) sbu = {} for molecule, name in zip(xyz.all_molecules, names): dummies_idx = molecule.indices_from_symbol("X") symmetric_mol = Molecule([ "H", ] * len(dummies_idx), [molecule[idx].coords for idx in dummies_idx], charge=len(dummies_idx)) symmetry = PointGroupAnalyzer(symmetric_mol, tolerance=0.1) sbu[name] = Fragment(atoms=molecule, symmetry=symmetry, name=name) return sbu
def read_mol(filename): """ Reads a molecule based on file extension. For example, anything ending in a "xyz" is assumed to be a XYZ file. Supported formats include xyz, gaussian input (gjf|g03|g09|com|inp), Gaussian output (.out|and pymatgen's JSON serialized molecules. Using openbabel, many more extensions are supported but requires openbabel to be installed. Args: filename (str): A filename to read from. Returns: A Molecule object. """ fname = os.path.basename(filename) if fnmatch(fname.lower(), "*.xyz*"): return XYZ.from_file(filename).molecule elif any([fnmatch(fname.lower(), "*.{}*".format(r)) for r in ["gjf", "g03", "g09", "com", "inp"]]): return GaussianInput.from_file(filename).molecule elif any([fnmatch(fname.lower(), "*.{}*".format(r)) for r in ["out", "lis", "log"]]): return GaussianOutput(filename).final_structure elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"): with zopen(filename) as f: s = json.load(f, cls=MontyDecoder) if type(s) != Molecule: raise IOError("File does not contain a valid serialized " "molecule") return s else: m = re.search("\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)", filename.lower()) if m: return BabelMolAdaptor.from_file(filename, m.group(1)).pymatgen_mol raise ValueError("Unrecognized file extension!")
def test_from_file(self): filepath = os.path.join(test_dir, 'multiple_frame_xyz.xyz') mxyz = XYZ.from_file(filepath) self.assertEqual(len(mxyz.all_molecules), 302) self.assertEqual(list(mxyz.all_molecules[0].cart_coords[0]), [0.20303525080000001, 2.8569761204000002, 0.44737723190000001]) self.assertEqual(list(mxyz.all_molecules[-1].cart_coords[-1]), [5.5355550720000002, 0.0282305931, -0.30993102189999999]) self.assertEqual(list(mxyz.molecule.cart_coords[-1]), [5.5355550720000002, 0.0282305931, -0.30993102189999999])
def form_xyz(self, filename): xyz = XYZ.from_file(filename) mols = xyz.all_molecules self.total_time = len(mols) for i in mols: self.sites.append(i.sites) self.N = len(self.sites[0]) self.time = np.arange(0, self.total_time * self.t_convert, self.t_convert) self.msd['time'] = self.time
def largercube(cube_length): """ read POSCAR in the current directory and output another POSCAR with larger cube size """ dir_path = os.path.dirname(os.path.realpath(__file__)) poscar = Poscar.from_file(os.path.join(dir_path, 'POSCAR')) structure = poscar.structure XYZ(structure).write_file(os.path.join(dir_path, 'POSCAR.xyz')) molecule = XYZ.from_file(os.path.join(dir_path, 'POSCAR.xyz')).molecule a = b = c = cube_length structure = molecule.get_boxed_structure(a, b, c) Poscar(structure).write_file(os.path.join(dir_path, 'POSCAR_larger.vasp'))
def main(): parser = argparse.ArgumentParser( description= "Replace the atom coordinates of the first job in QChem input file with the coordinates from" "an XYZ file") parser.add_argument("-i", "--input", dest="input", type=str, required=True, help="the QChem input filename") parser.add_argument("-c", "--coords", dest="coords", type=str, required=True, help="The XYZ file contains the new coords") parser.add_argument("-v", "--velocity", dest="velocity", type=str, default=None, help="The AIMD velocity file") parser.add_argument( "-o", "--output", dest="output", type=str, required=True, help="the QChem input filename with the coordinates from the XYZ file") options = parser.parse_args() qcinp = QcInput.from_file(options.input) charge, spin = qcinp.jobs[0].charge, qcinp.jobs[0].spin_multiplicity if options.velocity is None: new_mol = Molecule.from_file(options.coords) else: mxyz = XYZ.from_file(options.coords) new_mol = mxyz.all_molecules[-1] qcinp.jobs[0].params["rem"].pop("aimd_init_veloc", None) qcnv = QcNucVeloc(options.velocity) assert len(mxyz.molecules) == len(qcnv.velocities) qcinp.jobs[0].set_velocities(qcnv.velocities[-1]) if charge is not None: new_mol.set_charge_and_spin(charge, spin) qcinp.jobs[0].mol = new_mol qcinp.write_file(options.output) print( "created new QChem input file {new_file} using {old_inp} as an template and filled with coordinates " \ "from {coord_file}".format(old_inp=options.input, coord_file=options.coords, new_file=options.output))
def read_file(filename): ''' 根据path读取各个文件,不论是vasp还是cif还是xyz :param filename: 文件的路径 :return: 如果是vasp或者cif 则返回structure对象,如果是xyz则返回mol对象 ''' suffix = os.path.split(filename)[-1] suffix = suffix.split('.')[-1] if suffix == 'vasp' or suffix == 'POSCAR' or suffix == 'CONTCAR': structure = Poscar.from_file(filename).structure elif suffix == 'cif': structure = CifParser( filename, occupancy_tolerance=0.7).get_structures(primitive=False)[0] elif suffix == 'xyz': structure = XYZ.from_file(filename).molecule elif suffix == 'CHGCAR' or suffix == 'CHG': structure = Chgcar.from_file(filename) return structure
def run(self, copy_to_current_on_exit=False, site_property=None): """ Write the input file to the scratch directory, run packmol and return the packed molecule. Args: copy_to_current_on_exit (bool): Whether or not to copy the packmol input/output files from the scratch directory to the current directory. site_property (str): if set then the specified site property for the the final packed molecule will be restored. Returns: Molecule object """ scratch = tempfile.gettempdir() with ScratchDir(scratch, copy_to_current_on_exit=copy_to_current_on_exit ) as scratch_dir: self._write_input(input_dir=scratch_dir) packmol_input = open(os.path.join(scratch_dir, self.input_file), 'r') p = Popen(self.packmol_bin, stdin=packmol_input, stdout=PIPE, stderr=PIPE) (stdout, stderr) = p.communicate() output_file = os.path.join(scratch_dir, self.control_params["output"]) if os.path.isfile(output_file): packed_mol = XYZ.from_file(output_file) print("packed molecule written to {}".format( self.control_params["output"])) if site_property: packed_mol = self.restore_site_properties( site_property=site_property, filename=output_file) return packed_mol else: print("Packmol execution failed") print(stdout, stderr) return None
def read_mol(filename): """ Reads a molecule based on file extension. For example, anything ending in a "xyz" is assumed to be a XYZ file. Supported formats include xyz, gaussian input (gjf|g03|g09|com|inp), Gaussian output (.out|and pymatgen's JSON serialized molecules. Using openbabel, many more extensions are supported but requires openbabel to be installed. Args: filename (str): A filename to read from. Returns: A Molecule object. """ fname = os.path.basename(filename) if fnmatch(fname.lower(), "*.xyz*"): return XYZ.from_file(filename).molecule elif any([ fnmatch(fname.lower(), "*.{}*".format(r)) for r in ["gjf", "g03", "g09", "com", "inp"] ]): return GaussianInput.from_file(filename).molecule elif any([ fnmatch(fname.lower(), "*.{}*".format(r)) for r in ["out", "lis", "log"] ]): return GaussianOutput(filename).final_structure elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"): with zopen(filename) as f: s = json.load(f, cls=MontyDecoder) if type(s) != Molecule: raise IOError("File does not contain a valid serialized " "molecule") return s else: m = re.search("\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)", filename.lower()) if m: return BabelMolAdaptor.from_file(filename, m.group(1)).pymatgen_mol raise ValueError("Unrecognized file extension!")
#%% from pymatgen.core.sites import Site from pymatgen.io.xyz import XYZ import os os.chdir('/home/jinho93/oxides/wurtzite/zno/cp2k/1.aimd/3.16A/30/3.fix/output') xyz = XYZ.from_file('zno-pos-1.xyz') coords = [] for m in xyz.all_molecules: s: Site tmp = [] for s in m.sites: if s.species_string == 'Zn': tmp.append(s.z) coords.append(tmp) # %% import numpy as np coords = np.array(coords) print(coords.shape) #%% import matplotlib.pyplot as plt for i in range(coords.shape[1]): plt.plot(coords[:, i], color='black') plt.ylim((18, 30)) plt.xlim((0, 200))
def _parse_crest_output(self): """ Parse output file and directory to extract all command line inputs and output files. Sets the attributes: cmd_options: Dict of type {flag: value} sorted_structrues_energies: n x m x 2 list, for n conformers, m rotamers per conformer, and tuple of [Molecule, energy] properly_terminated: True or False if run properly terminated """ output_filepath = os.path.join(self.path, self.filename) # Get CREST command crest_cmd = None with open(output_filepath, "r") as xtbout_file: for line in xtbout_file: if "> crest" in line: crest_cmd = line.strip()[8:] break split_cmd = crest_cmd.split(" ") # Get input file if present try: self.coord_file = os.path.join(self.path, split_cmd[0]) self.input_structure = Molecule.from_file(filename=self.coord_file) except FileNotFoundError: print("Input file {} not found".format(split_cmd[0])) # Get CREST input flags for i, entry in enumerate(split_cmd): value = None if entry: if "-" in entry: option = entry[1:] if i + 1 < len(split_cmd): if "-" not in split_cmd[i + 1]: value = split_cmd[i + 1] self.cmd_options[option] = value # Get input charge for decorating parsed molecules chg = 0 if "chrg" in self.cmd_options.keys(): str_chg = self.cmd_options["chrg"] if "-" in str_chg: chg = int(str_chg) else: chg = int(str_chg[-1]) elif "c" in self.cmd_options.keys(): str_chg = self.cmd_options["c"] if "-" in str_chg: chg = int(str_chg) else: chg = int(str_chg[-1]) # Check for proper termination with open(output_filepath, "rb+") as xtbout_file: xtbout_file.seek(-2, 2) while xtbout_file.read(1) != b"\n": xtbout_file.seek(-2, 1) end_bstring = xtbout_file.read() if b"CREST terminated normally." in end_bstring: self.properly_terminated = True if self.properly_terminated: # Parse for number of conformers and rotamers conformer_pattern = re.compile( r"\s+\d+\s+(?P<Erel>\d*\.\d*)\s+(?P<Etot>-*\d+\.\d+)\s+" r"(?P<weight>-*\d+\.\d+)\s+" r"(?P<conformer>-*\d+\.\d+)\s+(?P<set>\d+)\s+(?P<degen>\d+)\s+" r"(?P<origin>\w+)\n") rotamer_pattern = re.compile( r"\s+\d+\s+(?P<Erel>\d*\.\d*)\s+(?P<Etot>-*\d+\.\d+)\s+" r"(?P<weight>-*\d+\.\d+)\s+" r"(?P<origin>\w+)\n") conformer_degeneracies = [] energies = [] with open(output_filepath, "r") as xtbout_file: for line in xtbout_file: conformer_match = conformer_pattern.match(line) rotamer_match = rotamer_pattern.match(line) if conformer_match: conformer_degeneracies.append( int(conformer_match["degen"])) energies.append(conformer_match["Etot"]) elif rotamer_match: energies.append(rotamer_match["Etot"]) # Get final rotamers file and read in all molecules, # sorted by conformer type and energy if "crest_rotamers.xyz" in os.listdir(self.path): final_rotamer_filename = "crest_rotamers.xyz" else: n_rot_files = [] for f in os.listdir(self.path): if "crest_rotamers" in f: n_rot_file = int(os.path.splitext(f)[0].split("_")[2]) n_rot_files.append(n_rot_file) if len(n_rot_files) > 0: final_rotamer_filename = "crest_rotamers_{}.xyz".format( max(n_rot_files)) try: rotamers_path = os.path.join(self.path, final_rotamer_filename) rotamer_structures = XYZ.from_file(rotamers_path).all_molecules for r in rotamer_structures: r.set_charge_and_spin(charge=chg) start = 0 for n, d in enumerate(conformer_degeneracies): self.sorted_structures_energies.append([]) i = 0 for i in range(start, start + d): self.sorted_structures_energies[n].append( [rotamer_structures[i], energies[i]]) start = i + 1 except FileNotFoundError: print("{} not found, no rotamer list processed".format( final_rotamer_filename)) # Get lowest energy conformer from 'crest_best.xyz' crestbest_path = os.path.join(self.path, "crest_best.xyz") try: lowest_e_struct = Molecule.from_file(crestbest_path) lowest_e_struct.set_charge_and_spin(charge=chg) self.lowest_energy_structure = lowest_e_struct except FileNotFoundError: print("{} not found".format(crestbest_path)) else: crestbest_path = os.path.join(self.path, "crest_best.xyz") try: lowest_e_struct = Molecule.from_file(crestbest_path) lowest_e_struct.set_charge_and_spin(charge=chg) self.lowest_energy_structure = lowest_e_struct except FileNotFoundError: print("{} not found".format(crestbest_path))
def xyz2struc(xyz_file): """ read xyz file and return molecule structure """ return XYZ.from_file(xyz_file).molecule
#%% from pymatgen import Element from pymatgen.io.xyz import XYZ import matplotlib.pyplot as plt import os os.chdir('/home/jinho93/new/oxides/perobskite/lanthanum-aluminate/periodic_step/cp2k/015_thick4/2000k') xyz = XYZ.from_file('lao-pos-1.xyz') output = [] for structure in xyz.all_molecules: p = 0 la = [] al = [] o = [] for i in structure.sites: if i.specie == Element.O: p -= 2 * i.z elif i.specie == Element.Al: p += 3 * i.z elif i.specie is Element.La: p += 3 * i.z output.append(p) plt.plot(output)
def fix_scf(self): comments = self.fix_step.params.get("comment", "") scf_pattern = re.compile( r"<SCF Fix Strategy>(.*)</SCF Fix " r"Strategy>", flags=re.DOTALL) old_strategy_text = re.findall(scf_pattern, comments) if len(old_strategy_text) > 0: old_strategy_text = old_strategy_text[0] od = self.outdata[self.error_step_id] if "Negative Eigen" in self.errors: if "thresh" not in self.fix_step.params["rem"]: self.fix_step.set_integral_threshold(thresh=12) return "use tight integral threshold" elif int(self.fix_step.params["rem"]["thresh"]) < 14: self.fix_step.set_integral_threshold(thresh=14) return "use even tighter integral threshold" if len(od["scf_iteration_energies"]) == 0 \ or len(od["scf_iteration_energies"][-1]) <= 10: if 'Exit Code 134' in self.errors: # immature termination of SCF return self.fix_error_code_134() else: return None if od["jobtype"] in ["opt", "ts", "aimd"] \ and len(od["molecules"]) >= 2: strategy = "reset" elif len(old_strategy_text) > 0: strategy = json.loads(old_strategy_text) strategy["current_method_id"] += 1 else: strategy = dict() scf_iters = od["scf_iteration_energies"][-1] if scf_iters[-1][1] >= self.rca_gdm_thresh: strategy["methods"] = [ "increase_iter", "rca_diis", "gwh", "gdm", "rca", "core+rca", "fon" ] strategy["current_method_id"] = 0 else: strategy["methods"] = [ "increase_iter", "diis_gdm", "gwh", "rca", "gdm", "core+gdm", "fon" ] strategy["current_method_id"] = 0 strategy["version"] = 2.0 # noinspection PyTypeChecker if strategy == "reset": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) if self.error_step_id > 0: self.set_scf_initial_guess("read") else: self.set_scf_initial_guess("sad") if od["jobtype"] in ["opt", "ts"]: self.set_last_input_geom(od["molecules"][-1]) else: assert od["jobtype"] == "aimd" from pymatgen.io.qchem import QcNucVeloc from pymatgen.io.xyz import XYZ scr_dir = od["scratch_dir"] qcnv_filepath = os.path.join(scr_dir, "AIMD", "NucVeloc") qc_md_view_filepath = os.path.join(scr_dir, "AIMD", "View.xyz") qcnv = QcNucVeloc(qcnv_filepath) qc_md_view = XYZ.from_file(qc_md_view_filepath) assert len(qcnv.velocities) == len(qc_md_view.all_molecules) aimd_steps = self.fix_step.params["rem"]["aimd_steps"] elapsed_steps = len(qc_md_view.all_molecules) remaining_steps = aimd_steps - elapsed_steps + 1 self.fix_step.params["rem"]["aimd_steps"] = remaining_steps self.set_last_input_geom(qc_md_view.molecule) self.fix_step.set_velocities(qcnv.velocities[-1]) self.fix_step.params["rem"].pop("aimd_init_veloc", None) traj_num = max([0] + [ int(f.split(".")[1]) for f in glob.glob("traj_View.*.xyz") ]) dest_view_filename = "traj_View.{}.xyz".format(traj_num + 1) dest_nv_filename = "traj_NucVeloc.{}.txt".format(traj_num + 1) logging.info( "Backing up trajectory files to {} and {}.".format( dest_view_filename, dest_nv_filename)) shutil.copy(qc_md_view_filepath, dest_view_filename) shutil.copy(qcnv_filepath, dest_nv_filename) if len(old_strategy_text) > 0: comments = scf_pattern.sub("", comments) self.fix_step.params["comment"] = comments if len(comments.strip()) == 0: self.fix_step.params.pop("comment") return "reset" elif strategy["current_method_id"] > len(strategy["methods"]) - 1: return None else: # noinspection PyTypeChecker method = strategy["methods"][strategy["current_method_id"]] if method == "increase_iter": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "rca_diis": self.fix_step.set_scf_algorithm_and_iterations( algorithm="rca_diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "gwh": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("gwh") elif method == "gdm": self.fix_step.set_scf_algorithm_and_iterations( algorithm="gdm", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "rca": self.fix_step.set_scf_algorithm_and_iterations( algorithm="rca", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "core+rca": self.fix_step.set_scf_algorithm_and_iterations( algorithm="rca", iterations=self.scf_max_cycles) self.set_scf_initial_guess("core") elif method == "diis_gdm": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis_gdm", iterations=self.scf_max_cycles) self.fix_step.set_scf_initial_guess("sad") elif method == "core+gdm": self.fix_step.set_scf_algorithm_and_iterations( algorithm="gdm", iterations=self.scf_max_cycles) self.set_scf_initial_guess("core") elif method == "fon": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") natoms = len(od["molecules"][-1]) self.fix_step.params["rem"]["occupations"] = 2 self.fix_step.params["rem"]["fon_norb"] = int(natoms * 0.618) self.fix_step.params["rem"]["fon_t_start"] = 300 self.fix_step.params["rem"]["fon_t_end"] = 300 self.fix_step.params["rem"]["fon_e_thresh"] = 6 self.fix_step.set_integral_threshold(14) self.fix_step.set_scf_convergence_threshold(7) else: raise ValueError("fix method " + method + " is not supported") strategy_text = "<SCF Fix Strategy>" strategy_text += json.dumps(strategy, indent=4, sort_keys=True) strategy_text += "</SCF Fix Strategy>" if len(old_strategy_text) > 0: comments = scf_pattern.sub(strategy_text, comments) else: comments += "\n" + strategy_text self.fix_step.params["comment"] = comments return method
def fix_scf(self): comments = self.fix_step.params.get("comment", "") scf_pattern = re.compile(r"<SCF Fix Strategy>(.*)</SCF Fix " r"Strategy>", flags=re.DOTALL) old_strategy_text = re.findall(scf_pattern, comments) if len(old_strategy_text) > 0: old_strategy_text = old_strategy_text[0] od = self.outdata[self.error_step_id] if "Negative Eigen" in self.errors: if "thresh" not in self.fix_step.params["rem"]: self.fix_step.set_integral_threshold(thresh=12) return "use tight integral threshold" elif int(self.fix_step.params["rem"]["thresh"]) < 14: self.fix_step.set_integral_threshold(thresh=14) return "use even tighter integral threshold" if len(od["scf_iteration_energies"]) == 0 \ or len(od["scf_iteration_energies"][-1]) <= 10: if 'Exit Code 134' in self.errors: # immature termination of SCF return self.fix_error_code_134() else: return None if od["jobtype"] in ["opt", "ts", "aimd"] \ and len(od["molecules"]) >= 2: strategy = "reset" elif len(old_strategy_text) > 0: strategy = json.loads(old_strategy_text) strategy["current_method_id"] += 1 else: strategy = dict() scf_iters = od["scf_iteration_energies"][-1] if scf_iters[-1][1] >= self.rca_gdm_thresh: strategy["methods"] = ["increase_iter", "rca_diis", "gwh", "gdm", "rca", "core+rca", "fon"] strategy["current_method_id"] = 0 else: strategy["methods"] = ["increase_iter", "diis_gdm", "gwh", "rca", "gdm", "core+gdm", "fon"] strategy["current_method_id"] = 0 strategy["version"] = 2.0 # noinspection PyTypeChecker if strategy == "reset": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) if self.error_step_id > 0: self.set_scf_initial_guess("read") else: self.set_scf_initial_guess("sad") if od["jobtype"] in ["opt", "ts"]: self.set_last_input_geom(od["molecules"][-1]) else: assert od["jobtype"] == "aimd" from pymatgen.io.qchem import QcNucVeloc from pymatgen.io.xyz import XYZ scr_dir = od["scratch_dir"] qcnv_filepath = os.path.join(scr_dir, "AIMD", "NucVeloc") qc_md_view_filepath = os.path.join(scr_dir, "AIMD", "View.xyz") qcnv = QcNucVeloc(qcnv_filepath) qc_md_view = XYZ.from_file(qc_md_view_filepath) assert len(qcnv.velocities) == len(qc_md_view.all_molecules) aimd_steps = self.fix_step.params["rem"]["aimd_steps"] elapsed_steps = len(qc_md_view.all_molecules) remaining_steps = aimd_steps - elapsed_steps + 1 self.fix_step.params["rem"]["aimd_steps"] = remaining_steps self.set_last_input_geom(qc_md_view.molecule) self.fix_step.set_velocities(qcnv.velocities[-1]) self.fix_step.params["rem"].pop("aimd_init_veloc", None) traj_num = max([0] + [int(f.split(".")[1]) for f in glob.glob("traj_View.*.xyz")]) dest_view_filename = "traj_View.{}.xyz".format(traj_num + 1) dest_nv_filename = "traj_NucVeloc.{}.txt".format(traj_num + 1) logging.info("Backing up trajectory files to {} and {}." .format(dest_view_filename, dest_nv_filename)) shutil.copy(qc_md_view_filepath, dest_view_filename) shutil.copy(qcnv_filepath, dest_nv_filename) if len(old_strategy_text) > 0: comments = scf_pattern.sub("", comments) self.fix_step.params["comment"] = comments if len(comments.strip()) == 0: self.fix_step.params.pop("comment") return "reset" elif strategy["current_method_id"] > len(strategy["methods"])-1: return None else: # noinspection PyTypeChecker method = strategy["methods"][strategy["current_method_id"]] if method == "increase_iter": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "rca_diis": self.fix_step.set_scf_algorithm_and_iterations( algorithm="rca_diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "gwh": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("gwh") elif method == "gdm": self.fix_step.set_scf_algorithm_and_iterations( algorithm="gdm", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "rca": self.fix_step.set_scf_algorithm_and_iterations( algorithm="rca", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") elif method == "core+rca": self.fix_step.set_scf_algorithm_and_iterations( algorithm="rca", iterations=self.scf_max_cycles) self.set_scf_initial_guess("core") elif method == "diis_gdm": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis_gdm", iterations=self.scf_max_cycles) self.fix_step.set_scf_initial_guess("sad") elif method == "core+gdm": self.fix_step.set_scf_algorithm_and_iterations( algorithm="gdm", iterations=self.scf_max_cycles) self.set_scf_initial_guess("core") elif method == "fon": self.fix_step.set_scf_algorithm_and_iterations( algorithm="diis", iterations=self.scf_max_cycles) self.set_scf_initial_guess("sad") natoms = len(od["molecules"][-1]) self.fix_step.params["rem"]["occupations"] = 2 self.fix_step.params["rem"]["fon_norb"] = int(natoms * 0.618) self.fix_step.params["rem"]["fon_t_start"] = 300 self.fix_step.params["rem"]["fon_t_end"] = 300 self.fix_step.params["rem"]["fon_e_thresh"] = 6 self.fix_step.set_integral_threshold(14) self.fix_step.set_scf_convergence_threshold(7) else: raise ValueError("fix method " + method + " is not supported") strategy_text = "<SCF Fix Strategy>" strategy_text += json.dumps(strategy, indent=4, sort_keys=True) strategy_text += "</SCF Fix Strategy>" if len(old_strategy_text) > 0: comments = scf_pattern.sub(strategy_text, comments) else: comments += "\n" + strategy_text self.fix_step.params["comment"] = comments return method
bv_sum.append(round(pma.calculate_bv_sum(test_site, nn), 2)) bv_elem.append(test_site.specie.symbol) bv_type.append('Mineral') bv_name.append(m) # print(bv_sum) # exit() #protein # d = '/home/kenneth/proj/pro-min/proteins/feS/clusters/findGeo/combineFindGeoResults' d = '/home/kenneth/proj/pro-min/proteins/feS/sites' xyzs = glob(os.path.join(d, '*.xyz')) for xyz in xyzs: print(xyz) if xyz != os.path.join(d, 'pdb.xyz'): xyzObj = XYZ.from_file(xyz) # print(dir(xyzObj)) mol = xyzObj.molecule for site in mol.sites: print(site) import re f = os.path.splitext(os.path.split(xyz)[1])[0] # print(re.split('[_\.]',f)) # exit() pdb, resNum, elName, resID, atomID, chain, geo = re.split( '[_\.]', f) # print(pdb,resNum,elName,resID,atomID,chain,geo) if (geo != 'irr' and site.specie.symbol == 'Fe'): nn = mol.get_neighbors(site, 3.0)
import os from pymatgen.io.xyz import XYZ os.chdir('/home/jinho93/new/oxides/perobskite/lanthanum-aluminate/periodic_step/gulp/015/0/thick/4') xyz = XYZ.from_file('lao.xyz') XYZ.from
#%% from pymatgen.io.xyz import XYZ from pymatgen import Molecule import os os.chdir('/home/jinho93/oxides/wurtzite/zno/cp2k/1.aimd/3.16A/30/3.fix/output') xyz = XYZ.from_file('526.xyz') m: Molecule for i, m in enumerate(xyz.all_molecules): if i % 30 == 0: m.to('xyz', f'{i}.xyz')