### Install tcal via pip Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt Commands to install the tcal package with various backend support options including PySCF and GPU-accelerated configurations. ```bash pip install yu-tcal pip install "yu-tcal[pyscf]" pip install "yu-tcal[gpu4pyscf-cuda12]" pip install "yu-tcal[gpu4pyscf-cuda11]" ``` -------------------------------- ### Install PySCF for Tcal Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Provides installation commands for PySCF with Tcal, supporting CPU and GPU (CUDA 11/12) configurations. This is crucial for users who need to leverage PySCF for their calculations. ```bash pip install "yu-tcal[pyscf]" pip install "yu-tcal[gpu4pyscf-cuda12]" pip install "yu-tcal[gpu4pyscf-cuda11]" ``` -------------------------------- ### Execute tcal command Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_sources/index.rst.txt This snippet shows the basic command to execute tcal with a Gaussian input file. It is used for initial calculation setup. ```bash tcal -cr xxx.gjf ``` -------------------------------- ### GET /tcal_pyscf/read_monomer Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Extracts MO coefficients from PySCF monomer results. ```APIDOC ## GET /tcal_pyscf/read_monomer ### Description Extracts and optionally prints or exports MO coefficients from monomer calculation results. ### Method GET ### Endpoint /tcal_pyscf/read_monomer ### Parameters #### Query Parameters - **is_matrix** (bool) - Optional - If true, prints MO coefficients. - **output_matrix** (bool) - Optional - If true, exports MO coefficients to CSV. ### Response #### Success Response (200) - **data** (object) - Extracted MO coefficient data. ### Response Example { "data": "[...coefficients...]" } ``` -------------------------------- ### Execute tcal with PySCF Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_sources/index.rst.txt This snippet demonstrates how to run tcal using PySCF for quantum chemistry calculations. It supports specifying calculation methods, basis sets, and GPU acceleration. It can also read from existing checkpoint files. ```bash tcal --pyscf -a xxx.xyz ``` ```bash tcal --pyscf -M "B3LYP/6-31G(d,p)" -a xxx.xyz ``` ```bash tcal --gpu4pyscf -M "B3LYP/6-31G(d,p)" -a xxx.xyz ``` ```bash tcal --pyscf -ar xxx.xyz ``` -------------------------------- ### GET /extract_coordinates Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Extracts molecular coordinates from a dimer GJF file. ```APIDOC ## GET /extract_coordinates ### Description Parses a GJF file reader to extract coordinate data for a dimer. ### Method GET ### Parameters #### Query Parameters - **reader** (TextIO) - Required - The file object to read from. ### Response #### Success Response (200) - **reader** (TextIO) - The file object. - **coordinates** (List[str]) - The list of extracted coordinates. ``` -------------------------------- ### GET /extract_num Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Utility to extract an integer from a string using regex patterns. ```APIDOC ## GET /extract_num ### Description Extracts an integer from a target string based on a provided regex pattern. ### Method GET ### Parameters #### Query Parameters - **pattern** (str) - Required - Regular expression pattern. - **line** (str) - Required - Target string. - **idx** (int) - Optional - Index of the integer to extract. ### Response #### Success Response (200) - **value** (int) - The extracted integer. ``` -------------------------------- ### POST /tcal_pyscf/run_pyscf Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Initiates PySCF calculations for monomer and dimer systems. ```APIDOC ## POST /tcal_pyscf/run_pyscf ### Description Runs the PySCF calculation workflow for the defined molecular system. ### Method POST ### Endpoint /tcal_pyscf/run_pyscf ### Parameters #### Request Body - **skip_monomer_num** (List[int]) - Optional - List of indices to skip calculation for. ### Response #### Success Response (200) - **status** (string) - Execution status message. ### Response Example { "status": "success" } ``` -------------------------------- ### GET /tcal/read_matrix Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Reads a matrix from a file stream, typically used for MO coefficients or overlap/fock matrices. ```APIDOC ## GET /tcal/read_matrix ### Description Reads a matrix from a provided file reader object, specifying the dimensions of the matrix. ### Method GET ### Endpoint /tcal/read_matrix ### Parameters #### Query Parameters - **n_basis** (int) - Required - Number of rows. - **n_bsuse** (int) - Required - Number of columns. ### Response #### Success Response (200) - **matrix** (ndarray) - The resulting matrix as a numpy array. #### Response Example { "matrix": [[0.1, 0.2], [0.3, 0.4]] } ``` -------------------------------- ### Tcal Initialization and Gaussian Execution Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Shows how to initialize the Tcal class for standard calculations and convert XYZ files to GJF format. It also includes the execution of Gaussian (g09 or g16) for monomer file creation and calculations. ```python tcal = Tcal(args.file, monomer1_atom_num=args.hetero) # convert xyz to gjf if args.xyz: tcal.convert_xyz_to_gjf(function=args.method, nprocshared=args.cpu, mem=args.mem) if not args.read: tcal.create_monomer_file() gaussian_command = 'g09' if args.g09 else 'g16' res = tcal.run_gaussian(gaussian_command, skip_monomer_num=args.skip) if res: print() Tcal.print_timestamp() after = time() print(f'Elapsed Time: {(after - before) * 1000:.0f} ms') exit() ``` -------------------------------- ### Initialize TcalPySCF for Quantum Chemistry Calculations Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal_pyscf.html The TcalPySCF class constructor initializes the environment for calculating transfer integrals. It requires an XYZ file path and accepts parameters for method selection, charge, spin, and computational resource allocation. ```python from tcal.tcal_pyscf import TcalPySCF # Initialize the calculator calc = TcalPySCF( file="dimer.xyz", method="B3LYP/6-31G(d,p)", ncore=4, max_memory_gb=16 ) ``` -------------------------------- ### Generate Molecular Orbital Cube Files Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal_pyscf.html The create_cube_file method generates Gaussian cube files for NHOMO, HOMO, LUMO, and NLUMO orbitals. It processes monomer checkpoint files to visualize electronic density distributions. ```python calc = TcalPySCF(file="dimer.xyz") # Generate cube files for visualization calc.create_cube_file() ``` -------------------------------- ### Print Current Timestamp Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Prints the current date and time in a formatted string. It uses the `datetime` module to get the current time and a dictionary to map month numbers to their abbreviations. ```python from datetime import datetime @staticmethod def print_timestamp() -> None: """Print timestamp.""" month = { 1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec', } dt_now = datetime.now() print(f"Timestamp: {dt_now.strftime('%a')} {month[dt_now.month]} {dt_now.strftime('%d %H:%M:%S %Y')}") ``` -------------------------------- ### Calculate Transfer Integrals with Gaussian Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt CLI commands to perform transfer integral calculations and APTA using Gaussian input files as the primary data source. ```bash tcal -a Anthracene.gjf tcal -a -g Anthracene.gjf tcal -a -M "B3LYP/6-31G(d,p)" Anthracene.gjf tcal -a --cpu 8 --mem 32 Anthracene.gjf tcal -ar Anthracene.gjf tcal -ao Anthracene.gjf ``` -------------------------------- ### Tcal Initialization and PySCF Execution Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Demonstrates the initialization of the Tcal class for PySCF calculations and the subsequent execution of the PySCF run. It handles arguments for GPU usage, CPU cores, memory, and other computational parameters. ```python tcal = TcalPySCF( args.file, monomer1_atom_num=args.hetero, method=args.method, use_gpu=args.gpu4pyscf, ncore=args.cpu, max_memory_gb=args.mem, cart=args.cart, ) if not args.read: tcal.run_pyscf(skip_monomer_num=args.skip) ``` -------------------------------- ### Create Cube File (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Creates a cube file. This function does not take any arguments and returns None. ```python from tcal import Tcal Tcal.create_cube_file() ``` -------------------------------- ### Analyze Transfer Integrals and APTA with Tcal Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt Demonstrates the standard workflow for reading monomer/dimer data, printing transfer integrals for specific orbital levels, and performing atomic pair transfer analysis (APTA). ```python tcal.read_monomer1() tcal.read_monomer2() tcal.read_dimer() tcal.print_transfer_integrals() # Perform atomic pair transfer analysis for HOMO apta = tcal.atomic_pair_transfer_analysis('HOMO', output_apta=True) # Analyze specific orbital levels apta = tcal.custom_atomic_pair_transfer_analysis( analyze_orb1=45, analyze_orb2=46, output_apta=True ) # Print transfer integrals between different levels tcal.print_transfer_integral_diff_levels(nlevel=3, output_ti_diff_levels=True) ``` -------------------------------- ### POST /run_gaussian Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Executes Gaussian calculations using provided gjf files and command strings. ```APIDOC ## POST /run_gaussian ### Description Executes Gaussian calculations for monomers and dimers based on the provided command. ### Method POST ### Endpoint /run_gaussian ### Parameters #### Request Body - **gaussian_command** (str) - Required - Command to execute Gaussian. - **skip_monomer_num** (List[int]) - Optional - List of monomer indices to skip (1, 2, or 3 for dimer). ### Response #### Success Response (200) - **return_code** (int) - Return code of the subprocess execution. ### Response Example { "return_code": 0 } ``` -------------------------------- ### Initialize Command Line Interface for tcal Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html The main function sets up an argparse interface to configure calculation parameters such as method, basis set, CPU/memory allocation, and specific analysis flags like APTA or cube file generation. ```python def main(): """This code is to execute tcal for command line.""" parser = argparse.ArgumentParser() parser.add_argument('file', help='file name', type=str) parser.add_argument('-a', '--apta', help='perform atomic pair transfer analysis', action='store_true') parser.add_argument('-c', '--cube', help='generate cube files', action='store_true') parser.add_argument('-M', '--method', help='calculation method and basis set', type=str, default='B3LYP/6-31G(d,p)') parser.add_argument('--cpu', help='setting the number of CPUs', type=int, default=4) parser.add_argument('--mem', help='setting the memory size [GB]', type=int, default=16) args = parser.parse_args() print('----------------------------------------') print(' tcal 4.0.3 (2026/02/26) by Matsui Lab. ') print('----------------------------------------') print(f'\nInput File Name: {args.file}') ``` -------------------------------- ### Perform Orbital and Heterodimer Analysis Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt Advanced CLI commands for analyzing specific orbital levels (LUMO, multi-level) and handling heterodimer structures. ```bash tcal -l Anthracene.gjf tcal --nlevel 3 Anthracene.gjf tcal --nlevel 0 Anthracene.gjf tcal --napta 45 46 Anthracene.gjf tcal -a --hetero 24 heterodimer.gjf tcal --pyscf -a --hetero 24 heterodimer.xyz ``` -------------------------------- ### Generate Dummy Cube Files Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Reads atomic coordinates from a Gaussian input file to calculate spatial boundaries and generates a dummy .cube file formatted for grid-based analysis. ```python def _create_dummy_cube_file(self) -> None: # Logic to parse coordinates and write cube file header with open(f'{self._base_path}.gjf', 'r') as f: # ... coordinate extraction logic ... with open(f'{self._base_path}_dummy.cube', 'w') as f: f.write('\n\n') f.write(f'1, {min_x/bohr:.3f}, {min_y/bohr:.3f}, {min_z/bohr:.3f}\n') f.write(f'{num_x}, {cube_delta/bohr:.3f}, 0.0, 0.0\n') f.write(f'{num_y}, 0.0, {cube_delta/bohr:.3f}, 0.0\n') f.write(f'{num_z}, 0.0, 0.0, {cube_delta/bohr:.3f}\n') ``` -------------------------------- ### POST /tcal/run_gaussian Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Executes Gaussian calculations for monomer and dimer files based on the provided command and skip parameters. ```APIDOC ## POST /tcal/run_gaussian ### Description Executes Gaussian gjf files using the specified command. Allows skipping specific calculations (monomer 1, monomer 2, or dimer) via the skip_monomer_num parameter. ### Method POST ### Endpoint /tcal/run_gaussian ### Parameters #### Request Body - **gaussian_command** (str) - Required - The command string to execute Gaussian. - **skip_monomer_num** (List[int]) - Optional - List of indices to skip (1: monomer 1, 2: monomer 2, 3: dimer). Default: [0]. ### Request Example { "gaussian_command": "g16", "skip_monomer_num": [1] } ### Response #### Success Response (200) - **return_code** (int) - The return code of the subprocess execution. #### Response Example { "return_code": 0 } ``` -------------------------------- ### Tcal Class Initialization Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Documentation for the Tcal class constructor. It details the parameters `file` and `monomer1_atom_num`, explaining their purpose and default values in initializing the transfer integral calculation object. ```python class Tcal: """Calculate transfer integrals.""" EV: float = 4.35974417e-18 / 1.60217653e-19 * 1000.0 def __init__(self, file: str, monomer1_atom_num: int = -1) -> None: """Inits TcalClass. Parameters ---------- file : str A path of gjf file. monomer1_atom_num: int Number of atoms in the first monomer. default -1 If monomer1_atom_num is -1, it is half the number of atoms in the dimer. """ if platform.system() == 'Windows': self.extension_log = '.out' else: self.extension_log = '.log' self._base_path = os.path.splitext(file)[0] self.monomer1_atom_num = monomer1_atom_num self.n_basis1 = None self.n_elect1 = None self.n_bsuse1 = None self.n_basis2 = None self.n_elect2 = None self.n_bsuse2 = None self.n_basis_d = None self.n_elect_d = None self.mo1 = None self.mo2 = None self.overlap = None self.fock = None self.atom_index = None self.atom_symbol = None self.atom_orbital = None self.n_atoms1 = None self.n_atoms2 = None ``` -------------------------------- ### Create Cube Files for Molecular Orbitals Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Executes Gaussian's formchk and cubegen utilities to convert checkpoint files into cube files. This process is performed for both monomers, generating files for NHOMO, HOMO, LUMO, and NLUMO orbitals. ```python def create_cube_file(self) -> None: self._execute(['formchk', f'{self._base_path}.chk', f'{self._base_path}.fchk']) self._create_dummy_cube_file() self._execute(['formchk', f'{self._base_path}_m1.chk', f'{self._base_path}_m1.fchk']) self._execute(['cubegen', '0', f'mo={self.n_elect1-1}', f'{self._base_path}_m1.fchk', f'{self._base_path}_m1_NHOMO.cube', '-1', 'h', f'{self._base_path}_dummy.cube']) # ... (repeated for other orbitals) ``` -------------------------------- ### Manage Calculation Workflow and File Conversion Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt Utility commands for generating visualization cube files, skipping specific calculation steps, and converting file formats. ```bash tcal -c Anthracene.gjf tcal -cr Anthracene.gjf tcal -a --skip 1 Anthracene.gjf tcal -x molecule.xyz tcal -x -M "B3LYP/cc-pVDZ" molecule.xyz ``` -------------------------------- ### Calculate Transfer Integrals with PySCF Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt CLI commands to perform transfer integral calculations using the PySCF backend, supporting XYZ files and GPU acceleration. ```bash tcal --pyscf -a molecule.xyz tcal --pyscf -M "B3LYP/6-31G(d,p)" -a molecule.xyz tcal --gpu4pyscf -M "B3LYP/6-31G(d,p)" -a molecule.xyz tcal --pyscf -ar molecule.xyz tcal --pyscf --cart -a molecule.xyz ``` -------------------------------- ### File Creation Functions Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Functions for creating various molecular files. ```APIDOC ## create_cube_file() ### Description Creates a cube file. ### Method Not applicable (function call) ### Endpoint Not applicable ### Parameters None ### Request Example ```python Tcal.create_cube_file() ``` ### Response #### Success Response (None) This function does not return any value. ## create_monomer_file() ### Description Creates GJF files for monomers from a GJF file of a dimer. ### Method Not applicable (function call) ### Endpoint Not applicable ### Parameters None ### Request Example ```python Tcal.create_monomer_file() ``` ### Response #### Success Response (None) This function does not return any value. ``` -------------------------------- ### Load Monomer Molecular Data from Checkpoint (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal_pyscf.html Loads the molecular structure (mol) and molecular orbital coefficients (mo_coeff) from a checkpoint file or from cached SCF results. It raises a FileNotFoundError if the checkpoint file does not exist and no cached results are available. ```python def _load_from_chk_monomer(self, chkfile: str, mf) -> Tuple: """Load mol and mo_coeff from memory or chkfile. Parameters ---------- chkfile : str Path to the checkpoint file. mf : SCF object or None Cached SCF result. If None, load from chkfile. Returns ------- tuple (mol, mo_coeff) """ if mf is not None: return mf.mol, self._to_numpy(mf.mo_coeff) if not os.path.exists(chkfile): raise FileNotFoundError(f'{chkfile} not found. Run run_pyscf() first.') mol = lib.chkfile.load_mol(chkfile) mo_coeff = lib.chkfile.load(chkfile, 'scf/mo_coeff') return mol, mo_coeff ``` -------------------------------- ### Initialize PairAnalysis (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Initializes the PairAnalysis class with atomic pair transfer integrals. It processes the input array to extract labels and transfer integral values, then calculates the number of atoms for each set. ```python class PairAnalysis: """Analyze atomic pair transfer integrals.""" def __init__(self, apta: ArrayLike) -> None: """Inits PairAnalysisClass. Parameters ---------- apta : array_like List of atomic pair transfer integrals including labels. """ self._labels = [] self._a_transfer = [] for row in apta[1:-1]: symbol = re.sub('[0-9]+', '', row[0]) self._labels.append(symbol) self._a_transfer.append(row[1:-1]) label = apta[0][1:-1] label = list(map(lambda x: re.sub('[0-9]+', '', x), label)) self._labels.extend(label) self._a_transfer = np.array(self._a_transfer, dtype=np.float64) self.n_atoms1 = self._a_transfer.shape[0] self.n_atoms2 = self._a_transfer.shape[1] ``` -------------------------------- ### Load Dimer Molecular Data from Checkpoint (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal_pyscf.html Loads the molecular structure (mol) and Fock matrix from a checkpoint file or from cached SCF results. It raises a FileNotFoundError if the checkpoint file does not exist and no cached results are available. This function is intended for dimer calculations. ```python def _load_from_chk_dimer(self, chkfile: str, mf) -> Tuple: """Load mol and fock from memory or chkfile. Parameters ---------- chkfile : str Path to the checkpoint file. mf : SCF object or None Cached SCF result. If None, load from chkfile. Returns ------- tuple (mol, fock) """ if mf is not None: return mf.mol, self._to_numpy(mf.get_fock()) if not os.path.exists(chkfile): raise FileNotFoundError(f'{chkfile} not found. Run run_pyscf() first.') mol = lib.chkfile.load_mol(chkfile) fock = lib.chkfile.load(chkfile, 'tcal/fock') return mol, fock ``` -------------------------------- ### Run PySCF Calculation Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal_pyscf.html Configures and executes an SCF calculation using PySCF. Supports both CPU and GPU backends (via gpu4pyscf) and allows customization of functional, basis set, charge, and spin. ```python def _run_pyscf_calculation(self, atoms, functional, basis, charge, spin, chkfile, label, use_gpu=False, ncore=4, max_memory_gb=16, cart=False): lib.num_threads(ncore) mol = gto.Mole() mol.atom = atoms mol.basis = basis mol.charge = charge mol.spin = spin mol.max_memory = max_memory_gb * 1000 mol.cart = cart mol.build() if use_gpu: if functional.upper() == 'HF': from gpu4pyscf.scf import hf as gpu_hf mf = gpu_hf.RHF(mol) else: from gpu4pyscf.dft import rks as gpu_rks mf = gpu_rks.RKS(mol) mf.xc = functional else: if functional.upper() == 'HF': mf = scf.RHF(mol) else: mf = dft.RKS(mol) mf.xc = functional mf.chkfile = chkfile mf.kernel() ``` -------------------------------- ### Perform PySCF Calculations with TcalPySCF Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt Configures and runs electronic structure calculations using PySCF as the backend, supporting GPU acceleration and custom memory/core settings. ```python from tcal.tcal_pyscf import TcalPySCF tcal = TcalPySCF( 'molecule.xyz', method='B3LYP/6-31G(d,p)', use_gpu=False, ncore=4, max_memory_gb=16, cart=False ) tcal.run_pyscf() tcal.read_monomer1() tcal.read_monomer2() tcal.read_dimer() tcal.print_transfer_integrals() apta = tcal.atomic_pair_transfer_analysis('HOMO') tcal.create_cube_file() ``` ```python from tcal.tcal_pyscf import TcalPySCF # Initialize with GPU acceleration enabled tcal = TcalPySCF( 'molecule.xyz', method='B3LYP/6-31G(d,p)', use_gpu=True, ncore=4, max_memory_gb=32 ) tcal.run_pyscf() tcal.read_monomer1() tcal.read_monomer2() tcal.read_dimer() tcal.print_transfer_integrals() ``` -------------------------------- ### Use Tcal Python API Source: https://context7.com/matsui-lab-yamagata/tcal/llms.txt Programmatic access to the Tcal class to automate monomer file creation and Gaussian calculation execution. ```python from tcal.tcal import Tcal tcal = Tcal('Anthracene.gjf') tcal.create_monomer_file() return_code = tcal.run_gaussian('g16') ``` -------------------------------- ### Print Matrix (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Prints a matrix to the console. It accepts array-like data as input. This is a static method. ```python from tcal import Tcal import numpy as np # Example usage: # matrix_data = np.array([[1, 2], [3, 4]]) # Tcal.print_matrix(matrix_data) ``` -------------------------------- ### Execute PySCF Calculations Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal_pyscf.html The run_pyscf method performs the electronic structure calculations for the specified monomers and dimer. Users can selectively skip calculations using the skip_monomer_num parameter. ```python calc = TcalPySCF(file="dimer.xyz") # Run calculations, skipping the dimer (3) calc.run_pyscf(skip_monomer_num=[3]) ``` -------------------------------- ### Create Monomer File (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Creates GJF files for monomers from a GJF file of a dimer. This function does not take any arguments and returns None. ```python from tcal import Tcal Tcal.create_monomer_file() ``` -------------------------------- ### Tcal Data Reading and Analysis Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Illustrates the process of reading monomer and dimer data, creating cube files, and printing transfer integrals. It also covers advanced analyses like custom atomic pair transfer analysis (APTA) and LUMO analysis. ```python if not (args.pyscf or args.gpu4pyscf): tcal.check_extension_log() tcal.read_monomer1(args.matrix) tcal.read_monomer2(args.matrix) tcal.read_dimer(args.matrix) if args.cube: tcal.create_cube_file() tcal.print_transfer_integrals() if args.nlevel is not None: tcal.print_transfer_integral_diff_levels(args.nlevel, output_ti_diff_levels=args.output) if args.apta: analyze_orbital = 'HOMO' elif args.lumo: analyze_orbital = 'LUMO' if args.napta: apta = tcal.custom_atomic_pair_transfer_analysis( analyze_orb1=args.napta[0], analyze_orb2=args.napta[1], output_apta=args.output ) pair_analysis = PairAnalysis(apta) pair_analysis.print_largest_pairs() pair_analysis.print_element_pairs() elif args.apta or args.lumo: apta = tcal.atomic_pair_transfer_analysis(analyze_orbital, output_apta=args.output) pair_analysis = PairAnalysis(apta) pair_analysis.print_largest_pairs() pair_analysis.print_element_pairs() print() ``` -------------------------------- ### Print Element Pairs (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Prints a summary of transfer integrals grouped by element pairs. It iterates through all possible atom pairs, determines the element pair combination, and accumulates the transfer integral values for each unique element pair. Only pairs with non-zero transfer are displayed. ```python def print_element_pairs(self) -> None: """Print element pairs.""" element_pair = { 'H-I': 0.0, 'C-C': 0.0, 'C-H': 0.0, 'C-S': 0.0, 'C-Se': 0.0, 'C-I': 0.0, 'S-S': 0.0, 'Se-Se': 0.0, 'N-S': 0.0, 'I-S': 0.0, 'I-I': 0.0, } keys = element_pair.keys() for i in range(self.n_atoms1): sym1 = self._labels[i] for j in range(self.n_atoms2): sym2 = self._labels[self.n_atoms1 + j] key = '-'.join(sorted([sym1, sym2])) if key in keys: element_pair[key] += self._a_transfer[i][j] print() print('---------------') print(' Element Pairs ') print('---------------') for k, value in element_pair.items(): if value != 0: print(f'{k:<5}\t{value:>9.3f}') ``` -------------------------------- ### File Conversion and Log Management Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Utilities for checking log file extensions and converting molecular coordinate files from XYZ format to Gaussian GJF input format. ```python def convert_xyz_to_gjf(self, function='B3LYP/6-31G(d,p)', nprocshared=4, mem=16, unit='GB'): coordinates = [] with open(f'{self._base_path}.xyz', 'r') as f: while True: line = f.readline() if not line: break line_list = line.strip().split() if len(line_list) == 4: symbol, x, y, z = line_list x, y, z = map(float, [x, y, z]) coordinates.append(f' {symbol} {x:14.8f} {y:14.8f} {z:14.8f}\n') with open(f'{self._base_path}.gjf', 'w') as f: # Logic to write Gaussian input header and coordinates... ``` -------------------------------- ### print_matrix Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Prints a matrix to the console with formatted alignment. ```APIDOC ## print_matrix ### Description Prints a matrix to the console with formatted alignment. ### Method `@staticmethod` ### Endpoint `Tcal.print_matrix(matrix: ArrayLike) -> None` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python matrix_data = [[1.0, 2.5, 3.14], [4.2, 5.0, 6.78]] Tcal.print_matrix(matrix_data) ``` ### Response #### Success Response (200) None (This function prints to the console and does not return a value). #### Response Example ``` 1.000 2.500 3.140 4.200 5.000 6.780 ``` ``` -------------------------------- ### Print Transfer Integrals (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Prints transfer integrals for NLUMO, LUMO, HOMO, and NHOMO. This function does not take any arguments. ```python from tcal import Tcal Tcal.print_transfer_integrals() ``` -------------------------------- ### POST /custom_atomic_pair_transfer_analysis Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Calculates atomic pair transfer integrals based on specified orbitals. ```APIDOC ## POST /custom_atomic_pair_transfer_analysis ### Description Calculate atomic pair transfer integrals for specified orbitals. ### Method POST ### Parameters #### Request Body - **analyze_orb1** (int) - Required - Analyze orbital index. - **analyze_orb2** (int) - Required - Analyze orbital index. - **output_apta** (bool) - Optional - If True, outputs a CSV file of the results. ### Response #### Success Response (200) - **result** (ndarray) - The array of atomic pair transfer analysis values. ``` -------------------------------- ### Print Matrix with Formatting Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Prints a matrix to the console with specific formatting. It iterates through rows and columns, aligning numbers within a fixed width. The first row and column have centered alignment, while others have right alignment. ```python from typing import ArrayLike @staticmethod def print_matrix(matrix: ArrayLike) -> None: """Print matrix. Parameters ---------- matrix : array_like """ for i, row in enumerate(matrix): for j, cell in enumerate(row[:-1]): if i == 0 or j == 0: print(f'{cell:^9}', end='\t') else: print(f'{cell:>9}', end='\t') if i == 0: print(f'{row[-1]:^9}') else: print(f'{row[-1]:>9}') ``` -------------------------------- ### Dimer File Reading Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Function to read overlap and Fock matrices from dimer log files. ```APIDOC ## read_dimer(_is_matrix: bool = False, _output_matrix: bool = False_) ### Description Extracts overlap and Fock matrices from the log file of a dimer. ### Method Not applicable (function call) ### Endpoint Not applicable ### Parameters * **is_matrix** (bool) - Optional - Indicates if the output should be a matrix. * **output_matrix** (bool) - Optional - If True, outputs the matrix. ### Request Example ```python Tcal.read_dimer(is_matrix=True, output_matrix=True) ``` ### Response #### Success Response (None) This function does not return any value. ``` -------------------------------- ### Generate Gaussian Input File Content Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Writes Gaussian input parameters, including checkpoint paths, memory, and calculation methods, to a file. It handles the structure of the input file by appending coordinates and defining link sections for multi-step calculations. ```python f.write(f'%Chk={self._base_path}.chk') f.write('\n') f.write(f'%NProcShared={nprocshared}') f.write('\n') f.write(f'%Mem={mem}{unit}\n') f.write(f'# {function}\n') f.write('# Symmetry=None\n') f.write('\n') f.write(f'{self._base_path}.gjf created by tcal\n') f.write('\n') f.write('0 1\n') for coordinate in coordinates: f.write(coordinate) f.write('\n') f.write('--Link1--\n') ``` -------------------------------- ### POST /read_dimer Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Extracts overlap and fock matrix data from a dimer log file. ```APIDOC ## POST /read_dimer ### Description Reads a dimer log file to extract overlap and fock matrices. ### Method POST ### Parameters #### Request Body - **is_matrix** (bool) - Optional - If True, prints matrices to console. - **output_matrix** (bool) - Optional - If True, outputs matrices to CSV files. ### Response #### Success Response (200) - **status** (string) - Confirmation of successful extraction. ``` -------------------------------- ### Read Dimer Matrices (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Extracts overlap and Fock matrices from a dimer log file. It parses the log to determine the number of basis functions and electrons, then reads the symmetric overlap and Fock matrices. Optionally prints these matrices or outputs them to CSV files. It also adjusts MO coefficients for dimer calculations. ```python def read_dimer( self, is_matrix: bool = False, output_matrix: bool = False ) -> None: """Extract overlap and fock matrix from log file of dimer. Parameters ---------- is_matrix : bool If it is True, print overlap and fock matrix., default False output_matrix : bool If it is True, Output overlap and fock matrix., default False """ print(f'reading {self._base_path}{self.extension_log}') with open(f'{self._base_path}{self.extension_log}', 'r', encoding='utf-8') as f: f = self.check_normal_termination(f) while True: line = f.readline() if not line: break if self.n_basis_d is None: self.n_basis_d = self.extract_num('[0-9]+ basis functions', line) if self.n_elect_d is None: self.n_elect_d = self.extract_num('[0-9]+ beta electrons', line) if '*** Overlap ***' in line: self.overlap = self.read_symmetric_matrix(f, self.n_basis_d) if 'Fock matrix (alpha):' in line: self.fock = self.read_symmetric_matrix(f, self.n_basis_d) if 'Gross orbital populations:' in line: self._read_gross_orb_populations(f) break zeros_matrix = np.zeros((self.n_bsuse1, self.n_basis2)) self.mo1 = np.hstack([self.mo1.T, zeros_matrix]) zeros_matrix = np.zeros((self.n_bsuse2, self.n_basis1)) self.mo2 = np.hstack([zeros_matrix, self.mo2.T]) if is_matrix: print() print(' *** Overlap *** ') self.print_matrix(self.overlap) print() print(' *** Fock matrix (alpha) *** ') self.print_matrix(self.fock) if output_matrix: self.output_csv(f'{self._base_path}_overlap.csv', self.overlap) self.output_csv(f'{self._base_path}_fock.csv', self.fock) ``` -------------------------------- ### Print Atomic Pair Transfer Analysis (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Creates and prints a list of atomic pair transfer analysis results. It takes a numpy array of transfer data and an optional message string as input. Returns the numpy array. ```python from tcal import Tcal import numpy as np # Example usage: # transfer_data = np.array([...]) # Result from custom_atomic_pair_transfer_analysis # Tcal.print_apta(transfer_data, message='My Analysis') ``` -------------------------------- ### Print Transfer Integrals (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Prints transfer integrals for specific orbitals: NLUMO, LUMO, HOMO, and NHOMO. This function provides a quick way to view key transfer integral values. ```python print_transfer_integrals() -> None ``` -------------------------------- ### Atomic Pair Transfer Analysis Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Functions related to calculating and analyzing atomic pair transfer integrals. ```APIDOC ## custom_atomic_pair_transfer_analysis(_analyze_orb1: int, _analyze_orb2: int, _output_apta: bool = False_) ### Description Calculates atomic pair transfer integrals. ### Method Not applicable (function call) ### Endpoint Not applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None * **analyze_orb1** (int) - Required - Analyze orbital. * **analyze_orb2** (int) - Required - Analyze orbital. * **output_apta** (bool) - Optional - If it is True, output csv file of atomic pair transfer integrals. ### Request Example ```python result = Tcal.custom_atomic_pair_transfer_analysis(analyze_orb1=1, analyze_orb2=2, output_apta=True) ``` ### Response #### Success Response (numpy.array) - **result** (numpy.array) - The array of atomic pair transfer analysis. #### Response Example ```json { "result": [ [0.1, 0.2], [0.3, 0.4] ] } ``` ## print_apta(_a_transfer: ndarray, _message: str = 'Atomic Pair Transfer Analysis'_) ### Description Creates a list of atomic pair transfer integrals (APTA) and prints it. ### Method Not applicable (function call) ### Endpoint Not applicable ### Parameters * **a_transfer** (numpy.array) - Required - Result of atomic pair transfer analysis. * **message** (str) - Optional - Message to print. ### Request Example ```python formatted_apta = Tcal.print_apta(a_transfer=result, message="My APTA Results") ``` ### Response #### Success Response (numpy.array) - **formatted_apta** (numpy.array) - The array of atomic pair transfer analysis. #### Response Example ```json { "formatted_apta": [ [0.1, 0.2], [0.3, 0.4] ] } ``` ``` -------------------------------- ### Print Transfer Integral Matrix for Different Levels Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Generates a matrix of transfer integrals across a specified range of orbitals for two monomers. It supports optional CSV output of the resulting matrix. ```python def print_transfer_integral_diff_levels(self, nlevel: int, output_ti_diff_levels: bool = False) -> None: if nlevel == 0: start1, start2, end1, end2 = 0, 0, len(self.mo1), len(self.mo2) else: start1, start2 = max(0, self.n_elect1 - nlevel), max(0, self.n_elect2 - nlevel) end1, end2 = min(len(self.mo1), self.n_elect1 + nlevel), min(len(self.mo2), self.n_elect2 + nlevel) ti_diff_levels = [] # ... (matrix construction logic) ... for i in range(start1, end1): tmp_list = [f'{i+1}'] for j in range(start2, end2): transfer = self.cal_transfer_integrals(self.mo1[i], self.overlap, self.fock, self.mo2[j]) tmp_list.append(f'{transfer:.3f}') ti_diff_levels.append(tmp_list) self.print_matrix(ti_diff_levels) if output_ti_diff_levels: self.output_csv(f'{self._base_path}_ti_diff_levels.csv', ti_diff_levels) ``` -------------------------------- ### Execute Gaussian Calculations with Subprocess Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Executes external Gaussian commands using the subprocess module. It captures output, handles return codes, and prints status messages upon completion or failure. ```python def _execute(self, command_list: List[str], complete_message: str = 'Calculation completed') -> subprocess.CompletedProcess: command = ' '.join(command_list) print(f'> {command}') res = subprocess.run(command_list, capture_output=True, text=True) if res.returncode: print(f'Failed to execute {command}') else: print(complete_message) return res ``` -------------------------------- ### Transfer Integral Functions Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Functions for printing and managing transfer integrals. ```APIDOC ## print_transfer_integral_diff_levels(_nlevel: int, _output_ti_diff_levels: bool = False_) ### Description Prints transfer integrals between different orbitals. ### Method Not applicable (function call) ### Endpoint Not applicable ### Parameters * **nlevel** (int) - Required - The number of levels to print. * **output_ti_diff_levels** (bool) - Optional - If True, outputs a CSV file of transfer integrals between different orbitals. ### Request Example ```python Tcal.print_transfer_integral_diff_levels(nlevel=5, output_ti_diff_levels=True) ``` ### Response #### Success Response (None) This function does not return any value. ## print_transfer_integrals() ### Description Prints transfer integrals of NLUMO, LUMO, HOMO, and NHOMO. ### Method Not applicable (function call) ### Endpoint Not applicable ### Parameters None ### Request Example ```python Tcal.print_transfer_integrals() ``` ### Response #### Success Response (None) This function does not return any value. ``` -------------------------------- ### Extract Dimer Overlap and Fock Matrices Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal_pyscf.html Retrieves the overlap and Fock matrices from a dimer calculation checkpoint file. It initializes the dimer-specific basis set properties and AO labels. ```python def read_dimer(self, is_matrix: bool = False, output_matrix: bool = False) -> None: print(f'reading {self._base_path}.chk') mol, fock = self._load_from_chk_dimer( chkfile=f'{self._base_path}.chk', mf=self._mf_d, ) self.n_basis_d = mol.nao_nr() self.n_elect_d = mol.nelectron // 2 self.overlap = mol.intor('int1e_ovlp') self.fock = fock self._build_ao_labels(mol) ``` -------------------------------- ### Print Atomic Pair Transfer Analysis (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/tcal.html Creates and prints a list of atomic pair transfer analysis results. It takes the analysis result array and an optional message string as input. The function returns the input array. ```python print_apta(_a_transfer: ndarray[Any, dtype[float64]], _message: str = 'Atomic Pair Transfer Analysis') -> ndarray[Any, dtype[float64]] ``` -------------------------------- ### Execute Gaussian Calculation (Python) Source: https://github.com/matsui-lab-yamagata/tcal/blob/main/docs/_modules/tcal/tcal.html Executes Gaussian calculations using a specified command. It allows skipping calculations for the first monomer, second monomer, or dimer based on the `skip_monomer_num` list. Returns the return code of the subprocess execution. ```python def run_gaussian( self, gaussian_command: str, skip_monomer_num: List[int] = [0] ) -> int: """Execute gjf files using gaussian. Parameters ---------- gaussian_command : str Command of gaussian. skip_monomer_num: list[int] If it is 1, skip 1st monomer calculation. If it is 2, skip 2nd monomer calculation. If it is 3, skip dimer calculation. Returns ------- int Returncode of subprocess.run. """ if 1 in skip_monomer_num: print('skip 1st monomer calculation') ```