### Install PyXtal from Source Source: https://pyxtal.readthedocs.io/en/latest/Installation.html Installs pyxtal by cloning the repository and then installing it locally. This method is useful for development or using the latest code. ```bash $ git clone https://github.com/MaterSim/pyxtal $ cd pyxtal $ pip install . ``` -------------------------------- ### Install Openbabel Package Source: https://pyxtal.readthedocs.io/en/latest/Installation.html Installs the openbabel package using apt-get and then installs the Python bindings via pip. Ensure swig is installed separately. ```bash $ sudo apt-get install openbabel $ pip install openbabel ``` -------------------------------- ### Install Swig Source: https://pyxtal.readthedocs.io/en/latest/Installation.html Installs swig, a prerequisite for the openbabel Python bindings. Older versions of swig (before 2.0) are not compatible. ```bash $ sudo apt-get install swig ``` -------------------------------- ### Install Openbabel Python Bindings Source: https://pyxtal.readthedocs.io/en/latest/_sources/Installation.rst.txt Install Openbabel using apt-get and then the Python bindings using pip. Ensure you are using swig version 2.0 or higher. ```bash $ sudo apt-get install openbabel $ pip install openbabel ``` ```bash $ sudo apt-get install swig ``` -------------------------------- ### Run PyXtal Installation Test Source: https://pyxtal.readthedocs.io/en/latest/Installation.html Executes the pyxtal test script to verify the installation. This command should produce specific output indicating a successful setup. ```bash $ pyxtal_test.py ``` -------------------------------- ### Install PyXtal using pip Source: https://pyxtal.readthedocs.io/en/latest/Installation.html Installs the pyxtal package directly from PyPI using pip. ```bash $ pip install pyxtal ``` -------------------------------- ### Verify PyXtal Installation Source: https://pyxtal.readthedocs.io/en/latest/_sources/Installation.rst.txt Run the pyxtal_test.py script to verify the installation. Successful output includes a banner, version information, and test completion messages. ```bash $ pyxtal_test.py ``` -------------------------------- ### PyXtal Crystal Generation Example Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/block_crystal.html Demonstrates generating random crystal structures using PyXtal, with and without a specified molecular block. This example iterates through different block configurations and prints the resulting structure representations. ```python if __name__ == "__main__": import pymatgen.analysis.structure_matcher as sm from pyxtal import pyxtal from pyxtal.representation import representation smiles = [ "C1=C(C=C(C=C1[N+](=O)[O-])[N+](=O)[O-])C(=O)O.smi", "CC1=CC2=C(C=C1)N3CC4=C(C=CC(=C4)C)N(C2)C3.smi", ] for block in [None, "xxv"]: print("block", block) for i in range(30): s = pyxtal(molecular=True) s.from_random(3, 14, smiles, block=block) rep2 = representation.from_pyxtal(s) strs = rep2.to_string() print(i, strs) ``` -------------------------------- ### Get Element Properties Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/database/element.html Demonstrates how to create an Element object and access its properties like atomic number (z), mass, and covalent radius. Also shows how to get all isotopic masses. ```python el = Element("Fe") print(el.z) print(el.mass) print(el.covalent_radius) print(el.scatter) print(el.all_masses()) ``` -------------------------------- ### pyxtal.get_init_translations() Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/molecular_crystal.html Gets initial translation vectors for sites. ```APIDOC ## `pyxtal.get_init_translations()` ### Description Retrieves the initial translation vectors associated with each Wythoff site in the crystal structure. These translations are used to generate all symmetry-equivalent atomic positions. ### Parameters - **xtal** (object) - The PyXtal crystal object. ``` -------------------------------- ### Worker Logger Setup Source: https://pyxtal.readthedocs.io/en/latest/pyxtal.database.html Function to set up logging for worker processes. ```APIDOC ## Worker Logger Setup ### Description Sets up the logging configuration for worker processes, ensuring consistent logging output across distributed tasks. ### Method - `setup_worker_logger(level='INFO')` ### Parameters - `level` (str): The logging level (e.g., 'DEBUG', 'INFO', 'WARNING', 'ERROR'). Defaults to 'INFO'. ### Example ```python from pyxtal.db import setup_worker_logger setup_worker_logger(level='DEBUG') ``` ``` -------------------------------- ### Pyxtal Builder Initialization and Setup Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/lego/builder.html Demonstrates the initialization of the pyxtal builder and setting up its parameters, including descriptors, reference environments, and structural criteria. ```python if __name__ == "__main__": xtal = pyxtal() xtal.from_spg_wps_rep(194, ['2c', '2b'], [2.46, 6.70]) cif_file = xtal.to_pymatgen() bu = builder(['C'], [1], db_file='reaxff.db', verbose=False) # True) bu.set_descriptor_calculator(mykwargs={'rcut': 1.9}) bu.set_reference_enviroments(cif_file) bu.set_criteria(CN={'C': [3]}) print(bu) print(bu.ref_xtal) if False: wp_libs = bu.get_wp_libs_from_spglist([191, 179], ncpu=1) for wp_lib in wp_libs[:4]: print(wp_lib) bu.generate_xtals_from_wp_libs(wp_libs[4:8], ncpu=2, N_max=4, early_quit=0.05) ``` -------------------------------- ### Get All Positions from Wyckoff Position Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/symmetry.html Returns a list of all symmetry-equivalent positions from a given Wyckoff position, starting from any single coordinate within it. Requires the Group object and a representative position. ```python >>> from pyxtal.symmetry import Group >>> wp2 = Group(62)[-1] >>> wp2 Wyckoff position 4a in space group 62 with site symmetry -1 0, 0, 0 1/2, 0, 1/2 0, 1/2, 0 1/2, 1/2, 1/2 >>> wp2.get_all_positions([1/2, 1/2, 1/2]) array([[0. , 0. , 0. ], [0.5, 0. , 0.5], [0. , 0.5, 0. ], [0.5, 0.5, 0.5]]) ``` -------------------------------- ### DFTB+ Calculator Initialization Example Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/dftb.html Demonstrates how to initialize the DFTB+ calculator with various Hamiltonian parameters, including SCC, SCCTolerance, and MaxAngularMomentum settings. ```python calc = Dftb(Hamiltonian_=\"DFTB\", # line is included by default Hamiltonian_SCC='Yes', Hamiltonian_SCCTolerance=1e-8, Hamiltonian_MaxAngularMomentum_=\"\", ``` ```python Hamiltonian_MaxAngularMomentum_H='s', Hamiltonian_MaxAngularMomentum_O='p') ``` -------------------------------- ### Get Unique Structures from Database Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/db.html Filters a crystallographic database to retain only unique structures based on topology, energy, and Pymatgen matching. Keeps structures with lower degrees of freedom (DOF) when duplicates are found. Requires pymatgen to be installed. ```python from pymatgen.analysis.structure_matcher import StructureMatcher matcher = StructureMatcher(stol=0.3, ltol=0.2, angle_tol=5) print(f"The {self.db_name:s} has {self.db.count():d} strucs") if db_name is None: db_name = self.db_name[:-3] + "_unique.db" if os.path.exists(db_name): os.remove(db_name) ``` -------------------------------- ### Create Atom Site Instance Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/wyckoff_site.html Example demonstrating how to create an atom_site instance using a Wyckoff position, coordinate, and specie. ```python if __name__ == "__main__": from pyxtal.symmetry import Wyckoff_position as WP wp = WP.from_group_and_letter(225, 'a') coordinate = [0.25, 0.25, 0.25] specie = 6 atom_site_instance = atom_site(wp=wp, coordinate=coordinate, specie=specie) # Print the created instance print(atom_site_instance) ``` -------------------------------- ### Option Parser Setup Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/lego/SO3.html Sets up an OptionParser for command-line arguments, including crystal file path, cutoff radius, and lmax. ```python if __name__ == "__main__": from optparse import OptionParser from ase.io import read import time # ---------------------- Options ------------------------ parser = OptionParser() parser.add_option("-c", "--crystal", dest="structure", help="crystal from file, cif or poscar, REQUIRED", metavar="crystal") parser.add_option("-r", "--rcut", dest="rcut", default=3.0, type=float, help="cutoff for neighbor calcs, default: 3.0" ) parser.add_option("-l", "--lmax", dest="lmax", default=2, type=int, help="lmax, default: 2" ) ``` -------------------------------- ### Initialize SO3 and Compute Properties Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/lego/SO3.html Demonstrates initializing the SO3 class with custom parameters and computing symmetry properties for an ASE Atoms object. Includes options for derivatives. ```python from ase.io import read from pyxtal.lego.SO3 import SO3 import time import numpy as np # Placeholder for parser options, assuming they are defined elsewhere class Options: def __init__(self): self.nmax = 2 self.lmax = 2 self.rcut = 5.0 self.alpha = 2.0 self.der = True self.structure = None # Mock parser for demonstration purposes class MockParser: def add_option(self, *args, **kwargs): pass def parse_args(self): return Options(), [] parser = MockParser() # Mocking the read function from ase.io def read(filename, format): # This is a placeholder. In a real scenario, it would load a structure. # For this example, we'll create a dummy ASE structure. from ase import Atoms from ase.build import bulk if filename is None and format == 'vasp': return bulk('Si', 'diamond', a=5.459, cubic=True) return Atoms('H2') # Default dummy structure (options, args) = parser.parse_args() if options.structure is None: from ase.build import bulk test = bulk('Si', 'diamond', a=5.459, cubic=True) else: test = read(options.structure, format='vasp') cell = test.get_cell() cell[0,1] += 0.5 test.set_cell(cell) lmax = options.lmax nmax = options.nmax rcut = options.rcut alpha = options.alpha der = options.der start1 = time.time() f = SO3(nmax=nmax, lmax=lmax, rcut=rcut, alpha=alpha) start2 = time.time() print(f) p = f.compute_p(test, atom_ids=[0]); print('from P', p) x = f.calculate(test, derivative=der) print('x', x['x']) dp, p = f.compute_dpdr(test); print('from dP', p) dp, p = f.compute_dpdr_5d(test); print('from dP5d', p) (x_data, spg, wps) = ([13.45493847, 0.98, 0.04, 0.86, 0.08, 0.94, 0.14, 0.22, 0.66, 0.22, 0.74, 0.28, 0.2, 0.18, 0.68], 226, ['192j', '192j', '192j', '96i', '192j']) from pyxtal import pyxtal xtal = pyxtal() xtal.from_spg_wps_rep(spg, wps, x_data, ['C']*len(wps)) atoms = xtal.to_ase() p1 = f.compute_p(atoms)[0]; print("from ase", p1) p2 = f.compute_p(atoms, atom_ids=[0])[0]; print("from self", p2) print(np.sum((p1-p2)**2)) assert(np.sum((p1-p2)**2)<1e-4) ``` -------------------------------- ### Get Maximal t-Subgroup (Instance Method) Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/symmetry.html Instance method to get the maximal t-subgroups for the current space group. ```python return self._get_max_t_subgroup(self.number) ``` -------------------------------- ### Example usage of CHARMM interface Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/charmm.html Demonstrates how to use the CHARMM interface by setting up a calculation with a given structure and CHARMM information, running the calculation, and accessing results like energy and lattice parameters. ```python if __name__ == "__main__": from pyxtal.db import database w_dir = "tmp" if not os.path.exists(w_dir): os.makedirs(w_dir) db = database("benchmarks/test.db") row = db.get_row("ACSALA") struc = db.get_pyxtal("ACSALA") c_info = row.data["charmm_info"] prm = open(w_dir + "/pyxtal.prm", "w") prm.write(c_info["prm"]) prm.close() rtf = open(w_dir + "/pyxtal.rtf", "w") rtf.write(c_info["rtf"]) rtf.close() calc = CHARMM(struc, atom_info=c_info, folder=w_dir) print(calc.structure.lattice) calc.run(clean=False) print(calc.structure.energy) print(calc.structure.lattice) ``` -------------------------------- ### Get Maximal k-Subgroup (Instance Method) Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/symmetry.html Instance method to get the maximal k-subgroups for the current space group. ```python return self._get_max_k_subgroup(self.number) ``` -------------------------------- ### Example VASP Calculation with Pyxtal Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/vasp.html Demonstrates a basic VASP calculation using the Pyxtal interface. Includes setting up the structure, running a calculation, and printing the energy and forces. Also shows how to run an optimization and read the band gap. ```python if __name__ == "__main__": while True: struc = pyxtal() struc.from_random(3, 19, ["C"], [4]) if struc.valid: break # set up the commands os.system("source /share/intel/mkl/bin/mklvars.sh intel64") cmd = "mpirun -n 4 /share/apps/bin/vasp544-2019u2/vasp_std" calc = VASP(struc, path="tmp", cmd=cmd) calc.run() print("Energy:", calc.energy) print("Forces", calc.forces) struc, eng, time, _ = optimize(struc, path="tmp", levels=[0, 1, 2], cmd=cmd, walltime="30s") print(struc) print("Energy:", eng) print("Time:", time) calc = VASP(struc, path="tmp", cmd=cmd) calc.run(level=4, read_gap=True) print("Energy:", calc.energy) print("Gap:", calc.gap) ``` -------------------------------- ### Install PyXtal Development Version Source: https://pyxtal.readthedocs.io/en/latest/Installation.html Installs or upgrades pyxtal to the latest development version directly from the master branch of the GitHub repository. ```bash $ pip install --upgrade git+https://github.com/MaterSim/PyXtal.git@master ``` -------------------------------- ### Initialize and Use Collection Class Source: https://pyxtal.readthedocs.io/en/latest/pyxtal.database.collection.html Demonstrates how to initialize a Collection object for molecular data and access specific molecule information. Also shows how to list all available molecules in the collection. ```python from pyxtal.database.collection import Collection test=Collection('molecules') test['H2O'] list(test) ``` -------------------------------- ### Get 1D Representation Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal.html Retrieves the 1D representation class, which differs for molecular and atomic crystals. Use the `standard` flag for atomic crystals to get a standard representation. ```python def get_1D_representation(self, standard=False): """ Get the 1D representation class for molecular crystals """ if self.molecular: rep = representation.from_pyxtal(self) else: rep = representation_atom.from_pyxtal(self, standard=standard) return rep ``` -------------------------------- ### Initialize and Use LAMMPSlib Calculator Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/lammpslib.html Demonstrates how to initialize a LAMMPS instance, create a pyxtal structure, set up LAMMPS parameters, and assign the LAMMPSlib calculator to the structure for energy, forces, and stress calculations. ```python lammps_name = "" comm = None log_file = "lammps.log" cmd_args = ["-echo", "log", "-log", log_file, "-screen", "none", "-nocite"] lmp = lammps(lammps_name, cmd_args, comm) struc = bulk("Si", "diamond", cubic=True) struc.set_tags([1] * len(struc)) parameters = [ "mass * 1.0", "pair_style tersoff", "pair_coeff * * Si.tersoff Si", "neighbor 1.0 bin", "neigh_modify every 1 delay 1 check yes", ] lammps = LAMMPSlib(lmp=lmp, lmpcmds=parameters) struc.set_calculator(lammps) print("positions: ") print(struc.get_positions()) print("energy: ") print(struc.get_potential_energy()) print("force: ") print(struc.get_forces()) print("stress: ") print(struc.get_stress()) ``` -------------------------------- ### Lattice Class Initialization with Optional Parameters Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/lattice.html Demonstrates initializing the Lattice class with various optional parameters like area, thickness, unique_axis, and random state. ```python from pyxtal.lattice import Lattice # Initialize a 2D lattice with specific parameters lattice_2d = Lattice('hexagonal', volume=50.0, PBC=[1,1,0], area=25.0, thickness=2.0, unique_axis='c') print(f"Lattice type: {lattice_2d.ltype}") print(f"Periodic boundary conditions: {lattice_2d.PBC}") print(f"Area: {lattice_2d.area}") print(f"Thickness: {lattice_2d.thickness}") print(f"Unique axis: {lattice_2d.unique_axis}") ``` -------------------------------- ### Example One-Hot Encoding Output Source: https://pyxtal.readthedocs.io/en/latest/Symmetry_representation.html This is an example of the one-hot encoded matrix output for the 8a site symmetry of space group 227, representing the presence (1) or absence (0) of symmetry operations. ```python >>> # one-hot encoding of the 8a site symmetry of space group 227 [[1 0 0 0 0 0 0 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0 0 0 0]] ``` -------------------------------- ### Example Wyckoff Split Initialization Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/wyckoff_split.html Demonstrates the initialization of the `wyckoff_split` class with different space groups, indices, and Wyckoff positions, printing the resulting transformation matrix and error information. ```python if __name__ == "__main__": # sp = wyckoff_split(G=14, idx=1, wp1=['2c', '4e'], group_type='t') # print(sp) for idx in range(4): sp = wyckoff_split(G=210, idx=idx, wp1=['8b'], group_type='k') sp = wyckoff_split(G=227, idx=idx, wp1=["96g"], group_type="t") #print(sp) print(sp.R) print(sp.error) ``` -------------------------------- ### Initialize DFTB Calculator Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/dftb.html Initializes the DFTB calculator with structure, SKF directory, and various computational parameters. Creates a folder for temporary files if it doesn't exist. ```python def __init__( self, struc, skf_dir, disp="D3", kresol=0.10, folder="tmp", label="test", prefix="geo_final", use_omp=False, scc_error=1e-6, scc_iter=500, ): self.struc = struc self.skf_dir = skf_dir self.folder = folder self.kresol = kresol self.disp = disp self.label = label self.kpts = Kgrid(struc, kresol) self.prefix = prefix self.use_omp = use_omp self.scc_error = scc_error self.scc_iter = scc_iter if not os.path.exists(self.folder): os.makedirs(self.folder) ``` -------------------------------- ### get_ops_from_transformation Source: https://pyxtal.readthedocs.io/en/latest/pyxtal.symmetry.html Gets symmetry operations from the generators. ```APIDOC ## get_ops_from_transformation ### Description Gets symmetry operations from the generators. ``` -------------------------------- ### Generate MOF-like Structures Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Demonstrates generating MOF-like structures by using pyxtal_molecule objects for building blocks. This example creates a structure using Na+ and N3- molecules. ```python from pyxtal import pyxtal xtal = pyxtal(molecular=True) from pyxtal.molecule import pyxtal_molecule m1 = pyxtal_molecule('Na+.smi') m2 = pyxtal_molecule('[N-]=[N+]=[N-].smi') for i, data in enumerate([(14, [4, 4]), (36, [4, 4]), ]): (spg, numIons) = data xtal.from_random(3, 14, [m1, m2], [4, 4]) xtal.to_file(f"{i}-{spg}.cif") ``` -------------------------------- ### DFTB.get_calculator Source: https://pyxtal.readthedocs.io/en/latest/pyxtal.interface.dftb.html Gets the ASE-style calculator for DFTB. ```APIDOC ## DFTB.get_calculator ### Description Get the ASE style calculator for DFTB. ### Parameters * **mode** (str) - Calculation mode. Options: ['single', 'relax', 'vc_relax']. * **step** (int, optional) - Optimization steps. Defaults to 500. * **ftol** (float, optional) - Force tolerance for relaxation. Defaults to 0.001. * **FixAngles** (bool, optional) - Whether to fix angles between lattice vectors. Defaults to False. * **eVperA** (bool, optional) - Whether to use eV/A as units. Defaults to True. * **md_params** (dict, optional) - Parameters for molecular dynamics. ``` -------------------------------- ### Example Usage of get_wyc_from_comp Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/util.html Demonstrates calling the `get_wyc_from_comp` function with different parameters, including setting a maximum number of Wyckoff compositions and specifying total bounds for the composition. This shows practical application and parameter tuning. ```python base = [48, 24, 12, 8, 6, 3, 1] upper_bounds = [None, None, None, None, None, 2, 2] sols = get_wyc_from_comp([15, 16, 17, 21], base, upper_bounds, verbose=True, max_wyc=1) sols = get_wyc_from_comp([15, 16, 17, 21], base, upper_bounds, verbose=True, max_wyc=1, num_wp=(3, 10)) ``` -------------------------------- ### Generate Crystal with PyXtal_main.py Source: https://pyxtal.readthedocs.io/en/latest/_sources/COMMAND_MODE.rst.txt Example of generating a crystal using PyXtal_main.py with specified symmetry, elements, and number of ions. Ensure the number of ions is consistent with the elements provided. ```bash $ pyxtal_main.py -s 36 -e Li -n 16 ``` -------------------------------- ### pyxtal.get_bounds() Source: https://pyxtal.readthedocs.io/en/latest/pyxtal.block_crystal.html Gets the bounds of the lattice vectors. ```APIDOC ## get_bounds() ### Description Gets the bounds of the lattice vectors. ### Method `pyxtal.get_bounds(xtal)` ### Parameters - **xtal** (object) - The crystal structure object. ### Returns - (list) - A list of lists, where each inner list contains the minimum and maximum values for a lattice vector component. ``` -------------------------------- ### pyxtal.get_site_labels() Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/molecular_crystal.html Gets the labels for each Wythoff site. ```APIDOC ## `pyxtal.get_site_labels()` ### Description Retrieves the symmetry-defined labels for each Wythoff site occupied by atoms or molecules in the crystal structure. This provides information about the symmetry of each position. ### Parameters - **xtal** (object) - The PyXtal crystal object. ``` -------------------------------- ### Importing pyxtal and related modules Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/descriptor.html Example of how to import the pyxtal library and its associated modules for use in a script. ```python if __name__ == "__main__": import importlib.resources from pyxtal import pyxtal ``` -------------------------------- ### Initialize CHARMM Calculator Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/charmm.html Initializes the CHARMM calculator with various parameters for structure optimization. Ensures the CHARMM executable is available. ```python import contextlib import os import shutil import subprocess import numpy as np [docs] class CHARMM: """ A calculator to perform oragnic crystal structure optimization in CHARMM. Args: struc: pyxtal.molecular_crystal.molecular_crystal object label (str): label for this calculation algo (str): "abnr" lat_mut (bool): mutate lattice or not rotate (bool): rotate lattice or not prefix (str): prefix of this calculation atom_info (dict): atom_labels folder (str): folder name opt (str): 'conv', 'conp', 'single' steps (int): optimization steps exe (str): charmm executable input (str): charmm input file output (str): charmm output file dump (str): charmm dump structure """ def __init__( self, struc, label="_", algo="abnr", lat_mut=False, rotate=False, prefix="pyxtal", atom_info=None, folder=".", opt="conp", steps=None, exe="charmm", input="charmm.in", output="charmm.log", dump="result.pdb", debug=False, timeout=25.0, ): self.errorE = 1e+5 self.error = False if steps is None: steps = [2000, 1000] self.debug = debug self.timeout = timeout # check charmm Executable if shutil.which(exe) is None: raise BaseException(f"{exe} is not installed") else: self.exe = exe self.atom_info = atom_info # Optimization setting self.opt = opt self.optlat = False self.algo = algo if type(steps) is list: self.steps = steps elif type(steps) is int: self.steps = [2000, steps] self.opt = opt # Files IO self.folder = folder self.prefix = prefix self.label = label self.rtf = self.prefix + ".rtf" self.prm = self.prefix + ".prm" self.psf = self.label + self.prefix + ".psf" self.crd = self.label + self.prefix + ".crd" self.input = self.label + input self.output = self.label + output self.dump = self.label.lower() + dump # charmm only output lower # For parsing the output self.positions = None self.forces = None self.optimized = False self.cell = None self.cputime = 0.0 # Structure Manipulation struc.resort() self.structure = struc try: self.structure.optimize_lattice() except: print("bug in Lattice") print(self.structure) print(self.structure.lattice) print(self.structure.lattice.matrix) self.error = True # print("\nbeginining lattice: ", struc.lattice) self.lat_mut = lat_mut self.rotate = rotate ``` -------------------------------- ### pyxtal.get_disps_optim() Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/molecular_crystal.html Gets displacement sets for optimization. ```APIDOC ## `pyxtal.get_disps_optim()` ### Description Generates sets of atomic displacements that can be used as starting points for geometry optimization calculations. This function is useful for exploring the potential energy surface around a given structure. ### Parameters - **xtal** (object) - The PyXtal crystal object. ``` -------------------------------- ### pyxtal.get_transition() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets the transition between crystal structures. ```APIDOC ## pyxtal.get_transition() ### Description Gets the transition between crystal structures. ### Method `pyxtal.get_transition(xtal1, xtal2)` ### Parameters - **xtal1**: The first crystal structure. - **xtal2**: The second crystal structure. ``` -------------------------------- ### Write CHARMM Input Files Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/charmm.html Sets up necessary files for a CHARMM calculation, including topology, parameter, coordinate, and PSF files. It handles lattice transformations and atom information based on the provided structure. ```python def write(self, cutoff=14.0): """ setup the necessary files for charmm calculation """ lat = self.structure.lattice if self.lat_mut: lat = lat.mutate() a, b, c, alpha, beta, gamma = lat.get_para(degree=True) ltype = lat.ltype if ltype in ['trigonal', 'Trigonal']: ltype = 'hexagonal' fft = self.FFTGrid(np.array([a, b, c])) with open(self.input, "w") as f: # General input f.write("! Automated Charmm calculation\n\n") f.write("bomlev -1\n") f.write("! top and par\n") f.write(f"read rtf card name {self.rtf:s}\n") f.write(f"read para card name {self.prm:s}\n") f.write("Read sequence card\n") f.write(f"{len(self.structure.mol_sites):5d}\n") atom_count = [] for site in self.structure.mol_sites: atom_count.append(len(site.molecule.mol)) if self.atom_info is None: f.write(f"U0{site.type:d} ") else: f.write("{:s} ".format( self.atom_info["resName"][site.type])) f.write("\ngenerate main first none last none setup warn\n") f.write("Read coor card free\n") f.write("* Residues coordinate\n*\n") f.write(f"{sum(atom_count):5d}\n") for i, site in enumerate(self.structure.mol_sites): res_name = f"U0{site.type:d}" if self.atom_info is None else self.atom_info[ "resName"][site.type] # reset lattice if needed (to move out later) site.lattice = lat # Rotate if needed if self.rotate: site.perturbate(lat.matrix, trans=0.5, rot="random") coords, species = site._get_coords_and_species(first=True) if i == 0: count = 0 else: count += atom_count[i - 1] for j, coord in enumerate(coords): if self.atom_info is None: label = f"{species[j]:s}{j + 1:d}" else: label = self.atom_info["label"][site.type][j] f.write( "{:"5d}{:"5d}{:">4s} {:<4s}{:"10.5f}{:"10.5f}{:"10.5f}\n".format( j + 1 + count, i + 1, res_name, label, *coord ) ) # quickly check if if abs(coord).max() > 500.0: print("Unexpected large input coordinates, stop and debug") print(self.structure) self.structure.to_file('bug.cif') import sys; sys.exit() f.write(f"write psf card name {self.psf:s}\n") f.write(f"write coor crd card name {self.crd:s}\n") f.write(f"read psf card name {self.psf:s}\n") f.write(f"read coor card name {self.crd:s}\n") ``` -------------------------------- ### pyxtal.get_dimensionality() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets the dimensionality of a crystal structure. ```APIDOC ## pyxtal.get_dimensionality() ### Description Gets the dimensionality of a crystal structure. ### Method `pyxtal.get_dimensionality(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### pyxtal.get_bounds() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets the bounds of a crystal structure. ```APIDOC ## pyxtal.get_bounds() ### Description Gets the bounds of a crystal structure. ### Method `pyxtal.get_bounds(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### Initialize and Use Collection Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/database/collection.html Demonstrates how to initialize a 'molecules' collection and access a specific molecule by its name. This snippet shows the basic usage pattern for retrieving pymatgen objects from the collection. ```python from pyxtal.database.collection import Collection test=Collection('molecules') test['H2O'] ``` -------------------------------- ### get_hm_number Source: https://pyxtal.readthedocs.io/en/latest/pyxtal.symmetry.html Gets the Hermann-Mauguin number with a specified tolerance. ```APIDOC ## get_hm_number ### Parameters * **tol**: Tolerance for the calculation (default is 1e-05). ``` -------------------------------- ### Basinhopping Example Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/lego/basinhopping.html Demonstrates the usage of the basinhopping function with a 2D function, specifying the number of iterations, a callback function, and a random seed. ```python rng = np.random.default_rng() ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs, niter=10, callback=print_fun, seed=rng) ``` -------------------------------- ### get_subgroup_composition Source: https://pyxtal.readthedocs.io/en/latest/pyxtal.symmetry.html Gets the composition of the subgroup Wyckoff positions. ```APIDOC ## get_subgroup_composition ### Description Get the composition of the subgroup Wyckoff positions. ### Parameters #### Path Parameters - **ids** (list, optional) - Nested list of Wyckoff position indices [[0]]. - **g_types** (list, optional) - List of subgroup types to consider (‘t’ for translationengleiche, ‘k’ for klassengleiche). Default is ['t', 'k']. - **max_atoms** (int, optional) - Maximum number of atoms to consider for subgroup search. Default is 100. - **max_wps** (int, optional) - Maximum number of Wyckoff positions to consider. Default is 20. - **verbose** (bool, optional) - Whether to print debug information. Default is False. ### Returns - **list**: List of multiplicities of the Wyckoff positions. ``` -------------------------------- ### Initialize Profile Class Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/XRD.html Instantiate the Profile class with a specified method, resolution, and optional user-defined keyword arguments for the profiling function. Default parameters are provided for 'mod_pseudo-voigt', 'gaussian', 'lorentzian', and 'pseudo-voigt' methods. ```python profile = Profile(method="mod_pseudo-voigt", res=0.02, user_kwargs=None) ``` -------------------------------- ### pyxtal.get_min_values() Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/molecular_crystal.html Gets the minimum values for lattice parameters. ```APIDOC ## `pyxtal.get_min_values()` ### Description Returns the minimum possible values for the lattice parameters (a, b, c, alpha, beta, gamma) that are consistent with the crystal's symmetry and composition. This can be useful for setting bounds in optimization or generation routines. ### Parameters - **xtal** (object) - The PyXtal crystal object. ``` -------------------------------- ### 1-D Minimization with Basinhopping Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/lego/basinhopping.html Demonstrates a basic 1-D minimization problem using scipy.optimize.basinhopping with a specified minimizer. Ensure numpy and scipy.optimize are installed. ```python import numpy as np from scipy.optimize import basinhopping func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x x0 = [1.] minimizer_kwargs = {"method": "BFGS"} ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs, niter=200) print("global minimum: x = %.4f, f(x) = %.4f" % (ret.x, ret.fun)) ``` -------------------------------- ### Initializing and Querying Crystallographic Database Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/db.html Demonstrates opening a database file, checking the number of entries, and retrieving a specific Pyxtal structure by its ID. ```python db = database("test.db") print("Total number of entries", len(db.codes)) # view structure c = db.get_pyxtal("HXMTAM") print(c) ``` -------------------------------- ### pyxtal.get_free_axis() Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/molecular_crystal.html Gets the free axis of rotation for molecules. ```APIDOC ## `pyxtal.get_free_axis()` ### Description Identifies the free axis of rotation for molecules within the crystal structure, particularly relevant for molecular crystals where certain orientations might be unrestricted by symmetry. ### Parameters - **xtal** (object) - The PyXtal crystal object. ``` -------------------------------- ### pyxtal.get_xtal_string() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets a string representation of a crystal structure. ```APIDOC ## pyxtal.get_xtal_string() ### Description Gets a string representation of a crystal structure. ### Method `pyxtal.get_xtal_string(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### pyxtal.get_tabular_representations() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets tabular representations of a crystal structure. ```APIDOC ## pyxtal.get_tabular_representations() ### Description Gets tabular representations of a crystal structure. ### Method `pyxtal.get_tabular_representations(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### Initialize Builder Instance Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/lego/builder.html Instantiate the builder class to set up a new structure generation process. Specify elements, composition, and optionally database/log files. ```python from pyxtal.lego.builder import builder bu = builder(['P', 'O', 'N'], [1, 1, 1], db_file='PON.db') ``` -------------------------------- ### pyxtal.get_tabular_representation() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets the tabular representation of a crystal structure. ```APIDOC ## pyxtal.get_tabular_representation() ### Description Gets the tabular representation of a crystal structure. ### Method `pyxtal.get_tabular_representation(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### pyxtal.get_std_representation() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets the standard representation of a crystal structure. ```APIDOC ## pyxtal.get_std_representation() ### Description Gets the standard representation of a crystal structure. ### Method `pyxtal.get_std_representation(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### Initialize LAMMPSlib Calculator Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/lammpslib.html Initializes the LAMMPSlib calculator with LAMMPS instance and optional commands. Handles directory creation and potential force field path setup. ```python import os import importlib.resources # Assuming Calculator is defined elsewhere and imported # from pyxtal.calculators.base import Calculator class LAMMPSlib(Calculator): def __init__( self, lmp, lmpcmds=None, path="tmp", molecule=False, lmp_file=None, calc_type="single", *args, **kwargs, ): Calculator.__init__(self, *args, **kwargs) self.lmp = lmp self.lmp_file = lmp_file self.molecule = molecule self.calc_type = calc_type self.folder = path if not os.path.exists(self.folder): os.makedirs(self.folder) self.lammps_data = self.folder + "/data.lammps" self.lammps_in = self.folder + "/in.lammps" with importlib.resources.as_file(importlib.resources.files("pyxtal") / "potentials") as path: self.ffpath = str(path) self.lmpcmds = lmpcmds self.paras = [] if lmpcmds is not None: for para in lmpcmds: if not self.molecule and para.find("pair_coeff") >= 0: tmp = para.split() filename = tmp[3] filename1 = self.ffpath + "/" + filename para = para.replace(filename, filename1) self.paras.append(para) ``` -------------------------------- ### GULP Calculator Class Initialization Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/gulp.html Initializes the GULP_OC class for performing organic crystal structure optimization in GULP. Sets up parameters like force field, optimization type, and executable path. ```python [docs] class GULP_OC: """ A calculator to perform oragnic crystal structure optimization in GULP Args: struc: structure object generated by Pyxtal ff: path of forcefield lib, e.g., `gaff` bond_type: specify the bond type or not (GULP can detect it automatically) opt: e.g., `conv`, `conp`, `single` steps: number of steps, int, e.g., `1000` exe: int, the way to call gulp executable atom_info: atomic labels/charges input: gulp input file name output: gulp output file name dump: dumped gulp file name """ ``` -------------------------------- ### pyxtal.get_spherical_images() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets spherical images for a crystal structure. ```APIDOC ## pyxtal.get_spherical_images() ### Description Gets spherical images for a crystal structure. ### Method `pyxtal.get_spherical_images(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### pyxtal.db.setup_worker_logger() Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/util.html Sets up a logger for database workers. ```APIDOC ## pyxtal.db.setup_worker_logger() ### Description Sets up a logger for database workers. ### Method `setup_worker_logger()` ``` -------------------------------- ### pyxtal.get_site_labels() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets the site labels for a crystal structure. ```APIDOC ## pyxtal.get_site_labels() ### Description Gets the site labels for a crystal structure. ### Method `pyxtal.get_site_labels(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### GULP Interface Example Usage - Pyxtal Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/gulp.html Demonstrates the usage of the GULP interface within Pyxtal. It includes creating a random structure, performing a single GULP calculation, converting structures to Pymatgen format, and running multiple optimizations. ```python if __name__ == "__main__": while True: struc = pyxtal() struc.from_random(3, 19, ["C"], [4]) if struc.valid: break print(struc) pmg1 = struc.to_pymatgen() calc = GULP(struc, opt="single", ff="tersoff.lib") calc.run(clean=False) # ; import sys; sys.exit() print(calc.energy) print(calc.stress) print(calc.forces) pmg2 = calc.to_pymatgen() # xtal = calc.pyxtal #calc.to_pyxtal() # print(calc.iter) # print(xtal) import pymatgen.analysis.structure_matcher as sm print(sm.StructureMatcher().fit(pmg1, pmg2)) struc, eng, time, _ = optimize(struc, ff="tersoff.lib") print(struc) print(eng) print(time) ``` -------------------------------- ### pyxtal.get_separations() Source: https://pyxtal.readthedocs.io/en/latest/Usage.html Gets the separations between atoms in a crystal structure. ```APIDOC ## pyxtal.get_separations() ### Description Gets the separations between atoms in a crystal structure. ### Method `pyxtal.get_separations(xtal)` ### Parameters - **xtal**: The crystal structure object. ``` -------------------------------- ### DFTB Calculator Initialization Source: https://pyxtal.readthedocs.io/en/latest/_modules/pyxtal/interface/dftb.html Initializes the DFTB calculator with specified parameters. ```APIDOC ## __init__ ```