### Example Calculation Setup Source: https://ase-lib.org/ase/calculators/onetep.html Demonstrates setting up a simple ONETEP calculation for a water molecule. ```APIDOC ## Examples Here is an example of setting up a calculation on a water molecule: ```python from ase.build import molecule from ase.calculators.onetep import Onetep from os import environ # water molecule from ASE database, centered in a ~ 24 Å box wat = molecule('H2O') wat.center(12) environ["ASE_ONETEP_COMMAND"]="export OMP_NUM_THREADS=8; mpirun -n 2 ~/onetep/bin/onetep.arch" calc = Onetep() wat.set_calculator(calc) ``` ``` -------------------------------- ### Pair Distribution Function Setup Source: https://ase-lib.org/_modules/ase/neighborlist.html Example showing the setup for calculating a pair distribution function by creating a larger atomic configuration using ase.build.bulk. ```python import numpy as np from ase.build import bulk, molecule atoms = bulk('Cu', cubic=True) * 3 ``` -------------------------------- ### CASTEP Calculation Example Source: https://ase-lib.org/_sources/ase/calculators/castep.rst This example demonstrates a basic CASTEP calculation setup using ASE. It requires the `ase_castep_demo.py` script to be available. ```python from ase.calculators.castep import Castep from ase.build import bulk # Create a bulk structure (e.g., Silicon) cell = bulk('Si', 'diamond', a=5.43) # Initialize the CASTEP calculator # Specify the path to the CASTEP executable if not in PATH # calculator = Castep(command='path/to/castep') calculator = Castep() # Assign the calculator to the cell cell.set_calculator(calculator) # Calculate the energy energy = cell.get_potential_energy() print(f"The calculated energy is: {energy} eV") # You can also set specific CASTEP parameters calc_params = { 'xc_functional': 'PBE', 'cut_off_energy': 300, 'spin_polarised': False, } calculator.set_params(calc_params) # Recalculate with new parameters energy_new = cell.get_potential_energy() print(f"The recalculated energy with PBE is: {energy_new} eV") # Accessing results after calculation print(f"Forces: {cell.get_forces()}") print(f"Stress: {cell.get_stress()}") ``` -------------------------------- ### ASE GULP Calculator Example Source: https://ase-lib.org/ase/calculators/gulp.html Example demonstrating the setup and execution of GULP calculations within ASE, including single-point energy calculation and geometry optimization using GULP's internal optimizer. ```python # flake8: noqa import numpy as np from ase import Atoms from ase.calculators.gulp import GULP, Conditions cluster = Atoms( symbols='O4SiOSiO2SiO2SiO2SiOSiO2SiO3SiO3H8', pbc=np.array([False, False, False], dtype=bool), cell=np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), positions=np.array( [ [-1.444348, -0.43209, -2.054785], [-0.236947, 2.98731, 1.200025], [3.060238, -1.05911, 0.579909], [2.958277, -3.289076, 2.027579], [-0.522747, 0.847624, -2.47521], [-2.830486, -2.7236, -2.020633], [-0.764328, -1.251141, 1.402431], [3.334801, 0.041643, -4.168601], [-1.35204, -2.009562, 0.075892], [-1.454655, -1.985635, -1.554533], [0.85504, 0.298129, -3.159972], [1.75833, 1.256026, 0.690171], [2.376446, -0.239522, -2.881245], [1.806515, -4.484208, -2.686456], [-0.144193, -2.74503, -2.177778], [0.167583, 1.582976, 0.47998], [-1.30716, 1.796853, -3.542121], [1.441364, -3.072993, -1.958788], [-1.694171, -1.558913, 2.704219], [4.417516, 1.263796, 0.563573], [3.066366, 0.49743, 0.071898], [-0.704497, 0.351869, 1.102318], [2.958884, 0.51505, -1.556651], [1.73983, -3.161794, -0.356577], [2.131519, -2.336982, 0.996026], [0.752313, -1.788039, 1.687183], [-0.142347, 1.685301, -1.12086], [2.32407, -1.845905, -2.588202], [-2.571557, -1.937877, 2.604727], [2.556369, -4.551103, -3.2836], [3.032586, 0.591698, -4.896276], [-1.67818, 2.640745, -3.27092], [5.145483, 0.775188, 0.95687], [-2.81059, -3.4492, -2.650319], [2.558023, -3.594544, 2.845928], [0.400993, 3.469148, 1.733289], ] ), ) c = Conditions(cluster) c.min_distance_rule( 'O', 'H', ifcloselabel1='O2', ifcloselabel2='H', elselabel1='O1' ) c_calc = GULP(keywords='conp', shel=['O1', 'O2'], conditions=c) # Single point calculation cluster.calc = c_calc print(cluster.get_potential_energy()) # Optimization using the internal optimizer of GULP c_calc.set(keywords='conp opti') opt = c_calc.get_optimizer(cluster) opt.run(fmax=0.05) print(cluster.get_potential_energy()) ``` -------------------------------- ### Basic VASP Calculation Setup Source: https://ase-lib.org/_modules/ase/calculators/vasp/vasp.html Demonstrates how to initialize and run a basic VASP calculation using the ASE calculator interface. Ensure VASP is installed and accessible in your environment. ```python from ase.calculators.vasp import Vasp from ase.build import bulk # Create a simple bulk structure (e.g., FCC Gold) atoms = bulk('Au', 'fcc', a=4.07) # Initialize the VASP calculator calc = Vasp( xc='PBE', # Exchange-correlation functional encut=400, # Energy cutoff kpts=(4, 4, 4), # k-point grid prec='Accurate',# Precision setting ibrion=2, # Relaxation algorithm (conjugate gradient) isif=3, # Allow cell shape, volume, and ions to relax ediff=1E-5, # Convergence criterion for electronic steps ediffg=-0.02, # Convergence criterion for ionic steps sigma=0.05, # Smearing width lwave=True, # Write wavefunctions lcharg=True, # Write charge density ncore=8, # Number of cores for parallelization (adjust as needed) setups='recommended' # Recommended POTCAR setups ) # Attach the calculator to the atoms object atoms.calc = calc # Perform a calculation (e.g., relaxation) energy = atoms.get_potential_energy() print(f'Final energy: {energy} eV') # You can also access other results like forces # forces = atoms.get_forces() # print(f'Forces: {forces}') ``` -------------------------------- ### Advanced GAMESSUS Calculation Setup Source: https://ase-lib.org/ase/calculators/gamess_us.html Example of setting up a more complex calculation, such as CCSD(T)/cc-pVDZ. ```APIDOC ## Advanced GAMESSUS Calculation Setup ### Description Configure advanced calculation types like CCSD(T) by specifying relevant keywords in the `contrl` and `basis` dictionaries. ### Method ```python calc = GAMESSUS(contrl={'scftyp': 'rhf', 'cctyp': 'ccsd(t)', 'ispher': 1, 'runtyp': 'energy'}, basis={'gbasis': 'CCD'}) ``` ### Input File Generation Example This setup generates the following GAMESS-US input: ``` >>> $CONTRL >>> SCFTYP=RHF >>> CCTYP=CCSD(T) >>> ISPHER=1 >>> RUNTYP=ENERGY >>> $END >>> >>> $BASIS >>> GBASIS=CCSD >>> $END ``` ### Notes - If `runtyp` is not specified, it will be set automatically. - If no basis is specified, 3-21G will be used by default. - Literal basis set definitions can be provided via the `basis` keyword. - Multiplicity is guessed based on initial magnetic moments if not set in `contrl['mult']`. ``` -------------------------------- ### Install ASE with Docs Dependencies Source: https://ase-lib.org/_sources/development/addingexamples.rst Install the ASE library with the 'docs' dependency group to get all necessary packages for documentation and example development. ```console $ pip install ase[docs] ``` -------------------------------- ### Install ASE Source: https://ase-lib.org/_sources/examples_generated/index.rst Install the ASE library using pip. This is the primary method for setting up ASE for use. ```bash pip install ase ``` -------------------------------- ### Install MySQL Server on Ubuntu Source: https://ase-lib.org/_sources/ase/db/db.rst Commands to install the MySQL server and secure the installation on a Ubuntu system. ```bash $ sudo apt-get install mysql-server $ sudo mysql_secure_installation ``` -------------------------------- ### Install ASE with Docs Dependencies Source: https://ase-lib.org/development/addingexamples.html Install the ASE library with the necessary packages for documentation, including Sphinx-Gallery. ```bash $ pip install ase[docs] ``` -------------------------------- ### Install Q-Chem Source: https://ase-lib.org/_sources/ase/calculators/qchem.rst Instructions for installing Q-Chem for ASE integration. Ensure a working copy is installed following the official Q-Chem website instructions. ```bash qchem PREFIX.inp PREFIX.out ``` -------------------------------- ### Install FFmpeg Tools on Ubuntu Source: https://ase-lib.org/_sources/development/making_movies.rst Install the necessary FFmpeg libraries and tools on Ubuntu using apt-get. ```bash sudo apt-get install libav-tools libavcodec-extra-53 libavdevice-extra-53 libavformat-extra-53 libavutil-extra-51 libpostproc-extra-52 libswscale-extra-2 ``` -------------------------------- ### Install ASE with testing dependencies Source: https://ase-lib.org/install.html Install ASE along with the necessary packages for running its tests. Use this if you plan to verify the installation by running the test suite. ```bash $ pip install --upgrade ase[test] ``` -------------------------------- ### Install ASE DB Backends Source: https://ase-lib.org/_sources/ase/db/db.rst Install the necessary backends for PostgreSQL, MySQL, and MariaDB databases. ```bash pip install git@gitlab.com:ase/ase-db-backends ``` -------------------------------- ### Get Species Indices Source: https://ase-lib.org/_modules/ase/symbols.html Returns a list of integers representing the index of each atom within its own species. For example, the first carbon atom gets index 0, the second carbon atom gets index 1, and so on. Requires the 'ase.Atoms' class for the example. ```python >>> from ase import Atoms >>> atoms = Atoms('CH3CH2OH') >>> atoms.symbols.species_indices() [0, 0, 1, 2, 1, 3, 4, 0, 5] ^ ^ ^ ^ ^ ^ ^ ^ ^ C H H H C H H O H ``` -------------------------------- ### Setup Surface and Adsorbate Source: https://ase-lib.org/examples_generated/tutorials/constraint_diffusion.html Initializes a 2x2-Al(001) surface with 3 layers and an Au atom adsorbed in a hollow site. Requires ASE build and calculator modules. ```python from ase.build import add_adsorbate, fcc100 from ase.calculators.emt import EMT from ase.constraints import FixAtoms, FixedPlane from ase.optimize import QuasiNewton # 2x2-Al(001) surface with 3 layers and an # Au atom adsorbed in a hollow site: slab = fcc100('Al', size=(2, 2, 3)) add_adsorbate(slab, 'Au', 1.7, 'hollow') slab.center(axis=2, vacuum=4.0) ``` -------------------------------- ### Install Ruff Linter Source: https://ase-lib.org/development/addingexamples.html Install the Ruff linter, which is used for checking example code quality before committing. ```bash $ pip install ruff ``` -------------------------------- ### Install Ruff Linter Source: https://ase-lib.org/_sources/development/addingexamples.rst Install the Ruff linter, which is used for checking code quality in ASE examples. ```console $ pip install ruff ``` -------------------------------- ### Build HTML Documentation Source: https://ase-lib.org/development/addingexamples.html Build the HTML version of the documentation, including the rendered examples, from the 'doc' directory. ```bash $ make html ``` -------------------------------- ### Basin Hopping Global Optimization Setup Source: https://ase-lib.org/_sources/ase/optimize.rst Demonstrates how to set up and use the BasinHopping algorithm for global optimization. Requires an ASE system, temperature, stepwidth, a local optimizer, and a force threshold. ```python from ase import * from ase.optimize.basin import BasinHopping bh = BasinHopping(atoms=system, # the system to optimize temperature=100 * kB, # 'temperature' to overcome barriers dr=0.5, # maximal stepwidth optimizer=LBFGS, # optimizer to find local minima fmax=0.1, # maximal force for the optimizer ) ``` -------------------------------- ### Build HTML Documentation Source: https://ase-lib.org/_sources/development/addingexamples.rst Build the HTML documentation for ASE, which includes rendering the examples. This command should be run from the 'doc' directory. ```console $ make html ``` -------------------------------- ### Set Element-Specific VASP Pseudopotential Setup Source: https://ase-lib.org/_sources/ase/calculators/vasp.rst Specify alternative pseudopotential setups for specific elements using a dictionary. For example, use '_sv' for Lithium. ```python calc = Vasp(xc='PBE', setups={'Li': '_sv'}) ``` -------------------------------- ### Initialize and Write Exciting Input File Source: https://ase-lib.org/ase/calculators/exciting.html Demonstrates initializing the ExcitingGroundStateTemplate and writing an input.xml file for a given atomic structure and ground state parameters. Use this when only generating input files without running a simulation. ```python from ase import Atoms from ase.calculators.exciting.exciting import ExcitingGroundStateTemplate # test structure, not real nitrogen_trioxide_atoms = Atoms( 'NO3', cell=[[2, 2, 0], [0, 4, 0], [0, 0, 6]], positions=[(0, 0, 0), (1, 3, 0), (0, 0, 1), (0.5, 0.5, 0.5)], pbc=True, ) gs_template_obj = ExcitingGroundStateTemplate() # Write an exciting input.xml file for the NO3 system. gs_template_obj.write_input( directory='./', atoms=nitrogen_trioxide_atoms, parameters={ 'title': None, 'species_path': './', 'ground_state_input': { 'rgkmax': 8.0, 'do': 'fromscratch', 'ngridk': [6, 6, 6], 'xctype': 'GGA_PBE_SOL', 'vkloff': [0, 0, 0], }, }, ) ``` -------------------------------- ### Example Usage Source: https://ase-lib.org/ase/vibrations/infrared.html Demonstrates how to set up and run an infrared intensity calculation using the ASE library. ```APIDOC ```python >>> from ase.io import read >>> from ase.calculators.vasp import Vasp >>> from ase.vibrations import Infrared >>> water = read('water.traj') # read pre-relaxed structure of water >>> calc = Vasp(prec='Accurate', ... ediff=1E-8, ... isym=0, ... idipol=4, # calculate the total dipole moment ... dipol=water.get_center_of_mass(scaled=True), ... ldipol=True) >>> water.calc = calc >>> ir = Infrared(water) >>> ir.run() >>> ir.summary() ------------------------------------- Mode Frequency Intensity ``` ``` -------------------------------- ### Example of Getting Bond Combination Value Source: https://ase-lib.org/_modules/ase/constraints/fix_internals.html Example demonstrating how to use `get_bondcombo` to retrieve the value of a linear combination of two bond lengths defined by specific atom indices and coefficients. ```python bondcombo = [[0, 1, 1.0], [2, 3, -1.0]] # Get the current value of the linear combination of two bond lengths ``` -------------------------------- ### Accessing Chemical Symbols with ASE Source: https://ase-lib.org/_modules/ase/atoms.html Demonstrates how to get and manipulate chemical symbols using the `symbols` property. It shows examples of checking symbols, getting indices, and listing unique species. ```python >>> from ase.build import molecule >>> atoms = molecule('CH3CH2OH') >>> atoms.symbols Symbols('C2OH6') >>> list(atoms.symbols) ['C', 'C', 'O', 'H', 'H', 'H', 'H', 'H', 'H'] >>> atoms.symbols == 'C' # doctest: +ELLIPSIS array([ True, True, False, False, False, False, False, False, False]...) >>> atoms.symbols.indices() {'C': array([0, 1]), 'O': array([2]), 'H': array([3, 4, 5, 6, 7, 8])} >>> list(atoms.symbols.indices()) # unique elements ['C', 'O', 'H'] >>> atoms.symbols.species() # doctest: +SKIP {'C', 'O', 'H'} ``` -------------------------------- ### GaussianOptimizer Setup Source: https://ase-lib.org/_modules/ase/calculators/gaussian.html Initialize a GaussianOptimizer for geometry optimization. Requires a Gaussian calculator object to be attached to the atoms. ```python from ase.calculators.gaussian import GaussianOptimizer from ase.atoms import Atoms from ase.calculators.gaussian import Gaussian atoms = Atoms('H2', positions=[(0, 0, 0), (0, 0, 0.74)], calculator=Gaussian()) optimizer = GaussianOptimizer(atoms) optimizer.run(fmax=0.05, steps=100) ``` -------------------------------- ### Instantiate and Use Espresso Calculator Source: https://ase-lib.org/ase/calculators/calculators.html Demonstrates how to instantiate the Espresso calculator with specific input data and pseudopotentials, then attach it to an ASE Atoms object and calculate the potential energy. Ensure Espresso and its pseudopotentials are correctly installed. ```python >>> from ase.build import bulk >>> from ase.calculators.espresso import Espresso >>> espresso = Espresso( input_data = { 'system': { 'ecutwfc': 60, }}, pseudopotentials = {'Si': 'si_lda_v1.uspp.F.UPF'}, ) >>> si = bulk('Si') >>> si.calc = espresso >>> si.get_potential_energy() -244.76638508140397 ``` -------------------------------- ### Get FHI-aims Version Source: https://ase-lib.org/_modules/ase/calculators/aims.html Extracts the FHI-aims version string from a given text. Useful for checking the installed version. ```python def get_aims_version(string): match = re.search(r'\s*FHI-aims version\s*:\s*(\S+)', string, re.M) return match.group(1) ``` -------------------------------- ### Initialize TransportCalculator and Get Transmission Source: https://ase-lib.org/ase/transport/transport.html Example of initializing the TransportCalculator with Hamiltonian matrices and energies, then calculating the transmission spectrum. ```python import numpy as np h = np.array((0,)).reshape((1,1)) h1 = np.array((0, -1, -1, 0)).reshape(2,2) energies = np.arange(-3, 3, 0.1) calc = TransportCalculator(h=h, h1=h1, energies=energies) T = calc.get_transmission() ``` -------------------------------- ### Example Calculator Configuration File Source: https://ase-lib.org/_sources/ase/calculators/calculators.rst This is an example of a configuration file used by ASE to define external calculator settings, including command paths and pseudopotential locations. ```ini [abinit] command = mpiexec /usr/bin/abinit pp_paths = /usr/share/abinit/pseudopotentials [espresso] command = mpiexec pw.x pseudo_path = /home/ase/upf_pseudos ``` -------------------------------- ### MM-only Geometry Optimization Example Source: https://ase-lib.org/_sources/ase/calculators/gromacs.rst Demonstrates an MM-only geometry optimization of a histidine molecule. Note: This is a simplified demo and not a proper MD setup. ```python from ase.calculators.gromacs import Gromacs from ase.optimize import QuasiNewton from ase.build import molecule # Create a molecule (e.g., histidine) # For this example, we'll use a placeholder, but in reality, you'd load 'his.pdb' # atoms = molecule('his') # This would require a 'his' definition or loading from file # Placeholder for atoms object, assuming it's loaded from 'his.pdb' # In a real scenario, you would load your structure, e.g.: # from ase.io import read # atoms = read('his.pdb') # Dummy atoms object for demonstration purposes if 'his.pdb' is not available # In a real case, this would be populated from the PDB file. from ase import Atoms atoms = Atoms('CH3', positions=[(0,0,0)]) # Replace with actual histidine atoms # Setup Gromacs calculator for MM-only relaxation calc = Gromacs(gromacspath='/path/to/gromacs/executable', force_field='oplsaa', water_model='tip3p', clean=True, gmx_path='gmx') # Specify gmx_path if needed # Set parameters for relaxation (example values) calc.set_own_params_runs('extra_grompp_parameters', '-maxwarn 1') calc.set_own_params_runs('integrator', 'md') # Using 'md' for relaxation example calc.set_own_params_runs('nsteps', '1000') calc.set_own_params_runs('dt', '0.002') calc.set_own_params_runs('nstxout', '100') calc.set_own_params_runs('nstvout', '100') calc.set_own_params_runs('nstenergy', '100') calc.set_own_params_runs('nstlog', '100') # Assign calculator to atoms atoms.calc = calc # Perform geometry optimization (using ASE's optimizer) # Note: For MM-only relaxation, a simple optimizer might suffice. # For QM/MM, the calculator handles the dynamics. # This part is more illustrative of using ASE optimizers with a calculator. # If you were doing a QM/MM run, you would typically not use ASE optimizers directly # but rather let Gromacs run its steps. # Example of using an ASE optimizer (if applicable for a specific MM task): # dyn = QuasiNewton(atoms) # dyn.run(fmax=0.1) print("Gromacs calculator setup for MM relaxation example.") # In a real QM/MM scenario, you would run the QM/MM calculation differently, # often by calling the calculator's 'get_potential_energy()' or similar methods # within a QM framework. ``` -------------------------------- ### Set up initial slab and adsorbate Source: https://ase-lib.org/_downloads/637ff7b17e4f116979c9642c62801ed2/diffusion_neb.ipynb Creates a 2x2x3 Al(001) surface and adds an Au atom in a hollow site, centering the structure with vacuum. ```python slab = fcc100('Al', size=(2, 2, 3)) add_adsorbate(slab, 'Au', 1.7, 'hollow') slab.center(axis=2, vacuum=4.0) ``` -------------------------------- ### FHI-aims Socket I/O Calculation Setup Source: https://ase-lib.org/ase/calculators/socketio/socketio.html This example demonstrates the setup for an FHI-aims calculation using an INET socket. Note that FHI-aims requires specific compilation flags to enable i-PI protocol support. For UNIX sockets, use the `unixsocket` argument instead of `port`. ```python from ase.build import molecule from ase.calculators.aims import Aims from ase.optimize import BFGS # Note that FHI-aim support for the i-PI protocol must be specifically # enabled at compile time, e.g.: make -f Makefile.ipi ipi.mpi # This example uses INET; see other examples for how to use UNIX sockets. port = 31415 atoms = molecule('H2O', vacuum=3.0) atoms.rattle(stdev=0.1) aims = Aims(directory='aims-calc', xc='LDA') opt = BFGS(atoms, trajectory='opt.aims.traj', logfile='opt.aims.log') # For running with UNIX socket, put unixsocket='mysocketname' ``` -------------------------------- ### Calculator set Method Example Source: https://ase-lib.org/development/calculators.html Demonstrates setting calculator parameters using keyword arguments. The 'parameters' keyword can be used to read from a file. ```python set(key1=value1, key2=value2, ...) set(parameters='file.json') ``` -------------------------------- ### Get Layer Information for Atoms Source: https://ase-lib.org/ase/geometry.html Identifies which layer each atom belongs to and the distance between layers based on Miller indices. Requires `numpy` and `ase.spacegroup.crystal_` for setup. ```python import numpy as np from ase.spacegroup import crystal_ from ase.geometry.geometry import get_layers_ atoms = crystal(‘Al’, [(0,0,0)], spacegroup=225, cellpar=4.05) np.round(atoms.positions, decimals=5) # doctest+NORMALIZE_WHITESPACE get_layers(atoms, (0,0,1)) # doctest+ELLIPSIS ``` -------------------------------- ### FixBondCombo get_value Static Method Source: https://ase-lib.org/_modules/ase/constraints/fix_internals.html A static method to get the current value of the bond combination constraint, likely used for verification or initial setup. ```python @staticmethod def get_value(atoms, indices, mic): return FixInternals.get_bondcombo(atoms, indices, mic) ``` -------------------------------- ### DFTB Calculator Initialization with Command and Slako Directory Source: https://ase-lib.org/_modules/ase/calculators/dftb.html Shows how to initialize the DFTB calculator, specifying the command to run DFTB+ and the directory for Slater-Koster files. It also demonstrates how to load configuration from environment variables or profile files. ```python if command is None: if 'DFTB_COMMAND' in self.cfg: command = self.cfg['DFTB_COMMAND'] + ' > PREFIX.out' if command is None and profile is None: try: profile = self.load_argv_profile(self.cfg, 'dftb') except BadConfiguration: pass if command is None: command = 'dftb+ > PREFIX.out' if slako_dir is None: if profile is not None: slako_dir = profile.configvars.get('skt_path') if slako_dir is None: slako_dir = self.cfg.get('DFTB_PREFIX', './') if not slako_dir.endswith('/'): slako_dir += '/' self.slako_dir = slako_dir ``` -------------------------------- ### Geometry Optimization with deMon-Nano Calculator Source: https://ase-lib.org/_sources/ase/calculators/demonnano.rst Example of performing a geometry optimization using the deMon-Nano calculator in ASE. This requires the deMon-Nano code to be installed and configured. ```python from ase.calculators.demonnano import DemonNano from ase.optimize import QuasiNewton from ase.build import fcc111 # Create a system # Note: This is a placeholder, replace with your actual system setup # For example, using ase.build.bulk or ase.io.read # atoms = fcc111('Cu', size=(2,2,1)) # Placeholder for atoms object # In a real scenario, you would load or build your atomic structure here. # Example: # from ase.build import molecule # atoms = molecule('H2O') # Dummy atoms object for demonstration purposes from ase import Atoms atoms = Atoms('H2', positions=[(0, 0, 0), (0, 0, 0.74)]) # Set up the deMon-Nano calculator # Ensure DEMONNANO_BASIS_PATH and ASE_DEMONNANO_COMMAND are set calculator = DemonNano() atoms.set_calculator(calculator) # Perform geometry optimization # The optimizer will use the calculator to find the minimum energy structure # Note: The 'fmax' parameter controls the convergence criteria for forces qn = QuasiNewton(atoms, trajectory='demonnano_relax.traj', logfile='demonnano_relax.log') qn.run(fmax=0.05) print('Geometry optimization finished.') print('Final energy:', atoms.get_total_energy()) ``` -------------------------------- ### SimpleQMMM Calculator Setup Source: https://ase-lib.org/ase/calculators/qmmm.html Instantiate the SimpleQMMM calculator by providing the QM region selection, QM calculator, and MM calculator. The QM calculator is used for the QM region, while the MM calculator handles the rest. This method is suitable for combining any two ASE calculators. ```python from ase.calculators.qmmm import SimpleQMMM atoms = ... atoms.calc = SimpleQMMM([0, 1, 2], QMCalculator(...), MMCalculator(...)) ``` -------------------------------- ### Initialize System Parameters Source: https://ase-lib.org/_downloads/417a2a426c542a96487eb049eaa837eb/neb_selfdiffusion.ipynb Sets up initial parameters for the Al(110) surface calculation, including lattice constants and heights. ```python from math import sqrt import numpy as np from ase import Atom, Atoms a = 4.0614 b = a / sqrt(2) h = b / 2 ``` -------------------------------- ### Get Surface Slab Tags Source: https://ase-lib.org/ase/build/surface.html Retrieve the tags assigned to atoms in a slab. Layers are tagged sequentially starting from the top layer, and adsorbates are tagged with 0. ```python >>> print(atoms.get_tags()) [3 3 3 3 2 2 2 2 1 1 1 1 0] ``` -------------------------------- ### Get Help for Database Select Method Source: https://ase-lib.org/examples_generated/tutorials/ase_database.html Demonstrates how to use the built-in help function to view documentation for specific methods, like `db.select()`. This is useful for understanding available parameters. ```python from ase.db import connect db = connect('database.db') help(db.select) ``` -------------------------------- ### Initialize ExpCellFilter with Atoms and Constraint Source: https://ase-lib.org/ase/filters.html This example shows how to initialize the ExpCellFilter with an Atoms object and apply a constraint to fix atomic positions. This setup is equivalent to using StrainFilter. ```python >>> # this should be equivalent to the StrainFilter >>> atoms = Atoms(...) >>> atoms.set_constraint(FixAtoms(mask=[True for atom in atoms])) >>> ecf = ExpCellFilter(atoms) ``` -------------------------------- ### Example: Water Molecule Calculation with ONETEP Source: https://ase-lib.org/ase/calculators/onetep.html Demonstrates setting up a ONETEP calculation for a water molecule, including centering the molecule in a box and setting the environment command. ```python from ase.build import molecule from ase.calculators.onetep import Onetep from os import environ # water molecule from ASE database, centered in a ~ 24 Å box wat = molecule('H2O') wat.center(12) eviron["ASE_ONETEP_COMMAND"]="export OMP_NUM_THREADS=8; mpirun -n 2 ~/onetep/bin/onetep.arch" ``` -------------------------------- ### Initialize Pourbaix Class Source: https://ase-lib.org/_modules/ase/pourbaix.html Instantiate the Pourbaix class with material name, reference energies, temperature, concentration, and reference electrode. ```python pb = Pourbaix('RuO2', refs_dct={'RuO2': 0.0, 'Ru': -2.0, 'O2': 0.0}) ``` -------------------------------- ### MOPAC Geometry Optimization Source: https://ase-lib.org/_modules/ase/calculators/mopac.html Utilize MOPAC's internal geometry optimization capabilities by setting the task to 'GRADIENTS'. This example shows how to perform an optimization starting from a simple H2 molecule. ```python from ase.build import molecule from ase.calculators.mopac import MOPAC atoms = molecule('H2') atoms.calc = MOPAC(label='H2', task='GRADIENTS') atoms.get_potential_energy() ``` -------------------------------- ### Basic Gaussian Calculation Setup Source: https://ase-lib.org/ase/calculators/gaussian.html Sets up a simple H2 molecule calculation using the Gaussian calculator with specified method and basis set. This is a common starting point for electronic structure calculations. ```python from ase import Atoms from ase.calculators.gaussian import Gaussian atoms = Atoms('H2', [[0, 0, 0], [0, 0, 0.74]]) atoms.calc = Gaussian(mem='1GB', chk='MyJob.chk', save=None, method='b3lyp', basis='6-31G', scf='qc') atoms.get_potential_energy() ``` -------------------------------- ### Dimer Method Setup Source: https://ase-lib.org/examples_generated/tutorials/neb_selfdiffusion.html Initializes atomic configurations and parameters for a Dimer method calculation, including lattice constants, atom positions, and cell parameters. This setup is for finding a transition state when the final configuration is unknown. ```python from ase.io import Trajectory from ase.mep import DimerControl, MinModeAtoms, MinModeTranslate a = 4.0614 b = a / sqrt(2) h = b / 2 initial = Atoms( 'Al2', positions=[(0, 0, 0), (a / 2, b / 2, -h)], cell=(a, b, 2 * h), pbc=(1, 1, 0), ) initial *= (2, 2, 2) initial.append(Atom('Al', (a / 2, b / 2, 3 * h))) initial.center(vacuum=4.0, axis=2) initial_copy = initial.copy() N = len(initial) # number of atoms # Make a mask of zeros and ones that select fixed atoms - the two ``` -------------------------------- ### Helper Function to Get Frame Positions in HISTORY File Source: https://ase-lib.org/_modules/ase/io/dlp4.html Internal function to determine the starting positions of frames within a DL_POLY HISTORY file. It handles different file format versions. ```python from typing import IO, Tuple, List def _get_frame_positions(fd: IO) -> Tuple[int, int, int, List[int]]: """Get positions of frames in HISTORY file.""" init_pos = fd.tell() fd.seek(0) record_len = len(fd.readline()) # system name, and record size items = fd.readline().strip().split() if len(items) not in (3, 5): raise RuntimeError("Cannot determine version of HISTORY file format.") levcfg, imcon, natoms = map(int, items[0:3]) if len(items) == 3: # DLPoly classic # we have to iterate over the entire file pos = [fd.tell() for line in fd if "timestep" in line] else: nframes = int(items[3]) pos = [((natoms * (levcfg + 2) + 4) * i + 3) * record_len for i in range(nframes)] fd.seek(init_pos) return levcfg, imcon, natoms, pos ``` -------------------------------- ### Browse Built Documentation Source: https://ase-lib.org/development/addingexamples.html Open the locally built HTML documentation in a web browser to review the changes and rendered examples. ```bash $ make browse ``` -------------------------------- ### Setup Initial State for Ethane NEB Calculation Source: https://ase-lib.org/_downloads/36744ebb76448154ecac8f64358c6c37/neb_idpp.ipynb Initializes an ethane molecule, attaches an EMT calculator, and relaxes the structure using the FIRE optimizer. This sets up the starting point for the NEB calculation. ```python from ase.build import molecule from ase.calculators.emt import EMT from ase.mep import NEB from ase.optimize.fire import FIRE # Create the molecule. initial = molecule('C2H6') # Attach calculators initial.calc = EMT() # Relax the molecule relax = FIRE(initial) relax.run(fmax=0.05) ``` -------------------------------- ### Get Reduced Atomic Basis for Rocksalt NaCl Source: https://ase-lib.org/ase/spacegroup/spacegroup.html Use `ase.spacegroup.get_basis()` to obtain a reduced basis representation of a crystal structure. This example demonstrates its use with rocksalt NaCl, explicitly providing the spacegroup number. ```python from ase.build import bulk from ase.spacegroup import get_basis atoms = bulk('NaCl', crystalstructure='rocksalt', a=5.64) spacegroup = 225 # Rocksalt basis = get_basis(atoms, spacegroup=spacegroup) basis ``` -------------------------------- ### Get Spacegroup from Atoms Object Source: https://ase-lib.org/_modules/ase/spacegroup/spacegroup.html Determines the spacegroup of an Atoms object using spglib. Requires spglib to be installed. Note: This function is deprecated and returns symmetry operations for a standard setting regardless of the input Atoms object. ```python from ase.build import bulk from ase.spacegroup import get_spacegroup atoms = bulk("Cu", "fcc", a=3.6, cubic=True) sg = get_spacegroup(atoms) print(sg) print(sg.no) ``` -------------------------------- ### NVE Simulation Setup with Langevin Source: https://ase-lib.org/_sources/examples_generated/tutorials/md.rst Sets up a constant temperature NVT simulation using the Langevin thermostat. Requires importing Langevin and units. ```Python dyn = Langevin(atoms, timestep=5 * units.fs, temperature_K=T, friction=0.02) ``` -------------------------------- ### Infrared.get_spectrum Source: https://ase-lib.org/ase/vibrations/infrared.html Get infrared spectrum. The method returns wavenumbers in cm^-1 with corresponding absolute infrared intensity. Start and end point, and width of the Gaussian/Lorentzian should be given in cm^-1. normalize=True ensures the integral over the peaks to give the intensity. ```APIDOC ## get_spectrum ### Description Get infrared spectrum. The method returns wavenumbers in cm^-1 with corresponding absolute infrared intensity. Start and end point, and width of the Gaussian/Lorentzian should be given in cm^-1. normalize=True ensures the integral over the peaks to give the intensity. ### Method `get_spectrum(_start =800_, _end =4000_, _npts =None_, _width =4_, _type ='Gaussian'_, _method ='standard'_, _direction ='central'_, _intensity_unit ='(D/A)2/amu'_, _normalize =False_)` ### Parameters #### Keyword Arguments - **_start** (float) - Start wavenumber in cm^-1. - **_end** (float) - End wavenumber in cm^-1. - **_npts** (int) - Number of points. - **_width** (float) - Width of the Gaussian/Lorentzian in cm^-1. - **_type** (str) - Type of peak broadening ('Gaussian' or 'Lorentzian'). - **_method** (str) - Method for calculating intensity ('standard'). - **_direction** (str) - Direction for calculation ('central'). - **_intensity_unit** (str) - Unit for intensity, e.g., '(D/A)2/amu'. - **_normalize** (bool) - Whether to normalize the spectrum. ``` -------------------------------- ### Setup Surface and Add Adsorbate Source: https://ase-lib.org/_sources/ase/build/surface.rst Create a surface slab and then use `add_adsorbate` to place an atom at a specific position and site. The `slab.center` method is used to add vacuum after the adsorbate is placed. ```python from ase.build import fcc111, add_adsorbate slab = fcc111('Al', size=(2,2,3)) add_adsorbate(slab, 'H', 1.5, 'ontop') slab.center(vacuum=10.0, axis=2) ``` -------------------------------- ### Initialize and Run Phonon Calculation Source: https://ase-lib.org/_modules/ase/phonons.html Set up a phonon calculation using a specified calculator and supercell, then run the calculation. This snippet demonstrates the basic workflow for obtaining phonon data. ```python from ase.build import bulk from ase.phonons import Phonons from gpaw import GPAW, FermiDirac atoms = bulk('Si', 'diamond', a=5.4) calc = GPAW(mode='fd', kpts=(5, 5, 5), h=0.2, occupations=FermiDirac(0.)) ph = Phonons(atoms, calc, supercell=(5, 5, 5)) ph.run() ph.read(method='frederiksen', acoustic=True) ``` -------------------------------- ### ASE Gromacs Calculator for MM Relaxation Source: https://ase-lib.org/ase/calculators/gromacs.html Example script demonstrating MM-only geometry optimization using the ASE Gromacs calculator. It prepares the system, generates topology, and runs the relaxation. Note: This is a simplified demo and not a proper MD setup. ```python """An example for using gromacs calculator in ase. Atom positions are relaxed. A sample call: python ./gromacs_example_mm_relax.py his.pdb """ import sys from ase.calculators.gromacs import Gromacs infile_name = sys.argv[1] CALC_MM_RELAX = Gromacs(clean=True) CALC_MM_RELAX.set_own_params_runs('extra_pdb2gmx_parameters', '-ignh') CALC_MM_RELAX.set_own_params_runs('init_structure', infile_name) CALC_MM_RELAX.generate_topology_and_g96file() CALC_MM_RELAX.write_input() CALC_MM_RELAX.set_own_params_runs( 'extra_editconf_parameters', '-bt cubic -c -d 0.8' ) CALC_MM_RELAX.run_editconf() CALC_MM_RELAX.set_own_params_runs('extra_genbox_parameters', '-cs spc216.gro') CALC_MM_RELAX.run_genbox() CALC_MM_RELAX.generate_gromacs_run_file() CALC_MM_RELAX.run() ``` -------------------------------- ### Instantiate Vasp Calculator with Directory and TXT Source: https://ase-lib.org/_sources/ase/calculators/vasp.rst Demonstrates setting the 'directory' for the VASP run and specifying the output file for stdout redirection using the 'txt' keyword. ```python Vasp(directory='my_vasp_run', txt='vasp.out') ``` -------------------------------- ### Get reduced basis using spglib Source: https://ase-lib.org/_modules/ase/spacegroup/utils.html Retrieves a reduced basis for an Atoms object using the spglib library. This function requires spglib to be installed and will raise an ImportError if it is not available. It uses spglib's functionality to identify and return the basis sites. ```python def _get_basis_spglib(atoms: Atoms, tol: float = 1e-5) -> np.ndarray: """Get a reduced basis using spglib. This requires having the spglib package installed. :param atoms: Atoms, atoms object to get basis from :param tol: ``float``, numeric tolerance for positional comparisons Default: ``1e-5`` """ if not _has_spglib(): # Give a reasonable alternative solution to this function. raise ImportError( 'This function requires spglib. Use "get_basis" and specify ' 'the spacegroup instead, or install spglib.') scaled_positions = atoms.get_scaled_positions() reduced_indices = _get_reduced_indices(atoms, tol=tol) return scaled_positions[reduced_indices] ``` -------------------------------- ### Calculate and summarize vibrational modes Source: https://ase-lib.org/ase/vibrations/modes.html This example demonstrates how to initialize and run vibrational mode calculations for an Atoms object. It includes optimizing the structure first and then printing a summary of the vibrational frequencies and zero-point energy. Use this to get a quick overview of the vibrational properties. ```python from ase import Atoms from ase.calculators.emt import EMT from ase.optimize import BFGS from ase.vibrations import Vibrations n2 = Atoms('N2', [(0, 0, 0), (0, 0, 1.1)], calculator=EMT()) BFGS(n2).run(fmax=0.01) vib = Vibrations(n2) vib.run() vib.summary() ``` -------------------------------- ### Get reduced atomic indices using spglib Source: https://ase-lib.org/_modules/ase/spacegroup/utils.html Obtains a list of reduced atomic indices for an Atoms object using spglib. This function assumes spglib is installed and does not perform checks. It prepares the cell, scaled positions, and atomic numbers for spglib and returns the unique equivalent atoms. ```python def _get_reduced_indices(atoms: Atoms, tol: float = 1e-5) -> list[int]: """Get a list of the reduced atomic indices using spglib. Note: Does no checks to see if spglib is installed. :param atoms: ase Atoms object to reduce :param tol: ``float``, numeric tolerance for positional comparisons """ from ase.spacegroup.symmetrize import spglib_get_symmetry_dataset # Create input for spglib spglib_cell = (atoms.get_cell(), atoms.get_scaled_positions(), atoms.numbers) symmetry_data = spglib_get_symmetry_dataset(spglib_cell, symprec=tol) return list(set(symmetry_data.equivalent_atoms)) ``` -------------------------------- ### Build Web Page Source: https://ase-lib.org/development/newrelease.html Navigate to the doc directory and run make clean and make to build the web page. Use 'make inspect' to check generated images. ```bash cd doc make clean make ```