diff --git a/docs/_build/doctrees/analysis/analysis.doctree b/docs/_build/doctrees/analysis/analysis.doctree new file mode 100644 index 00000000..d9ecfcde Binary files /dev/null and b/docs/_build/doctrees/analysis/analysis.doctree differ diff --git a/docs/_build/doctrees/analysis/transition_state_analysis.doctree b/docs/_build/doctrees/analysis/transition_state_analysis.doctree new file mode 100644 index 00000000..c9ba2157 Binary files /dev/null and b/docs/_build/doctrees/analysis/transition_state_analysis.doctree differ diff --git a/docs/_build/doctrees/analysis/vdd_charge_analysis.doctree b/docs/_build/doctrees/analysis/vdd_charge_analysis.doctree new file mode 100644 index 00000000..c739f62c Binary files /dev/null and b/docs/_build/doctrees/analysis/vdd_charge_analysis.doctree differ diff --git a/docs/_build/doctrees/api/modules.doctree b/docs/_build/doctrees/api/modules.doctree new file mode 100644 index 00000000..4f8a55fe Binary files /dev/null and b/docs/_build/doctrees/api/modules.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.analysis.doctree b/docs/_build/doctrees/api/tcutility.analysis.doctree new file mode 100644 index 00000000..a195191a Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.analysis.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.analysis.vdd.doctree b/docs/_build/doctrees/api/tcutility.analysis.vdd.doctree new file mode 100644 index 00000000..fe3e698a Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.analysis.vdd.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.analysis.vibration.doctree b/docs/_build/doctrees/api/tcutility.analysis.vibration.doctree new file mode 100644 index 00000000..233c0c47 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.analysis.vibration.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.data.doctree b/docs/_build/doctrees/api/tcutility.data.doctree new file mode 100644 index 00000000..7805c3a9 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.data.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.doctree b/docs/_build/doctrees/api/tcutility.doctree new file mode 100644 index 00000000..e426854f Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.job.doctree b/docs/_build/doctrees/api/tcutility.job.doctree new file mode 100644 index 00000000..6f84f672 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.job.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.job.postscripts.doctree b/docs/_build/doctrees/api/tcutility.job.postscripts.doctree new file mode 100644 index 00000000..eb48ec62 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.job.postscripts.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.report.doctree b/docs/_build/doctrees/api/tcutility.report.doctree new file mode 100644 index 00000000..e5956327 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.report.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.results.doctree b/docs/_build/doctrees/api/tcutility.results.doctree new file mode 100644 index 00000000..52366107 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.results.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.tc_typing.doctree b/docs/_build/doctrees/api/tcutility.tc_typing.doctree new file mode 100644 index 00000000..7592d507 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.tc_typing.doctree differ diff --git a/docs/_build/doctrees/api/tcutility.typing.doctree b/docs/_build/doctrees/api/tcutility.typing.doctree new file mode 100644 index 00000000..4fbc8164 Binary files /dev/null and b/docs/_build/doctrees/api/tcutility.typing.doctree differ diff --git a/docs/_build/doctrees/cli_scripts/main.doctree b/docs/_build/doctrees/cli_scripts/main.doctree new file mode 100644 index 00000000..009144a2 Binary files /dev/null and b/docs/_build/doctrees/cli_scripts/main.doctree differ diff --git a/docs/_build/doctrees/environment.pickle b/docs/_build/doctrees/environment.pickle new file mode 100644 index 00000000..87d3f81e Binary files /dev/null and b/docs/_build/doctrees/environment.pickle differ diff --git a/docs/_build/doctrees/index.doctree b/docs/_build/doctrees/index.doctree new file mode 100644 index 00000000..e24ca2cd Binary files /dev/null and b/docs/_build/doctrees/index.doctree differ diff --git a/docs/_build/doctrees/results/results.doctree b/docs/_build/doctrees/results/results.doctree new file mode 100644 index 00000000..234a67f0 Binary files /dev/null and b/docs/_build/doctrees/results/results.doctree differ diff --git a/docs/_build/doctrees/tcutility.job.doctree b/docs/_build/doctrees/tcutility.job.doctree new file mode 100644 index 00000000..72774406 Binary files /dev/null and b/docs/_build/doctrees/tcutility.job.doctree differ diff --git a/docs/_build/html/.buildinfo b/docs/_build/html/.buildinfo new file mode 100644 index 00000000..509ef0df --- /dev/null +++ b/docs/_build/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 9e747c02196262440d033b6da27cdc10 +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/_build/html/_downloads/1a62c028c9da69253548783ae8a76070/water_dimer.xyz b/docs/_build/html/_downloads/1a62c028c9da69253548783ae8a76070/water_dimer.xyz new file mode 100644 index 00000000..82bf70ee --- /dev/null +++ b/docs/_build/html/_downloads/1a62c028c9da69253548783ae8a76070/water_dimer.xyz @@ -0,0 +1,8 @@ +6 + +O -1.61075942 0.14972207 0.00000000 +O 1.27324620 -0.14984188 0.00000000 +H -2.05173067 -0.71502154 0.00000000 +H -0.65160034 -0.06225163 0.00000000 +H 1.52042212 0.38869649 -0.77034720 +H 1.52042212 0.38869649 0.77034720 diff --git a/docs/_build/html/_downloads/2a505c3581f7da7bf9082296ef7cb96f/frag_NH3BH3.py b/docs/_build/html/_downloads/2a505c3581f7da7bf9082296ef7cb96f/frag_NH3BH3.py new file mode 100644 index 00000000..f18bf044 --- /dev/null +++ b/docs/_build/html/_downloads/2a505c3581f7da7bf9082296ef7cb96f/frag_NH3BH3.py @@ -0,0 +1,13 @@ +from tcutility.job import ADFFragmentJob +from tcutility import molecule + +# load a molecule +mol = molecule.load('NH3BH3.xyz') + +# define a new job using the Job context-manager +with ADFFragmentJob() as job: + # add the molecule + job.molecule(mol) + # add the fragments. The fragment atoms are defined in the input xyz file + for fragment_name, fragment in molecule.guess_fragments(mol).items(): + job.add_fragment(fragment, fragment_name) diff --git a/docs/_build/html/_downloads/4d6b7e579d62ed9e5d25258a67fecb73/NH3BH3.xyz b/docs/_build/html/_downloads/4d6b7e579d62ed9e5d25258a67fecb73/NH3BH3.xyz new file mode 100644 index 00000000..86aa7d08 --- /dev/null +++ b/docs/_build/html/_downloads/4d6b7e579d62ed9e5d25258a67fecb73/NH3BH3.xyz @@ -0,0 +1,10 @@ +8 + +N 0.00000000 0.00000000 -0.81474153 frag=Donor +B -0.00000000 -0.00000000 0.83567034 frag=Acceptor +H 0.47608351 -0.82460084 -1.14410295 frag=Donor +H 0.47608351 0.82460084 -1.14410295 frag=Donor +H -0.95216703 0.00000000 -1.14410295 frag=Donor +H -0.58149793 1.00718395 1.13712667 frag=Acceptor +H -0.58149793 -1.00718395 1.13712667 frag=Acceptor +H 1.16299585 -0.00000000 1.13712667 frag=Acceptor diff --git a/docs/_build/html/_downloads/d1984d07233b61c9fa5986aed5cd64fb/GO_water_dimer.py b/docs/_build/html/_downloads/d1984d07233b61c9fa5986aed5cd64fb/GO_water_dimer.py new file mode 100644 index 00000000..3d3a7f16 --- /dev/null +++ b/docs/_build/html/_downloads/d1984d07233b61c9fa5986aed5cd64fb/GO_water_dimer.py @@ -0,0 +1,49 @@ +import pathlib as pl + +from scm.plams import AMSJob, Molecule, Settings, config, finish, init +from tcutility.job import ADFJob + +current_file_path = pl.Path(__file__).parent +mol_path = current_file_path / "water_dimer.xyz" + + +def try_plams_job(mol: Molecule) -> None: + # Test case with plams for checking if plams works solely on Windows + run_set = Settings() + run_set.input.ams.Task = "GeometryOptimization" + run_set.input.adf.Basis.Type = "DZP" + run_set.input.adf.XC.GGA = "BP86" + + config.log.file = 7 + config.log.stdout = 7 + + init(path=str(current_file_path), folder="GO_water_dimer", config_settings=config) + AMSJob(molecule=mol, name="water_dimer", settings=run_set).run() + finish() + + +def try_tcutility_job(mol: Molecule) -> None: + # Test case with tcutility for checking if tcutility works solely on Windows + with ADFJob(use_slurm=False) as job: + job.molecule(mol) + job.rundir = str(current_file_path / "calculations") + job.name = "GO_water_dimer" + job.functional("BP86-D3(BJ)") + job.basis_set("TZ2P") + job.quality("Good") + job.optimization() + + +def main(): + current_file_path = pl.Path(__file__).parent + mol_path = current_file_path / "water_dimer.xyz" + + mol = Molecule(str(mol_path)) + + # Use these functions to test if a plams and tcutility job can be run on Windows, Mac, and Linux. Both do not use slurm. + try_plams_job(mol) + try_tcutility_job(mol) + + +if __name__ == "__main__": + main() diff --git a/docs/_build/html/_modules/index.html b/docs/_build/html/_modules/index.html new file mode 100644 index 00000000..c1188207 --- /dev/null +++ b/docs/_build/html/_modules/index.html @@ -0,0 +1,362 @@ + + + + + + + + + + Overview: module code — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + + + + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility.html b/docs/_build/html/_modules/tcutility.html new file mode 100644 index 00000000..88956906 --- /dev/null +++ b/docs/_build/html/_modules/tcutility.html @@ -0,0 +1,348 @@ + + + + + + + + + + tcutility — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility

+ensure_list = lambda x: [x] if not isinstance(x, (list, tuple, set)) else list(x)  # noqa: E731
+squeeze_list = lambda x: x[0] if len(x) == 1 else x  # noqa: E731
+
+
+
+[docs] +def ensure_2d(x, transposed=False): + x = ensure_list(x) + if transposed: + if not isinstance(x[0], (list, tuple, set)): + x = [ensure_list(x)] + else: + x = [ensure_list(y) for y in x] + else: + x = [ensure_list(y) for y in x] + return x
+ + + +from tcutility import constants, formula, geometry, log, molecule, results, slurm, data, analysis, report, pathfunc # noqa: F401, E402 +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/analysis/vdd/charge.html b/docs/_build/html/_modules/tcutility/analysis/vdd/charge.html new file mode 100644 index 00000000..5eca94d5 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/analysis/vdd/charge.html @@ -0,0 +1,349 @@ + + + + + + + + + + tcutility.analysis.vdd.charge — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.analysis.vdd.charge

+import attrs
+
+
+
+[docs] +@attrs.define +class VDDCharge: + atom_index: int # index of the atom in the molecules + atom_symbol: str # symbol of the atom + charge: float # mili-electrons + frag_index: int # index of the fragment in the fragments list + +
+[docs] + def change_unit(self, ratio: float): + self.charge *= ratio
+
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/analysis/vdd/manager.html b/docs/_build/html/_modules/tcutility/analysis/vdd/manager.html new file mode 100644 index 00000000..2f4726ea --- /dev/null +++ b/docs/_build/html/_modules/tcutility/analysis/vdd/manager.html @@ -0,0 +1,601 @@ + + + + + + + + + + tcutility.analysis.vdd.manager — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.analysis.vdd.manager

+from __future__ import annotations
+
+import copy
+import functools
+import pathlib as pl
+from itertools import zip_longest
+from typing import Dict, List, Optional, Sequence, Union
+
+import attrs
+import matplotlib.pyplot as plt
+import numpy as np
+import pandas as pd
+
+import tcutility.log as log
+from tcutility.analysis.vdd import charge
+from tcutility.constants import VDD_UNITS
+from tcutility.results import result
+
+PRINT_FORMAT = {"me": "%+.0f", "e": "%+.3f"}
+
+
+
+[docs] +def change_unit_decorator(func): + @functools.wraps(func) + def wrapper(self, unit: str = "me", *args, **kwargs): + current_unit = self.unit + self.change_unit(unit) + result = func(self, *args, **kwargs) + self.change_unit(current_unit) + return result + + return wrapper
+ + + +
+[docs] +def create_vdd_charge_manager(results: result.Result) -> VDDChargeManager: + """Create a VDDChargeManager from a Result object.""" + vdd_charges: Dict[str, List[charge.VDDCharge]] = {} + atom_symbols = results.molecule.atom_symbols # type: ignore + frag_indices = results.molecule.frag_indices # type: ignore + calc_dir = pl.Path(results.files["root"]) # type: ignore + is_fragment_calculation = results.adf.used_regions # type: ignore + mol_charge = results.molecule.mol_charge # type: ignore + + # Convert the VDD charges to VDDCharge objects + for irrep, charge_array in results.properties.vdd.items(): # type: ignore + irrep = "vdd" if irrep == "charges" else irrep + vdd_charges[irrep] = [] + for atom_index, (frag_index, vdd_charge) in enumerate(zip(frag_indices, charge_array)): + atom_symbol = atom_symbols[atom_index] + vdd_charges[irrep].append(charge.VDDCharge(atom_index + 1, atom_symbol, vdd_charge, frag_index)) + + return VDDChargeManager(vdd_charges, is_fragment_calculation, calc_dir, mol_charge)
+ + + +
+[docs] +@attrs.define +class VDDChargeManager: + """Class to manage the VDD charges. It can be used to print the VDD charges in a nice table and write them to a text file or excel file.""" + + vdd_charges: Dict[str, List[charge.VDDCharge]] # {"vdd": [VDDCharge, ...], "irrep1": [VDDCharge, ...], ...} + is_fragment_calculation: bool + calc_dir: pl.Path + mol_charge: int + name: str = attrs.field(init=False) + unit: str = attrs.field(init=False, default="e") # unit of the VDD charges. Available units are "me" (mili-electrons) and "e" (electrons) + irreps: List[str] = attrs.field(init=False, default=set()) + + def __attrs_post_init__(self): + self.irreps = list(self.vdd_charges.keys()) + self.name = self.calc_dir.name if self.calc_dir is not None else self.name + self.change_unit("me") + log.info(f"VDDChargeManager created for {self.name}") + + def __str__(self) -> str: + """Prints the VDD charges in a nice table. Checks if the calculation is a fragment calculation and prints the summed VDD charges if it is.""" + individual_charges_table = self.get_vdd_charges_table() + summed_charges_table = self.get_summed_vdd_charges_table() + + ret_str = f"{self.name}\nVDD charges (in unit {self.unit}):\n{individual_charges_table}\n\n" + if self.is_fragment_calculation: + ret_str += f"Summed VDD charges (in unit {self.unit}):\n{summed_charges_table}\n" + + return ret_str + +
+[docs] + def charge_is_conserved(self) -> bool: + """Check if the total charge of the molecule is conserved. The total charge is the sum of the VDD charges.""" + tolerance = 1e-4 if self.unit == "e" else 1e-1 + is_conserved = np.isclose(self.mol_charge, sum([charge.charge for charge in self.vdd_charges["vdd"]]), atol=tolerance) + return is_conserved # type: ignore since numpy _bool is not recognized as bool
+ + +
+[docs] + def change_unit(self, new_unit: str) -> None: + """Change the unit of the VDD charges. Available units are "me" (mili-electrons) and "e" (electrons).""" + if new_unit not in VDD_UNITS: + raise ValueError(f"Unit {new_unit} is not available. Choose from {VDD_UNITS.keys()}") + + if new_unit == self.unit: + return + + ratio = VDD_UNITS[new_unit] / VDD_UNITS[self.unit] + [charge.change_unit(ratio) for charges in self.vdd_charges.values() for charge in charges] + self.unit = new_unit
+ + +
+[docs] + @change_unit_decorator + def get_vdd_charges(self) -> Dict[str, List[charge.VDDCharge]]: + """Get the VDD charges in the specified unit ([me] or [e]).""" + return copy.deepcopy(self.vdd_charges)
+ + +
+[docs] + @change_unit_decorator + def get_summed_vdd_charges(self, irreps: Optional[Sequence[str]] = None) -> Dict[str, Dict[str, float]]: + """Get the summed VDD charges per fragment for the specified unit ([me] or [e]).""" + irreps = irreps if irreps is not None else self.irreps + summed_vdd_charges: Dict[str, Dict[str, float]] = {} + + for irrep in irreps: + summed_vdd_charges[irrep] = {} + for vdd_charge in self.vdd_charges[irrep]: + frag_index = str(vdd_charge.frag_index) + summed_vdd_charges[irrep].setdefault(frag_index, 0.0) + summed_vdd_charges[irrep][frag_index] += vdd_charge.charge + + return copy.deepcopy(summed_vdd_charges)
+ + +
+[docs] + def get_vdd_charges_dataframe(self) -> pd.DataFrame: + """Get the VDD charges as a pandas DataFrame in a specified unit ([me] or [e]).""" + frag_indices = [charge.frag_index for charge in self.vdd_charges["vdd"]] + atom_symbols = [f"{charge.atom_index}{charge.atom_symbol}" for charge in self.vdd_charges["vdd"]] + charges = [[charge.charge for charge in charges] for _, charges in self.vdd_charges.items()] + headers = ["Frag", "Atom"] + [irrep for irrep, _ in self.vdd_charges.items()] + combined_table = list(zip_longest(frag_indices, atom_symbols, *charges, fillvalue="")) + df = pd.DataFrame(combined_table, columns=headers).rename(columns={"vdd": "Total"}) + return df
+ + +
+[docs] + def get_summed_vdd_charges_dataframe(self) -> pd.DataFrame: + """Get the summed VDD charges as a pandas DataFrame in a specified unit ([me] or [e]).""" + summed_data = self.get_summed_vdd_charges() + summed_data["Frag"] = {str(key): int(key) for key in summed_data["vdd"].keys()} + df = pd.DataFrame(summed_data).pipe(lambda df: df[df.columns.tolist()[-1:] + df.columns.tolist()[:-1]]) # move the "Frag" column to the front + return df.rename(columns={"vdd": "Total"})
+ + +
+[docs] + def get_vdd_charges_table(self) -> str: + df = self.get_vdd_charges_dataframe() + return df.to_string(float_format=lambda x: PRINT_FORMAT[self.unit] % x, justify="center", index=False, col_space=6)
+ + +
+[docs] + def get_summed_vdd_charges_table(self) -> str: + df = self.get_summed_vdd_charges_dataframe() + return df.to_string(float_format=lambda x: PRINT_FORMAT[self.unit] % x, justify="center", col_space=6, index=False)
+ + +
+[docs] + @staticmethod + def write_to_txt(output_dir: Union[str, pl.Path], managers: Union[VDDChargeManager, Sequence[VDDChargeManager]], unit: str = "me") -> None: + """Write the VDD charges to a text file. It is a static method because multiple managers can be written to the same file.""" + out_dir = pl.Path(output_dir) if not isinstance(output_dir, pl.Path) else output_dir + files = [out_dir / "VDD_charges_per_atom.txt", out_dir / "VDD_charges_per_fragment.txt"] + managers = managers if isinstance(managers, Sequence) else [managers] + + # Print charges per atom and per fragment in seperate files + for i, file in enumerate(files): + with open(file, "w") as f: + f.write("VDD charges:\n") + for manager in managers: + f.write(f"{manager.name} (unit = {manager.unit})\n") + if i == 0: + f.write(manager.get_vdd_charges_table()) + else: + f.write(manager.get_summed_vdd_charges_table()) if manager.is_fragment_calculation else f.write("No fragment calculation\n") + f.write("\n\n")
+ + +
+[docs] + def write_to_excel(self, output_file: Optional[Union[str, pl.Path]] = None) -> None: + """Write the VDD charges to an excel file. Results are written to two sheets: "VDD charges" and "Summed VDD charges".""" + file = pl.Path(output_file) if output_file is not None else self.calc_dir / f"vdd_charges_{self.name}.xlsx" + file = file.with_suffix(".xlsx") if not file.suffix == ".xlsx" else file + + df = self.get_vdd_charges_dataframe() + + with pd.ExcelWriter(file) as writer: + df.to_excel(writer, sheet_name=f"VDD charges (in {self.unit})", index=False, float_format=PRINT_FORMAT[self.unit]) + if self.is_fragment_calculation: + df_summed = self.get_summed_vdd_charges_dataframe() + df_summed.to_excel(writer, sheet_name=f"Summed VDD charges (in {self.unit})", index=False, float_format=PRINT_FORMAT[self.unit])
+ + +
+[docs] + def plot_vdd_charges_per_atom(self, output_file: Optional[Union[str, pl.Path]] = None, unit: str = "me") -> None: + """Plot the VDD charges as a bar graph for each irrep.""" + file = pl.Path(output_file) if output_file is not None else self.calc_dir / f"vdd_charges_{self.name}.png" + file = file.with_suffix(".png") if not file.suffix == ".png" else file + self.change_unit(unit) + + # Increase the global font size + plt.rcParams.update({"font.size": 14}) + + num_irreps = len(self.vdd_charges) + n_max_charges = max([len(charges) for charges in self.vdd_charges.values()]) + _, axs = plt.subplots(num_irreps, 1, figsize=(n_max_charges * 1.15, 5 * num_irreps), sharey=True) + axs = [axs] if num_irreps == 1 else axs + + # Initialize a variable to keep track of the most positive/negative values + adjusted_abs_max_values = [] + + counter = 1 + for ax, (irrep, charges) in zip(axs, self.vdd_charges.items()): + atom_symbols = [f"{charge.atom_index}{charge.atom_symbol} ({charge.frag_index})" for charge in charges] + charge_values = [charge.charge for charge in charges] + + bars = ax.bar(atom_symbols, charge_values, color="sandybrown", edgecolor="black") + if counter == len(axs): + ax.set_xlabel("Atom (#Fragment Number)") + ax.set_ylabel(f"Charge ({unit})") + ax.set_title(f"VDD Charges {self.name} - {irrep}") + ax.yaxis.grid(True) # Only display vertical grid lines + + # Add the charge value on top of each bar. If the value is negative, place the text below the bar + for bar in bars: + yval = bar.get_height() + x_pos = bar.get_x() + bar.get_width() / 2 + + if yval <= 0: + ax.text(x_pos, yval + yval * 0.1, int(yval), va="top", ha="center") + else: + ax.text(x_pos, yval + yval * 0.1, int(yval), va="bottom", ha="center") + adjusted_abs_max_values.append(yval + yval * 0.1) + counter += 1 + + # Making sure the values do not extend outside the plot. Also determines the y-axis limits for all subplotss + min_value, max_value = min(adjusted_abs_max_values), max(adjusted_abs_max_values) + + # Axes adjustments + # Set the y-axis limits for all subplots based on the most positive/negative values + for ax in axs: + ax.set_ylim([min_value - abs(min_value) * 0.2, max_value + abs(max_value) * 0.2]) + + # plt.tight_layout() + plt.savefig(file, dpi=300)
+
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/analysis/vibration/ts_vibration.html b/docs/_build/html/_modules/tcutility/analysis/vibration/ts_vibration.html new file mode 100644 index 00000000..c2f40c29 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/analysis/vibration/ts_vibration.html @@ -0,0 +1,484 @@ + + + + + + + + + + tcutility.analysis.vibration.ts_vibration — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.analysis.vibration.ts_vibration

+import numpy as np
+import warnings
+from tcutility import results
+from scm import plams
+
+
+
+[docs] +def avg_relative_bond_length_delta(base: plams.Molecule, pos: plams.Molecule, neg: plams.Molecule, atom1: int, atom2: int) -> float: + """Function to calculate relative atom distance change in vibrational mode + + Args: + base: plams.Molecule object containing the coordinates before applying vibration + pos: plams.Molecule object with the vibrational mode added + neg: plams.Molecule object with the vibrational mode subtracted + atom1: label for the first atom + atom2: label for the second atom + + Returns: + Average relative difference from the baseline distance between selected atoms in this vibrational mode (as percentage). + """ + basedist = base[atom1].distance_to(base[atom2]) + x = abs((pos[atom1].distance_to(pos[atom2]) / basedist) - 1) # distances between positive and negative vibration are normalized with base distance + y = abs((neg[atom1].distance_to(neg[atom2]) / basedist) - 1) # variances are obtained and averaged + return (x + y) / 2
+ + + +
+[docs] +def determine_ts_reactioncoordinate(data: results.Result, mode_index: int = 0, bond_tolerance: float = 1.28, min_delta_dist: float = 0.0) -> np.ndarray: + """Function to retrieve reaction coordinate from a given transitionstate, using the first imaginary frequency. + + Args: + data: TCutility.results.Result object containing calculation data + mode_index: vibrational mode index to analyze + bond_tolerance: parameter for plams.Molecule.guess_bonds() function + min_delta_dist: minimum relative bond length change before qualifying as active atom. If 0, all bond changes are counted + + Returns: + Array containing all the obtained reaction coordinates. Reaction coordinate format is [active_atom1, active_atom2, sign], using Distance reactioncoordinate + Symmetry elements are ignored, by convention the atom labels are increasing (atom1 < atom2) + """ + + assert "modes" in data.properties.vibrations, "Vibrational data is required, but was not present in .rkf file" + + outputmol = data.molecule.output + + base = np.array(outputmol).reshape(-1, 3) + tsimode = np.array(data.properties.vibrations.modes[mode_index]).reshape(-1, 3) + + posvib = outputmol.copy() + posvib.from_array(base + tsimode) + posvib.guess_bonds(dmax=bond_tolerance) + negvib = outputmol.copy() + negvib.from_array(base - tsimode) + negvib.guess_bonds(dmax=bond_tolerance) + + pairs = np.where(posvib.bond_matrix() - negvib.bond_matrix()) + rc = np.array( + [ + [a + 1, b + 1, np.sign(posvib.bond_matrix()[a][b] - negvib.bond_matrix()[a][b])] + for a, b in np.c_[pairs[0], pairs[1]] # bond matrices and pairs matrix are 0-indexed unlike the plams.Molecule labels, hence a+1 and b+1 are needed + if a < b and avg_relative_bond_length_delta(outputmol, posvib, negvib, a + 1, b + 1) > min_delta_dist + ], + dtype=int, + ) + return rc
+ + + +
+[docs] +def validate_transitionstate(calc_dir: str, rcatoms: list = None, analyze_modes: int = 1, **kwargs) -> bool: + """Function to determine whether a transition state calculation yielded the expected transition state. Checks the reaction coordinates provided by the user (or in the .rkf file User Input section) and compares + this against the reaction coordinates found in the imaginary modes of the transitionstate. If the transitionstate has multiple imaginary frequencies, it is possible to check multiple modes for the expected + reaction coordinate. + + Args: + calc_dir: path pointing to the desired calculation. + rcatoms: list or array containing expected reaction coordinates, to check against the transition state. If not defined, it is obtained from the ams.rkf user input. + Only uses 'Distance' reaction coordinate. Format should be [atomlabel1, atomlabel2, (optional) sign] + analyze_modes: Number of imaginary modes to analyze, default only the first mode. Modes are ordered lowest frequency first. If 0 or negative value is provided, analyze all modes with imaginary frequency. + **kwargs: keyword arguments for use in :func:`determine_ts_reactioncoordinate`. + + Returns: + Boolean value, True if the found transition state reaction coordinates contain the expected reaction coordinates, False otherwise. + If multiple modes are analyzed, returns True if at least one mode contains the expected reaction coordinates. + """ + + data = results.read(calc_dir) + assert "modes" in data.properties.vibrations, "Vibrational data is required, but was not present in .rkf file" + + nimag = sum(1 for x in data.properties.vibrations.frequencies if x < 0) + if nimag == 0: + return False # no imaginary modes found in transitionstate + + if analyze_modes > 0: # if positive value is provided, check that many imaginary vibrational modes. Otherwise all imaginary ones are analyzed + nimag = min(nimag, analyze_modes) # limit to the actual number of vibrational modes + + if isinstance(rcatoms, type(None)): + assert "reactioncoordinate" in data.input.transitionstatesearch, "Reaction coordinate is a required input, but was neither provided nor present in the .rkf file" + rcatoms = np.array([[int(float(y)) for y in x.split()[1:]] for x in data.input.transitionstatesearch.reactioncoordinate if x.split()[0] == "Distance"]) + assert len(rcatoms) > 0, "Reaction coordinate data was present in .rkf file, but no reaction coordinate using Distance was provided" + + # cast the reaction coordinate as 2d array. If reaction coordinate sign is provided, it must be provided for all reaction coordinates. + # the np.atleast_2d() function will cause a deprecation warning if the dimensions mismatch, this is raised as a value error instead + with warnings.catch_warnings(record=True) as w: + rcatoms = np.atleast_2d(rcatoms) + if len(w) > 0: + raise ValueError(w[-1].message) + + assert np.all([len(x) == 2 or len(x) == 3 for x in rcatoms]), "Invalid format of reaction coordinate. Reaction coordinate format must be [label1, label2, (optional) sign]" + + ret = [] + + for idx in range(nimag): + result = determine_ts_reactioncoordinate(data, mode_index=idx, **kwargs) + if len(result) == 0: + ret.append(False) + continue + + # sort for consistency + for index, [a, b, *c] in enumerate(rcatoms): + if c: + c = np.sign(c) + if a > b: + a, b = b, a + rcatoms[index] = [a, b, *c] + rcatoms = rcatoms[rcatoms[:, 1].argsort()] + rcatoms = rcatoms[rcatoms[:, 0].argsort()] + result = result[result[:, 1].argsort()] + result = result[result[:, 0].argsort()] + + # (optional) check for internal consistency if the reaction coordinate sign is provided + # only the first reaction coordinate sign is arbitrary, check remaining coordinates for consistency + if len(rcatoms[0]) > 2: + foundmatch = False + for idx, rc in enumerate(result): + if rc[0] == rcatoms[0][0] and rc[1] == rcatoms[0][1]: + result[:, 2] = result[:, 2] if np.sign(result[idx][2]) == rcatoms[0][2] else -result[:, 2] + foundmatch = True + break + if not foundmatch: # at least one element of rcatoms is not present in result + ret.append(False) + continue + else: + result = result[:, :-1] + + ret.append(set(str(x) for x in rcatoms).issubset(set(str(y) for y in result))) + + return any(ret)
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/cache.html b/docs/_build/html/_modules/tcutility/cache.html new file mode 100644 index 00000000..9503e073 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/cache.html @@ -0,0 +1,508 @@ + + + + + + + + + + tcutility.cache — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.cache

+import time
+import functools
+import json
+import os
+import platformdirs
+
+
+_timed_func_cache = {}
+_time_since_cache = {}
+
+_func_cache = {}
+
+_general_cache = {}
+
+_cache_dir = platformdirs.user_cache_dir(appname='TCutility', appauthor='TheoCheM', ensure_exists=True)
+
+
+[docs] +def timed_cache(delay: float): + ''' + Decorator that creates a timed cache for the function or method. + This cache will expire after a chosen amount of time. + + Args: + delay: the expiry time for the function cache. + ''' + def decorator(func): + # this is the main decorator returned by timed_cache + @functools.wraps(func) + def inner_decorator(*args, **kwargs): + # we have to create a tuple of the kwargs items to ensure we can hash the arguments + arguments = args, tuple(kwargs.items()) + + # the time since the last caching + dT = time.perf_counter() - _time_since_cache[func] + # if the cache has expired, we remove it from the cache + # and set the new time_since_cache + if dT >= delay: + _timed_func_cache[func].pop(arguments, None) + _time_since_cache[func] = time.perf_counter() + + # check if the arguments were called before + if arguments in _timed_func_cache[func]: + return _timed_func_cache[func][arguments] + + # if it is not present we add it to the cache + res = func(*args, **kwargs) + _timed_func_cache[func][arguments] = res + return res + + # initialize the cache and time_since_cache + _timed_func_cache[func] = {} + _time_since_cache[func] = -delay + + return inner_decorator + return decorator
+ + + +
+[docs] +def cache(func): + ''' + Function decorator that stores results from previous calls to the function or method. + ''' + @functools.wraps(func) + def inner_decorator(*args, **kwargs): + # we have to create a tuple of the kwargs items to ensure we can hash the arguments + arguments = args, tuple(kwargs.items()) + + # check if the arguments were called before + if arguments in _func_cache[func]: + return _func_cache[func][arguments] + + # if it is not present we add it to the cache + res = func(*args, **kwargs) + _func_cache[func][arguments] = res + return res + + _func_cache[func] = {} + return inner_decorator
+ + + +def _get_from_cache_file(file, func, args, kwargs): + ''' + Retrieve results from a JSON file. Return `None` if not found. + ''' + # open the file and parse the data + with open(os.path.join(_cache_dir, file)) as cfile: + data = json.loads(cfile.read()) + + # we now go through the data + # it is formatted as a list of dicts + # each dict has the 'func', 'args', 'kwargs' and 'value' keys + for datum in data: + # func is set as the function qualname + if datum['func'] != func.__qualname__: + continue + + # args is retrieved as a list + if datum['args'] != list(args): + continue + + # kwargs is simply a dict + if datum['kwargs'] != kwargs: + continue + + # if we did not exit the loop yet we return the value + return datum['value'] + + +def _write_to_cache_file(file, func, args, kwargs, value): + ''' + Write results to the file. + ''' + # we open the file to get the data + with open(os.path.join(_cache_dir, file)) as cfile: + data = json.loads(cfile.read()) + + # add the new results to the file + new = { + 'func': func.__qualname__, + 'args': args, + 'kwargs': kwargs, + 'value': value + } + data.append(new) + + with open(os.path.join(_cache_dir, file), 'w+') as cfile: + cfile.write(json.dumps(data, indent=4)) + + +def _clear_cache_file(file): + ''' + Function that clears a file and writes a new beginning of a list. + ''' + os.makedirs(_cache_dir, exist_ok=True) + with open(os.path.join(_cache_dir, file), 'w+') as cfile: + cfile.write('[]') + + +
+[docs] +def cache_file(file): + ''' + Function decorator that stores results of a function to a file. + Because results are written to a file the values persist between Python sessions. + This is useful, for example, for online API calls. + + Args: + file: the filepath to store function call results to. + Files will be stored in the platform dependent temporary file directory. + + .. seealso:: + `platformdirs.user_cache_dir <https://platformdirs.readthedocs.io/en/latest/api.html#platformdirs.user_cache_dir>`_ for information on the temporary directory. + ''' + def decorator(func): + # make the file if it doesnt exist + if not os.path.exists(os.path.join(_cache_dir, file)): + _clear_cache_file(file) + + @functools.wraps(func) + def inner_decorator(*args, **kwargs): + # check if the arguments were called before + cached = _get_from_cache_file(file, func, args, kwargs) + if cached is not None: + return cached + + # if it is not present we add it to the cache file + res = func(*args, **kwargs) + _write_to_cache_file(file, func, args, kwargs, res) + return res + + return inner_decorator + return decorator
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/cite.html b/docs/_build/html/_modules/tcutility/cite.html new file mode 100644 index 00000000..9a539964 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/cite.html @@ -0,0 +1,535 @@ + + + + + + + + + + tcutility.cite — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.cite

+import requests
+import json
+import os
+from tcutility import spell_check, cache
+
+
+
+# @cache.cache_file('dois')
+@cache.cache
+def _get_doi_data(doi: str) -> dict:
+	'''
+	Get information about an article using the crossref.org API.
+
+	Args:
+		doi: the DOI to get information about.
+	'''
+	print(f'http://api.crossref.org/works/{doi}')
+	data = requests.get(f'http://api.crossref.org/works/{doi}').text
+	if data == 'Resource not found.':
+		raise ValueError(f'Could not find DOI {doi}.')
+	data = json.loads(data)
+	return data
+
+
+# @cache.cache_file('journal_abbrvs')
+@cache.cache
+def _get_journal_abbreviation(journal: str) -> str:
+	'''
+	Get the journal name abbreviation using the abbreviso API.
+
+	Args:
+		journal: the name of the journal to get the abbreviation of.
+	'''
+	return requests.get(f"https://abbreviso.toolforge.org/a/{journal}").text
+
+
+@cache.cache
+def _get_publisher_city(publisher: str) -> str:
+	'''
+	Get the city of a publisher.
+	'''
+	with open(os.path.join(os.path.split(__file__)[0], 'data', 'cite', '_publisher_cities.json')) as cities:
+		cities = json.loads(cities.read())
+	return cities.get(publisher)
+
+
+
+[docs] +def cite(doi: str, style: str = 'wiley', mode='html') -> str: + ''' + Format an article in a certain style. + + Args: + doi: the article DOI to generate a citation for. + style: the style formatting to use. Can be ``['wiley', 'acs', 'rsc']``. + mode: the formatting mode. Can be ``['html', 'latex', 'plain']``. + ''' + # check if the style was correctly given + spell_check.check(style, ['wiley', 'acs', 'rsc']) + spell_check.check(mode, ['html', 'latex', 'plain']) + + # get the information about the DOI + data = _get_doi_data(doi) + + if data['message']['type'] == 'journal-article': + citation = _format_article(data, style) + + if data['message']['type'] == 'book-chapter' or (data['message']['type'] == 'other' and 'ISBN' in data['message']): + citation = _format_book_chapter(data, style) + + if mode == 'plain': + citation = citation.replace('<i>', '') + citation = citation.replace('</i>', '') + citation = citation.replace('<b>', '') + citation = citation.replace('</b>', '') + + if mode == 'latex': + citation = citation.replace('<i>', r'\textit{') + citation = citation.replace('</i>', '}') + citation = citation.replace('<b>', r'\textbf{') + citation = citation.replace('</b>', '}') + + return citation
+ + + +def _format_article(data: dict, style: str) -> str: + # grab usefull data + journal = data['message']['container-title'][0] + journal_abbreviation = _get_journal_abbreviation(journal) + year = data['message']['issued']['date-parts'][0][0] + volume = data['message']['volume'] + pages = data['message'].get('page').replace('-', '–') + title = data['message']['title'][0] + doi = data['message']['DOI'] + + # Get the initials from the author given names + # also store the family names + initials = [] + last_names = [] + for author in data['message']['author']: + # we get the capital letters from the first names + # these will become the initials for this author + firsts = [char + '.' for char in author['given'].title() if char.isupper()] + firsts = " ".join(firsts) + initials.append(firsts) + last_names.append(author['family'].title()) + + # format the citation correctly + if style == 'wiley': + names = [f'{first} {last}' for first, last in zip(initials, last_names)] + citation = f'{", ".join(names)}, <i>{journal_abbreviation}</i> <b>{year}</b>, <i>{volume}</i>' + if pages: + citation += f', {pages}' + citation += '.' + + elif style == 'acs': + names = [f'{last}, {first}' for first, last in zip(initials, last_names)] + citation = f'{"; ".join(names)} {title} <i>{journal_abbreviation}</i> <b>{year}</b>, <i>{volume}</i>' + if pages: + citation += f', {pages}' + citation += f'. DOI: {doi}' + + elif style == 'rsc': + names = [f'{first} {last}' for first, last in zip(initials, last_names)] + citation = f'{", ".join(names)}, <i>{journal_abbreviation}</i> {year}, <b>{volume}</b>' + if pages: + citation += f', {pages}' + citation += '.' + + return citation + + +def _format_book_chapter(data: dict, style: str) -> str: + # grab usefull data + publisher = data['message']['publisher'] + year = data['message']['published-print']['date-parts'][0][0] + pages = data['message'].get('page') + book_title = data['message']['container-title'][0] + chapter_title = data['message']['title'][0] + city = _get_publisher_city(publisher) + + for isbn in data['message']['isbn-type']: + if isbn['type'] == 'electronic': + original_book_data = _get_doi_data(f"{data['message']['prefix']}/{isbn['value']}") + break + + # Get the initials from the author given names + # also store the family names + n_authors = len(data['message']['author']) + initials = [] + last_names = [] + for author in data['message']['author']: + # we get the capital letters from the first names + # these will become the initials for this author + firsts = [char + '.' for char in author['given'].title() if char.isupper()] + firsts = " ".join(firsts) + initials.append(firsts) + last_names.append(author['family'].title()) + + n_editors = len(original_book_data['message']['editor']) + editor_initials = [] + editor_last_names = [] + for author in original_book_data['message']['editor']: + # we get the capital letters from the first names + # these will become the initials for this author + firsts = [char + '.' for char in author['given'].title() if char.isupper()] + firsts = " ".join(firsts) + editor_initials.append(firsts) + editor_last_names.append(author['family'].title()) + + # format the citation correctly + if style == 'wiley': + names = [f'{last}, {first}' for first, last in zip(initials, last_names)] + editors = [f'{first} {last}' for first, last in zip(editor_initials, editor_last_names)] + if n_authors == 1: + names = names[0] + + if 1 < n_authors < 4: + names = ", ".join(names[:-1]) + ' and ' + names[-1] + + if n_authors >= 4: + names = ", ".join(names[:3]) + ' et al.' + + if n_editors == 1: + editors = editors[0] + + if 1 < n_editors < 4: + editors = ", ".join(editors[:-1]) + ' and ' + editors[-1] + + if n_editors >= 4: + editors = ", ".join(editors[:3]) + ' et al.' + + citation = f'{names} ({year}). {chapter_title}. In: <i>{book_title}</i> (ed. {editors}), {pages}. {city}: {publisher}' + + elif style == 'acs': + raise NotImplementedError('No support for ACS style yet') + + elif style == 'rsc': + raise NotImplementedError('No support for RSC style yet') + + return citation + + +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/data/atom.html b/docs/_build/html/_modules/tcutility/data/atom.html new file mode 100644 index 00000000..bc6ba612 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/data/atom.html @@ -0,0 +1,442 @@ + + + + + + + + + + tcutility.data.atom — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.data.atom

+import pathlib as pl
+
+
+# read data
+data_dir = pl.Path(__file__).parents[0] / "_atom_data_info"
+
+with open(data_dir / "name.txt") as data:
+    lines = data.readlines()
+_element_order = [line.split(",")[1].strip() for line in lines]
+
+with open(data_dir / "symbol.txt") as data:
+    lines = data.readlines()
+_symbol_order = [line.split(",")[1].strip() for line in lines]
+
+with open(data_dir / "radius.txt") as data:
+    lines = data.readlines()
+_radii = {int(line.split(",")[0]): float(line.split(",")[1].strip()) for line in lines}
+
+with open(data_dir / "color.txt") as data:
+    lines = data.readlines()
+_colors = {int(line.split(",")[0]): [int(x.strip()) for x in line.split(",")[1:]] for line in lines}
+
+
+
+[docs] +def parse_element(val): + """ + Parse a str or int to an atom number. + + Args: + val: Element name, symbol or atom number. + + Returns: + Atom number corresponding to val. + + Examples: + + .. code-block:: python + + parse_element('Hydrogen') == 1 + parse_element('C') == 6 + parse_element(23) == 23 + """ + # we will assume an integer value is an atom number already + if isinstance(val, int): + return val + # if it is not an int it should be a string + if val.lower() in _element_order: + # first try to get it in the element name list + return _element_order.index(val.lower()) + if val in _symbol_order: + # alternatively try to get it in the symbol list + return _symbol_order.index(val) + raise KeyError(f'Element "{val}" not parsable.')
+ + + +
+[docs] +def radius(element): + ''' + Args: + element: the symbol, name or atom number of the element. See :func:`parse_element`. + Return: + The empirical covalent radius of an element in angstroms, up to element 96. + ''' + num = parse_element(element) + return _radii.get(num)
+ + + +
+[docs] +def color(element): + ''' + Args: + element: the symbol, name or atom number of the element. See :func:`parse_element`. + + Return: + The standard CPK colors of the elements, up to element 109. + ''' + num = parse_element(element) + return _colors[num]
+ + + +
+[docs] +def atom_number(element): + return parse_element(element)
+ + + +
+[docs] +def symbol(element): + num = parse_element(element) + return _symbol_order[num]
+ + + +
+[docs] +def element(element): + num = parse_element(element) + return _element_order[num]
+ + + +if __name__ == "__main__": + print(symbol(0)) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/data/basis_sets.html b/docs/_build/html/_modules/tcutility/data/basis_sets.html new file mode 100644 index 00000000..9e256fd4 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/data/basis_sets.html @@ -0,0 +1,422 @@ + + + + + + + + + + tcutility.data.basis_sets — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.data.basis_sets

+import json
+import pathlib as pl
+from tcutility import data
+
+
+available_basis_sets = { 
+'ADF': [
+	'SZ',
+	'DZ',
+	'DZP',
+	'TZP',
+	'TZ2P',
+	'QZ4P',
+	'mTZ2P',
+	'AUG/ASZ',
+	'AUG/ADZ',
+	'AUG/ADZP',
+	'AUG/ATZP',
+	'AUG/ATZ2P',
+	'Corr/TZ3P',
+	'Corr/QZ6P',
+	'Corr/ATZ3P',
+	'Corr/AQZ6P',
+	'ET/ET-pVQZ',
+	'ET/ET-QZ3P',
+	'ET/ET-QZ3P-1DIFFUSE',
+	'ET/ET-QZ3P-2DIFFUSE',
+	'ET/ET-QZ3P-3DIFFUSE',
+	'TZ2P-J',
+	'QZ4P-J',
+	'POLTDDFT/DZ',
+	'POLTDDFT/DZP',
+	'POLTDDFT/TZP',
+],
+'BAND': {},
+'ORCA': {},
+}
+
+
+# read data
+data_dir = pl.Path(__file__).parents[0] / "_atom_data_info"
+
+with open(data_dir / "norbs.json") as inp:
+	_number_of_orbitals = json.loads(inp.read())
+
+
+
+[docs] +def number_of_orbitals(element, basis_set): + ''' + Get the number of atomic orbitals for a certain element and basis-set. + + Args: + element: the element for which to get the number of AOs. + basis_set: the basis-set for which to get the number of AOs. + + .. warning:: + This function currently only works for the following basis-sets: + [``SZ``, ``DZ``, ``DZP``, ``TZP``, ``TZ2P``, ``TZ2P-J``, ``mTZ2P``, ``QZ4P``, ``QZ4P-J``, ``jcpl``]. + It also only works for no-frozen-core calculations with ``NOSYM`` symmetry. + ''' + symbol = data.atom.symbol(element) + return _number_of_orbitals[basis_set][symbol]
+ + + +
+[docs] +def number_of_virtuals(element, basis_set): + ''' + Get the number of virtual atomic orbitals for a certain element and basis-set. + The number of virtuals is equal to the total number of AOs minus half the number of electrons in the atom. + + Args: + element: the element for which to get the number of AOs. + basis_set: the basis-set for which to get the number of AOs. + + .. warning:: + This function currently only works for the following basis-sets: + [``SZ``, ``DZ``, ``DZP``, ``TZP``, ``TZ2P``, ``TZ2P-J``, ``mTZ2P``, ``QZ4P``, ``QZ4P-J``, ``jcpl``]. + It also only works for no-frozen-core calculations with ``NOSYM`` symmetry. + ''' + num = data.atom.atom_number(element) + symbol = data.atom.symbol(element) + return _number_of_orbitals[basis_set][symbol] - num/2
+ + + +if __name__ == '__main__': + print(number_of_orbitals('Pd', 'DZ')) + print(number_of_virtuals('Pd', 'DZ')) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/data/functionals.html b/docs/_build/html/_modules/tcutility/data/functionals.html new file mode 100644 index 00000000..35d715f6 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/data/functionals.html @@ -0,0 +1,603 @@ + + + + + + + + + + tcutility.data.functionals — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.data.functionals

+'''
+Module used for obtaining information about exchange-correlation functionals.
+For example, it can be useful to obtain 
+'''
+import os
+from tcutility import results, cache
+import re
+
+
+j = os.path.join
+
+
+
+[docs] +@cache.cache +def get(functional_name: str) -> results.Result: + ''' + Return information about a given functional. + + Args: + functional_name: the name of the functional. It should exist in the :func:`get_available_functionals` keys. + + Return: + A :class:`Result <tcutility.results.result.Result>` object containing information about the functional if it exists. Else it will return ``None``. + + .. seealso:: + :func:`get_available_functionals` for an overview of the information returned. + ''' + info = functionals.get(functional_name, None) + if info is None: + info = functionals.get(functional_name_from_path_safe_name(functional_name), None) + + if info is None: + raise KeyError(f'Could not find info for functional {functional_name}.') + + return info
+ + + +
+[docs] +def functional_name_from_path_safe_name(path_safe_name: str) -> results.Result: + ''' + Return information about a given functional given its path-safe name. + This can be useful when you want to know the functional from a path name. + + Return: + A :class:`Result <tcutility.results.result.Result>` object containing information about the functional if it exists. Else it will return ``None``. + + .. seealso:: + :func:`get_available_functionals` for an overview of the information returned. + ''' + for functional, functional_info in functionals.items(): + if path_safe_name.lower() == functional_info.path_safe_name.lower(): + return functional + elif path_safe_name.replace('-', '').lower() == functional_info.path_safe_name.replace('-', '').lower(): + return functional
+ + + + +
+[docs] +def get_available_functionals(): + ''' + Function that returns a dictionary of all available XC-functionals. + + Returns: + : A :class:`Result <tcutility.results.result.Result>` object containing information about all available XC-functionals. + The functional names are stored as the keys and the functional information is stored as the values. + The values contain the following information: + + - ``name`` **(str)** - the name of the functional. + - ``path_safe_name`` **(str)** - the name of the functional made suitable for file paths. + This name is the same as the normal name, but without parentheses. Asterisks are replaced with lower-case ``s``. + - ``name_no_disp`` **(str)** - the name of functional without the dispersion correction. + - ``category`` **(str)** - the category the functional belongs to. + - ``dispersion`` **(str)** - the dispersion correction part of the functional name. + - ``dispersion_name`` **(str)** - the name of the dispersion correction as it would be written in ADF. + - ``includes_disp`` **(bool)** - whether the functional already includes a dispersion correction. + - ``use_libxc`` **(bool)** - whether the functional is from the LibXC library. + - ``available_in_adf`` **(bool)** - whether the functional is available in ADF. + - ``available_in_band`` **(bool)** - whether the functional is available in BAND. + - ``available_in_orca`` **(bool)** - whether the functional is available in ORCA. + - ``adf_settings`` **(:class:`Result <tcutility.results.result.Result>`)** - the settings that are used to select the functional in the ADF input. + - ``name_latex`` **(str)** - the name of the functional formatted to be used with LaTeX renderers. + - ``name_html`` **(str)** - the name of the functional formatted to be used with HTML renderers. + - ``dois`` **(List[str])** - a list of relevant dois for this functional. + ''' + def set_dispersion(func): + disp_map = { + '-D4': 'GRIMME4', + '-D3(BJ)': 'GRIMME3 BJDAMP', + '-D3BJ': 'GRIMME3 BJDAMP', + '-D3': 'GRIMME3', + '-dDsC': 'dDsC', + '-dUFF': 'UFF', + '-MBD': 'MBD', + '-MBD@rsSC': 'MBD', + '-D': 'DEFAULT' + } + + # set some default values for useful parameters + func.name_no_disp = func.name + func.dispersion = None + func.dispersion_name = None + + # go through every dispersion correction and check if we are using it + for disp_suffix, disp_name in disp_map.items(): + if func.name.endswith(disp_suffix): + # dispersion will be the suffix without the - + func.dispersion = disp_suffix[1:] + func.dispersion_name = disp_name + + # check if the functional already includes the dispersion correction + if func.includes_disp: + break + + # else we set the name of the functional without dispersion for later + func.name_no_disp = func.name[:-len(disp_suffix)] + # get the dispersion settings for ADF. Try to get custom values if they were provided. + func.adf_settings.XC.Dispersion = func.disp_params or disp_name + break + + def set_functional(func): + # set the functional settings for ADF + # first go through some special functionals that require special settings + if func.name_no_disp == 'BMK': + func.adf_settings.XC.LibXC = 'HYB_MGGA_X_BMK GGA_C_BMK' + return + + if func.name in ['LCY-BLYP', 'LCY-BP86', 'LCY-PBE']: + func.adf_settings.XC.GGA = func.name.split('-')[1] + func.adf_settings.XC.RANGESEP = '' + func.adf_settings.XC.xcfun = '' + return + + if func.name in ['CAMY-B3LYP']: + func.adf_settings.XC.Hybrid = 'CAMY-B3LYP' + func.adf_settings.XC.RANGESEP = '' + func.adf_settings.XC.xcfun = '' + return + + if func.name == 'GGA:SSB-D': + func.adf_settings.XC.GGA = 'SSB-D' + return + + if func.name == 'MetaGGA:SSB-D': + func.adf_settings.XC.MetaGGA = 'SSB-D' + return + + if func.name_no_disp == 'HartreeFock': + func.adf_settings.XC.HartreeFock = '' + return + + if func.name == 'MP2': + func.adf_settings.XC.MP2 = '' + return + + if func.name in ['SOS-MP2', 'SCS-MP2']: + func.adf_settings.XC.MP2 = '' + func.adf_settings.XC.EmpiricalScaling = func.name[:-4] + return + + # the normal functionals are defined based on their category, or selected from libxc + if func.use_libxc: + func.adf_settings.XC.LibXC = func.name_no_disp + else: + func.adf_settings.XC[func.category] = func.name_no_disp + + # gather all data about available functionals + functionals = results.Result() # store all info in this dict + + with open(j(os.path.split(__file__)[0], 'available_functionals.txt')) as file: + lines = file.readlines() + + # read the references first + # references are given as + # [refname] doi + # and in-line + # - xcname {options} [refname1][refname2]... + dois = {} + for line in lines: + if not line.startswith('['): + continue + + line = line.split('#')[0].strip() + + ref, doi = line.strip().split() + ref = ref[1:-1] + dois[ref] = doi + + for line in lines: + # there can be empty lines + if not line.strip(): + continue + + # and comment lines + if line.startswith('#'): + continue + + # we don't read the references here + if line.startswith('['): + continue + + # functional names are given starting with - + # category names without - + if not line.startswith('- '): + curr_category = line.strip() + continue + + line = line.split('#')[0].strip() + + # store data about the func in a dict + func = results.Result() + func.category = curr_category + # separate the functional name from the line + functional_name = line[2:].split('!')[0].split(',')[0].split('[')[0].strip() + func.name = functional_name + func.name_latex = functional_name + func.name_html = functional_name + func.path_safe_name = functional_name.replace(')', '').replace('(', '').replace('*', 's').replace(' ', '-') + + if functional_name.startswith('WB'): + func.name_latex = func.name_latex.replace('WB', r'$\omega$B') + func.name_html = func.name_html.replace('WB', '&omega;B') + + if 'r2SCAN' in functional_name: + func.name_latex = func.name_latex.replace('r2SCAN', r'r$^2$SCAN') + func.name_html = func.name_html.replace('r2SCAN', 'r<sup>2</sup>SCAN') + + if 'and' in functional_name: + func.name_latex = func.name_latex.replace('and', '&') + func.name_html = func.name_html.replace('and', '&amp;') + + if '*' in functional_name: + func.name_latex = func.name_latex.replace('*', r'$^*$') + func.name_html = func.name_html.replace('*', '<sup>*</sup>') + + if 'B2PIPLYP' in functional_name: + func.name_latex = func.name_latex.replace('B2PIPLYP', r'B2$\pi$PLYP') + func.name_html = func.name_html.replace('B2PIPLYP', 'B2&pi;PLYP') + + # check if custom params were given for dispersion + if 'GRIMME' in line: + # func.disp_params = line.split('!')[0].split(',')[1].strip().strip("'") + func.disp_params = re.findall(r"'(.*)'", line) + + func.use_libxc = '!libxc' in line + func.includes_disp = '!includesdisp' in line + func.available_in_adf = '!noadf' not in line + func.available_in_band = '!band' in line + func.available_in_orca = '!orca' in line + + # get references + refs = re.findall(r'\[([a-zA-Z0-9]+)\]', line) + func.dois = [dois[ref] for ref in refs] + + set_dispersion(func) + set_functional(func) + + functionals[functional_name] = func + + return functionals
+ + +functionals = get_available_functionals() + +categories = [] +for functional in functionals: + if get(functional).category not in categories: + categories.append(get(functional).category) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/data/molecules.html b/docs/_build/html/_modules/tcutility/data/molecules.html new file mode 100644 index 00000000..68e9daa3 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/data/molecules.html @@ -0,0 +1,364 @@ + + + + + + + + + + tcutility.data.molecules — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.data.molecules

+from tcutility import molecule
+import os
+
+
+j = os.path.join
+
+root_dir = j(os.path.split(__file__)[0], 'molecules')
+
+
+
+[docs] +def get(name): + p = j(root_dir, f'{name.removesuffix(".xyz")}.xyz') + return molecule.load(p)
+ + + +
+[docs] +def get_molecules(tags=None): + for f in os.listdir(root_dir): + if not f.endswith('.xyz'): + continue + + mol = get(f) + if tags is None or any(tag in mol.flags.tags for tag in tags): + yield mol
+ + + +if __name__ == '__main__': + for mol in get_molecules(): + print(mol, mol.flags) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/environment.html b/docs/_build/html/_modules/tcutility/environment.html new file mode 100644 index 00000000..8e20209a --- /dev/null +++ b/docs/_build/html/_modules/tcutility/environment.html @@ -0,0 +1,364 @@ + + + + + + + + + + tcutility.environment — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.environment

+import os
+from enum import Enum, auto
+
+
+
+[docs] +class OSName(Enum): + """ + An enumeration of the different operating systems. + """ + + WINDOWS = auto() + LINUX = auto() + MACOS = auto()
+ + + +
+[docs] +def get_os_name() -> OSName: + """ + Get the name of the operating system. Returns a value from the :class:`OSName <tcutility.environment.OSName>` enumeration. + """ + os_name = os.name + if os_name == "nt": + return OSName.WINDOWS + elif os_name == "posix": + return OSName.LINUX + elif os_name == "mac": + return OSName.MACOS + else: + raise ValueError(f"Unknown operating system: {os_name}")
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/errors.html b/docs/_build/html/_modules/tcutility/errors.html new file mode 100644 index 00000000..79bed3ec --- /dev/null +++ b/docs/_build/html/_modules/tcutility/errors.html @@ -0,0 +1,384 @@ + + + + + + + + + + tcutility.errors — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.errors

+"""Module containing errors to distinguish between tcutility-specific errors and general python errors from other packages / scripts."""
+
+from tcutility.log import loadbar
+
+some_list = {"a": 1, "b": 2, "c": 3}
+loadbar(some_list)
+
+
+
+[docs] +class TCError(Exception): + """Base class for all errors in the tcutility package.""" + + pass
+ + + +
+[docs] +class TCJobError(TCError): + """An error that occurs when a job fails to run properly.""" + + def __init__(self, job_class: str, message: str): + self.job_class = job_class + self.message = message + super().__init__(f"Error in job class {job_class}: {message}")
+ + + +
+[docs] +class TCMoleculeError(TCError): + """An error that occurs when a molecule is not in a valid state.""" + + pass
+ + + +# ----------------- +# ADF-related errors +# ----------------- + + +
+[docs] +class TCCompDetailsError(TCError): + """An error that occurs when the computation details are not in a valid state. It expects a section such as a "Functional" or "Basis set" and a message.""" + + def __init__(self, section: str, message: str): + self.section = section + self.message = message + super().__init__(f"Error in {section}: {message}")
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/formula.html b/docs/_build/html/_modules/tcutility/formula.html new file mode 100644 index 00000000..1533e82b --- /dev/null +++ b/docs/_build/html/_modules/tcutility/formula.html @@ -0,0 +1,441 @@ + + + + + + + + + + tcutility.formula — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.formula

+from typing import Union
+from scm import plams
+
+
+
+[docs] +def parse_molecule(molecule: plams.Molecule) -> str: + """ + Analyse a molecule and return the molstring describing its parts. Each part will then be separated by a ``+`` sign in the new string. + + Args: + molecule: ``plams.Molecule`` object to be parsed. + + Returns: + A string that contains each part of the molecule separated by a ``+`` sign, for use in :func:`molecule` function for further formatting. + """ + # to separate a molecule we need to have bonds + molecule.guess_bonds() + parts = [] + # go through each part of the molecule + for part in molecule.separate(): + # get a dictionary of counts for each element + form = part.get_formula(True) + # add all elements with their number, but only if the number is larger than 1. + # this prevents the creation of strings containing e.g. C1H3Cl2 + parts.append("".join([sym + (str(num) if num > 1 else "") for sym, num in form.items()])) + + return " + ".join(parts)
+ + + +
+[docs] +def molecule(molecule: Union[str, plams.Molecule], mode: str = "unicode") -> str: + """ + Parse and return a string containing a molecular formula that will show up properly in LaTeX, HTML or unicode. + + Args: + molecule: ``plams.Molecule`` object or a string that contains the molecular formula to be parsed. + It can be either single molecule or a reaction. Molecules should be separated by ``+`` or ``->``. + mode: the formatter to convert the string to. Should be ``unicode``, ``html``, ``latex``, ``pyplot``. + + Returns: + A string that is formatted to be rendered nicely in either HTML or LaTeX. + In the returned strings any numbers will be subscripted and ``+``, ``-``, ``*`` and ``•`` will be superscripted. + For ``latex`` and ``pyplot`` modes we apply ``\\mathrm`` to letters. + + Examples: + >>> molecule('C9H18NO*') + 'C₉H₁₈NO•' + + >>> molecule('C2H2 + CH3* -> C2H2CH3', mode='html') + 'C<sub>2</sub>H<sub>2</sub> + CH<sub>3</sub><sup>•</sup> -> C<sub>2</sub>H<sub>2</sub>CH3' + + .. seealso:: + The :func:`parse_molecule` function is used to convert ``plams.Molecule`` objects to a molecular formula. + + """ + # to take care of plus-signs used to denote reactions we have to first split + # the molstring into its parts. + if isinstance(molecule, plams.Molecule): + molstring = parse_molecule(molecule) + else: + molstring = molecule + + molstring = molstring.replace("*", "•") + for part in molstring.split(): + # if part is only a plus-sign we skip this part. This is only true when the plus-sign + # is used to denote a reaction + if part in ["+", "->"]: + continue + + # parse the part + partret = part + # numbers should be subscript + for num in "0123456789": + if mode in ["latex", "pyplot"]: + partret = partret.replace(num, f"_{num}") + if mode == "html": + partret = partret.replace(num, f"<sub>{num}</sub>") + if mode == "unicode": + partret = partret.replace(num, "₀₁₂₃₄₅₆₇₈₉"[int(num)]) + + for letter in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": + if mode in ["latex", "pyplot"]: + partret = partret.replace(letter, f"\mathrm{{{letter}}}") + + # signs should be superscript + for sign in "+-•": + # negative charges should be denoted by em dash and not a normal dash + if mode in ["latex", "pyplot"]: + partret = partret.replace(sign, f'^{sign.replace("-", "—")}') + if mode == "html": + partret = partret.replace(sign, f'<sup>{sign.replace("-", "—")}</sup>') + if mode == "unicode": + partret = partret.replace(sign, "⁺⁻•"["+-•".index(sign)]) + # replace the part in the original string + molstring = molstring.replace(part, partret) + + if mode == 'pyplot': + return fr"${molstring}$" + + return molstring
+ + + +if __name__ == "__main__": + print(molecule("F- + CH3Cl", "html")) + mol = plams.Molecule(r"D:\Users\Yuman\Desktop\PhD\TCutility\test\fixtures\chloromethane_sn2_ts\ts sn2.results\output.xyz") + print(molecule(mol)) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/geometry.html b/docs/_build/html/_modules/tcutility/geometry.html new file mode 100644 index 00000000..19be0649 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/geometry.html @@ -0,0 +1,1061 @@ + + + + + + + + + + tcutility.geometry — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.geometry

+import numpy as np
+from math import sin, cos, atan2, sqrt
+import scipy
+from typing import Tuple, Union, Sequence
+from scm import plams
+
+
+
+[docs] +class Transform: + ''' + Transformation matrix that handles rotation, translation and scaling of sets of 3D coordinates. + + Build and return a transformation matrix. + This 4x4 matrix encodes rotations, translations and scaling. + + :math:`\\textbf{M} = \\begin{bmatrix} \\textbf{R}\\text{diag}(S) & \\textbf{T} \\\\ \\textbf{0}_3 & 1 \\end{bmatrix}` + + where :math:`\\textbf{R} \\in \\mathbb{R}^{3 \\times 3}`, :math:`\\textbf{T} \\in \\mathbb{R}^{3 \\times 1}` and :math:`\\textbf{0}_3 = [0, 0, 0] \\in \\mathbb{R}^{1 \\times 3}`. + + When applied to a coordinates :math:`[\\textbf{x}, \\textbf{y}, \\textbf{z}, \\textbf{1}]^T \\in \\mathbb{R}^{n \\times 4}` it will apply these transformations simultaneously. + ''' + def __init__(self): + # initialize an empty transformation matrix + self.M = self._build_matrix() + + def __str__(self): + return str(self.M) + + def __call__(self, *args, **kwargs): + return self.apply(*args, **kwargs) + +
+[docs] + def apply(self, v: np.ndarray) -> np.ndarray: + """ + Applies the transformation matrix to vector(s) :math:`v \\in \\mathbb{R}^{N \\times 3}`. + + Application is a three-step process: + + #. Append row vector of ones to the bottom of :math:`v` + #. Apply the transformation matrix: :math:`\\textbf{M}v` + #. Remove the bottom row vector of ones and return the result + + Returns: + A new array :math:`v' = \\textbf{M}v` that has been transformed using this transformation matrix. + + .. note:: + + The ``Transform.__call__()`` method redirects to this method. Calling ``transform.apply(coords)`` is the same as ``transform(coords)``. + """ + is_mol = isinstance(v, plams.Molecule) + if is_mol: + mol = v.copy() + + v = np.array(v) + v = np.atleast_2d(v) + v = np.asarray(v).T + N = v.shape[1] + v = np.vstack([v, np.ones(N)]) + vprime = self.M @ v + + if is_mol: + mol.from_array(vprime[:3, :].T) + return mol + + return vprime[:3, :].T
+ + + def __matmul__(self, other): + if isinstance(other, Transform): + return self.combine_transforms(other) + +
+[docs] + def combine_transforms(self, other: "Transform") -> "Transform": + """ + Combine two different transform objects. This involves creating + a new Transform object and multiplying the two transform matrices + and assigning it to the new object. + + Args: + other: the transformation matrix object to combine this one with. + + Returns: + A new transformation matrix that is a product of the original (left side) and other (right side) matrices. + + .. note:: + + The ``Transform.__matmul__()`` method redirects to this method. Calling ``new = this.combine_transforms(other)`` is the same as ``new = this @ other``. + """ + new = Transform() + new.M = self.M @ other.M + return new
+ + +
+[docs] + def translate(self, T: np.ndarray = None, x: float = None, y: float = None, z: float = None): + """ + Add a translation component to the transformation matrix. + Arguments can be given as a container of x, y, z values. They can also be given separately. + You can also specify x, y and z components separately + + Example usage: + | ``Transform.translate([2, 3, 0])`` + | ``Transform.translate(x=2, y=3)`` + """ + if T is None: + T = [x or 0, y or 0, z or 0] + + self.M = self._build_matrix(T=T) @ self.M
+ + +
+[docs] + def rotate(self, R: np.ndarray = None, x: float = None, y: float = None, z: float = None): + r""" + Add a rotational component to transformation matrix. + Arguments can be given as a rotation matrix R \in R^3x3 or by specifying the angle to rotate along the x, y or z axes + + Example usage: + | ``Transform.rotate(get_rotmat(x=1, y=-1))`` + | ``Transform.rotate(x=1, y=-1)`` + + .. seealso:: + + :func:`get_rotmat` + :func:`rotate` + """ + if R is None: + R = get_rotmat(x=x, y=y, z=z) + + self.M = self._build_matrix(R=R) @ self.M
+ + +
+[docs] + def scale(self, S: np.ndarray = None, x: float = None, y: float = None, z: float = None): + """ + Add a scaling component to the transformation matrix. + Arguments can be given as a container of x, y, z values. + You can also specify x, y and z components separately + + Example usage: + | ``Transform.scale([0, 0, 3])`` + | ``Transform.scale(z=3)`` + """ + if S is None: + S = [x or 1, y or 1, z or 1] + elif isinstance(S, (float, int)): + S = [S, S, S] + + self.M = self._build_matrix(S=S) @ self.M
+ + +
+[docs] + def reflect(self, normal: np.ndarray = None): + """ + Add a reflection across a plane given by a normal vector to the transformation matrix. + The reflection is given as + + :math:`R = \\mathbb{I} - 2\\frac{nn^T}{n^Tn} \\in \\mathbb{R}^{3 \\times 3}` + + where :math:`n` is the normal vector of the plane to reflect along. + + Args: + normal: the normal vector of the plane to reflect across. + If not given or ``None``, it will be set to one unit along the x-axis, i.e. a reflection along the yz-plane. + + References: + https://en.wikipedia.org/wiki/Reflection_(mathematics) + """ + if normal is None: + normal = np.array([[1, 0, 0]]) + + normal = np.atleast_2d(np.array(normal)) + + # normalize the normal to be sure + normal = normal.T / np.linalg.norm(normal) + R = np.eye(3) - 2 * (normal @ normal.T) / (normal.T @ normal) + self.M = self.M @ self._build_matrix(R=R)
+ + + def _build_matrix(self, R: np.ndarray = None, T: np.ndarray = None, S: np.ndarray = None) -> np.ndarray: + ''' + Build the transformation matrix for this object. + ''' + # set the default matrix and vectors + R = R if R is not None else get_rotmat() + T = T if T is not None else np.array([0, 0, 0]) + S = S if S is not None else np.array([1, 1, 1]) + + return np.array([[R[0, 0] * S[0], R[0, 1], R[0, 2], T[0]], [R[1, 0], R[1, 1] * S[1], R[1, 2], T[1]], [R[2, 0], R[2, 1], R[2, 2] * S[2], T[2]], [0, 0, 0, 1]]) + +
+[docs] + def get_rotmat(self): + return self.M[:3, :3]
+ + +
+[docs] + def get_translation(self): + return self.M[:3, 3]
+ + +
+[docs] + def to_vtkTransform(self): + import vtk + vtktrans = vtk.vtkTransform() + vtktrans.PostMultiply() + + angles = rotmat_to_angles(self.get_rotmat()) + vtktrans.RotateX(angles[0] * 180 / np.pi) + vtktrans.RotateY(angles[1] * 180 / np.pi) + vtktrans.RotateZ(angles[2] * 180 / np.pi) + + vtktrans.Translate(self.get_translation()) + + return vtktrans
+
+ + + + +
+[docs] +class KabschTransform(Transform): + """ + Use Kabsch-Umeyama algorithm to calculate the optimal transformation matrix :math:`T_{Kabsch}` that minimizes the + RMSD between two sets of coordinates :math:`X \\in \\mathbb{R}^{N \\times 3}` and :math:`Y \\in \\mathbb{R}^{N \\times 3}`, such that + + :math:`\\text{arg}\\min_{T_{Kabsch}} \\text{RMSD}(T_{Kabsch}(X), Y)` + + It is numerically stable and works when the covariance matrix is singular. + Both sets of points must be the same size for this algorithm to work. + The coordinates are first centered onto their centroids before determining the optimal rotation matrix. + + Args: + X: array containing the first set of coordinates. The Kabsch transformation matrix will be made such that applying it to ``X`` will yield ``Y``. + Y: array containing the second set of coordinates. These coordinates is the target to transform to. + + .. warning:: + In principle, the Kabsch-Umeyama algorithm does not care about the dimensions of the coordinates, + however we will always assume 3D coordinates as that is our most common use-case. Further, the :class:`Transform` class also assumes 3D coordinates. + If you would like to make use of 2D or 1D Transforms we suggest you simply set the correct axes to zero. + + .. seealso:: + :class:`Transform` + The main transformation class. + + Example: + + .. code-block:: python + + from tcutility import geometry + import numpy as np + + # create two arrays that are the same + X, Y = np.arange(5 * 3).reshape(5, 3), np.arange(5 * 3).reshape(5, 3) + + # create a transformation matrix to change X + Tx = geometry.Transform() + Tx.rotate(x=1, y=1, z=1) + Tx.translate(x=1, y=1, z=1) + + X = Tx(X) + + # get the Kabsch transformation matrix + Tkabsch = geometry.KabschTransform(X, Y) + + # check if applying the transformation matrix to X yields Y + assert np.isclose(Tkabsch(X), Y).all() + + + References: + | https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem + | https://en.wikipedia.org/wiki/Kabsch_algorithm + """ + def __init__(self, X: np.ndarray, Y: np.ndarray): + # make sure arrays are 2d and the same size + X, Y = np.atleast_2d(X), np.atleast_2d(Y) + assert X.shape == Y.shape, f"Matrices X with shape {X.shape} and Y with shape {Y.shape} are not the same size" + + # center the coordinates + centroid_x = np.mean(X, axis=0) + centroid_y = np.mean(Y, axis=0) + Xc = X - centroid_x + Yc = Y - centroid_y + + # calculate covariance matrix H + H = Xc.T @ Yc + + # first do single value decomposition on covariance matrix + # this step ensures that the algorithm is numerically stable + # and removes problems with singular covariance matrices + U, _, V = scipy.linalg.svd(H) + + # get the sign of the determinant of V.T @ U.T + sign = np.sign(np.linalg.det(V.T @ U.T)) + # then build the optimal rotation matrix + d = np.diag([1, 1, sign]) + R = V.T @ d @ U.T + + # build the transformation: + # We have that Y ~= (R @ (X - centroid_x).T).T + centroid_y + # the normal order is to first translate X by -centroid_x + # then rotate with R + # finally translate by +centroid_y + self.M = self._build_matrix() + self.translate(-centroid_x) + self.rotate(R) + self.translate(centroid_y)
+ + + +
+[docs] +class MolTransform(Transform): + ''' + A subclass of :class:`Transform` that is designed to generate transformation for a molecule. + It adds, among others, methods for aligning atoms to specific vectors, planes, or setting the centroid of the molecule. + The nice thing is that the class applies the transformations based only on the atom indices given by the user. + + Args: + mol: the molecule that is used for the alignment. + + .. note:: + Indexing starts at 1 instead of 0. + ''' + def __init__(self, mol: plams.Molecule): + self.mol = mol + super().__init__() + +
+[docs] + def center(self, *indices): + ''' + Center the molecule on given indices or by its centroid. + + Args: + indices: the indices that are used to center the molecule. + If not given the centering will be done based on all atoms. + ''' + tmol = self.apply(self.mol) + if len(indices) == 0: + indices = range(1, len(tmol) + 1) + C = np.array([tmol.as_array()[i - 1] for i in indices]) + self.translate(-np.mean(C, axis=0))
+ + +
+[docs] + def align_to_vector(self, index1: int, index2: int, vector: Sequence[float] = None): + ''' + Align the molecule such that a bond lays on a given vector. + + Args: + index1: index of the first atom. + index2: index of the second atom. + vector: the vector to align the atoms to. If not given or `None` it defaults to `(1, 0, 0)`. + ''' + # get the transformed mol + tmol = self.apply(self.mol) + # and coordinates + C1, C2 = tmol.as_array()[index1 - 1], tmol.as_array()[index2 - 1] + if vector is None: + vector = [1, 0, 0] + + R = vector_align_rotmat(C1 - C2, vector) + self.rotate(R)
+ + +
+[docs] + def align_to_plane(self, index1: int, index2: int, index3: int, vector: Sequence[float] = None): + ''' + Align a molecule such that the normal of the plane defined by three atoms is aligned to a given vector. + + Args: + index1: index of the first atom. + index2: index of the second atom. + index3: index of the third atom. + vector: the vector to align the atoms to. If not given or `None` it defaults to (0, 1, 0). + ''' + # get the transformed mol + tmol = self.apply(self.mol) + # and coordinates + C1, C2, C3 = tmol.as_array()[index1 - 1], tmol.as_array()[index2 - 1], tmol.as_array()[index3 - 1] + if vector is None: + vector = [0, 1, 0] + + # calculate normal vector and align it to the given vector + n = np.cross(C1 - C2, C3 - C2) + R = vector_align_rotmat(n, vector) + self.rotate(R)
+
+ + + +
+[docs] +def get_rotmat(x: float = None, y: float = None, z: float = None) -> np.ndarray: + """ + Create a rotation matrix based on the Tait-Bryant sytem. + In this system, x, y, and z are angles of rotation around + the corresponding axes. This function uses the right-handed + convention + + Args: + x: Rotation around the x-axis in radians. + y: Rotation around the y-axis in radians. + z: Rotation around the z-axis in radians. + + Returns: + the rotation matrix :math:`\\textbf{R} \\in \\mathbb{R}^{3 \\times 3}` with the specified axis rotations. + + + .. seealso:: + + :func:`apply_rotmat` + For applying the rotation matrix to coordinates. + + :func:`rotate` + For rotating coordinates directly, given Tait-Bryant angles. + + :meth:`Transform.rotate` + The :class:`Transform` class allows you to also rotate. + """ + # start with identity matrix + R = np.eye(3) + + # apply rotation around each axis separately + if x is not None: + c = cos(x) + s = sin(x) + R = R @ np.array(([1, 0, 0], [0, c, -s], [0, s, c])) + + if y is not None: + c = cos(y) + s = sin(y) + R = R @ np.array(([c, 0, s], [0, 1, 0], [-s, 0, c])) + + if z is not None: + c = cos(z) + s = sin(z) + R = R @ np.array(([c, -s, 0], [s, c, 0], [0, 0, 1])) + + return R
+ + + +
+[docs] +def rotmat_to_angles(R: np.ndarray) -> Tuple[float]: + thetax = atan2(R[2, 1], R[2, 2]) + thetay = atan2(-R[2, 0], sqrt(R[2, 1]**2 + R[2, 2]**2)) + thetaz = atan2(R[1, 0], R[0, 0]) + return thetax, thetay, thetaz
+ + + +
+[docs] +def apply_rotmat(coords: np.ndarray, R: np.ndarray) -> np.ndarray: + """ + Apply a rotation matrix to a set of coordinates. + + Args: + coords: the coordinates :math`\\in \\mathbb{R}^{n \\times 3}` to rotate. + R: the rotation matrix to apply. + + Returns: + New coordinates :math`\\in \\mathbb{R}^{n \\times 3}` rotated using the given rotation matrix. + + .. seealso:: + + :func:`get_rotmat` + For creating a rotation matrix. + + :func:`rotate` + For rotating coordinates directly, given Tait-Bryant angles. + """ + coords = np.atleast_2d(coords) + return (R @ coords.T).T.squeeze()
+ + + +
+[docs] +def rotate(coords: np.ndarray, x: float = None, y: float = None, z: float = None) -> np.ndarray: + """ + Build and apply a rotation matrix to a set of coordinates. + + Args: + coords: the coordinates :math`\\in \\mathbb{R}^{n \\times 3}` to rotate. + x: Rotation around the x-axis in radians. + y: Rotation around the y-axis in radians. + z: Rotation around the z-axis in radians. + + .. seealso:: + :func:`get_rotmat` + For creating a rotation matrix. + """ + return apply_rotmat(coords, get_rotmat(x, y, z))
+ + + +
+[docs] +def vector_align_rotmat(a: np.ndarray, b: np.ndarray) -> np.ndarray: + """ + Calculate a rotation matrix that aligns vector a onto vector b. + + Args: + a: vector that is to be aligned. + b: vector that is the target of the alignment. + + Returns: + Rotation matrix R, such that ``geometry.apply_rotmat(a, R) == b``. + """ + # normalize the vectors first + a = np.array(a) / np.linalg.norm(a) + b = np.array(b) / np.linalg.norm(b) + + c = a @ b + if c == 1: + # if a == b we simply return the identity matrix + return np.eye(3) + if c == -1: + # when a == -b we cannot directly calculate R, as 1/(1+c) is undefined + # instead, we first create a random rotation matrix and apply it to a + # to get a new vector aprime. We then align aprime to b, which is possible since aprime != -b + # to get the final rotation matrix we simply multiply the random and alignment rotation matrices + Rrand = get_rotmat(np.pi / 3, np.pi / 3, np.pi / 3) + return vector_align_rotmat(apply_rotmat(a, Rrand), b) @ Rrand + + v = np.cross(a, b) + skew = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) + R = np.eye(3) + skew + skew @ skew / (1 + c) + return R
+ + + +
+[docs] +def RMSD(X: np.ndarray, Y: np.ndarray, axis: Union[int, None] = None, use_kabsch: bool = True, include_mirror: bool = False) -> float: + r""" + Calculate Root Mean Squared Deviations between two sets of points ``X`` and ``Y``. + By default Kabsch' algorithm is used to align the sets of points prior to calculating the RMSD. + Optionally the axis can be given to calculate the RMSD along different axes. + + RMSD is given as + + :math:`\text{RMSD}(X, Y) = \frac{1}{N}\sqrt{\sum_i^N (X_i - Y_i)^2}` + + when using the Kabsch algorithm to align the two sets of coordinates we first obtain the :class:`KabschTransform` :math:`T_{Kabsch}` and then + + :math:`\text{RMSD}(X, Y) = \frac{1}{N}\sqrt{\sum_i^N (T_{Kabsch}(X_i) - Y_i)^2}` + + Args: + X: the first set of coordinates to compare. It must have the same dimensions as ``Y``. + Y: the second set of coordinates to compare. It must have the same dimensions as ``X``. + axis: axis to compare. Defaults to ``None``. + use_kabsch: whether to use Kabsch' algorithm to align ``X`` and ``Y`` before calculating the RMSD. Defaults to ``True``. + include_mirror: return the lowest value between the RMSD of the supplied coordinates and also the RMSD of mirrored X with Y. + This will only be done if ``use_kabsch == True``. + + Returns: + RMSD in the units of X and Y. If ``axis`` is set to an integer this function will return a vector of RMSD's along that axis. + + .. note:: + It is generally recommended to enable the use of the Kabsch-Umeyama algorithm prior to calculating the RMSD. + This will ensure you get the lowest possible RMSD for you sets of coordinates. + + .. seealso:: + :class:`KabschTransform` + """ + + X = np.array(X) + Y = np.array(Y) + + assert X.shape == Y.shape + + # apply Kabsch transform + if use_kabsch: + Tkabsch = KabschTransform(X, Y) + Xprime = Tkabsch(X) + + rmsd = np.sqrt(np.sum((Xprime - Y) ** 2, axis=axis) / X.shape[0]) + + # if we include the mirror image we have to apply a reflection to the coordinates + # and then recalculate the kabsch transform in the mirror coordinates + # then we calculate the new RMSD and take the smaller of the new and old RMSD + if include_mirror and use_kabsch: + Tmirror = Transform() + Tmirror.reflect() + Tkabsch_mirror = KabschTransform(Tmirror(X), Y) + Xprime = Tkabsch_mirror(Tmirror(X)) + rmsd_mirrored = np.sqrt(np.sum((Xprime - Y) ** 2, axis=axis) / X.shape[0]) + rmsd = min(rmsd, rmsd_mirrored) + + return rmsd
+ + + +
+[docs] +def random_points_on_sphere(shape: Tuple[int], radius: float = 1) -> np.ndarray: + """ + Generate random points on a sphere with a specified radius. + + Args: + shape: The shape of the resulting points, generally shape[0] coordinates with shape[1] dimensions + radius: The radius of the sphere to generate the points on. + + Returns: + Array of coordinates on a sphere. + """ + x = np.random.randn(*shape) + x = x / np.linalg.norm(x, axis=1, keepdims=True) * radius + return x
+ + + +
+[docs] +def random_points_in_anular_sphere(shape: Tuple[int], min_radius: float = 0, max_radius: float = 1): + """ + Generate random points in an sphere or anular sphere with specified radii. + An anular sphere is a hollow sphere of a certain thickness. + + Args: + shape: The shape of the resulting points, generally shape[0] coordinates with shape[1] dimensions + min_radius: The lowest radius of the sphere to generate the points in. + max_radius: The largest radius of the sphere to generate the points in. + + Returns: + Array of coordinates on a sphere. + """ + random_radii = np.random.rand(shape[0]) * (max_radius - min_radius) + min_radius + return random_points_on_sphere(shape, random_radii)
+ + + +
+[docs] +def random_points_on_spheroid(coordinates: np.ndarray, Nsamples: int = 1, margin: float = 0): + """ + Generate random points on a spheroid generated by a set of coordinates. + + Args: + coordinates: The (n x dim) set of coordinates that is used to generate the minimum-volume spheroid. + Nsamples: The number of samples to return. + margin: the spacing between the sampling spheroid and the minimum-volume spheroid. + + Returns: + Array of coordinates on a spheroid. + """ + # for this to work we should first get the centroid of our molecule + centroid = np.mean(coordinates, axis=0) + # and get the centered coordiantes + Xc = coordinates - centroid + + # we then do a singular-value decomposition to obtain + # the three principle components (Vh) with their eigenvalues (s) + _, s, Vh = scipy.linalg.svd(Xc) + + # then compute a transformation matrix for generating the correct spheroid + transform = Transform() + transform.translate(centroid) + transform.rotate((np.diag(s/2 + margin) @ Vh).T) + + # to sample the spheroid we generate points on a + # sphere and transform them to our spheroid + p = random_points_on_sphere((Nsamples, Xc.shape[1])) + return transform(p)
+ + + +
+[docs] +def parameter(coordinates, *indices, pyramidal=False): + ''' + Return geometry information about a set of coordinates given indices. + ''' + assert 1 <= len(indices) <= 4, "Number of indices must be between 1, 2, 3 or 4" + + coordinates = np.array(coordinates) + selected_coords = [coordinates[i] for i in indices] + + if len(indices) == 1: + return selected_coords[0] + + if len(indices) == 2: + return np.linalg.norm(selected_coords[0] - selected_coords[1]) + + if len(indices) == 3: + a = selected_coords[0] - selected_coords[1] + b = selected_coords[2] - selected_coords[1] + a = a / np.linalg.norm(a) + b = b / np.linalg.norm(b) + + return np.arccos(a @ b) / np.pi * 180 + + if len(indices) == 4 and not pyramidal: + a = selected_coords[0] - selected_coords[1] + b = selected_coords[2] - selected_coords[1] + + u = selected_coords[1] - selected_coords[2] + v = selected_coords[3] - selected_coords[2] + + n1, n2 = np.cross(a, b), np.cross(u, v) + + n1 = n1 / np.linalg.norm(n1) + n2 = n2 / np.linalg.norm(n2) + + return np.arccos(n1 @ n2) / np.pi * 180 + + + if len(indices) == 4 and pyramidal: + ang1 = parameter(coordinates, indices[1], indices[0], indices[2]) + ang2 = parameter(coordinates, indices[2], indices[0], indices[3]) + ang3 = parameter(coordinates, indices[3], indices[0], indices[1]) + + return 360 - ang1 - ang2 - ang3
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/adf.html b/docs/_build/html/_modules/tcutility/job/adf.html new file mode 100644 index 00000000..e70d6fc9 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/adf.html @@ -0,0 +1,1116 @@ + + + + + + + + + + tcutility.job.adf — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.adf

+import os
+
+from scm import plams
+
+from tcutility import data, formula, log, molecule, results, spell_check
+from tcutility.errors import TCCompDetailsError, TCJobError
+from tcutility.job.ams import AMSJob
+from tcutility.job.generic import Job
+
+j = os.path.join
+
+
+
+[docs] +class ADFJob(AMSJob): + def __init__(self, *args, **kwargs): + self.settings = results.Result() + self._functional = None + self._core = None + self.solvent("vacuum") + self.basis_set("TZ2P") + self.quality("Good") + self.SCF(thresh=1e-8) + self.single_point() + + # by default print the fock matrix + self.settings.input.adf.print = "SFOSiteEnergies" + super().__init__(*args, **kwargs) + + def __str__(self): + return f"{self._task}({self._functional}/{self._basis_set}), running in {os.path.join(os.path.abspath(self.rundir), self.name)}" + +
+[docs] + def basis_set(self, type: str = "TZ2P", core: str = "None"): + """ + Set the basis-set type and frozen core approximation for this calculation. + + Args: + typ: the type of basis-set to use. Default is TZ2P. + core: the size of the frozen core approximation. Default is None. + + Raises: + ValueError: if the basis-set name or core is incorrect. + + .. note:: If the selected functional is the r2SCAN-3c functional, then the basis-set will be set to mTZ2P. + + .. seealso:: + :mod:`tcutility.data.basis_sets` for an overview of the available basis-sets in ADF. + """ + spell_check.check(type, data.basis_sets.available_basis_sets["ADF"], ignore_case=True) + spell_check.check(core, ["None", "Small", "Large"], ignore_case=True) + if self._functional == "r2SCAN-3c" and type != "mTZ2P": + log.warn(f"Basis set {type} is not allowed with r2SCAN-3c, switching to mTZ2P.") + typ = "mTZ2P" + self._basis_set = typ + self._core = core + self.settings.input.adf.basis.type = typ + self.settings.input.adf.basis.core = core
+ + +
+[docs] + def spin_polarization(self, val: int): + """ + Set the spin-polarization of the system. If the value is not zero the calculation will also be unrestricted. + """ + self.settings.input.adf.SpinPolarization = val + if val != 0: + self.settings.input.adf.Unrestricted = "Yes"
+ + +
+[docs] + def multiplicity(self, val: int): + """ + Set the multiplicity of the system. If the value is not one the calculation will also be unrestricted. + We use the following values: + + 1) singlet + 2) doublet + 3) triplet + 4) ... + + The multiplicity is equal to 2*S+1 for spin-polarization S. + """ + self.settings.input.adf.SpinPolarization = (val - 1) // 2 + if val != 1: + self.settings.input.adf.Unrestricted = "Yes"
+ + +
+[docs] + def unrestricted(self, val: bool): + """ + Whether the calculation should be unrestricted. + """ + self.settings.input.adf.Unrestricted = "Yes" if val else "No"
+ + +
+[docs] + def occupations(self, strategy: str): + """ + Set the orbital filling strategy for ADF. + + Args: + strategy: the name of the filling strategy. This can contain multiple of the options allowed. + + .. seealso:: + The SCM documentation can be found at https://www.scm.com/doc/ADF/Input/Electronic_Configuration.html#aufbau-smearing-freezing + """ + self.settings.input.adf.Occupations = strategy
+ + +
+[docs] + def quality(self, val: str = "Good"): + """ + Set the numerical quality of the calculation. + + Args: + val: the numerical quality value to set to. This is the same as the ones used in the ADF GUI. Defaults to Good. + + Raises: + ValueError: if the quality value is incorrect. + """ + spell_check.check(val, ["Basic", "Normal", "Good", "VeryGood", "Excellent"], ignore_case=True) + self.settings.input.adf.NumericalQuality = val
+ + +
+[docs] + def SCF_convergence(self, thresh: float = 1e-8): + """ + Set the SCF convergence criteria for the job. + + Args: + thresh: the convergence criteria for the SCF procedure. Defaults to 1e-8. + + .. deprecated:: 0.9.2 + Please use :meth:`ADFJob.SCF` instead of this method. + """ + log.warn("This method has been deprecated, please use ADFJob.SCF instead.") + self.SCF(thresh=thresh)
+ + +
+[docs] + def SCF(self, iterations: int = 300, thresh: float = 1e-8): + """ + Set the SCF settings for this calculations. + + Args: + iterations: number of iterations to perform for this calculation. Defaults to 300. + thresh: the convergence criteria for the SCF procedure. Defaults to 1e-8. + + .. note:: + When setting the number of iterations to 0 or 1 the ``AlwaysClaimSuccess`` key will also be set to ``Yes``. + This is to prevent the job from being flagged as a failure when reading it using :mod:`tcutility.results`. + """ + self.settings.input.adf.SCF.Iterations = iterations + self.settings.input.adf.SCF.Converge = thresh + + if iterations in [0, 1]: + self.settings.input.ams.EngineDebugging.AlwaysClaimSuccess = "Yes"
+ + +
+[docs] + def functional(self, funtional_name: str, dispersion: str = None): + """ + Set the functional to be used by the calculation. This also sets the dispersion if it is specified in the functional name. + + Args: + funtional_name: the name of the functional. The value can be the same as the ones used in the ADF GUI. + dispersion: dispersion setting to use with the functional. This is used when you want to use a functional from LibXC. + + Raises: + ValueError: if the functional name is not recognized. + + .. note:: Setting the functional to r2SCAN-3c will automatically set the basis-set to mTZ2P. + + .. seealso:: + :mod:`tcutility.data.functionals` for an overview of the available functionals in ADF. + """ + # before adding the new functional we should clear any previous functional settings + self.settings.input.adf.pop("XC", None) + + functional = funtional_name.strip() + functional = functional.replace("-D4(EEQ)", "-D4") # D4(EEQ) and D4 are the same, unlike D3 and D3(BJ) + self._functional = functional + + if functional == "r2SCAN-3c" and self._basis_set != "mTZ2P": + log.info(f"Switching basis set from {self._basis_set} to mTZ2P for r2SCAN-3c.") + self.basis_set("mTZ2P") + + if functional == "SSB-D": + raise TCCompDetailsError(section="Functional", message='There are two functionals called SSB-D, please use "GGA:SSB-D" or "MetaGGA:SSB-D".') + + if not data.functionals.get(functional): + raise TCCompDetailsError(section="Functional", message=f"XC-functional {functional} not found.") + else: + func = data.functionals.get(functional) + self.settings.input.adf.update(func.adf_settings)
+ + +
+[docs] + def relativity(self, level: str = "Scalar"): + """ + Set the treatment of relativistic effects for this calculation. + + Args: + level: the level to set. Can be the same as the values in the ADF GUI and documentation. By default it is set to Scalar. + + Raises: + ValueError: if the relativistic correction level is not correct. + """ + spell_check.check(level, ["Scalar", "None", "Spin-Orbit"], ignore_case=True) + self.settings.input.adf.relativity.level = level
+ + +
+[docs] + def solvent(self, name: str = None, eps: float = None, rad: float = None, use_klamt: bool = False): + """ + Model solvation using COSMO for this calculation. + + Args: + name: the name of the solvent you want to use. Please see the ADF manual for a list of available solvents. + eps: the dielectric constant of your solvent. You can use this in place of the solvent name if you need more control over COSMO. + rad: the radius of the solvent molecules. You can use this in place of the solvent name if you need more control over COSMO. + use_klamt: whether to use the klamt atomic radii. This is usually used when you have charged species (?). + + Raises: + ValueError: if the solvent name is given, but incorrect. + + .. seealso:: + :mod:`tcutility.data.cosmo` for an overview of the available solvent names and formulas. + """ + if name: + spell_check.check(name, data.cosmo.available_solvents, ignore_case=True, insertion_cost=0.3) + self._solvent = name + else: + self._solvent = f"COSMO(eps={eps} rad={rad})" + + if name == "vacuum": + self.settings.input.adf.pop("Solvation", None) + return + + self.settings.input.adf.Solvation.Surf = "Delley" + solv_string = "" + if name: + solv_string += f"name={name} " + else: + self.settings.input.adf.Solvation.Solv = f"eps={eps} rad={rad} " + if use_klamt: + solv_string += "cav0=0.0 cav1=0.0" + else: + solv_string += "cav0=0.0 cav1=0.0067639" + self.settings.input.adf.Solvation.Solv = solv_string + + self.settings.input.adf.Solvation.Charged = "method=CONJ corr" + self.settings.input.adf.Solvation["C-Mat"] = "POT" + self.settings.input.adf.Solvation.SCF = "VAR ALL" + self.settings.input.adf.Solvation.CSMRSP = None + + if use_klamt: + radii = {"H": 1.30, "C": 2.00, "N": 1.83, "O": 1.72, "F": 1.72, "Si": 2.48, "P": 2.13, "S": 2.16, "Cl": 2.05, "Br": 2.16, "I": 2.32} + self.settings.input.adf.solvation.radii = radii
+ + +
+[docs] + def symmetry(self, group: str): + """ + Specify the symmetry group to be used by ADF. + + Args: + group: the symmetry group to be used. + """ + self.settings.input.adf.Symmetry = group
+ + + def _check_job(self): + # if we have spinpolarization we do not want to use DFTB to calculate the initial hessian + if self.settings.input.adf.SpinPolarization != 0 and self.settings.input.ams.GeometryOptimization.InitialHessian.Type == "CalculateWithFastEngine": + # we simply remove it from the geometryoptimization block + self.settings.input.ams.GeometryOptimization.pop("InitialHessian", None)
+ + + +
+[docs] +class ADFFragmentJob(ADFJob): + def __init__(self, *args, **kwargs): + self.decompose_elstat = kwargs.pop('decompose_elstat', False) + self.child_jobs = {} + # self.childjobs_no_electrons = {} + super().__init__(*args, **kwargs) + self.name = "EDA" + +
+[docs] + def add_fragment(self, mol: plams.Molecule, name: str = None, charge: int = 0, spin_polarization: int = 0): + """ + Add a fragment to this job. Optionally give the name, charge and spin-polarization of the fragment as well. + + Args: + mol: the molecule corresponding to the fragment. + name: the name of the fragment. By default it will be set to ``fragment{N+1}`` if ``N`` is the number of fragments already present. + charge: the charge of the fragment to be added. + spin_polarization: the spin-polarization of the fragment to be added. + """ + # in case of giving fragments as indices we dont want to add the fragment to the molecule later + add_frag_to_mol = True + # we can be given a list of atoms + if isinstance(mol, list) and isinstance(mol[0], plams.Atom): + mol_ = plams.Molecule() + [mol_.add_atom(atom) for atom in mol] + mol = mol_ + + # or a list of integers + if isinstance(mol, list) and isinstance(mol[0], int): + if not self._molecule: + log.error(f"Trying to add fragment based on atom indices, but main job does not have a molecule yet. Call the {self.__class__.__name__}.molecule method to add one.") + return + mol_ = plams.Molecule() + [mol_.add_atom(self._molecule[i]) for i in mol] + mol = mol_.copy() + add_frag_to_mol = False + + # check if the atoms in the new fragment are already present in the other fragments. + # if it is we should raise an error + for child in self.child_jobs.values(): + if any((atom.symbol, atom.coords) == (myatom.symbol, myatom.coords) for atom in child._molecule for myatom in mol): + raise TCJobError(job_class=self.__class__.__name__, message="The atoms in the new fragment are already present in the other fragments.") + + name = name or f"fragment{len(self.childjobs) + 1}" + self.childjobs[name] = ADFJob(test_mode=self.test_mode) + self.childjobs[name].molecule(mol) + self.childjobs[name].charge(charge) + self.childjobs[name].spin_polarization(spin_polarization) + setattr(self, name, self.childjobs[name]) + + if not add_frag_to_mol: + return + + if self._molecule is None: + self._molecule = self.child_jobs[name]._molecule.copy() + else: + for atom in self.child_jobs[name]._molecule.copy(): + if any((atom.symbol, atom.coords) == (myatom.symbol, myatom.coords) for myatom in self._molecule): + continue + self._molecule.add_atom(atom)
+ + +
+[docs] + def guess_fragments(self): + """ + Guess what the fragments are based on data stored in the molecule provided for this job. + This will automatically set the correct fragment molecules, names, charges and spin-polarizations. + + .. seealso:: + | :func:`tcutility.molecule.guess_fragments` for an explanation of the xyz-file format required to guess the fragments. + | :meth:`ADFFragmentJob.add_fragment` to manually add a fragment. + + .. note:: + This function will be automatically called if there were no fragments given to this calculation. + """ + frags = molecule.guess_fragments(self._molecule) + if frags is None: + log.error("Could not load fragment data for the molecule.") + return False + + for fragment_name, fragment in frags.items(): + charge = fragment.flags.get("charge", 0) + spin_polarization = fragment.flags.get("spinpol", 0) + self.add_fragment(fragment, fragment_name, charge=charge, spin_polarization=spin_polarization) + + return True
+ + +
+[docs] + def remove_virtuals(self, frag=None, subspecies=None, nremove=None): + """ + Remove virtual orbitals from the fragments. + + Args: + frag: the fragment to remove virtuals from. If set to ``None`` we remove all virtual orbitals of all fragments. + subspecies: the symmetry subspecies to remove virtuals from. If set to ``None`` we assume we have ``A`` subspecies. + nremove: the number of virtuals to remove. If set to ``None`` we will guess the number of virtuals based on the basis-set chosen. + """ + if frag is None: + self.settings.input.adf.RemoveAllFragVirtuals = "Yes" + return + + # if nremove is not given we will get it from the atoms in the fragment + if nremove is None: + # guess the virtual numbers only works for non-frozen-core calculations + if self._core.lower() != "none": + raise TCJobError(job_class=self.__class__.__name__, message="Cannot guess number of virtual orbitals for calculations with a frozen core.") + # the basis-set has to be present in the prepared data + if self._basis_set.lower() not in [bs.lower() for bs in data.basis_sets._number_of_orbitals.keys()]: + raise TCJobError(job_class=self.__class__.__name__, message=f"Cannot guess number of virtual orbitals for calculations with the {self._basis_set} basis-set.") + + # sum up the number of virtuals per atom in the fragment + nremove = 0 + for atom in self.child_jobs[frag]._molecule: + nremove += data.basis_sets.number_of_virtuals(atom.symbol, self._basis_set) + # positive charge adds a virtual and negative removes a virtual + nremove += self.child_jobs[frag].settings.input.ams.System.charge or 0 + + self.settings.input.adf.setdefault("RemoveFragOrbitals", "") + self.settings.input.adf.RemoveFragOrbitals += f""" + {frag} + {subspecies or 'A'} {nremove} + SubEnd + End + """
+ + +
+[docs] + def run(self): + """ + Run the ``ADFFragmentJob``. This involves setting up the calculations for each fragment as well as the parent job. + It will also submit a calculation with the SCF iterations set to 0 in order to facilitate investigation of the field effects using PyOrb. + """ + # check if the user defined fragments for this job + + if len(self.childjobs) == 0: + log.warn("Fragments were not specified yet, trying to read them from the xyz file ...") + + # if they did not define the fragments, try to guess them using the xyz-file + if not self.guess_fragments(): + log.error("Please specify the fragments using ADFFragmentJob.add_fragment or specify them in the xyz file.") + raise + + mol_str = " + ".join([formula.molecule(child._molecule) for child in self.childjobs.values()]) + log.flow(f"ADFFragmentJob [{mol_str}]", ["start"]) + # obtain some system wide properties of the molecules + charge = sum([child.settings.input.ams.System.charge or 0 for child in self.childjobs.values()]) + unrestricted = any([(child.settings.input.adf.Unrestricted or "no").lower() == "yes" for child in self.childjobs.values()]) + spinpol = sum([child.settings.input.adf.SpinPolarization or 0 for child in self.childjobs.values()]) + log.flow(f"Level: {self._functional}/{self._basis_set}") + log.flow(f"Solvent: {self._solvent}") + log.flow(f"Charge: {charge}", ["straight"]) + log.flow(f"Unrestricted: {unrestricted}", ["straight"]) + log.flow(f"Spin-Polarization: {spinpol}", ["straight"]) + log.flow() + # this job and all its children should have the same value for unrestricted + [child.unrestricted(unrestricted) for child in self.child_jobs.values()] + + # propagate the post- and preambles to the child_jobs + [child.add_preamble(preamble) for preamble in self._preambles for child in self.child_jobs.values()] + [child.add_postamble(postamble) for postamble in self._postambles for child in self.child_jobs.values()] + + # we now update the child settings with the parent settings + # this is because we have to propagate settings such as functionals, basis sets etc. + sett = self.settings.as_plams_settings() # first create a plams settings object + # same for the children + child_setts = {name: child.settings.as_plams_settings() for name, child in self.child_jobs.items()} + # update the children using the parent settings + [child_sett.update(sett) for child_sett in child_setts.values()] + [child_sett.input.adf.pop("RemoveFragOrbitals", None) for child_sett in child_setts.values()] + [child_sett.input.adf.pop("RemoveAllFragVirtuals", None) for child_sett in child_setts.values()] + # same for sbatch settings + [child.sbatch(**self._sbatch) for child in self.child_jobs.values()] + # now set the charge, spinpol, unrestricted for the parent + self.charge(charge) + self.spin_polarization(spinpol) + self.unrestricted(unrestricted) + if unrestricted: + self.settings.input.adf.UnrestrictedFragments = "Yes" + + elstat_jobs = {} + + # now we are going to run each child job + for i, (child_name, child) in enumerate(self.child_jobs.items(), start=1): + # the child name will be prepended with SP showing that it is the singlepoint calculation + child.name = f'frag_{child_name}' + child.rundir = j(self.rundir, self.name) + + # # add the path to the child adf.rkf file as a dependency to the parent job + self.settings.input.adf.fragments[child_name] = j(child.workdir, 'adf.rkf') + + # recast the plams.Settings object into a Result object as that is what run expects + child.settings = results.Result(child_setts[child_name]) + log.flow(f'Fragment ({i}/{len(self.child_jobs)}) {child_name} [{formula.molecule(child._molecule)}]', ['split']) + log.flow(f'Charge: {child.settings.input.ams.System.charge}', ['straight', 'straight']) + log.flow(f'Spin-Polarization: {child.settings.input.adf.SpinPolarization}', ['straight', 'straight']) + log.flow(f'Work dir: {child.workdir}', ['straight', 'straight']) + if child.can_skip(): + log.flow(log.Emojis.warning + " Already ran, skipping", ["straight", "end"]) + log.flow() + else: + log.flow(log.Emojis.good + ' Submitting', ['straight', 'end']) + child.run() + self.dependency(child) + log.flow(f'SlurmID: {child.slurm_job_id}', ['straight', 'skip', 'end']) + log.flow() + + if self.decompose_elstat: + child_STOFIT = ADFJob(child) + child_STOFIT.name += '_STOFIT' + elstat_jobs[child_STOFIT.name] = child_STOFIT + child_STOFIT.settings.input.adf.STOFIT = '' + child_STOFIT.settings.input.adf.PRINT = 'SFOSiteEnergies Elstat' + child_STOFIT.settings.input.adf.pop("NumericalQuality") + child_STOFIT.settings.input.adf.BeckeGrid.Quality = "Excellent" + + log.flow(f'Fragment ({i}/{len(self.child_jobs)}) {child_name} [{formula.molecule(child._molecule)}] with STOFIT', ['split']) + log.flow(f'Charge: {child_STOFIT.settings.input.ams.System.charge}', ['straight', 'straight']) + log.flow(f'Spin-Polarization: {child_STOFIT.settings.input.adf.SpinPolarization}', ['straight', 'straight']) + log.flow(f'Work dir: {child_STOFIT.workdir}', ['straight', 'straight']) + + if child_STOFIT.can_skip(): + log.flow(log.Emojis.warning + ' Already ran, skipping', ['straight', 'end']) + log.flow() + else: + log.flow(log.Emojis.good + ' Submitting', ['straight', 'end']) + child_STOFIT.run() + self.dependency(child_STOFIT) + log.flow(f'SlurmID: {child_STOFIT.slurm_job_id}', ['straight', 'skip', 'end']) + log.flow() + + child_NoElectrons = ADFJob(child) + child_NoElectrons.name += '_NoElectrons' + elstat_jobs[child_NoElectrons.name] = child_NoElectrons + child_NoElectrons.settings.input.adf.STOFIT = '' + child_NoElectrons.settings.input.adf.PRINT = 'SFOSiteEnergies Elstat' + child_NoElectrons.charge(molecule.number_of_electrons(child_NoElectrons._molecule)) + child_NoElectrons.spin_polarization(0) + child_NoElectrons.settings.input.adf.pop("NumericalQuality") + child_NoElectrons.settings.input.adf.BeckeGrid.Quality = "Excellent" + + log.flow(f'Fragment ({i}/{len(self.child_jobs)}) {child_name} [{formula.molecule(child._molecule)}] without Electrons', ['split']) + log.flow(f'Charge: {child_NoElectrons.settings.input.ams.System.charge}', ['straight', 'straight']) + log.flow(f'Spin-Polarization: {child_NoElectrons.settings.input.adf.SpinPolarization}', ['straight', 'straight']) + log.flow(f'Work dir: {child_NoElectrons.workdir}', ['straight', 'straight']) + + if child_NoElectrons.can_skip(): + log.flow(log.Emojis.warning + ' Already ran, skipping', ['straight', 'end']) + log.flow() + else: + log.flow(log.Emojis.good + ' Submitting', ['straight', 'end']) + child_NoElectrons.run() + self.dependency(child_NoElectrons) + log.flow(f'SlurmID: {child_NoElectrons.slurm_job_id}', ['straight', 'skip', 'end']) + log.flow() + + # in the parent job the atoms should have the region and adf.f defined as options + atom_lines = [] + # for each atom we check which child it came from + for atom in self._molecule: + for child_name, child in self.child_jobs.items(): + for childatom in child._molecule: + # we check by looking at the symbol and coordinates of the atom + if (atom.symbol, atom.x, atom.y, atom.z) == (childatom.symbol, childatom.x, childatom.y, childatom.z): + # now write the symbol and coords as a string with the correct suffix + atom_lines.append(f'\t\t{atom.symbol} {atom.x} {atom.y} {atom.z} region={child_name} adf.f={child_name}') + + old_name = self.name + # write the atoms block as a string with new line characters + self.settings.input.ams.system.atoms = ("\n" + "\n".join(atom_lines) + "\n\tEnd").expandtabs(4) + # set the _molecule to None, otherwise it will overwrite the atoms block + self._molecule = None + # run this job + self.rundir = j(self.rundir, old_name) + self.name = 'complex' + log.flow(log.Emojis.good + ' Submitting parent job', ['split']) + + super().run() + log.flow(f"SlurmID: {self.slurm_job_id}", ["straight", "end"]) + log.flow() + + # also do the calculation with SCF cycles set to 1 + old_iters = self.settings.input.adf.SCF.Iterations or 300 + self.SCF(iterations=0) + # we must repopulate the sbatch settings for the new run + [self._sbatch.pop(key, None) for key in ["D", "chdir", "J", "job_name", "o", "output"]] + self.name = "complex_SCF0" + log.flow(log.Emojis.good + " Submitting extra job with 0 SCF iterations", ["split"]) + + super().run() + log.flow(f"SlurmID: {self.slurm_job_id}", ["straight", "end"]) + log.flow() + + # also do the calculation with no electrons on the fragments if the user requested a elstat decomposition + if self.decompose_elstat: + frag_names = self.child_jobs.keys() + # reset the SCF iterations + self.SCF(iterations=old_iters) + self.settings.input.adf.pop("NumericalQuality") + self.settings.input.adf.BeckeGrid.Quality = "Excellent" + [self._sbatch.pop(key, None) for key in ['D', 'chdir', 'J', 'job_name', 'o', 'output']] + self.name = 'complex_STOFIT' + + # set the region and fragment files correctly + atom_lines_ = [] + for line in atom_lines: + for frag in frag_names: + line = line.replace(frag, f'{frag}_STOFIT') + atom_lines_.append(line) + + self.settings.input.ams.system.atoms = ('\n' + '\n'.join(atom_lines_) + '\n\tEnd').expandtabs(4) + # set the fragment references correctly + self.settings.input.adf.pop('fragments') + for frag_name in frag_names: + self.settings.input.adf.fragments[frag_name + '_STOFIT'] = j(elstat_jobs['frag_' + frag_name + '_STOFIT'].workdir, 'adf.rkf') + self.settings.input.adf.STOFIT = '' + self.settings.input.adf.PRINT = 'SFOSiteEnergies Elstat' + + log.flow(log.Emojis.good + ' Submitting complex with STOFIT', ['split']) + super().run() + log.flow(f'SlurmID: {self.slurm_job_id}', ['straight', 'end']) + log.flow() + + for frag in frag_names: + # other_frags stores fragment names for fragments that keep their electrons + other_frags = [frag_ for frag_ in frag_names if frag_ != frag] + + # we must repopulate the sbatch settings for the new run + [self._sbatch.pop(key, None) for key in ['D', 'chdir', 'J', 'job_name', 'o', 'output']] + self.name = f'complex_{frag}_NoElectrons' + + # set the region and fragment files correctly + atom_lines_ = [] + for line in atom_lines: + line = line.replace(frag, f'{frag}_NoElectrons') + for other_frag in other_frags: + line = line.replace(other_frag, f'{other_frag}_STOFIT') + atom_lines_.append(line) + self.settings.input.ams.system.atoms = ('\n' + '\n'.join(atom_lines_) + '\n\tEnd').expandtabs(4) + + # set the fragment references correctly + self.settings.input.adf.pop('fragments') + self.settings.input.adf.fragments[frag + '_NoElectrons'] = j(elstat_jobs['frag_' + frag + '_NoElectrons'].workdir, 'adf.rkf') + for other_frag in other_frags: + self.settings.input.adf.fragments[other_frag + '_STOFIT'] = j(elstat_jobs['frag_' + other_frag + '_STOFIT'].workdir, 'adf.rkf') + + other_charge = sum([elstat_jobs['frag_' + other_frag + '_STOFIT'].settings.input.ams.System.charge for other_frag in other_frags]) + total_charge = other_charge + (elstat_jobs['frag_' + frag + '_NoElectrons'].settings.input.ams.System.charge) + self.charge(total_charge) + + other_spin_polarization = sum([elstat_jobs['frag_' + other_frag + '_STOFIT'].settings.input.adf.SpinPolarization for other_frag in other_frags]) + total_spin_polarization = other_spin_polarization + (elstat_jobs['frag_' + frag + '_NoElectrons'].settings.input.adf.SpinPolarization) + self.spin_polarization(total_spin_polarization) + + log.flow(log.Emojis.good + f' Submitting complex with 0 electrons in fragment {frag}', ['split']) + + super().run() + log.flow(f'SlurmID: {self.slurm_job_id}', ['straight', 'end']) + log.flow() + + log.flow(log.Emojis.finish + ' Done, bye!', ['startinv'])
+
+ + + +
+[docs] +class DensfJob(Job): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.settings = results.Result() + self.rundir = "tmp" + self.name = "densf" + self.gridsize() + self._mos = [] + self._sfos = [] + self.settings.ADFFile = None + + def __str__(self): + return f"Densf({self.target}), running in {self.workdir}" + +
+[docs] + def gridsize(self, size="medium"): + """ + Set the size of the grid to be used by Densf. + + Args: + size: either "coarse", "medium", "fine". Defaults to "medium". + """ + spell_check.check(size, ["coarse", "medium", "fine"], ignore_case=True) + self.settings.grid = size
+ + +
+[docs] + def orbital(self, orbital: "pyfmo.orbitals.sfo.SFO" or "pyfmo.orbitals.mo.MO"): # noqa: F821 + """ + Add a PyOrb orbital for Densf to calculate. + """ + import pyfmo + + if isinstance(orbital, (pyfmo.orbitals.sfo.SFO, pyfmo.orbitals2.objects.SFO)): + self._sfos.append(orbital) + elif isinstance(orbital, (pyfmo.orbitals.mo.MO, pyfmo.orbitals2.objects.MO)): + self._mos.append(orbital) + else: + raise TCJobError(job_class=self.__class__.__name__, message=f"Unknown object {orbital} of type{type(orbital)}. It should be a pyfmo.orbitals.sfo.SFO or pyfmo.orbitals.mos.MO object.") + + # check if the ADFFile is the same for all added orbitals + if self.settings.ADFFile is None: + self.settings.ADFFile = orbital.kfpath + + elif self.settings.ADFFile != orbital.kfpath: + raise TCJobError(job_class=self.__class__.__name__, message="RKF file that was previously set not the same as the one being set now. Please start a new job for each RKF file.")
+ + + def _setup_job(self): + os.makedirs(self.workdir, exist_ok=True) + + # set up the input file. This should always contain calling of the densf program, as per the SCM documentation + with open(self.inputfile_path, "w+") as inpf: + inpf.write("$AMSBIN/densf << eor\n") + inpf.write(f"ADFFile {self.settings.ADFFile}\n") + inpf.write(f"GRID {self.settings.grid}\n") + inpf.write("END\n") + + if len(self._mos) > 0: + inpf.write("Orbitals SCF\n") + for orb in self._mos: + inpf.write(f' {orb.symmetry} {orb.index_in_symlabel + 1}\n') + inpf.write('END\n') + + if len(self._sfos) > 0: + inpf.write("Orbitals SFO\n") + for orb in self._sfos: + inpf.write(f" {orb.symmetry} {orb.index}\n") + inpf.write("END\n") + # cuboutput prefix is always the original run directory containing the adf.rkf file and includes the grid size + inpf.write(f"CUBOUTPUT {os.path.split(self.settings.ADFFile)[0]}/{self.settings.grid}\n") + inpf.write("eor\n") + + # the runfile should simply execute the input file. + with open(self.runfile_path, "w+") as runf: + runf.write("#!/bin/sh\n\n") + runf.write("\n".join(self._preambles) + "\n\n") + runf.write(f"sh {self.inputfile_path}\n") + runf.write("\n".join(self._postambles)) + + return True + + @property + def output_cub_paths(self): + """ + The output cube file paths that will be/were calculated by this job. + """ + paths = [] + cuboutput = f"{os.path.split(self.settings.ADFFile)[0]}/{self.settings.grid}" + + for mo in self._mos: + spin_part = '' if mo.spin == 'AB' else f'_{mo.spin}' + paths.append(f'{cuboutput}%SCF_{mo.symmetry}{spin_part}%{mo.index_in_symlabel + 1}.cub') + + for sfo in self._sfos: + spin_part = '' if sfo.spin == 'AB' else f'_{sfo.spin}' + paths.append(f'{cuboutput}%SFO_{sfo.symmetry}{spin_part}%{sfo.index}.cub') + + return paths + +
+[docs] + def can_skip(self): + return all(os.path.exists(path) for path in self.output_cub_paths)
+
+ + + +if __name__ == "__main__": + # import pyfmo + + # orbs = pyfmo.orbitals.Orbitals('/Users/yumanhordijk/PhD/MM2024/calculations/IRC/pi_beta_trans_TS1/pi_beta/pi_beta_trans/complex.00039/adf.rkf') + # with DensfJob() as job: + # job.orbital(orbs.sfos['frag1(HOMO)']) + + with ADFFragmentJob() as job: + ... +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/ams.html b/docs/_build/html/_modules/tcutility/job/ams.html new file mode 100644 index 00000000..d77eca81 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/ams.html @@ -0,0 +1,595 @@ + + + + + + + + + + tcutility.job.ams — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.ams

+from scm import plams
+import tcutility
+from tcutility import log
+from tcutility.job.generic import Job
+import os
+import numpy as np
+from typing import List
+
+j = os.path.join
+
+
+
+[docs] +class AMSJob(Job): + ''' + This is the AMS base job which will serve as the parent class for ADFJob, DFTBJob and the future BANDJob. + It holds all methods related to changing the settings at the AMS level. It also handles preparing the jobs, e.g. writing runfiles and inputs. + ''' + def __str__(self): + return f'{self._task}({self._functional}/{self._basis_set}), running in {os.path.join(os.path.abspath(self.rundir), self.name)}' + +
+[docs] + def single_point(self): + ''' + Set the task of the job to single point. + ''' + self._task = 'SP' + self.settings.input.ams.task = 'SinglePoint'
+ + +
+[docs] + def transition_state(self, distances: list = None, angles: list = None, dihedrals: list = None, ModeToFollow: int = 1): + ''' + Set the task of the job to transition state search. Optionally you can give some TS coordinates to accelerate convergence. + By default also calculates the normal modes after convergence. + + Args: + distances: sequence of tuples or lists containing [atom_index1, atom_index2, factor]. Atom indices start at 1. + angles: sequence of tuples or lists containing [atom_index1, atom_index2, atom_index3, factor]. Atom indices start at 1. + dihedrals: sequence of tuples or lists containing [atom_index1, atom_index2, atom_index3, atom_index4, factor]. Atom indices start at 1. + ModeToFollow: the vibrational mode to follow during optimization. + ''' + self._task = 'TS' + self.settings.input.ams.task = 'TransitionStateSearch' + + self.settings.input.ams.TransitionStateSearch.ModeToFollow = ModeToFollow + + if distances is not None: + self.settings.input.ams.TransitionStateSearch.ReactionCoordinate.Distance = [" ".join([str(x) for x in dist]) for dist in distances] + if angles is not None: + self.settings.input.ams.TransitionStateSearch.ReactionCoordinate.Angle = [" ".join([str(x) for x in ang]) for ang in angles] + if dihedrals is not None: + self.settings.input.ams.TransitionStateSearch.ReactionCoordinate.Dihedral = [" ".join([str(x) for x in dihedral]) for dihedral in dihedrals] + + # for TS searches we quickly calculate the hessian with DFTB + self.settings.input.ams.GeometryOptimization.InitialHessian.Type = 'CalculateWithFastEngine' + self.vibrations(True) # also calculate vibrations by default
+ + +
+[docs] + def optimization(self): + ''' + Set the task of the job to geometry optimization. By default also calculates the normal modes after convergence. + ''' + self._task = 'GO' + self.settings.input.ams.task = 'GeometryOptimization' + self.settings.input.ams.GeometryOptimization.InitialHessian.Type = 'CalculateWithFastEngine' + self.vibrations(True)
+ + +
+[docs] + def IRC(self, direction: str = 'both', hess_file: str = None, step_size: float = 0.2, min_path_length: float = 0.1, max_points: int = 300): + ''' + Set the task of the job to intrinsic reaction coordinate (IRC). + + Args: + direction: the direction to take the first step into. By default it will be set to ``both``. + hess_file: the path to a ``.rkf`` file to read the Hessian from. This is the ``adf.rkf`` file for ADF calculations. + If set to ``None`` the Hessian will be calculated prior to starting the IRC calculation. + step_size: the size of the step taken between each constrained optimization. By default it will be set to ``0.2`` :math:`a_0\\sqrt{Da}`. + min_path_length: the length of the IRC path before switching to minimization. By default it will be set to ``0.1`` |angstrom|. + max_points: the maximum number of IRC points in a direction. Be default it is set to ``300``. + ''' + self._task = 'IRC' + self.settings.input.ams.task = 'IRC' + self.settings.input.ams.IRC.Direction = direction + if hess_file: + self.settings.input.ams.IRC.InitialHessian.File = hess_file + self.settings.input.ams.IRC.InitialHessian.Type = 'FromFile' + self.settings.input.ams.IRC.Step = step_size + self.settings.input.ams.IRC.MinPathLength = min_path_length + self.settings.input.ams.IRC.MaxPoints = max_points + + self.add_postscript(tcutility.job.postscripts.clean_workdir) + self.add_postscript(tcutility.job.postscripts.write_converged_geoms)
+ + +
+[docs] + def PESScan(self, distances: list = None, angles: list = None, dihedrals: list = None, sumdists: list = None, difdists: list = None, npoints: int = 10): + ''' + Set the task of the job to potential energy surface scan (PESScan). + + Args: + distances: sequence of tuples or lists containing ``[atom_index1, atom_index2, start, end]``. + Atom indices start at 1. Distances are given in |angstrom|. + angles: sequence of tuples or lists containing ``[atom_index1, atom_index2, atom_index3, start, end]``. + Atom indices start at 1. Angles are given in degrees + dihedrals: sequence of tuples or lists containing ``[atom_index1, atom_index2, atom_index3, atom_index4, start, end]``. + Atom indices start at 1. Angles are given in degrees + sumdists: sequence of tuples or lists containing ``[atom_index1, atom_index2, atom_index3, atom_index4, start, end]``. + Atom indices start at 1. Sum of distances is given in |angstrom|. + difdists: sequence of tuples or lists containing ``[atom_index1, atom_index2, atom_index3, atom_index4, start, end]``. + Atom indices start at 1. Difference of distances is given in |angstrom|. + npoints: the number of PES points to optimize. + + .. note:: + Currently we only support generating settings for 1-dimensional PESScans. + We will add support for N-dimensional PESScans later. + ''' + self._task = 'PESScan' + self.settings.input.ams.task = 'PESScan' + self.settings.input.ams.PESScan.ScanCoordinate.nPoints = npoints + if distances is not None: + self.settings.input.ams.PESScan.ScanCoordinate.Distance = [" ".join([str(x) for x in dist]) for dist in distances] + if angles is not None: + self.settings.input.ams.PESScan.ScanCoordinate.Angle = [" ".join([str(x) for x in ang]) for ang in angles] + if dihedrals is not None: + self.settings.input.ams.PESScan.ScanCoordinate.Dihedral = [" ".join([str(x) for x in dihedral]) for dihedral in dihedrals] + if sumdists is not None: + self.settings.input.ams.PESScan.ScanCoordinate.SumDist = [" ".join([str(x) for x in dist]) for dist in sumdists] + if difdists is not None: + self.settings.input.ams.PESScan.ScanCoordinate.DifDist = [" ".join([str(x) for x in dist]) for dist in difdists] + + self.add_postscript(tcutility.job.postscripts.clean_workdir) + self.add_postscript(tcutility.job.postscripts.write_converged_geoms)
+ + +
+[docs] + def vibrations(self, enable: bool = True, NegativeFrequenciesTolerance: float = -5): + ''' + Set the calculation of vibrational modes. + + Args: + enable: whether to calculate the vibrational modes. + NegativeFrequenciesTolerance: the tolerance for negative modes. + Modes with frequencies above this value will not be counted as imaginary. + Use this option when you experience a lot of numerical noise. + ''' + self.settings.input.ams.Properties.NormalModes = 'Yes' if enable else 'No' + self.settings.input.ams.Properties.PESPointCharacter = 'Yes' + self.settings.input.ams.PESPointCharacter.NegativeFrequenciesTolerance = NegativeFrequenciesTolerance + self.settings.input.ams.NormalModes.ReScanFreqRange = '-10000000.0 10.0'
+ + +
+[docs] + def geometry_convergence(self, gradients: float = 1e-5, energy: float = 1e-5, step: float = 1e-2, stress: float = 5e-4): + ''' + Set the convergence criteria for the geometry optimization. + + Args: + gradients: the convergence criteria for the gradients during geometry optimizations. Defaults to ``1e-5``. + energy: the convergence criteria for the energy during geometry optimizations. Defaults to ``1e-5``. + step: the convergence criteria for the step-size during geometry optimizations. Defaults to ``1e-2``. + stress: the convergence criteria for the stress-energy per atom during geometry optimizations. Defaults to ``5e-4`` + ''' + self.settings.input.ams.GeometryOptimization.Convergence.Gradients = gradients + self.settings.input.ams.GeometryOptimization.Convergence.Energy = energy + self.settings.input.ams.GeometryOptimization.Convergence.Step = step + self.settings.input.ams.GeometryOptimization.Convergence.StressEnergyPerAtom = stress
+ + +
+[docs] + def charge(self, val: int): + ''' + Set the charge of the system. + ''' + self.settings.input.ams.System.Charge = val
+ + +
+[docs] + def electric_field(self, direction: List[float], magnitude: float = None): + ''' + Set an electric field for this system. + + Args: + direction: the vector with the direction and strength of the electric field. + magnitude: if given, the direction will be normalized and magnitude will be used as the field strength. + ''' + # if magnitude is given we normalize the direction vector and give it the correct length + if magnitude is not None: + direction = np.array(direction)/np.linalg.norm(direction) * magnitude + + ex, ey, ez = tuple(direction) + self.settings.input.ams.System.ElectrostaticEmbedding.ElectricField = f'{ex} {ey} {ez}'
+ + + def _setup_job(self): + ''' + Set up the calculation. This will create the working directory and write the runscript and input file for ADF to use. + ''' + os.makedirs(self.rundir, exist_ok=True) + + if os.path.exists(self.workdir): + for file in os.listdir(self.workdir): + p = os.path.join(self.workdir, file) + if p.endswith('.rkf'): + os.remove(p) + if 'ams.kid' in p: + os.remove(p) + if p.startswith('t21.'): + os.remove(p) + if p.startswith('t12.'): + os.remove(p) + + if not self._molecule and not self._molecule_path and 'atoms' not in self.settings.input.ams.system: + log.error(f'You did not supply a molecule for this job. Call the {self.__class__.__name__}.molecule method to add one.') + return + + if not self._molecule: + self.settings.input.ams.system.GeometryFile = self._molecule_path + + # sometimes we have to check if a job is able to run or requires some special consideration + # those types of checks should be defined in _check_job + self._check_job() + + # we will use plams to write the input and runscript + sett = self.settings.as_plams_settings() + job = plams.AMSJob(name=self.name, molecule=self._molecule, settings=sett) + + os.makedirs(self.workdir, exist_ok=True) + with open(self.inputfile_path, 'w+') as inpf: + inpf.write(job.get_input()) + + with open(self.runfile_path, 'w+') as runf: + runf.write('#!/bin/sh\n\n') # the shebang is not written by default by ADF + runf.write('\n'.join(self._preambles) + '\n\n') + runf.write(job.get_runscript()) + runf.write('\n'.join(self._postambles)) + + # in case we are rerunning a calculation we need to remove ams.log + if os.path.exists(j(self.workdir, 'ams.log')): + os.remove(j(self.workdir, 'ams.log')) + + return True + + def _check_job(self): + ... + + @property + def output_mol_path(self): + ''' + The default file path for output molecules when running ADF calculations. It will not be created for singlepoint calculations. + ''' + return j(self.workdir, 'output.xyz')
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/crest.html b/docs/_build/html/_modules/tcutility/job/crest.html new file mode 100644 index 00000000..7d3542f8 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/crest.html @@ -0,0 +1,651 @@ + + + + + + + + + + tcutility.job.crest — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.crest

+from scm import plams
+from tcutility.data import molecules
+from tcutility.job.generic import Job
+from tcutility import log
+import os
+
+
+j = os.path.join
+
+
+
+[docs] +class CRESTJob(Job): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.crest_path = 'crest' + self.xtb_path = 'xtb' + self._charge = 0 + self._spinpol = 0 + self._temp = 400 + self._mdlen = 'x1' + + def _setup_job(self): + self.add_postamble('mkdir rotamers') + self.add_postamble('mkdir conformers') + self.add_postamble(f'split -d -l {len(self._molecule.atoms) + 2} -a 5 crest_conformers.xyz conformers/') + self.add_postamble(f'split -d -l {len(self._molecule.atoms) + 2} -a 5 crest_rotamers.xyz rotamers/') + + self.add_postamble('for file in conformers/* rotamers/*') + self.add_postamble('do') + self.add_postamble(' mv "$file" "$file.xyz"') + self.add_postamble('done') + + os.makedirs(self.workdir, exist_ok=True) + + self._molecule.write(j(self.workdir, 'coords.xyz')) + + options = [ + 'coords.xyz', + f'-xnam "{self.xtb_path}"', + '--noreftopo', + f'-c {self._charge}', + f'-u {self._spinpol}', + f'-tnmd {self._temp}', + f'-mdlen {self._mdlen}', + ] + + options = ' '.join(options) + + with open(self.runfile_path, 'w+') as runf: + runf.write('#!/bin/sh\n\n') # the shebang is not written by default by ADF + runf.write('\n'.join(self._preambles) + '\n\n') + runf.write(f'{self.crest_path} {options}\n') + runf.write('\n'.join(self._postambles)) + + return True + +
+[docs] + def spin_polarization(self, val: int): + ''' + Set the spin-polarization of the system. + ''' + self._spinpol = val
+ + +
+[docs] + def multiplicity(self, val: int): + ''' + Set the multiplicity of the system. If the value is not one the calculation will also be unrestricted. + We use the following values: + + 1) singlet + 2) doublet + 3) triplet + 4) ... + + The multiplicity is equal to 2*S+1 for spin-polarization of S. + ''' + self._spinpol = (val - 1)//2
+ + +
+[docs] + def charge(self, val: int): + ''' + Set the charge of the system. + ''' + self._charge = val
+ + +
+[docs] + def md_temperature(self, val: float): + ''' + Set the temperature of the molecular dynamics steps. Defaults to 400K. + ''' + self._temp = val
+ + +
+[docs] + def md_length(self, val: float): + ''' + Set the length of the molecular dynamics steps. The default length will be multiplied by this value, e.g. the default value is 1. + ''' + self._mdlen = f'x{val}'
+ + + @property + def best_conformer_path(self): + return j(self.workdir, 'crest_best.xyz') + + @property + def conformer_directory(self): + return j(self.workdir, 'conformers') + + @property + def rotamer_directory(self): + return j(self.workdir, 'rotamers') + +
+[docs] + def get_conformer_xyz(self, number: int = None): + ''' + Return paths to conformer xyz files for this job. + + Args: + number: the number of files to return, defaults to 10. If the directory already exists, for example if the job was already run, we will return up to `number` files. + ''' + if os.path.exists(self.conformer_directory): + return [j(self.conformer_directory, file) for i, file in enumerate(sorted(os.listdir(self.conformer_directory)))] + + for i in range(number or 10): + yield j(self.conformer_directory, f'{str(i).zfill(5)}.xyz')
+ + +
+[docs] + def get_rotamer_xyz(self, number: int = None): + ''' + Return paths to rotamer xyz files for this job. + + Args: + number: the number of files to return, defaults to 10. If the directory already exists, for example if the job was already run, we will return up to `number` files. + ''' + if os.path.exists(self.rotamer_directory): + return [j(self.rotamer_directory, file) for i, file in enumerate(os.listdir(self.rotamer_directory))] + + for i in range(number or 10): + yield j(self.rotamer_directory, f'{str(i).zfill(5)}.xyz')
+
+ + + +
+[docs] +class QCGJob(CRESTJob): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.crest_path = 'crest' + self._nsolv = 10 + self._fix_solute = False + self._ensemble_generation_mode = 'NCI-MTD' + self._solvent = None + self._nofix = True + +
+[docs] + def solvent(self, mol, nsolv=None): + if self._nsolv: + self._nsolv = nsolv + + if isinstance(mol, plams.Molecule): + self._solvent = mol + + elif isinstance(mol, str) and os.path.exists(mol): + self._solvent = plams.Molecule(mol) + + elif isinstance(mol, str): + # here we can get the molecule name using tcutility.data.molecules + self._solvent = molecules.get(mol) + # we can check if the alpb solvent name is defined in the xyz file + alpb = self._solvent.flags.get('alpb', None) + if alpb: + self.alpb(alpb) + + elif isinstance(mol, list) and isinstance(mol[0], plams.Atom): + self._solvent = plams.Molecule() + [self._solvent.add_atom(atom) for atom in mol] + + elif isinstance(mol, plams.Atom): + self._solvent = plams.Molecule() + self._solvent.add_atom(mol)
+ + +
+[docs] + def nsolv(self, nsolv): + self._nsolv = nsolv
+ + +
+[docs] + def alpb(self, solvent): + self._alpb = solvent
+ + +
+[docs] + def ensemble_mode(self, mode): + self._ensemble_generation_mode = mode
+ + +
+[docs] + def nofix(self, enable=True): + self._nofix = enable
+ + + def _setup_job(self): + self.add_postamble('mkdir ensemble/ensemble') + self.add_postamble(f'split -d -l {len(self._molecule.atoms) + len(self._solvent.atoms) * self._nsolv + 2} -a 5 ensemble/final_ensemble.xyz ensemble/ensemble') + + self.add_postamble('for file in ensemble/ensemble/*') + self.add_postamble('do') + self.add_postamble(' mv "$file" "$file.xyz"') + self.add_postamble('done') + + if not self._solvent: + log.error(f'Did not provide a solvent molecule for this job. Call the {self.__class__.__name__}.solvent method to add one.') + + os.makedirs(self.workdir, exist_ok=True) + + self._molecule.write(j(self.workdir, 'coords.xyz')) + self._solvent.write(j(self.workdir, 'solvent.xyz')) + + ensemble_mode_option = { + 'NCI-MTD': '--ncimtd', + 'MD': '--md', + 'MTD': '--mtd', + }.get(self._ensemble_generation_mode, self._ensemble_generation_mode) + + options = [ + 'coords.xyz', + f'-xnam "{self.xtb_path}"', + '--qcg solvent.xyz', + '--ensemble', + f'--nsolv {self._nsolv}', + f'--chrg {self._charge}', + f'--uhf {self._spinpol}', + f'--tnmd {self._temp}', + f'--mdlen {50 * float(self._mdlen[1:])}', + ensemble_mode_option, + ] + + if self._alpb: + options.append(f'--alpb {self._alpb}') + + if self._nofix: + options.append('--nofix') + + options = ' '.join(options) + + with open(self.runfile_path, 'w+') as runf: + runf.write('#!/bin/sh\n\n') + runf.write('\n'.join(self._preambles) + '\n\n') + runf.write(f'{self.crest_path} {options}\n') + runf.write('\n'.join(self._postambles)) + + return True + + @property + def ensemble_directory(self): + return j(self.workdir, 'ensemble', 'ensemble') + +
+[docs] + def get_ensemble_xyz(self, number: int = None): + ''' + Return paths to conformer xyz files for this job. + + Args: + number: the number of files to return, defaults to 10. If the directory already exists, for example if the job was already run, we will return up to `number` files. + ''' + if os.path.exists(self.ensemble_directory): + return [j(self.ensemble_directory, file) for i, file in enumerate(sorted(os.listdir(self.ensemble_directory)))] + + for i in range(number or 10): + yield j(self.ensemble_directory, f'{str(i).zfill(5)}.xyz')
+ + + @property + def best_ensemble_path(self): + return j(self.workdir, 'ensemble', 'ensemble', 'crest_best.xyz')
+ + + +if __name__ == '__main__': + # with CRESTJob() as job: + # job.rundir = 'tmp/SN2' + # job.name = 'CREST' + # job.molecule('../../../test/fixtures/xyz/transitionstate_radical_addition.xyz') + # job.sbatch(p='tc', ntasks_per_node=32) + + with QCGJob(test_mode=True) as job: + job.rundir = 'calculations/Ammonia' + job.name = 'QCG' + job.molecule('ammonia.xyz') + job.solvent('water', 10) + print(job._solvent) + job.sbatch(p='tc', n=32) + + # for i in range(40): + # with CRESTJob(test_mode=False, overwrite=True) as job: + # job.rundir = 'tmp/SN2' + # job.name = 'CREST' + # job.molecule('../../../test/fixtures/xyz/transitionstate_radical_addition.xyz') + # job.sbatch(p='tc', ntasks_per_node=32) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/dftb.html b/docs/_build/html/_modules/tcutility/job/dftb.html new file mode 100644 index 00000000..feb5f068 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/dftb.html @@ -0,0 +1,421 @@ + + + + + + + + + + tcutility.job.dftb — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.dftb

+from tcutility.job.ams import AMSJob
+from tcutility import results
+import os
+
+
+j = os.path.join
+
+
+
+[docs] +class DFTBJob(AMSJob): + ''' + Setup and run a density functional with tight-binding (DFTB) calculation as implemented in the Amsterdam modelling suite (AMS). + This class supports all methods of the parent :class:`AMSJob <tcutility.job.ams.AMSJob>`. + ''' + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.settings = results.Result() + self._model = None + self.kspace('Good') + self.single_point() + self.model('GFN1-xTB') + self.solvent('vacuum') + +
+[docs] + def kspace(self, quality: str = 'Good'): + ''' + Set the k-space integration quality for this job. + + Args: + quality: the type of basis-set to use. Default is ``Good``. + ''' + self.settings.input.DFTB.kspace.quality = quality
+ + +
+[docs] + def model(self, name: str = 'GFN1-xTB', dispersion: str = None, parameter_dir: str = None): + ''' + Set the model Hamiltonian for the job to use. + + Args: + name: name of the model Hamiltonian. This is the same name as the one in the DFTB gui. Default is ``GFN1-xTB``. + ''' + self.settings.input.DFTB.Model = name + + if dispersion is None: + for disp_suffix in ['-UFF', '-ULG', '-D2', '-D3-BJ', '-D4', '-Auto']: + if not name.endswith(disp_suffix): + continue + self.settings.input.DFTB.DispersionCorrection = disp_suffix[1:] + self.settings.input.DFTB.Model[:-len(disp_suffix)] + else: + self.settings.input.DFTB.DispersionCorrection = dispersion + + if parameter_dir: + self.settings.input.DFTB.ResourcesDir = parameter_dir
+ + +
+[docs] + def solvent(self, name: str = None, grid_size=974): + ''' + Model solvation using the GBSA model. + + Args: + name: the name of the solvent you want to use. Must be ``None``, ``Acetone``, ``Acetonitrile``, ``CHCl3``, ``CS2``, ``DMSO``, ``Ether``, ``H2O``, ``Methanol``, ``THF`` or ``Toluene``. + grid_size: the size of the grid used to construct the solvent accessible surface. Must be ``230``, ``974``, ``2030`` or ``5810``. + ''' + if name == 'vacuum': + self.settings.input.DFTB.pop('solvation', None) + return + + self.settings.input.DFTB.Solvation.Solvent = name + self.settings.input.DFTB.Solvation.SurfaceGrid = grid_size
+
+ + + +if __name__ == '__main__': + with DFTBJob(test_mode=False, overwrite=True) as job: + job.rundir = 'tmp/SN2' + job.name = 'DFTB' + job.molecule('../../../test/fixtures/xyz/transitionstate_radical_addition.xyz') + job.sbatch(p='tc', ntasks_per_node=15) + job.model('GFN1-xTB') + job.optimization() + job.kspace('Good') + job.solvent('H2O') +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/generic.html b/docs/_build/html/_modules/tcutility/job/generic.html new file mode 100644 index 00000000..88b62931 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/generic.html @@ -0,0 +1,692 @@ + + + + + + + + + + tcutility.job.generic — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.generic

+import os
+import shutil
+import stat
+import subprocess as sp
+from typing import List, Union
+
+import dictfunc
+from scm import plams
+
+from tcutility import log, molecule, results, slurm
+from tcutility.environment import OSName, get_os_name
+from tcutility.errors import TCJobError
+
+j = os.path.join
+
+
+def _python_path():
+    """
+    Sometimes it is necessary to have the Python path as some environments don't have its path.
+    This function attempts to find the Python path and returns it.
+    """
+    python = sp.run("which python", shell=True, capture_output=True).stdout.decode().strip()
+
+    if python == "" or not os.path.exists(python):
+        python = sp.run("which python3", shell=True, capture_output=True).stdout.decode().strip()
+
+    # we default to the python executable
+    if python == "" or not os.path.exists(python):
+        python = "python"
+
+    return python
+
+
+
+[docs] +class Job: + """This is the base Job class used to build more advanced classes such as :class:`AMSJob <tcutility.job.ams.AMSJob>` and :class:`ORCAJob <tcutility.job.orca.ORCAJob>`. + The base class contains an empty :class:`Result <tcutility.results.result.Result>` object that holds the settings. + It also provides :meth:`__enter__` and :meth:`__exit__` methods to make use of context manager syntax. + + All class methods are in principle safe to overwrite, but the :meth:`_setup_job` method **must** be overwritten. + + Args: + test_mode: whether to enable the testing mode. If enabled, the job will be setup like normally, but the running step is skipped. This is useful if you want to know what the job settings look like before running the real calculations. + overwrite: whether to overwrite a previously run job in the same working directory. + wait_for_finish: whether to wait for this job to finish running before continuing your runscript. + delete_on_finish: whether to remove the workdir for this job after it is finished running. + """ + + def __init__( + self, *base_jobs: List["Job"], test_mode: bool = None, overwrite: bool = None, wait_for_finish: bool = None, delete_on_finish: bool = None, delete_on_fail: bool = None, use_slurm: bool = True + ): + self._sbatch = results.Result() + self._molecule = None + self._molecule_path = None + self.slurm_job_id = None + self.name = "calc" + self.rundir = "tmp" + self._preambles = [] + self._postambles = [] + self._postscripts = [] + + self.test_mode = test_mode + self.overwrite = overwrite + self.wait_for_finish = wait_for_finish + self.delete_on_finish = delete_on_finish + self.use_slurm = use_slurm + + # update this job with base_jobs + for base_job in base_jobs: + self.__dict__.update(base_job.copy().__dict__) + + self.test_mode = self.test_mode if test_mode is None else test_mode + self.overwrite = self.overwrite if overwrite is None else overwrite + self.wait_for_finish = self.wait_for_finish if wait_for_finish is None else wait_for_finish + self.delete_on_finish = self.delete_on_finish if delete_on_finish is None else delete_on_finish + self.delete_on_fail = delete_on_fail if delete_on_fail is None else delete_on_fail + self.use_slurm = self.use_slurm if use_slurm is None else use_slurm + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + if exc_type: + fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] + log.error(f'Job set-up failed with exception: {exc_type.__name__}({exc_value}) in File "{fname}", line {exc_tb.tb_lineno}.') + return True + self.run() + +
+[docs] + def can_skip(self): + """ + Check whether the job can be skipped. We check this by loading the calculation and checking if the job status was fatal. + Fatal in this case means that the job failed, canceled or could not be found. In those cases we want to run the job. + + .. note:: + This method works for the :class:`ADFJob <tcutility.job.adf.ADFJob>`, :class:`ADFFragmentJob <tcutility.job.adf.ADFFragmentJob>`, + :class:`DFTBJob <tcutility.job.dftb.DFTBJob>` and :class:`ORCAJob <tcutility.job.orca.ORCAJob>` objects, but not + yet for :class:`CRESTJob <tcutility.job.crest.CRESTJob>` and :class:`QCGJob <tcutility.job.crest.QCGJob>`. For the latter objects the job will always be rerun. + This will be fixed in a later version of TCutility. + """ + res = results.read(self.workdir) + return not res.status.fatal
+ + +
+[docs] + def in_queue(self): + """ + Check whether the job is currently managed by slurm. + We check this by loading the calculation and checking if the job status is 'RUNNING', 'COMPLETING', 'CONFIGURING' or 'PENDING'. + """ + res = results.read(self.workdir) + return res.status.name in ["RUNNING", "COMPLETING", "CONFIGURING", "PENDING"]
+ + + def __repr__(self): + return f"{type(self)}(name={self.name}, rundir={self.rundir})" + +
+[docs] + def sbatch(self, **kwargs): + """ + Change slurm settings, for example, to change the partition or change the number of cores to use. + The arguments are the same as you would use for sbatch (`see sbatch manual <https://slurm.schedmd.com/sbatch.html>`_). E.g. to change the partition to 'tc' call: + + ``job.sbatch(p='tc')`` or ``job.sbatch(partition='tc')``. + + Flags can be set as arguments with a boolean to enable or disable them: + + ``job.sbatch(exclusive=True)`` will set the ``--exclusive`` flag. + + .. warning:: + + Note that some sbatch options, such as ``--job-name`` contain a dash, which cannot be used in Python arguments. + To use these options you should use an underscore, like ``job.sbatch(job_name='water_dimer_GO')``. + + .. note:: + + When running the job using sbatch we add a few extra default options: + + * ``-D/--chdir {self.workdir}`` to make sure the job starts in the correct directory + * ``-J/--job-name {self.rundir}/{self.name}`` to give a nicer job-name when calling squeue + * ``-o/--output {self.name}.out`` to redirect the output from the default slurm-{id}.out + + You can still overwrite them if you wish. + """ + for key, value in kwargs.items(): + if key == "dependency" and "dependency" in self._sbatch: + value = self._sbatch["dependency"] + "," + value + self._sbatch[key] = value
+ + + def _setup_job(self): + """ + Set up the current job. This method should create the working directory, runscript and input file. + Method must return True if it was successful. + """ + raise NotImplementedError("You must implement the _setup_job method in your subclass.") + +
+[docs] + def run(self): + """ + Run this job. We detect if we are using slurm. If we are we submit this job using sbatch. Otherwise, we will run the job locally. + """ + if self.overwrite: + shutil.rmtree(self.workdir) + os.makedirs(self.workdir, exist_ok=True) + + if self.can_skip(): + log.info(f"Skipping calculation {j(self.rundir, self.name)}, it is already finished or currently pending or running.") + return + + # write the post-script calls to the post-ambles: + if self.delete_on_finish: + self.add_postamble(f"rm -r {self.workdir}") + + if self.delete_on_fail: + self.add_postamble("# this will delete the calculation if it failed") + self.add_postamble(f"if [[ `tc read -s {self.workdir}` = FAILED || `tc read -s {self.workdir}` = UNKNOWN ]]; then rm -r {self.workdir}; fi;") + + for postscript in self._postscripts: + self._postambles.append(f'{_python_path()} {postscript[0]} {" ".join(postscript[1])}') + + # setup the job and check if it was successfull + setup_success = self._setup_job() + + if self.test_mode or not setup_success: + return + + if slurm.has_slurm() and self.use_slurm: + # set some default sbatch settings + if any(option not in self._sbatch for option in ["D", "chdir"]): + self._sbatch.setdefault("D", self.workdir) + if any(option not in self._sbatch for option in ["J", "job_name"]): + self._sbatch.setdefault("J", f"{self.rundir}/{self.name}") + if any(option not in self._sbatch for option in ["o", "output"]): + self._sbatch.setdefault("o", f"{self.name}.out") + self._sbatch.prune() + + # submit the job with sbatch + sbatch_result = slurm.sbatch(os.path.split(self.runfile_path)[1], **self._sbatch) + + # store the slurm job ID + self.slurm_job_id = sbatch_result.id + # and write the command to a file so we can rerun it later + with open(j(self.workdir, "submit.sh"), "w+") as cmd_file: + cmd_file.write(sbatch_result.command) + # make the submit command executable + os.chmod(j(self.workdir, "submit.sh"), stat.S_IRWXU) + + # if we requested the job to hold we will wait for the slurm job to finish + if self.wait_for_finish: + slurm.wait_for_job(self.slurm_job_id) + else: + os_name = get_os_name() + + if os_name == OSName.Windows: + raise TCJobError("Generic Job", "Running jobs on Windows is not supported.") + + # if we are not using slurm, we can execute the file. For this we need special permissions, so we have to set that first. + os.chmod(self.runfile_path, os.stat(self.runfile_path).st_mode | stat.S_IEXEC) + + runfile_dir, runscript = os.path.split(self.runfile_path) + command = ["./" + runscript] if os.name == "posix" else ["sh", runscript] + print(f"Running command: {command} in directory: {runfile_dir}") + + with open(f"{os.path.split(self.runfile_path)[0]}/{self.name}.out", "w+") as out: + sp.run(command, cwd=runfile_dir, stdout=out, shell=True)
+ + +
+[docs] + def add_preamble(self, line: str): + """ + Add a preamble for the runscript. This should come after the shebang, but before the calculation is ran by the program (ADF or ORCA). + This can used, for example, to load some modules. E.g. to load a specific version of AMS we can call: + job.add_preamble('module load ams/2023.101') + """ + self._preambles.append(line)
+ + +
+[docs] + def add_postamble(self, line: str): + """ + Add a postamble for the runscript. This should come after the calculation is ran by the program (ADF or ORCA). + This can be used, for example, to remove or copy some files. E.g. to remove all t12.* files we can call: + job.add_postamble('rm t12.*') + """ + self._postambles.append(line)
+ + +
+[docs] + def add_postscript(self, script, *args): + """ + Add a post-script to this calculation. + This should be either a Python module with a __file__ attribute or the path to a Python script. + The post-script will be called with Python and any given args will be added as arguments when calling the script. + + Args: + script: a Python object with a __file__ attribute or the file-path to a script. + *args: positional arguments to pass to the post-script. + """ + if not isinstance(script, str): + script = script.__file__ + self._postscripts.append((script, args))
+ + +
+[docs] + def dependency(self, otherjob: "Job"): + """ + Set a dependency between this job and otherjob. + This means that this job will run after the other job is finished running succesfully. + """ + if otherjob.can_skip() and not otherjob.in_queue(): + return + + if hasattr(otherjob, "slurm_job_id"): + self.sbatch(dependency=f"afterok:{otherjob.slurm_job_id}") + self.sbatch(kill_on_invalid_dep="Yes")
+ + + @property + def workdir(self): + """ + The working directory of this job. All important files are written here, for example the input file and runscript. + """ + return j(os.path.abspath(self.rundir), self.name) + + @property + def runfile_path(self): + """ + The file path to the runscript of this job. + """ + return j(self.workdir, f"{self.name}.run") + + @property + def inputfile_path(self): + """ + The file path to the input file of this job. + """ + return j(self.workdir, f"{self.name}.in") + + @property + def output_mol_path(self): + """ + This method should return the name of the output molecule if it makes sense to give it back. + E.g. for ADF it will be output.xyz in the workdir for optimization jobs. + """ + raise NotImplementedError("You must implement the _setup_job method in your subclass.") + +
+[docs] + def molecule(self, mol: Union[str, plams.Molecule, plams.Atom, List[plams.Atom]]): + """ + Add a molecule to this calculation in various formats. + + Args: + mol: the molecule to read, can be a path (str). If the path exists already we read it. If it does not exist yet, it will be read in later. mol can also be a plams.Molecule object or a single or a list of plams.Atom objects. + """ + if isinstance(mol, plams.Molecule): + self._molecule = mol + + elif isinstance(mol, str) and os.path.exists(mol): + self._molecule = molecule.load(mol) + + elif isinstance(mol, str): + self._molecule_path = os.path.abspath(mol) + + elif isinstance(mol, list) and isinstance(mol[0], plams.Atom): + self._molecule = plams.Molecule() + [self._molecule.add_atom(atom) for atom in mol] + + elif isinstance(mol, plams.Atom): + self._molecule = plams.Molecule() + self._molecule.add_atom(mol)
+ + +
+[docs] + def copy(self): + """ + Make and return a copy of this object. + """ + import copy + + cp = Job() + # cast this object to a list of keys and values + lsts = dictfunc.dict_to_list(self.__dict__) + # copy everthing in the lists + lsts = [[copy.copy(x) for x in lst] for lst in lsts] + # and return a new result object + cp.__dict__.update(results.Result(dictfunc.list_to_dict(lsts))) + return cp
+
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/nmr.html b/docs/_build/html/_modules/tcutility/job/nmr.html new file mode 100644 index 00000000..981878bd --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/nmr.html @@ -0,0 +1,430 @@ + + + + + + + + + + tcutility.job.nmr — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.nmr

+import os
+from typing import Tuple
+
+from tcutility.job.adf import ADFJob
+from tcutility.job.generic import Job
+
+j = os.path.join
+
+
+
+[docs] +class NMRJob(Job): + """ + A job that handles calculation of Nuclear Magnetic Resonance (NMR) chemical shifts. + The job will first run an :class:`tcutility.job.adf.ADFJob` calculation at the SAOP/TZ2P level of theory to prepare for the NMR program of AMS. + The NMR shifts will be calculated for all atoms and any additional coordinate (NICS). + New NICS points can be given using the :meth:`NMRJob.add_nics_point` method. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.pre_nmr_job = ADFJob(*args, **kwargs) + self.pre_nmr_job.functional("SAOP") + self.pre_nmr_job.basis_set("TZ2P") + self.pre_nmr_job.settings.input.adf.save = "TAPE10" + self.nics_points = [] + + def _setup_job(self): + os.makedirs(self.workdir, exist_ok=True) + + # set up the pre_nmr_job + self.pre_nmr_job.rundir = self.rundir + self.pre_nmr_job.name = self.name + "_pre" + self.pre_nmr_job.molecule(self._molecule or self._molecule_path) + self.pre_nmr_job.sbatch(**self._sbatch) + + # we have to add the NICS points in the pre_nmr_job + multipole_coords = [] + for point in self.nics_points: + multipole_coords.append(f" {point[0]} {point[1]} {point[2]} 0.0") + self.pre_nmr_job.settings.input.ams.System.ElectrostaticEmbedding.MultipolePotential.Coordinates = "\n" + "\n".join(multipole_coords) + "\n End" + + # we copy the pre_nmr_job output files to the main job directory + self.pre_nmr_job.add_postamble(f'cp {j(self.pre_nmr_job.workdir, "adf.rkf")} {j(self.workdir, "TAPE21")}') + self.pre_nmr_job.add_postamble(f'cp {j(self.pre_nmr_job.workdir, "TAPE10")} {j(self.workdir, "TAPE10")}') + self.pre_nmr_job.run() + + # some extra settings for the main job + self.dependency(self.pre_nmr_job) + # NMR will name the calculation as TAPE21 instead of adf.rkf, so we rename it here + self.add_postamble(f'mv {j(self.workdir, "TAPE21")} {j(self.workdir, "adf.rkf")}') + + # write the input for the NMR job + # the ghost block holds the NICS points + ghost_block = "\t" + if len(self.nics_points) > 0: + ghost_block += "Ghosts\n" + for point in self.nics_points: + ghost_block += f" {point[0]} {point[1]} {point[2]}\n" + ghost_block += "SubEnd\n" + + # write input and runfile + with open(self.inputfile_path, "w+") as inpf: + inpf.write("NMR\n") + inpf.write("\tout all\n") + inpf.write(ghost_block + "\n") + inpf.write("End\n") + + with open(self.runfile_path, "w+") as runf: + runf.write("#!/bin/sh\n\n") # the shebang is not written by default by ADF + runf.write("\n".join(self._preambles) + "\n\n") + runf.write(f"$AMSBIN/nmr {self.inputfile_path} < /dev/null\n") + runf.write("\n".join(self._postambles)) + + return True + +
+[docs] + def add_nics_point(self, coordinate: Tuple[float, float, float]): + """ + Add a NICS point to be calculated. + + Args: + coordinate: the (x, y, z) coordinates of a NICS point to calculate the chemical shift for. Has to be given as cartesian coordinates and using unit angstrom. + """ + self.nics_points.append(coordinate)
+
+ + + +if __name__ == "__main__": + with NMRJob(test_mode=True) as job: + job.molecule(r"D:\Users\Yuman\Desktop\PhD\TCutility\examples\job\water_dimer.xyz") + job.add_nics_point([0, 1, 2]) + job.add_nics_point([0, 1, 2]) + job.add_nics_point([0, 1, 2]) + job.add_nics_point([0, 1, 2]) + job.add_nics_point([0, 1, 2]) + job.add_nics_point([0, 1, 2]) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/orca.html b/docs/_build/html/_modules/tcutility/job/orca.html new file mode 100644 index 00000000..25b0bfa9 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/orca.html @@ -0,0 +1,622 @@ + + + + + + + + + + tcutility.job.orca — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.orca

+import os
+import subprocess as sp
+from typing import List, Union
+
+from scm import plams
+
+from tcutility import ensure_list, log, results, slurm, spell_check
+from tcutility.errors import TCMoleculeError
+from tcutility.job.generic import Job
+
+j = os.path.join
+
+
+
+[docs] +class ORCAJob(Job): + def __init__(self, use_tmpdir=False, *args, **kwargs): + super().__init__(*args, **kwargs) + self.settings = results.Result() + self.settings.main = set() + self._charge = 0 + self._multiplicity = 1 + self._ghosts = [] + self._method = None + self.memory = None + self.processes = None + self.orca_path = None + self.use_tmpdir = use_tmpdir + + self.single_point() + +
+[docs] + def main(self, val: Union[str, List[str]]): + """ + Add main options for this ORCA calculation, they will be added to the input prepended with exclamation marks. + + Args: + val: the main options to add. This can be a string or a list of strings with the main options. + """ + # we want to split a string such as 'CC-pVTZ Opt CCSD(T)' into loose parts and add them separately + # this should always return a list + if isinstance(val, str): + val = val.split() + # add each + [self.settings.main.add(key) for key in val]
+ + +
+[docs] + def remove_main(self, val: Union[str, List[str]]): + if isinstance(val, str): + val = val.split() + + lower_main = {key.casefold(): key for key in self.settings.main} + for v in val: + if v.casefold() in lower_main: + self.settings.main.discard(lower_main[v.casefold()])
+ + + def __remove_task(self): + [self.remove_main(task) for task in ["sp", "opt", "optts", "neb-ts"]] + +
+[docs] + def method(self, method): + spell_check.check(method, ["HF", "MP2", "CCSD", "CCSD(T)", "CCSDT"]) + self.settings.main.add(method) + self._method = method
+ + +
+[docs] + def reference(self, ref): + spell_check.check(ref, ["UNO", "UHF", "UKS", "RHF", "RKS", "ROHF", "ROKS"]) + self.settings.main.add(ref) + self._method = ref
+ + +
+[docs] + def QRO(self, enable=True): + self.settings.MDCI.UseQROs = enable
+ + +
+[docs] + def basis_set(self, value): + self.settings.main.add(value)
+ + +
+[docs] + def single_point(self): + self.__remove_task() + self.settings.main.add("SP")
+ + +
+[docs] + def transition_state(self): + self.__remove_task() + self.vibrations() + self.settings.main.add("OptTS")
+ + +
+[docs] + def optimization(self): + self.__remove_task() + self.vibrations() + self.settings.main.add("Opt")
+ + +
+[docs] + def vibrations(self, enable=True, numerical=False): + self.remove_main("NumFreq") + self.remove_main("Freq") + if not enable: + return + if numerical: + self.settings.main.add("NumFreq") + else: + self.settings.main.add("Freq")
+ + +
+[docs] + def charge(self, val): + self._charge = val
+ + +
+[docs] + def spin_polarization(self, val): + self._multiplicity = val + 1
+ + +
+[docs] + def multiplicity(self, val): + self._multiplicity = val
+ + +
+[docs] + def ghost_atoms(self, indices: Union[int, List[int]]): + self._ghosts.extend(ensure_list(indices))
+ + +
+[docs] + def get_memory_usage(self): + mem = self.memory or self._sbatch.mem or None + + ntasks = self.processes + if ntasks is None: + if self._sbatch.n: + ntasks = self._sbatch.n + if self._sbatch.ntasks: + ntasks = self._sbatch.ntasks + if self._sbatch.ntasks_per_node: + ntasks = self._sbatch.ntasks_per_node * self._sbatch.get("N", 1) * self._sbatch.get("nodes", 1) + + return mem, ntasks
+ + +
+[docs] + def molecule(self, mol: Union[str, plams.Molecule, plams.Atom, List[plams.Atom]], natoms: int = None): + """ + Add a molecule to this calculation in various formats. + + Args: + mol: the molecule to read, can be a path (str). If the path exists already we read it. If it does not exist yet, it will be read in later. mol can also be a plams.Molecule object or a single or a list of plams.Atom objects. + natoms: If the molecule is supplied as a path you should also give the number of atoms. + """ + super().molecule(mol) + self.natoms = natoms
+ + +
+[docs] + def get_input(self): + # set the correct memory usage and processes + mem, ntasks = self.get_memory_usage() + if ntasks and mem: + if self._molecule is not None: + natoms = len(self._molecule) - len(self._ghosts) + else: + if not hasattr(self, "natoms") or self.natoms is None: + raise TCMoleculeError("You set the molecule as a path and did not supply the number of atoms.") + natoms = self.natoms + + ntasks = min(ntasks, (natoms - 1) * 3) + self.settings.PAL.nprocs = ntasks + self.settings.maxcore = int(mem / ntasks * 0.75) + else: + log.warn("MaxCore and nprocs not specified. Please use SBATCH settings or set job.processes and job.memory.") + + ret = "" + for key in self.settings.main: + ret += f"!{key}\n" + ret += "\n" + + for option, block in self.settings.items(): + if option == "main": + continue + + if isinstance(block, results.Result): + ret += f"%{option}\n" + + for key, val in block.items(): + ret += f" {key} {val}\n" + + ret += "END\n\n" + else: + ret += f"%{option} {block}\n" + + ret += "\n" + + if self._molecule_path: + ret += f"* xyzfile {self._charge} {self._multiplicity} {os.path.abspath(self._molecule_path)}\n" + + else: + ret += f"* xyz {self._charge} {self._multiplicity}\n" + for i, atom in enumerate(self._molecule, start=1): + if i in self._ghosts: + ret += f" {atom.symbol:2}: {atom.x: >13f} {atom.y: >13f} {atom.z: >13f}\n" + else: + ret += f" {atom.symbol:3} {atom.x: >13f} {atom.y: >13f} {atom.z: >13f}\n" + ret += "*\n" + + return ret
+ + + def _setup_job(self): + try: + if self.orca_path is None and not self.test_mode: + self.orca_path = sp.check_output(["which", "orca"]).decode().strip() + except sp.CalledProcessError: + log.warn(f'Could not find the orca path. Set the {self.__class__.__name__}.orca_path attribute to add it. Now setting it to "$(which orca)", make sure the orca executable is findable.') + self.orca_path = "$(which orca)" + + if not self._molecule and not self._molecule_path: + log.error(f"You did not supply a molecule for this job. Call the {self.__class__.__name__}.molecule method to add one.") + return + + os.makedirs(self.workdir, exist_ok=True) + with open(self.inputfile_path, "w+") as inp: + inp.write(self.get_input()) + + with open(self.runfile_path, "w+") as runf: + runf.write("#!/bin/sh\n\n") + runf.write("\n".join(self._preambles) + "\n\n") + + # when using temporary directories for SLURM we need to do some extra setup + # this is mainly moving the calculation directory to the TMPDIR location + # and after the jobs is finished we copy back the results and remove the TMPDIR + if self.use_tmpdir and slurm.has_slurm(): + runf.write('export TMPDIR="$TMPDIR/$SLURM_JOB_ID"\n') + runf.write("mkdir -p $TMPDIR\n") + runf.write("cd $TMPDIR\n") + runf.write(f"cp {self.inputfile_path} $TMPDIR\n") + + runf.write(f"{self.orca_path} $TMPDIR/{self.name}.in\n") + + runf.write(f"cp $TMPDIR/* {self.workdir}\n") + runf.write("rm -rf $TMPDIR\n") + + else: + runf.write(f"{self.orca_path} {self.inputfile_path}\n") + + runf.write("\n".join(self._postambles)) + + return True + + @property + def output_mol_path(self): + """ + The default file path for output molecules when running ADF calculations. It will not be created for singlepoint calculations. + """ + return j(self.workdir, "OPT.xyz")
+ + + +if __name__ == "__main__": + job = ORCAJob() + job.main("OPT cc-pVTZ") + job.remove_main("OPT OPTTS NEB") +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/job/xtb.html b/docs/_build/html/_modules/tcutility/job/xtb.html new file mode 100644 index 00000000..48bf0a12 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/job/xtb.html @@ -0,0 +1,516 @@ + + + + + + + + + + tcutility.job.xtb — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.job.xtb

+from tcutility.job.generic import Job
+from tcutility import spell_check
+import os
+from typing import Union
+
+
+j = os.path.join
+
+
+
+[docs] +class XTBJob(Job): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.xtb_path = 'xtb' + self._options = ['coords.xyz'] + self._scan = {} + + def _setup_job(self): + os.makedirs(self.workdir, exist_ok=True) + + self._molecule.write(j(self.workdir, 'coords.xyz')) + + if self._scan: + with open(j(self.workdir, 'scan.inp'), 'w+') as scaninp: + for key, value in self._scan.items(): + scaninp.write(f'${key}\n') + for line in value: + scaninp.write(f' {line}\n') + scaninp.write('$end\n') + + options = ' '.join(self._options) + with open(self.runfile_path, 'w+') as runf: + runf.write('#!/bin/sh\n\n') # the shebang is not written by default by ADF + runf.write('\n'.join(self._preambles) + '\n\n') + runf.write(f'{self.xtb_path} {options}\n') + runf.write('\n'.join(self._postambles)) + + return True + +
+[docs] + def model(self, method: Union[str, int]): + ''' + Set the method used by XTB. This includes GFN0-xTB, GFN1-xTB, GFN2-xTB and GFNFF. + + Args: + method: the method to use. Can be specified by its full name, e.g. 'GFN2-xTB', is the same as 'GFN2' or simply 2. + ''' + if isinstance(method, int): + if not 0 >= method >= 2: + raise ValueError(f'GFN{method}-xTB does not exist. Please choose one of GFN[0, 1, 2]-xTB.') + self._options.append(f'--gfn {method}') + return + + if method.lower() in ['gfn0', 'gfn0-xtb']: + self._options.append('--gfn 0') + return + + if method.lower() in ['gfn1', 'gfn1-xtb']: + self._options.append('--gfn 1') + return + + if method.lower() in ['gfn2', 'gfn2-xtb']: + self._options.append('--gfn 2') + return + + if method.lower() in ['gfnff', 'ff']: + self._options.append('--gfnff') + return + + raise ValueError(f'Did not recognize the method {method} for XTB.')
+ + +
+[docs] + def solvent(self, name: str = None, model: str = 'alpb'): + ''' + Model solvation using the ALPB or GBSA model. + + Args: + name: the name of the solvent you want to use. Must be ``None``, ``Acetone``, ``Acetonitrile``, ``CHCl3``, ``CS2``, ``DMSO``, ``Ether``, ``H2O``, ``Methanol``, ``THF`` or ``Toluene``. + grid_size: the size of the grid used to construct the solvent accessible surface. Must be ``230``, ``974``, ``2030`` or ``5810``. + ''' + spell_check.check(model, ['alpb', 'gbsa'], ignore_case=True) + self._options.append(f'--{model} {name}')
+ + +
+[docs] + def spin_polarization(self, val: int): + ''' + Set the spin-polarization of the system. + ''' + self._options.append(f'-u {val}')
+ + +
+[docs] + def multiplicity(self, val: int): + ''' + Set the multiplicity of the system. If the value is not one the calculation will also be unrestricted. + We use the following values: + + 1) singlet + 2) doublet + 3) triplet + 4) ... + + The multiplicity is equal to 2*S+1 for spin-polarization of S. + ''' + self._options.append(f'-u {(val - 1)//2}')
+ + +
+[docs] + def charge(self, val: int): + ''' + Set the charge of the system. + ''' + self._options.append(f'-c {val}')
+ + +
+[docs] + def vibrations(self, enable: bool = True): + self._options.append('--hess')
+ + +
+[docs] + def optimization(self, quality: str = 'Normal', calculate_hess: bool = True): + ''' + Do a geometry optimization and calculate the normal modes of the input structure. + + Args: + quality: the convergence criteria of the optimization. + See https://xtb-docs.readthedocs.io/en/latest/optimization.html#optimization-levels. + calculate_hess: whether to calculate the Hessian and do a normal mode analysis after optimization. + ''' + spell_check.check(quality, ['crude', 'sloppy', 'loose', 'lax', 'normal', 'tight', 'vtight', 'extreme'], ignore_case=True) + + if calculate_hess: + self._options.append(f'--ohess {quality}') + else: + self._options.append(f'--opt {quality}')
+ + +
+[docs] + def PESScan(self, distances: list = [], angles: list = [], dihedrals: list = [], npoints: int = 20, quality: str = 'Normal', mode: str = 'concerted'): + ''' + Set the task of the job to potential energy surface scan (PESScan). + + Args: + distances: sequence of tuples or lists containing ``[atom_index1, atom_index2, start, end]``. + Atom indices start at 1. Distances are given in |angstrom|. + angles: sequence of tuples or lists containing ``[atom_index1, atom_index2, atom_index3, start, end]``. + Atom indices start at 1. Angles are given in degrees + dihedrals: sequence of tuples or lists containing ``[atom_index1, atom_index2, atom_index3, atom_index4, start, end]``. + Atom indices start at 1. Angles are given in degrees + npoints: the number of PES points to optimize. + + .. note:: + Currently we only support generating settings for 1-dimensional PESScans. + We will add support for N-dimensional PESScans later. + ''' + self.optimization(quality=quality, calculate_hess=False) + self._options.append('--input scan.inp') + + self._scan.setdefault('scan', [f'mode={mode}']) + # self._scan.setdefault('opt', [f'maxcycles=50']) + for i, d in enumerate(distances): + self._scan['scan'].append(f'distance: {d[0]},{d[1]},{d[2]}; {d[2]}, {d[3]}, {npoints}') + for i, a in enumerate(angles, start=i): + self._scan['scan'].append(f'angle: {a[0]},{a[1]},{a[2]},{a[3]}; {a[3]}, {a[4]}, {npoints}') + for i, a in enumerate(dihedrals, start=i): + self._scan['scan'].append(f'dihedral: {a[0]},{a[1]},{a[2]},{a[3]},{a[4]}; {a[4]}, {a[5]}, {npoints}')
+ + + @property + def output_mol_path(self): + return f'{self.workdir}/xtbopt.xyz'
+ + +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/log.html b/docs/_build/html/_modules/tcutility/log.html new file mode 100644 index 00000000..f353b2be --- /dev/null +++ b/docs/_build/html/_modules/tcutility/log.html @@ -0,0 +1,865 @@ + + + + + + + + + + tcutility.log — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.log

+import inspect
+import json
+import os
+import sys
+from datetime import datetime
+from math import ceil
+from time import perf_counter
+from typing import Any, Generator, Iterable, List, Sequence, TypeVar, Union
+
+import numpy as np
+
+from tcutility import ensure_2d
+
+# from threading import Thread
+
+
+###########################################################
+# MODULE LEVEL VARIABLES USED TO CHANGE LOGGING BEHAVIOUR #
+logfile = sys.stdout  # stream or file to send prints to. Default sys.stdout is the standard Python print output
+errfile = sys.stderr  # stream or file to send prints to. Default sys.stderr is the standard Python print output
+tab_level = 0  # number of tabs to add before a logged message. This is useful to build a sense of structure in a long output
+max_width = 0  # maximum width of printed messages. Default 0 means unbounded
+print_date = True  # print time stamp before a logged message
+log_level = 20  # the level of verbosity. Messages with a log_level >= this number will be sent to logfile
+
+
+
+[docs] +class Emojis: + """ + Class containing some useful emojis and other characters. + Supports dot-notation and indexation to get a character. + + E.g. ``Emojis.wait == Emojis['wait']`` + """ + + wait = "🕒" + good = "✅" + cancel = "🛑" + sleep = "💤" + fail = "❌" + send = "📤" + receive = "📥" + empty = "⠀⠀" + finish = "🏁" + warning = "⚠️" + question = "❔" + info = "ℹ️" + rarrow = "─>" + larrow = "<─" + lrarrow = rlarrow = "<─>" + angstrom = "Å" + + def __init__(self): + raise SyntaxError("Do not instantiate the Emojis-class.") + + def __class_getitem__(cls, item): + return getattr(cls, item)
+ + + +
+[docs] +class NoPrint: + """ + Context-manager that suppresses printing. It works by redirecting prints to a temporary output file. + This file is deleted after exiting the context-manager. + """ + + def __init__(self, stdout=None, stderr=None): + self.stdout = stdout or logfile + self.stderr = stderr or errfile + self.overflow = open(str(os.getpid()) + "_NOPRINT.tmp", "w+") + + def __enter__(self): + global logfile, errfile + logfile = self.overflow + errfile = self.overflow + + def __exit__(self, *args, **kwargs): + global logfile, errfile + logfile = self.stdout + errfile = self.stderr + self.overflow.close() + os.remove(str(os.getpid()) + "_NOPRINT.tmp")
+ + + +
+[docs] +def time_stamp(): + """ + Return the current timestamp in a "[YYYY/MM/DD HH:MM:SS] "" format. + """ + now = datetime.now() + return f"[{now.year}/{str(now.month).zfill(2)}/{str(now.day).zfill(2)} {str(now.hour).zfill(2)}:{str(now.minute).zfill(2)}:{str(now.second).zfill(2)}] "
+ + + +
+[docs] +def log(message: Any = "", level: int = 20, end: str = "\n"): + r""" + Print a nicely formatteed message. + This function adds the current timestamp and supports multi-line printing (split on the ``\n`` escape character). + For verbosity levels we use the following convention: + + .. code-block:: + + NOTSET = 0 + DEBUG = 10 + INFO = 20 + WARN = 30 + ERROR = 40 + CRITICAL = 50 + + + Args: + message: the message to send. Before printing we will use the ``message.__str__`` method to get the string representation. If the message is a ``dict`` we use the ``json`` module to format the message nicely. + level: the level to print the message at. We compare the level against the module-wide ``log_level`` variable (by default ``log_level = 20``). If the level is below ``log_level`` we do not print it. + end: the end of the string. This is usually the new-line character ``\n``. + """ + if level < log_level: + return + + # dictionaries are handled specially so that they look nice + if isinstance(message, dict): + message = json.dumps(message, indent=4, sort_keys=True) + + # Print each line separately + splitted_message = str(message).split("\n") + for m in splitted_message: + # handle lines that exceed the maximum print width + if max_width > 0 and len(m) > max_width: + m = m[: max_width - 4] + " ..." + + # add the tab-levels and timestamp + m = "\t" * tab_level + m + if print_date: + m = time_stamp() + m + + print(m, file=logfile, end=end, flush=True)
+ + + +
+[docs] +def flow(message: str = "", tags: List[str] = ["straight"], level: int = 20) -> None: + """ + Function to create flowchart-like output. + It will print a message prepended by flow elements (arrows and lines). + The flow elements are determined based on the given tags. + """ + elements = { + "start": "┯ ", + "startinv": "┷ ", + "end": "╰─> ", + "straight": "│ ", + "split": "├─> ", + "skip": " ", + "vert": "────", + "endvert": "╰──> ", + "splitvert": "├──> ", + } + s = "" + for tag in tags: + s += elements[tag] + log(s + message, level=level)
+ + + +
+[docs] +def table(rows: List[List[Any]], header: Union[List[str], None] = None, sep: str = " ", hline: List[int] = [], level: int = 20) -> str: + r""" + Print a table given rows and a header. Values in rows will be cast to strings first. + + Args: + rows: list of `nrows` sequences containing `ncols` data inside the table. + header: list of `ncols` strings that represent the column names of the table. They will be printed at the top of the table. + sep: str representing the separation between columns. + hline: list of integers specifying rows after which lines will be drawn. Supports negative indices, e.g. -1 will draw a line at the end of the table. + + Returns: + str: the table in string format, where lines are separated by "\n" + """ + rows = ensure_2d(rows) + nrows = len(rows) + ncols = len(rows[0]) + + hline = [h + nrows + 1 if h < 0 else h for h in hline] + + if header: + rows = [header] + rows + hline = [0] + hline + + rows = [[str(x) for x in row] for row in rows] + + column_sizes = [max(len(row[i]) for row in rows) for i in range(ncols)] + return_str = "" + for i, row in enumerate(rows): + row_str = sep.join([x.ljust(column_size) for x, column_size in zip(row, column_sizes)]) + "\n" + return_str += row_str + if i in hline: + return_str += "─" * len(row_str) + "\n" + + log(return_str, level=level) + return return_str
+ + + +
+[docs] +def rectangle_list(values: Sequence, spaces_before: int = 0, level: int = 20): + """ + This function prints a list of strings in a rectangle to the output. + This is similar to what the ls program does in unix. + """ + n_shell_col = os.get_terminal_size().columns + # we first have to determine the correct dimensions of our rectangle + for ncol in range(1, n_shell_col): + # the number of rows for the number of columns + nrows = ceil(len(values) / ncol) + # we then get what the rectangle would be + mat = [[str(x) for x in values[i * ncol : (i + 1) * ncol]] for i in range(nrows)] + # and determine for each column the width + col_lens = [max([len(row[i]) for row in mat if i < len(row)] + [0]) for i in range(ncol)] + # then calculate the length of each row based on the column lengths + # we use a spacing of 2 spaces between each column + row_len = 22 * print_date + spaces_before + sum(col_lens) + 2 * len(col_lens) - 2 + + # if the rows are too big we exit the loop + if row_len > n_shell_col: + break + + # store the previous loops results + prev_col_lens = col_lens + prev_mat = mat + + # then print the strings with the right column widths + for row in prev_mat: + log(" " * spaces_before + " ".join([x.ljust(col_len) for x, col_len in zip(row, prev_col_lens)]), level=level)
+ + + +T = TypeVar("T") + + +
+[docs] +def loadbar(sequence: Union[Iterable[T], Sequence[T]], comment: str = "", Nsegments: int = 50, Nsteps: int = 10, level: int = 20) -> Generator[T, None, None]: + """ + Return values from an iterable ``sequence`` and also print a progress bar for the iteration over this sequence. + + Args: + sequence: any iterable sequence. Should define the ``__len__`` method. + comment: a string to be printed at the end of the loading bar to give information about the loading bar. + Nsegments: length of the loading bar in characters. + Nsteps: number of times to print the loading bar during iteration. If the output is a tty-type stream Nsteps will be set to the length of sequence. + """ + if not isinstance(sequence, Sequence): + chars = ["⠀", "⠄", "⠆", "⠦", "⠧", "⠷", "⠿", "⠻", "⠛", "⠙", "⠉", "⠈", "⠀"] + iteration = 0 + if not logfile.isatty() and comment: + log(comment, level=level) + + starttime = perf_counter() + for val in sequence: + iteration += 1 + elapsed_time = perf_counter() - starttime + time_per_step = elapsed_time / iteration + # every 0.1 seconds we change the character + char_step = int(elapsed_time / 0.1) % len(chars) + if logfile.isatty(): + log(f"{chars[char_step]} {comment} [Steps: {iteration}, Elapsed: {elapsed_time:.1f}s]", end="\r", level=level) + + yield val + + log(level=level) + return + + N = len(sequence) + # if the output stream is tty-type we set the number of steps to the lenth of the sequence so the loading bar looks smoother + Nsteps = N if logfile.isatty() else Nsteps + Ndigits = int(np.log10(N)) + 1 # well-known method to get number of digits of an integer + # we track what the maximum length of the loading bar is. + # We use the '\r' return carriage when logging, so we have to overwrite the whole previous line. + # For this we must know the largest length of our loading bar strings. + max_length = 0 + + # track when the loading bar started. We use this to calculate the ETA later + loading_bar_start_time = perf_counter() + for i, val in enumerate(sequence): + # we only print the loading bar on every Nsteps iterations + if i % (N // min(N, Nsteps)) != 0: + yield val + continue + + # calculate how many segments should be filled and empty + Nfilled_segments = int(i / N * Nsegments) + filled = "─" * Nfilled_segments + empty = " " * (Nsegments - Nfilled_segments) + + # determine what the cursor should look like + if Nfilled_segments == Nsegments: # if the bar is fully filled it should be just a stripe + cursor = "─" + elif i == 0: # if the bar is empty we don't draw the cursor + cursor = " " + else: # normal case + cursor = ">" + + # calculate the ETA. In the first iteration we cannot know yet + if i == 0: + eta = "???" + else: + # the algorithm simply extrapolates the current time taken to the case of the final iteration + time_taken = perf_counter() - loading_bar_start_time + time_per_step = time_taken / i + time_left = time_per_step * (N - i) + eta = f"{time_left:.1f}" + + # build the loading bar string + s = f'{i:{Ndigits}}/{N} {"├" if i > 0 else "|"}{filled + cursor + empty}{"│"} {i/N:4.0%} {comment} [ETA: {eta}s]'.ljust(max_length) + + # update the max loading bar string length + max_length = max(len(s), max_length) + log(s, end="\r", level=level) + + yield val + + # plot the final iteration at 100% filled + s = f'{i+1:{Ndigits}}/{N} {"├"}{"─"*(Nsegments+1)}┤ 100% {comment}'.ljust(max_length) + log(s, end="\r", level=level) + log(level=level)
+ + + +
+[docs] +def boxed(message: str, title: Union[str, None] = None, message_align: str = "left", title_align: str = "left", round_corners: bool = True, double_edge: bool = False, level: int = 20) -> None: + r""" + Print a message surrounded by a box with optional title. + + Args: + message: the message to place in the box. Multiline messages are separated by "\n". + title: the title placed in the top edge of the box. + message_align: alignment of the text inside the box. One of ["left", "center", "right"]. + title_align: alignment of the title. One of ["left", "center", "right"]. + round_corners: whether the corners of the box should be rounded or not. Rounded corners are only available for single-edge boxes. + double_edge: whether the edges of the box should be double. + + Returns: + The printed message in strings format. + """ + # define the edges and corners + straights = ["│", "─"] + if round_corners and not double_edge: + corners = ["╭", "╮", "╯", "╰"] + elif double_edge: + corners = ["╔", "╗", "╝", "╚"] + straights = ["║", "═"] + else: + corners = ["┌", "┐", "┘", "└"] + + # get the width the box should have + messages = message.split("\n") + # the length is influenced by both the messages as well as the title + maxlen = max(max(len(message) for message in messages), len(title or "")) + + # build first row containing the title + if title is not None: + if title_align == "left": + s = corners[0] + (" " + title + " ").ljust(maxlen + 2, straights[1]) + corners[1] + "\n" + elif title_align == "right": + s = corners[0] + (" " + title + " ").rjust(maxlen + 2, straights[1]) + corners[1] + "\n" + else: + s = corners[0] + (" " + title + " ").center(maxlen + 2, straights[1]) + corners[1] + "\n" + else: + s = corners[0] + straights[1] * (maxlen + 2) + corners[1] + "\n" + + # build main body of box + for message in messages: + if message_align == "left": + s += f"{straights[0]} " + message.ljust(maxlen) + f" {straights[0]}\n" + if message_align == "right": + s += f"{straights[0]} " + message.rjust(maxlen) + f" {straights[0]}\n" + if message_align == "center": + s += f"{straights[0]} " + message.center(maxlen) + f" {straights[0]}\n" + + # build bottom row + s += corners[3] + straights[1] * (maxlen + 2) + corners[2] + + log(s, level=level)
+ + + +
+[docs] +def debug(message: str, level: int = 10, caller_level: int = 2): + """ + Print a debug message. + """ + log(f"[DEBUG]({caller_name(caller_level)}): " + message, level=level)
+ + + +
+[docs] +def info(message: str, level: int = 20, caller_level: int = 2): + """ + Print an informative message. + """ + log(f"[INFO]({caller_name(caller_level)}): " + message, level=level)
+ + + +
+[docs] +def warn(message: str, level: int = 30, caller_level: int = 2): + """ + Print a warning message. + """ + log(f"[WARNING]({caller_name(caller_level)}): " + message, level=level)
+ + + +
+[docs] +def error(message: str, level: int = 40, caller_level: int = 2): + """ + Print an error message. + """ + log(f"[ERROR]({caller_name(caller_level)}): " + message, level=level)
+ + + +
+[docs] +def critical(message: str, level: int = 50, caller_level: int = 2): + """ + Print a critical message. + """ + log(f"[CRITICAL]({caller_name(caller_level)}): " + message, level=level)
+ + + +
+[docs] +def caller_name(level: int = 1) -> str: + """ + Return the full name of the caller of a function. + + Args: + level: the number of levels to skip when getting the caller name. Level 1 is always this function. When used by a different function it should be set to 2. E.g. when using the log.warn function level is set to 2. + + Returns: + The full name of the caller function. + """ + stack = inspect.stack() + names = [stack[level][3]] # add the original function, this should be at a certain levels, since this function is called by warn or info or error + for frame in stack[level:]: + if frame.function == "<module>": # <module> is always there, so we can skip it + continue + + # get the more interesting names + # first check if the + if hasattr(frame[0], "f_locals") and "self" in frame[0].f_locals: + clas = frame[0].f_locals["self"].__class__ + module = clas.__module__ + if module == "builtins": + names.append(clas.__qualname__) + else: + names.append(module + "." + clas.__qualname__) + elif hasattr(frame[0], "f_code"): + names.append(frame[0].f_code.co_name) + names_ordered = [] + for name in names[::-1]: + if name not in names_ordered: + names_ordered.append(name) + return ".".join(names_ordered)
+ + + +if __name__ == "__main__": + boxed("testing, 1, 2, 3, 4, 5, 6, 7, 8\nsecond row, 1, 2, 3, 4, 5, 6\n...\n...\n\n...\n...\nLast row here", title="ReactionRunner") + + with NoPrint(): + log("test test test") + log("test test test") + log("test test test") + log("test test test") + + log() + + flow("Start", ["start"]) + flow() + flow("First step", ["split"]) + flow("First substep of first step", ["straight", "split"]) + flow("Second substep of first step", ["straight", "split"]) + flow("Third and final substep of first step", ["straight", "end"]) + flow() + flow("Second step", ["split"]) + flow("Substep of second step", ["straight", "split"]) + flow("Substep of substep of second step", ["straight", "straight", "end"]) + flow("Substep of substep of substep of second step", ["straight", "straight", "skip", "end"]) + flow("Substep of second step", ["straight", "end"]) + flow() + flow("Final step", ["split"]) + flow() + flow(f"{Emojis.good} The end", ["startinv"]) + + log() + + info("This is important info") + warn("This is an important warning!") + + import time + + for x in loadbar(range(100), "Sleeping test"): + time.sleep(0.01) + + x = np.linspace(1, 12, 12) + rows = np.vstack([x, x**2, x**3, x**4, x**5]).astype(int).T.tolist() + table(rows, header=["X", "y=x^2", "y=x^3", "y=x^4", "y=x^5"], hline=[-1]) + + from tcutility import log as cli_log + + class TestClass: + def test_method(self): + cli_log.warn("I am testing the warning function") + + TestClass().test_method() + + rectangle_list(range(1000)) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/molecule.html b/docs/_build/html/_modules/tcutility/molecule.html new file mode 100644 index 00000000..f261b8c3 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/molecule.html @@ -0,0 +1,667 @@ + + + + + + + + + + tcutility.molecule — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.molecule

+import pathlib as pl
+from typing import Dict, List, Union
+
+from scm import plams
+
+from tcutility import ensure_list
+from tcutility.results import result
+from tcutility.data import atom
+
+
+
+[docs] +def number_of_electrons(mol: plams.Molecule) -> int: + nel = 0 + for at in mol: + nel += atom.atom_number(at.symbol) + return nel
+ + + +
+[docs] +def parse_str(s: str): + # checks if string should be an int, float, bool or string + + # sanitization first + # empty s returns None + # if s is not a str return it + if s == "": + return None + if not isinstance(s, str): + return s + + if "," in s: + return [parse_str(part.strip()) for part in s.split(",")] + + # to parse the string we use try/except method + try: + return int(s) + except ValueError: + pass + + try: + return float(s) + except ValueError: + pass + + # bool type casting always works, so we have to specifically check for correct strings + if s in ["True", "False"]: + return bool(s) + + return s
+ + + +
+[docs] +def load(path) -> plams.Molecule: + """ + Load a molecule from a given xyz file path. + The xyz file is structured as follows: + + .. code-block:: + + [int] + Comment line + [str] [float] [float] [float] atom_tag1 atom_tag2 atom_key1=... + [str] [float] [float] [float] atom_tag1 atom_tag2 atom_key1=... + [str] [float] [float] [float] + + mol_tag1 + mol_tag2 + mol_key1=... + mol_key2 = ... + + + The xyz file is parsed and returned as a :class:`plams.Molecule <plams.mol.molecule.Molecule>` object. + Flags and tags are given as ``mol.flags`` and ``mol.flags.tags`` respectively. + Similarly for the atoms, the flags and tags are given as ``mol.atoms[i].flags`` and ``mol.atoms[i].flags.tags`` + """ + + def parse_flags(args): + ret = result.Result() + ret.tags = set() + for arg in args: + # flags are given as key=value pairs + # tags are given as loose keys + if "=" in arg: + key, value = arg.split("=") + ret[key.strip()] = parse_str(value.strip()) + else: + ret.tags.add(parse_str(arg.strip())) + return ret + + with open(path) as f: + lines = [line.strip() for line in f.readlines()] + + mol = plams.Molecule() + + natoms = int(lines[0]) + mol.comment = lines[1] + # not all lines in the file will define atoms. Lines after line natoms+2 will be used for flags + atom_lines = lines[2 : natoms + 2] + for line in atom_lines: + # parse every atom first + symbol, x, y, z, *args = line.split() + at = plams.Atom(symbol=symbol, coords=(float(x), float(y), float(z))) + at.flags = parse_flags(args) + mol.add_atom(at) + + # after the atoms we parse the flags for the molecule + flag_lines = lines[natoms + 2 :] + flag_lines = [line.strip() for line in flag_lines if line.strip()] + mol.flags = parse_flags(flag_lines) + + return mol
+ + + +
+[docs] +def guess_fragments(mol: plams.Molecule) -> Dict[str, plams.Molecule]: + """ + Guess fragments based on data from the xyz file. Two methods are currently supported, see the tabs below. + We also support reading of charges and spin-polarizations for the fragments. + They should be given as ``charge_{fragment_name}`` and ``spinpol_{fragment_name}`` respectively. + + + .. tabs:: + + .. group-tab:: First method + + .. code-block:: + + 8 + + N 0.00000000 0.00000000 -0.81474153 + B -0.00000000 -0.00000000 0.83567034 + H 0.47608351 -0.82460084 -1.14410295 + H 0.47608351 0.82460084 -1.14410295 + H -0.95216703 0.00000000 -1.14410295 + H -0.58149793 1.00718395 1.13712667 + H -0.58149793 -1.00718395 1.13712667 + H 1.16299585 -0.00000000 1.13712667 + + frag_Donor = 1, 3-5 + frag_Acceptor = 2, 6-8 + charge_Donor = -1 + spinpol_Acceptor = 2 + + In this case, fragment atom indices must be provided below the coordinates. + The fragment name must be prefixed with ``frag_``. Indices can be given as integers or as ranges using ``-``. + + .. group-tab:: Second method + + .. code-block:: + + 8 + + N 0.00000000 0.00000000 -0.81474153 frag=Donor + B -0.00000000 -0.00000000 0.83567034 frag=Acceptor + H 0.47608351 -0.82460084 -1.14410295 frag=Donor + H 0.47608351 0.82460084 -1.14410295 frag=Donor + H -0.95216703 0.00000000 -1.14410295 frag=Donor + H -0.58149793 1.00718395 1.13712667 frag=Acceptor + H -0.58149793 -1.00718395 1.13712667 frag=Acceptor + H 1.16299585 -0.00000000 1.13712667 frag=Acceptor + + charge_Donor = -1 + spinpol_Acceptor = 2 + + In this case, fragment atoms are marked with the `frag` flag which gives the name of the fragment the atom belongs to. + + Args: + mol: the molecule that is to be split into fragments. It should have defined either method shown above. + If it does not define these methods this function returns ``None``. + + Returns: + A dictionary containing fragment names as keys and :class:`plams.Molecule <scm.plams.mol.molecule.Molecule>` objects as values. + Atoms that were not included by either method will be placed in the molecule object with key ``None``. + + """ + + # first method, check if the fragments are defined as molecule flags + fragment_flags = [flag for flag in mol.flags if flag.startswith("frag_")] + if len(fragment_flags) > 0: + # we split here to get of the frag_ prefix + fragment_mols = {frag.split("_", 1)[1]: plams.Molecule() for frag in fragment_flags} + for frag in fragment_flags: + frag_name = frag.split("_", 1)[1] + indices = [] + index_line = ensure_list(mol.flags[frag]) + for indx in index_line: + if isinstance(indx, int): + indices.append(indx) + elif isinstance(indx, str) and "-" in indx: + indices.extend(range(int(indx.split("-")[0]), int(indx.split("-")[1]) + 1)) + else: + raise ValueError(f"Fragment index {indx} could not be parsed.") + + [fragment_mols[frag_name].add_atom(mol[i]) for i in indices] + fragment_mols[frag_name].flags = {"tags": set()} + if f"charge_{frag_name}" in mol.flags: + fragment_mols[frag_name].flags["charge"] = mol.flags[f"charge_{frag_name}"] + if f"spinpol_{frag_name}" in mol.flags: + fragment_mols[frag_name].flags["spinpol"] = mol.flags[f"spinpol_{frag_name}"] + + return result.Result(fragment_mols) + + # second method, check if the atoms have a frag= flag defined + fragment_names = set(at.flags.get("frag") for at in mol) + if len(fragment_names) > 0: + fragment_mols = {name: plams.Molecule() for name in fragment_names} + for at in mol: + # get the fragment the atom belongs to and add it to the list + fragment_mols[at.flags.get("frag")].add_atom(at) + + for frag in fragment_names: + fragment_mols[frag].flags = {"tags": set()} + if f"charge_{frag}" in mol.flags: + fragment_mols[frag].flags["charge"] = mol.flags[f"charge_{frag}"] + if f"spinpol_{frag}" in mol.flags: + fragment_mols[frag].flags["spinpol"] = mol.flags[f"spinpol_{frag}"] + + return result.Result(fragment_mols)
+ + + +# ============================================================================= +# Writing Functions for Molecule objects ====================================== +# ============================================================================= + + +def _xyz_format(mol: plams.Molecule, include_n_atoms: bool = True) -> str: + """Returns a string representation of a molecule in the xyz format, e.g.: + + C 0.00000000 0.00000000 0.00000000 + H 1.00000000 0.00000000 0.00000000 + H 0.00000000 1.00000000 0.00000000 + H 0.00000000 0.00000000 1.00000000 + + ... + """ + n_atoms = len(mol.atoms) + if include_n_atoms: + return f"{n_atoms}\n" + "\n".join([f"{at.symbol:6s}{at.x:16.8f}{at.y:16.8f}{at.z:16.8f}" for at in mol.atoms]) + + return "\n".join([f"{at.symbol:6s}{at.x:16.8f}{at.y:16.8f}{at.z:16.8f}" for at in mol.atoms]) + + +def _amv_format(mol: plams.Molecule, step: int, energy: Union[float, None] = None) -> str: + """Returns a string representation of a molecule in the amv format, e.g.: + + Geometry 1, Energy: -0.5 Ha + C 0.00000000 0.00000000 0.00000000 + H 1.00000000 0.00000000 0.00000000 + H 0.00000000 1.00000000 0.00000000 + H 0.00000000 0.00000000 1.00000000 + ... + + If no energy is provided, the energy is not included in the string representation""" + if energy is None: + return f"Geometry {step}\n" + "\n".join([f"{at.symbol:6s}{at.x:16.8f}{at.y:16.8f}{at.z:16.8f}" for at in mol.atoms]) + return f"Geometry {step}, Energy: {energy} Ha\n" + "\n".join([f"{at.symbol:6s}{at.x:16.8f}{at.y:16.8f}{at.z:16.8f}" for at in mol.atoms]) + + +
+[docs] +def write_mol_to_xyz_file(mols: Union[List[plams.Molecule], plams.Molecule], filename: Union[str, pl.Path], include_n_atoms: bool = False) -> None: + """Writes a list of molecules to a file in xyz format.""" + mols = mols if isinstance(mols, list) else [mols] + out_file = pl.Path(f"{filename}.xyz") + + [mol.delete_all_bonds() for mol in mols] + write_string = "\n\n".join([_xyz_format(mol, include_n_atoms) for mol in mols]) + out_file.write_text(write_string) + + return None
+ + + +
+[docs] +def write_mol_to_amv_file(mols: Union[List[plams.Molecule], plams.Molecule], energies: Union[List[float], None], filename: Union[str, pl.Path]) -> None: + """Writes a list of molecules to a file in amv format.""" + mols = mols if isinstance(mols, list) else [mols] + out_file = pl.Path(f"{filename}.amv") + energies = energies if energies is not None else [0.0 for _ in mols] + + [mol.delete_all_bonds() for mol in mols] + write_string = "\n\n".join([_amv_format(mol, step, energy) for step, (mol, energy) in enumerate(zip(mols, energies), 1)]) + out_file.write_text(write_string) + + return None
+ + + +
+[docs] +def save(mol: plams.Molecule, path: str, comment: str = None): + """Save a molecule in a custom xyz file format. + Molecule and atom flags can be provided as the "flags" parameter of the object (mol.flags and atom.flags). + """ + comment = comment or mol.comment if hasattr(mol, "comment") else "" + with open(path, "w+") as f: + f.write(f"{len(mol.atoms)}\n{comment}\n") + for at in mol.atoms: + flags_str = "" + flags = at.flags if hasattr(at, "flags") else {} + for key, value in flags.items(): + if key == "tags": + if len(value) > 0: + flags_str += " ".join([str(x) for x in value]) + " " + else: + continue + else: + flags_str += f"{key}={value} " + + f.write(f"{at.symbol}\t{at.coords[0]: .10f}\t{at.coords[1]: .10f}\t{at.coords[2]: .10f}\t{flags_str}\n") + + f.write("\n") + + flags = mol.flags if hasattr(mol, "flags") else {} + for key, value in flags.items(): + if key == "tags": + f.write("\n".join([str(x) for x in value]) + "\n") + else: + f.write(f"{key} = {value}\n")
+ + + +if __name__ == "__main__": + # mol = load(r"D:\Users\Yuman\Desktop\PhD\ychem\calculations2\5ef3a511141a993d83552515df6bf882a7560dd806f88df4e2c2887b4d2a9595\transitionstate\input_mol.xyz") + mol = load("../../examples/job/NH3BH3.xyz") + frags = guess_fragments(mol) + print(frags) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/pathfunc.html b/docs/_build/html/_modules/tcutility/pathfunc.html new file mode 100644 index 00000000..e215d5f7 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/pathfunc.html @@ -0,0 +1,535 @@ + + + + + + + + + + tcutility.pathfunc — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.pathfunc

+import os
+import re
+from typing import Dict, List
+
+from tcutility import results
+
+j = os.path.join
+
+
+
+[docs] +def split_all(path: str) -> List[str]: + """ + Split a path into all of its parts. + + Args: + path: the path to be split, it will be separated using :func:`os.path.split`. + + Returns: + A list of parts of the original path. + + Example: + .. code-block:: python + + >>> split_all('a/b/c/d') + ['a', 'b', 'c', 'd'] + """ + parts = [] + while True: + a, b = os.path.split(path) + if not a or not b: + parts.append(path) + return parts[::-1] + parts.append(b) + path = a
+ + + +
+[docs] +def get_subdirectories(root: str, include_intermediates: bool = False) -> List[str]: + """ + Get all sub-directories of a root directory. + + Args: + root: the root directory. + include_intermediates: whether to include intermediate sub-directories instead of only the lowest levels. + + Returns: + A list of sub-directories with ``root`` included in the paths. + + Example: + Given a file-structure as follows: + + .. code-block:: + + root + |- subdir_a + | |- subsubdir_b + | |- subsubdir_c + |- subdir_b + |- subdir_c + + Then we get the following outputs. + + .. tabs:: + + .. group-tab:: Including intermediates + + .. code-block:: python + + >>> get_subdirectories('root', include_intermediates=True) + ['root', + 'root/subdir_a', + 'root/subdir_a/subsubdir_b', + 'root/subdir_a/subsubdir_c', + 'root/subdir_b', + 'root/subdir_c'] + + .. group-tab:: Excluding intermediates + + .. code-block:: python + + >>> get_subdirectories('root', include_intermediates=False) + ['root/subdir_a/subsubdir_b', + 'root/subdir_a/subsubdir_c', + 'root/subdir_b', + 'root/subdir_c'] + """ + dirs = [root] + subdirs = set() + + while len(dirs) > 0: + _dirs = [] + for cdir in dirs: + csubdirs = [j(cdir, d) for d in os.listdir(cdir) if os.path.isdir(j(cdir, d))] + if len(csubdirs) == 0: + subdirs.add(cdir) + else: + if include_intermediates: + subdirs.add(cdir) + _dirs.extend(csubdirs) + + dirs = _dirs + + return subdirs
+ + + +
+[docs] +def match(root: str, pattern: str) -> Dict[str, dict]: + """ + Find and return information about subdirectories of a root that match a given pattern. + + Args: + root: the root of the subdirectories to look in. + pattern: a string specifying the pattern the subdirectories should correspond to. + It should look similar to a format string, without the ``f`` in front of the string. + Inside curly braces you can put a variable name, which you can later extract from the results. + Anything inside curly braces will be matched to word characters (``[a-zA-Z0-9_-]``) including dashes and underscores. + + Returns: + | A |Result| object containing the matched directories as keys and information (also |Result| object) about those matches as the values. + Each information dictionary contains the variables given in the pattern. + | E.g. using a pattern such as ``{a}/{b}/{c}`` will populate the ``info.a``, ``info.b`` and ``info.c`` keys of the info |Result| object. + + Example: + Given a file-structure as follows: + + .. code-block:: + + root + |- NH3-BH3 + | |- BLYP_QZ4P + | | |- extra_dir + | | |- blablabla + | | + | |- BLYP_TZ2P + | | |- another_dir + | | + | |- M06-2X_TZ2P + | + |- SN2 + | |- BLYP_TZ2P + | |- M06-2X_TZ2P + | | |- M06-2X_TZ2P + + We can run the following scripts to match the subdirectories. + + .. code-block:: python + + from tcutility import log + # get the matches, we want to extract the system name (NH3-BH3 or SN2) + # and the functional and basis-set + # we don't want the subdirectories + matches = match('root', '{system}/{functional}_{basis_set}') + + # print the matches as a table + rows = [] + for d, info in matches.items(): + rows.append([d, info.system, info.functional, info.basis_set]) + + log.table(rows, ['Directory', 'System', 'Functional', 'Basis-Set']) + + which prints + + .. code-block:: + + [2024/01/17 14:39:08] Directory System Functional Basis-Set + [2024/01/17 14:39:08] ─────────────────────────────────────────────────────────── + [2024/01/17 14:39:08] root/SN2/M06-2X_TZ2P SN2 M06-2X TZ2P + [2024/01/17 14:39:08] root/NH3-BH3/BLYP_TZ2P NH3-BH3 BLYP TZ2P + [2024/01/17 14:39:08] root/NH3-BH3/M06-2X_TZ2P NH3-BH3 M06-2X TZ2P + [2024/01/17 14:39:08] root/SN2/BLYP_TZ2P SN2 BLYP TZ2P + [2024/01/17 14:39:08] root/NH3-BH3/BLYP_QZ4P NH3-BH3 BLYP QZ4P + """ + # get the number and names of substitutions in the given pattern + substitutions = re.findall(r"{(\w+[+*?]?)}", pattern) + # the pattern should resolve to words and may contain - and _ + # replace them here + for sub in substitutions: + quantifier = sub[-1] if sub[-1] in "+*?" else "+" + pattern = pattern.replace("{" + sub + "}", f"([a-zA-Z0-9_-]{quantifier})") + + ret = results.Result() + # root dir can be any level deep. We should count how many directories are in root + root_length = len(split_all(root)) + # get all subdirectories first, we can loop through them later + subdirs = get_subdirectories(root, include_intermediates=True) + # remove the root from the subdirectories. We cannot use str.removeprefix because it was added in python 3.9 + subdirs = [j(*split_all(subdir)[root_length:]) for subdir in subdirs if len(split_all(subdir)[root_length:]) > 0] + for subdir in subdirs: + # check if we get a match with our pattern + match = re.fullmatch(pattern, subdir) + if not match: + continue + + p = j(root, subdir) + # get the group data and add it to the return dictionary. We skip the first group because it is the full directory path + ret[p] = results.Result(directory=p, **{substitutions[i]: match.group(i + 1) for i in range(len(substitutions))}) + + return ret
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/report/character.html b/docs/_build/html/_modules/tcutility/report/character.html new file mode 100644 index 00000000..9fc27f72 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/report/character.html @@ -0,0 +1,433 @@ + + + + + + + + + + tcutility.report.character — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.report.character

+import os
+
+from tcutility import cache, log
+
+
+def _load_data() -> dict:
+    """
+    Load character width data. It is stored in a file where each line is formatted as:
+
+            {font} {character} {width}
+
+    Font names that originally contained spaces, for example "Times New Roman", will have the spaces replaced
+    by underscores.
+
+    Returns:
+            We return a nested dictionary with the first key being the font and the nested key the characters.
+            The widths are given in pixel sizes and are for font-size 1.
+    """
+    with open(os.path.join(os.path.split(__file__)[0], "_char_widths.txt"), encoding="utf-8") as widths:
+        lines = widths.readlines()
+
+    ret = {}
+    for line in lines:
+        # we split each line into parts by white space
+        parts = line.split()
+        # if there are only 2 parts, that means that the character was a space
+        if len(parts) == 2:
+            font, width = parts
+            character = " "
+        else:
+            font, character, width = line.split()
+
+        # fonts that contain spaces in the name had the spaces replaced by underscores
+        # here we restore the original spaces
+        font = font.replace("_", " ")
+        width = float(width)
+
+        ret.setdefault(font, {})
+        ret[font][character] = width
+
+    return ret
+
+
+widths = _load_data()
+
+
+
+[docs] +@cache.cache +def get_pixel_width(character: str, font: str = "calibri", font_size: float = 11) -> float: + """ + Get the pixel width of a character for a given font and font-size. + For this we need to interpolate the pixel width between two reference values. + In the _char_widths.txt file you will find for each font a set of character pixel widths for font-size 1. + We then simply multiply the 1-width value by the desired value to get the correct pixel width. + See + + Args: + character: the character to get the pixel width for. + font: the font family that is used. + font_size: the font-size to get the pixel width at. + """ + if font not in widths.keys(): + raise ValueError(f"Could not find font {font}.") + + return widths[font][character] * font_size
+ + + +
+[docs] +def text_width(text: str, font: str = "calibri", font_size: float = 11, mode: str = "pixels") -> float: + """ + Get the width of a string for a given font and font size. + + Args: + text: the object to determine the length for. + Will be cast to a string before calculating width. + font: the font family that is used. + font_size: the font-size to get the pixel width at. + mode: the width-mode. Can be 'excel' or 'pixels'. + + Returns: + The width of the text for a certain font and font size. + If mode is 'excel' we pad it with 8 pixels and then divide by 7.6 (i.e. standard excel char width). + """ + if font not in widths.keys(): + log.error(f"Could not find font {font}. Defaulting to Calibri.") + font = "calibri" + + pixels = sum(get_pixel_width(char, font, font_size) for char in str(text)) + if mode == "excel": + return (pixels + 8) / 7.6 + if mode == "word": + return (pixels + 8) / 7.6 + + return pixels
+ + + +if __name__ == "__main__": + print(text_width("this is a test text", font="test")) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results.html b/docs/_build/html/_modules/tcutility/results.html new file mode 100644 index 00000000..4cb14ff7 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results.html @@ -0,0 +1,461 @@ + + + + + + + + + + tcutility.results — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results

+"""
+This module provides basic and general information about calculations done using AMS given a calculation directory.
+This includes information about the engine used (ADF, DFTB, BAND, ...), general information such as timings, files, status of the calculation, etc.
+This information is used in further analysis programs.
+
+"""
+
+from typing import Union
+
+from . import result
+
+Result = result.Result
+
+import os  # noqa: E402
+import pathlib as pl  # noqa: E402
+
+from .. import slurm  # noqa: E402
+from . import adf, ams, cache, dftb, orca, xtb  # noqa: E402
+
+
+
+[docs] +def get_info(calc_dir: str): + try: + return ams.get_ams_info(calc_dir) + except: # noqa + pass + + try: + return orca.get_info(calc_dir) + except: # noqa + pass + + try: + return xtb.get_info(calc_dir) + except: # noqa + pass + + res = Result() + + # if we cannot correctly read the info, we return some generic result object + # before that, we check the job status by checking slurm + if slurm.workdir_info(os.path.abspath(calc_dir)): + res.engine = "unknown" + + state = slurm.workdir_info(os.path.abspath(calc_dir)).statuscode + state_name = {"CG": "COMPLETING", "CF": "CONFIGURING", "PD": "PENDING", "R": "RUNNING"}.get(state, "UNKNOWN") + + res.status.fatal = False + res.status.name = state_name + res.status.code = state + res.status.reasons = [] + else: + res.engine = "unknown" + res.status.fatal = True + res.status.name = "UNKNOWN" + res.status.code = "U" + res.status.reasons = [] + + # give a little more specific information about the error + if not os.path.exists(calc_dir): + res.status.reasons.append(f"Could not find folder {calc_dir}") + elif not os.path.isdir(calc_dir): + res.status.reasons.append(f"Path {calc_dir} is not a directory") + else: + res.status.reasons.append(f"Could not read calculation in {calc_dir}") + + return res
+ + + +
+[docs] +def read(calc_dir: Union[str, pl.Path]) -> Result: + """Master function for reading data from calculations. It reads general information as well as engine-specific information. + + Args: + calc_dir: path pointing to the working directory for the desired calculation + + Returns: + dictionary containing information about the calculation + """ + calc_dir = str(calc_dir) if isinstance(calc_dir, pl.Path) else calc_dir + + ret = Result() + ret.update(get_info(calc_dir)) + if ret.engine == "adf": + try: + ret.adf = adf.get_calc_settings(ret) + except: # noqa + ret.adf = None + + try: + ret.properties = adf.get_properties(ret) + except: # noqa + ret.properties = None + + try: + ret.level = adf.get_level_of_theory(ret) + except: # noqa + ret.level = None + + elif ret.engine == "dftb": + ret.dftb = dftb.get_calc_settings(ret) + ret.properties = dftb.get_properties(ret) + elif ret.engine == "xtb": + # ret.xtb = xtb.get_calc_settings(ret) + ret.properties = xtb.get_properties(ret) + + elif ret.engine == "orca": + try: + ret.orca = orca.get_calc_settings(ret) + except: # noqa + ret.orca = None + + try: + ret.properties = orca.get_properties(ret) + except: # noqa + ret.properties = None + + # unload cached KFReaders associated with this calc_dir + to_delete = [key for key in cache._cache if key.startswith(os.path.abspath(calc_dir))] + [cache.unload(key) for key in to_delete] + return ret
+ + + +if __name__ == "__main__": + res = read("/Users/yumanhordijk/Library/CloudStorage/OneDrive-VrijeUniversiteitAmsterdam/RadicalAdditionBenchmark/data/abinitio/P_C2H2_NH2/OPT_pVTZ") + print(res.molecule) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results/adf.html b/docs/_build/html/_modules/tcutility/results/adf.html new file mode 100644 index 00000000..2ce3857f --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results/adf.html @@ -0,0 +1,702 @@ + + + + + + + + + + tcutility.results.adf — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results.adf

+from typing import Dict, List
+
+import numpy as np
+from scm.plams import KFReader
+
+from tcutility import constants, ensure_list
+from tcutility.results import Result, cache
+from tcutility.tc_typing import arrays
+
+# ------------------------------------------------------------- #
+# ------------------- Calculation Settings -------------------- #
+# ------------------------------------------------------------- #
+
+
+
+[docs] +def get_calc_settings(info: Result) -> Result: + """Function to read calculation settings for an ADF calculation. + + Args: + info: Result object containing ADF calculation settings. + + Returns: + :Result object containing properties from the ADF calculation: + + - **task (str)** – the task that was set for the calculation. + - **relativistic (bool)** – whether or not relativistic effects were enabled. + - **relativistic_type (str)** – the name of the relativistic approximation used. + - **unrestricted_sfos (bool)** – whether or not SFOs are treated in an unrestricted manner. + - **unrestricted_mos (bool)** – whether or not MOs are treated in an unrestricted manner. + - **symmetry.group (str)** – the symmetry group selected for the molecule. + - **symmetry.labels (list[str])** – the symmetry labels associated with the symmetry group. + - **used_regions (bool)** – whether regions were used in the calculation. + - **charge (int)** - the charge of the system. + - **spin_polarization (int)** - the spin-polarization of the system. + - **multiplicity (int)** - the multiplicity of the system. This is equal to 2|S|+1 for spin-polarization S. + """ + assert info.engine == "adf", f"This function reads ADF data, not {info.engine} data" + + ret = Result() + + # set the calculation task at a higher level + ret.task = info.input.task + + # the VibrationalAnalysis task does not produce adf.rkf files + # in that case we end the reading here, since the following + # variables do not apply + if ret.task.lower() == "vibrationalanalysis": + return ret + + reader_adf = cache.get(info.files["adf.rkf"]) + + relativistic_type_map = { + 0: "None", + 1: "scalar Pauli", + 3: "scalar ZORA", # scalar ZORA + MAPA + 4: "scalar ZORA + full pot.", + 5: "scalar ZORA + APA", + 6: "scalar X2C + MAPA", + 7: "scalar X2C ZORA + MAPA", + 11: "spin-orbit Pauli", + 13: "spin-orbit ZORA", # spin-orbit ZORA + MAPA + 14: "spin-orbit ZORA + full pot.", + 15: "spin-orbit ZORA + APA", + 16: "spin-orbit X2C + MAPA", + 17: "spin-orbit X2C ZORA + MAPA", + } + # determine if calculation used relativistic corrections + # if it did, variable 'escale' will be present in 'SFOs' + # if it didnt, only variable 'energy' will be present + ret.relativistic = ("SFOs", "escale") in reader_adf + ret.relativistic_type = relativistic_type_map[reader_adf.read("General", "ioprel")] + + # determine if MOs are unrestricted or not + # general, nspin is 1 for restricted and 2 for unrestricted calculations + ret.unrestricted_mos = reader_adf.read("General", "nspin") == 2 + + # determine if SFOs are unrestricted or not + ret.unrestricted_sfos = reader_adf.read("General", "nspinf") == 2 + + # get the symmetry group + ret.symmetry.group = reader_adf.read("Geometry", "grouplabel").strip() + + # get the symmetry labels + ret.symmetry.labels = reader_adf.read("Symmetry", "symlab").strip().split() + + # determine if the calculation used regions or not + frag_order = reader_adf.read("Geometry", "fragment and atomtype index") + frag_order = frag_order[: len(frag_order) // 2] + ret.used_regions = max(frag_order) != len(frag_order) + + ret.charge = reader_adf.read("Molecule", "Charge") + + ret.spin_polarization = 0 + if ret.unrestricted_mos: + nalpha = 0 + nbeta = 0 + for label in ret.symmetry.labels: + nalpha += sum(ensure_list(reader_adf.read(label, "froc_A"))) + nbeta += sum(ensure_list(reader_adf.read(label, "froc_B"))) + ret.spin_polarization = nalpha - nbeta + ret.multiplicity = 2 * ret.spin_polarization + 1 + + return ret
+ + + +# ------------------------------------------------------------- # +# ------------------------ Properties ------------------------- # +# ------------------------------------------------------------- # + + +# ----------------------- VDD charges ------------------------- # + + +def _read_vdd_charges(kf_reader: KFReader) -> arrays.Array1D[np.float64]: + """Returns the VDD charges from the KFReader object.""" + vdd_scf: List[float] = ensure_list(kf_reader.read("Properties", "AtomCharge_SCF Voronoi")) # type: ignore since plams does not include typing for KFReader. List[float] is returned + vdd_ini: List[float] = ensure_list(kf_reader.read("Properties", "AtomCharge_initial Voronoi")) # type: ignore since plams does not include typing for KFReader. List[float] is returned + + # VDD charges are scf - initial charges. Note, these are in units of electrons while most often these are denoted in mili-electrons + return np.array([float((scf - ini)) for scf, ini in zip(vdd_scf, vdd_ini)]) + + +def _get_vdd_charges_per_irrep(results_type: KFReader) -> Dict[str, arrays.Array1D[np.float64]]: + """Extracts the Voronoi Deformation Density charges from the fragment calculation sorted per irrep.""" + symlabels = str(results_type.read("Symmetry", "symlab")).split() # split on whitespace + + # If there is only one irrep, there is no irrep decomposition + if len(symlabels) == 1: + return {} + + vdd_irrep = np.array(results_type.read("Properties", "Voronoi chrg per irrep")) + n_atoms = int(results_type.read("Molecule", "nAtoms")) # type: ignore since no static typing. Returns an int + + # NOTE: apparently, the irrep charges are minus the total VDD charges. That's why the minus sign in the second line below + vdd_irrep = vdd_irrep[-len(symlabels) * n_atoms :] # vdd_irrep = vdd_irrep.reshape((n_headers, len(symlabels), n_atoms)) # NOQA E203 + vdd_per_irrep = {irrep: -vdd_irrep[i * n_atoms : (i + 1) * n_atoms] for i, irrep in enumerate(symlabels)} # NOQA E203 + return vdd_per_irrep + + +# ----------------------- Vibrations ------------------------- # + + +def _read_vibrations(reader: cache.TrackKFReader) -> Result: + ret = Result() + ret.number_of_modes = reader.read("Vibrations", "nNormalModes") + ret.frequencies = ensure_list(reader.read("Vibrations", "Frequencies[cm-1]")) + if ("Vibrations", "Intensities[km/mol]") in reader: + ret.intensities = ensure_list(reader.read("Vibrations", "Intensities[km/mol]")) + ret.number_of_imag_modes = len([freq for freq in ret.frequencies if freq < 0]) + ret.character = "minimum" if ret.number_of_imag_modes == 0 else "transitionstate" + ret.modes = [] + for i in range(ret.number_of_modes): + ret.modes.append(reader.read("Vibrations", f"NoWeightNormalMode({i+1})")) + return ret + + +
+[docs] +def get_properties(info: Result) -> Result: + """Function to get properties from an ADF calculation. + + Args: + info: Result object containing ADF properties. + + Returns: + :Result object containing properties from the ADF calculation: + + - **energy.bond (float)** – bonding energy (|kcal/mol|). + - **energy.elstat.total (float)** – total electrostatic potential (|kcal/mol|). + - **energy.elstat.Vee (float)** – electron-electron repulsive term of the electrostatic potential (|kcal/mol|). + - **energy.elstat.Ven (float)** – electron-nucleus attractive term of the electrostatic potential (|kcal/mol|). + - **energy.elstat.Vnn (float)** – nucleus-nucleus repulsive term of the electrostatic potential (|kcal/mol|). + - **energy.orbint.total (float)** – total orbital interaction energy containing contributions from each symmetry label and correction energy(|kcal/mol|). + - **energy.orbint.{symmetry label} (float)** – orbital interaction energy from a specific symmetry label (|kcal/mol|). + - **energy.orbint.correction (float)** - orbital interaction correction energy, the difference between the total and the sum of the symmetrized interaction energies (|kcal/mol|) + - **energy.pauli.total (float)** – total Pauli repulsion energy (|kcal/mol|). + - **energy.dispersion (float)** – total dispersion energy (|kcal/mol|). + - **energy.gibbs (float)** – Gibb's free energy (|kcal/mol|). Only populated if vibrational modes were calculated. + - **energy.enthalpy (float)** – enthalpy (|kcal/mol|). Only populated if vibrational modes were calculated. + - **energy.nuclear_internal (float)** – nuclear internal energy (|kcal/mol|). Only populated if vibrational modes were calculated. + - **vibrations.number_of_modes (int)** – number of vibrational modes for this molecule, 3N-5 for non-linear molecules and 3N-6 for linear molecules, where N is the number of atoms. + - **vibrations.number_of_imag_modes (int)** – number of imaginary vibrational modes for this molecule. + - **vibrations.frequencies (float)** – vibrational frequencies associated with the vibrational modes, sorted from low to high (|cm-1|). + - **vibrations.intensities (float)** – vibrational intensities associated with the vibrational modes (|km/mol|). + - **vibrations.modes (list[float])** – list of vibrational modes sorted from low frequency to high frequency. + - **vibrations.character (str)** – Character of the molecule based on the number of imaginary vibrational modes. Can be "minimum" or "transition state". + - **vdd.charges (nparray[float] (1D))** - 1D array of Voronoi Deformation Denisty (VDD) charges in [electrons], being the difference between the final (SCF) and initial VDD charges. + - **vdd.charges.{symmetry label} (nparray[float] (1D))** - 1D array of Voronoi Deformation Denisty (VDD) charges in [electrons] per irrep. + - **s2** - expectation value of the :math:`S^2` operator. + - **s2_expected** - ideal expectation value of the :math:`S^2` operator. For restricted calculations this should always equal ``s2``. + - **spin_contamination** - the amount of spin-contamination observed in this calculation. It is equal to (s2 - s2_expected) / (s2_expected). Ideally this value should be below 0.1. + """ + + assert info.engine == "adf", f"This function reads ADF data, not {info.engine} data" + + ret = Result() + + if info.adf.task.lower() == "vibrationalanalysis": + reader_ams = cache.get(info.files["ams.rkf"]) + ret.vibrations = _read_vibrations(reader_ams) + return ret + + reader_adf = cache.get(info.files["adf.rkf"]) + + # read energies (given in Ha in rkf files) + ret.energy.bond = reader_adf.read("Energy", "Bond Energy") * constants.HA2KCALMOL + + # total electrostatic potential + ret.energy.elstat.total = reader_adf.read("Energy", "elstat") * constants.HA2KCALMOL + + # we can further decompose elstat if it was enabled + if info.files.out: + with open(info.files.out) as output: + lines = output.readlines() + + skip_next = -1 + for line in lines: + if "Electrostatic Interaction Energies" in line: + skip_next = 4 + continue + if skip_next == 0: + f1, f2, Vee, Ven, Vnn, total = line.strip().split() + ret.energy.elstat.Vee = float(Vee) * constants.HA2KCALMOL + ret.energy.elstat.Ven = float(Ven) * constants.HA2KCALMOL + ret.energy.elstat.Vnn = float(Vnn) * constants.HA2KCALMOL + skip_next -= 1 + + + # print(info.files) + + # read the total orbital interaction energy + ret.energy.orbint.total = reader_adf.read("Energy", "Orb.Int. Total") * constants.HA2KCALMOL + + # to calculate the orbital interaction term: + # the difference between the total and the sum of the symmetrized interaction energies should be calculated + # therefore the correction is first set equal to the total orbital interaction. + ret.energy.orbint.correction = ret.energy.orbint.total + + # looping over every symlabel, to get the energy per symmetry label + for symlabel in info.adf.symmetry.labels: + symlabel = symlabel.split(":")[0] + ret.energy.orbint[symlabel] = reader_adf.read("Energy", f"Orb.Int. {symlabel}") * constants.HA2KCALMOL + + # the energy per symmetry label is abstracted from the "total orbital interaction" + # obtaining the correction to the orbital interaction term + ret.energy.orbint.correction -= ret.energy.orbint[symlabel] + + ret.energy.pauli.total = reader_adf.read("Energy", "Pauli Total") * constants.HA2KCALMOL + ret.energy.dispersion = reader_adf.read("Energy", "Dispersion Energy") * constants.HA2KCALMOL + + if ("Thermodynamics", "Gibbs free Energy") in reader_adf: + ret.energy.gibbs = reader_adf.read("Thermodynamics", "Gibbs free Energy") * constants.HA2KCALMOL + ret.energy.enthalpy = reader_adf.read("Thermodynamics", "Enthalpy") * constants.HA2KCALMOL + ret.energy.nuclear_internal = reader_adf.read("Thermodynamics", "Internal Energy total") * constants.HA2KCALMOL + + # vibrational information + if ("Vibrations", "nNormalModes") in reader_adf: + ret.vibrations = _read_vibrations(reader_adf) + + # read the Voronoi Deformation Charges Deformation (VDD) before and after SCF convergence (being "inital" and "SCF") + try: + ret.vdd.charges = _read_vdd_charges(reader_adf) + ret.vdd.update(_get_vdd_charges_per_irrep(reader_adf)) + except KeyError: + pass + + # read spin-squared operator info + # the total spin + S = info.adf.spin_polarization * 1 / 2 + ret.s2_expected = S * (S + 1) + # this is the real expectation value + if ("Properties", "S2calc") in reader_adf: + ret.s2 = reader_adf.read("Properties", "S2calc") + else: + ret.s2 = 0 + + # calculate the contamination + # if S is 0 then we will get a divide by zero error, but spin-contamination should be 0 + if S != 0: + ret.spin_contamination = (ret.s2 - ret.s2_expected) / (ret.s2_expected) + else: + ret.spin_contamination = 0 + + return ret
+ + + +
+[docs] +def get_level_of_theory(info: Result) -> Result: + """Function to get the level-of-theory from an input-file. + + Args: + inp_path: Path to the input file. Can be a .run or .in file create for AMS + + Returns: + :Dictionary containing information about the level-of-theory: + + - **summary (str)** - a summary string that gives the level-of-theory in a human-readable format. + - **xc.functional (str)** - XC-functional used in the calculation. + - **xc.category (str)** - category the XC-functional belongs to. E.g. GGA, MetaHybrid, etc ... + - **xc.dispersion (str)** - the dispersion correction method used during the calculation. + - **xc.summary (str)** - a summary string that gives the XC-functional information in a human-readable format. + - **xc.empiricalScaling (str)** - which empirical scaling parameter was used. Useful for MP2 calculations. + - **basis.type (str)** - the size/type of the basis-set. + - **basis.core (str)** - the size of the frozen-core approximation. + - **quality (str)** - the numerical quality setting. + """ + sett = info.input + ret = Result() + # print(json.dumps(sett, indent=4)) + xc_categories = ["GGA", "LDA", "MetaGGA", "MetaHybrid", "Model", "LibXC", "DoubleHybrid", "Hybrid", "MP2", "HartreeFock"] + ret.xc.functional = "VWN" + ret.xc.category = "LDA" + for cat in xc_categories: + if cat.lower() in [key.lower() for key in sett.adf.xc]: + ret.xc.functional = sett.adf.xc[cat] + ret.xc.category = cat + + ret.basis.type = sett.adf.basis.type + ret.basis.core = sett.adf.basis.core + ret.quality = sett.adf.NumericalQuality or "Normal" + + ret.xc.dispersion = None + if "dispersion" in [key.lower() for key in sett.adf.xc]: + ret.xc.dispersion = " ".join(sett.adf.xc.dispersion.split()) + + # the empirical scaling value is used for MP2 calculations + ret.xc.empirical_scaling = None + if "empiricalscaling" in [key.lower() for key in sett.adf.xc]: + ret.xc.empiricalscaling = sett.adf.xc.empiricalscaling + + # MP2 and HF are a little bit different from the usual xc categories. They are not key-value pairs but only the key + # we start building the ret.xc.summary string here already. This will contain the human-readable functional name + if ret.xc.category == "MP2": + ret.xc.summary = "MP2" + if ret.xc.empiricalscaling: + ret.xc.summary += f"-{ret.xc.empiricalscaling}" + elif ret.xc.category == "HartreeFock": + ret.xc.summary = "HF" + else: + ret.xc.summary = ret.xc.functional + + # If dispersion was used, we want to add it to the ret.xc.summary + if ret.xc.dispersion: + if ret.xc.dispersion.lower() == "grimme3": + ret.xc.summary += "-D3" + if ret.xc.dispersion.lower() == "grimme3 bjdamp": + ret.xc.summary += "-D3(BJ)" + if ret.xc.dispersion.lower() == "grimme4": + ret.xc.summary += "-D4" + if ret.xc.dispersion.lower() == "ddsc": + ret.xc.summary += "-dDsC" + if ret.xc.dispersion.lower() == "uff": + ret.xc.summary += "-dUFF" + if ret.xc.dispersion.lower() == "mbd": + ret.xc.summary += "-MBD@rsSC" + if ret.xc.dispersion.lower() == "default": + ret.xc.summary += "-D" + + # ret.summary is simply the ret.xc.summary plus the basis set type + ret.summary = f"{ret.xc.summary}/{ret.basis.type}" + return ret
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results/ams.html b/docs/_build/html/_modules/tcutility/results/ams.html new file mode 100644 index 00000000..31ec78e5 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results/ams.html @@ -0,0 +1,991 @@ + + + + + + + + + + tcutility.results.ams — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results.ams

+import os
+import re
+from datetime import datetime
+from typing import List
+
+import numpy as np
+from scm import plams
+
+from tcutility import constants, ensure_list
+from tcutility.results import Result, cache
+from tcutility.tc_typing import arrays
+
+j = os.path.join
+
+
+
+[docs] +def get_calc_files(calc_dir: str) -> dict: + """Function that returns files relevant to AMS calculations stored in ``calc_dir``. + + Args: + calc_dir: path pointing to the desired calculation + + Returns: + Dictionary containing filenames and paths + """ + # collect all files in the current directory and subdirectories + files = [] + for root, _, files_ in os.walk(os.path.abspath(calc_dir)): + if os.path.split(root)[1].startswith("."): + continue + + # some results are stored in dirs called {name}.results, if the calculations uses fragments there will be additional dirs called + # {name}.{fragname}.results, which do not contain new information as the required info is copied over to {name}.results. Therefore + # we should skip the fragment directories + if os.path.split(root)[1].endswith(".results") and len(os.path.split(root)[1].split(".")) > 2: + continue + + # we only need the rkf files in the .results directories + if root.endswith(".rkf") and ".results" not in root: + continue + + # opened files end in ~ and should be ignored + if root.endswith("~"): + continue + + # t21 files for specific atoms are not usefull and should be ignored + if "t21." in root: + continue + + # if a calculation is running or did not finish correctly there might be tmp. dirs, which should be ignored + if os.path.split(root)[1].startswith("tmp."): + continue + + # the rest can all be stored + files.extend([j(root, file) for file in files_]) + + # parse the filenames + ret = {} + ret["root"] = os.path.abspath(calc_dir) + for file in files: + # rkf files are either called /{program}.rkf, or /{name}.{program}.rkf, so we must parse them in a special way + if file.endswith(".rkf"): + f = os.path.split(file)[1] + parts = f.split(".") + f = f"{parts[-2]}.rkf" + ret[f] = os.path.abspath(file) + + # logfiles are generally called either {name}.log or {name}.logfile + if file.endswith(".logfile") or file.endswith(".log") or file.endswith(".err"): + f = os.path.split(file)[1] + parts = f.split(".") + f = ".".join(parts[1:]).replace("logfile", "log") + ret[f] = os.path.abspath(file) + + if file.endswith(".out") and "CreateAtoms" not in file: + ret["out"] = os.path.abspath(file) + + return ret
+ + + +
+[docs] +def get_ams_version(calc_dir: str) -> Result: + """Function to get the AMS version used in the calculation. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Dictionary containing results about the AMS version: + + - **full (str)** – the full version string as written by SCM. + - **major (str)** – major AMS version, should correspond to the year of release. + - **minor (str)** – minor AMS version. + - **micro (str)** – micro AMS version, should correspond to the internal revision number. + - **date (datetime.datetime)** – date the AMS version was released. + """ + ret = Result() + files = get_calc_files(calc_dir) + reader_ams = cache.get(files["ams.rkf"]) + + # store information about the version of AMS + ret.full = str(reader_ams.read("General", "release")) + # decompose the full version string + ret.major = ret.full.split(".")[0] + ret.minor = ret.full.split()[0].split(".")[1] + ret.micro = ret.full.split()[1] + ret.date = datetime.strptime(ret.full.split()[-1][1:-1], "%Y-%m-%d") + + return ret
+ + + +
+[docs] +def get_ams_info(calc_dir: str) -> Result: + """Function to read useful info about the calculation in ``calc_dir``. Returned information will depend on the type of file that is provided. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Dictionary containing results about the calculation and AMS: + + - **ams_version (Result)** – information about the AMS version used, see :func:`get_ams_version`. + - **engine (str)** – the engine that was used to perform the calculation, for example 'adf', 'dftb', ... + - **job_id (str)** – the ID of the job, can be used to check if two calculations are the same. Might also be used as a unique identifier for the calculation. + - **status (Result)** – information about calculation status, see :func:`get_calculation_status`. + - **is_multijob (bool)** – whether the job was a multijob, for example a fragment analysis. + - **molecule (Result)** – information about the input and output molecules and the molecular system in general, see :func:`get_molecules`. + - **history (Result)** – information about history variables, see :func:`get_history`. + """ + ret = Result() + ret.files = get_calc_files(calc_dir) + reader_ams = cache.get(ret.files["ams.rkf"]) + + # check what the program is first. The program can be either AMS or one of the engines (ADF, DFTB, ...) + if ("General", "engine") in reader_ams: + ret.engine = str(reader_ams.read("General", "engine")).strip().lower() + # if program cannot be read from reader it is probably an old version of ADF, so we should default to ADF + else: + ret.engine = "adf" + + # store the input of the calculation + ret.input = get_ams_input(reader_ams.read("General", "user input")) + + # store the job id, which should be unique for the job + ret.job_id = reader_ams.read("General", "jobid") if ("General", "jobid") in reader_ams else None + + # store information about the version of AMS + ret.ams_version = get_ams_version(calc_dir) + + # store the computation timings, only available in ams.rkf + ret.timing = get_timing(calc_dir) + + # store the calculation status + ret.status = get_calculation_status(calc_dir) + + # check if this was a multijob + ret.is_multijob = False + if len([file for file in ret.files if file.endswith(".rkf")]) > 2: + ret.is_multijob = True + + # read molecules + ret.molecule = get_molecules(calc_dir) + + # and history variables + ret.history = get_history(calc_dir) + + ret.pes = get_pes(calc_dir) + + cache.unload(ret.files["ams.rkf"]) + return ret
+ + + +
+[docs] +def get_timing(calc_dir: str) -> Result: + """Function to get the timings from the calculation. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Dictionary containing results about the timings: + + - **cpu (float)** – time spent performing calculations on the cpu. + - **sys (float)** – time spent by the system (file IO, process creation/destruction, etc ...). + - **total (float)** – total time spent by AMS on the calculation, can be larger than the sum of cpu and sys. + """ + ret = Result() + files = get_calc_files(calc_dir) + reader_ams = cache.get(files["ams.rkf"]) + + ret.cpu = reader_ams.read("General", "CPUTime") if ("General", "CPUTime") in reader_ams else None + ret.sys = reader_ams.read("General", "SysTime") if ("General", "SysTime") in reader_ams else None + ret.total = reader_ams.read("General", "ElapsedTime") if ("General", "ElapsedTime") in reader_ams else None + + return ret
+ + + +
+[docs] +def get_calculation_status(calc_dir: str) -> Result: + """Function that returns the status of the calculation described in reader. + In case of non-succes it will also give possible reasons for the errors/warnings. + + Args: + reader: ``plams.KFReader`` or ``plams.KFFile`` object pointing to the desired calculation + + Returns: + :Dictionary containing information about the calculation status: + + - **fatal (bool)** – True if calculation cannot be analysed correctly, False otherwise + - **reasons (list[str])** – list of reasons to explain the status, they can be errors, warnings, etc. + - **name (str)** – calculation status written as a string, one of ("SUCCESS", "RUNNING", "UNKNOWN", "SUCCESS(W)", "FAILED") + - **code (str)** – calculation status written as a single character, one of ("S", "R", "U", "W" "F") + """ + files = get_calc_files(calc_dir) + reader_ams = cache.get(files["ams.rkf"]) + + ret = Result() + ret.fatal = True + ret.name = None + ret.code = None + ret.reasons = [] + + termination_status = str(reader_ams.read("General", "termination status")).strip() + + # parse the logfile to find errors and warnings + if "log" in files: + with open(files["log"]) as logfile: + for line in logfile.readlines(): + # the first 25 characters include the timestamp and two spaces + line_ = line.strip()[25:] + # errors and warnings have a predictable format + if line_.lower().startswith("error:") or line_.lower().startswith("warning: "): + ret.reasons.append(line_) + + if termination_status == "NORMAL TERMINATION": + ret.fatal = False + ret.name = "SUCCESS" + ret.code = "S" + return ret + + if termination_status == "IN PROGRESS": + ret.fatal = False + ret.reasons.append("Calculation in progress") + ret.name = "RUNNING" + ret.code = "R" + return ret + + if termination_status == "UNKNOWN": + ret.reasons.append("Calculation status unknown") + ret.name = "UNKNOWN" + ret.code = "U" + return ret + + if termination_status == "NORMAL TERMINATION with warnings": + ret.fatal = False + ret.name = "SUCCESS(W)" + ret.code = "W" + return ret + + if termination_status == "NORMAL TERMINATION with errors": + ret.name = "FAILED" + ret.code = "F" + return ret + + # if we have not excited the function yet we do not know what the status is + # probably means that there was a parsing error in ams, which will be placed in termination status + ret.reasons.append(termination_status) + ret.name = "UNKNOWN" + ret.code = "U" + return ret
+ + + +# ------------------------------------------------------------- # +# ------------------------- Geometry -------------------------- # +# ------------------------------------------------------------- # + + +# -------------------- Fragment indices ----------------------- # + + +def _get_fragment_indices_from_input_order(results_type) -> arrays.Array1D: + """Function to get the fragment indices from the input order. This is needed because the fragment indices are stored in internal order in the rkf file.""" + frag_indices = np.array(results_type.read("Geometry", "fragment and atomtype index")).reshape(2, -1) # 1st row: Fragment index; 2nd row atomtype index + atom_order = np.array(results_type.read("Geometry", "atom order index")).reshape(2, -1) # 1st row: input order; 2nd row: internal order + return frag_indices[0][atom_order[0] - 1] + + +# ------------------------ Molecule -------------------------- # + + +def _make_molecule(kf_variable: str, reader_ams: plams.KFReader, natoms: int, atnums: List[int]) -> plams.Molecule: + """Makes a plams.Molecule object from the given kf_variable ("InputMolecule" or "Molecule") and reader.""" + # read output molecule + ret_mol = plams.Molecule() + coords = np.array(reader_ams.read(kf_variable, "Coords")).reshape(natoms, 3) * constants.BOHR2ANG + for atnum, coord in zip(atnums, coords): + ret_mol.add_atom(plams.Atom(atnum=atnum, coords=coord)) + if ("Molecule", "fromAtoms") in reader_ams and ("Molecule", "toAtoms") in reader_ams and ("Molecule", "bondOrders"): + at_from = ensure_list(reader_ams.read("InputMolecule", "fromAtoms")) + at_to = ensure_list(reader_ams.read("InputMolecule", "toAtoms")) + bos = ensure_list(reader_ams.read("InputMolecule", "bondOrders")) + for at1, at2, order in zip(at_from, at_to, bos): + ret_mol.add_bond(plams.Bond(ret_mol[at1], ret_mol[at2], order=order)) + else: + ret_mol.guess_bonds() + return ret_mol + + +
+[docs] +def get_molecules(calc_dir: str) -> Result: + """ + Function to get molecules from the calculation, including input, output and history molecules. + It will also add bonds to the molecule if they are given in the rkf file, else it will guess them. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Dictionary containing information about the molecular systems: + + - **number_of_atoms (int)** – number of atoms in the molecule. + - **atom_numbers (list[int])** – list of atomic numbers for each atom in the molecule. + - **atom_symbols (list[str])** – list of elements for each atom in the molecule. + - **atom_masses (list[float])** – list of atomic masses for each atom in the molecule. + - **input (plams.Molecule)** – molecule that was given in the input for the calculation. + - **output (plams.Molecule)** – final molecule that was given as the output for the calculation. If the calculation was a singlepoint calculation output and input molecules will be the same. + - **frag_indices (numpy array[int] (1D))** – list of fragment indices for each atom in the molecule. The indices are given in the order of the atoms in the molecule. + """ + files = get_calc_files(calc_dir) + # all info is stored in reader_ams + reader_ams = cache.get(files["ams.rkf"]) + + ret = Result() + + # read general + atnums = ensure_list(reader_ams.read("InputMolecule", "AtomicNumbers")) # type: ignore plams does not include type hints. Returns list[int] + natoms = len(atnums) + ret.number_of_atoms = natoms + ret.atom_numbers = atnums + ret.atom_symbols = str(reader_ams.read("InputMolecule", "AtomSymbols")).split() + ret.atom_masses = reader_ams.read("InputMolecule", "AtomMasses") + + # read input molecule + ret.input = _make_molecule("InputMolecule", reader_ams, natoms, atnums) + + # read output molecule + ret.output = _make_molecule("Molecule", reader_ams, natoms, atnums) + + # add fragment indices to the molecule using adf file + try: + reader_adf = cache.get(files["adf.rkf"]) + ret.frag_indices = _get_fragment_indices_from_input_order(reader_adf) + except KeyError: + ret.frag_indices = np.ones(natoms) + + # add the charges to the molecule + try: + ret.mol_charge = reader_ams.read("Molecule", "Charge") + except KeyError: + ret.mol_charge = 0.0 + + return ret
+ + + +
+[docs] +def get_pes(calc_dir: str) -> Result: + """ + Function to get PES scan variables. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Dictionary containing information about the PES scan: + + - ``nscan_coords`` **int** – the number of scan-coordinates for this PES scan. + - ``scan_coord_name`` **list[str] | str** – the names of the scan-coordinates. + If there is more than one scan-coordinates it will be a list of strings, otherwise it will be a single string. + - ``scan_coord`` **list[np.ndarray] | np.ndarray** – arrays of values for the scan-coordinates. + If there is more than one scan-coordinates it will be a list of arrays, otherwise it will be a single array. + - ``npoints`` **list[int] | int** – number of scan points for the scan-coordinates. + If there is more than one scan-coordinates it will be a list of integers, otherwise it will be a single integer. + """ + # read history mols + files = get_calc_files(calc_dir) + # all info is stored in reader_ams + reader_ams = cache.get(files["ams.rkf"]) + + # check if we have done a PESScan + if ("PESScan", "nPoints") not in reader_ams: + return + + ret = Result() + + ret.nscan_coords = reader_ams.read("PESScan", "nScanCoord") + ret.scan_coord_name = [reader_ams.read("PESScan", f"ScanCoord({i+1})").strip() for i in range(ret.nscan_coords)] + ret.npoints = [reader_ams.read("PESScan", f"nPoints({i+1})") for i in range(ret.nscan_coords)] + ret.scan_coord = [np.linspace(reader_ams.read("PESScan", f"RangeStart({i+1})"), reader_ams.read("PESScan", f"RangeEnd({i+1})"), ret.npoints[i]) for i in range(ret.nscan_coords)] + if ("PESScan", "PES") in reader_ams: + ret.energies = np.array(reader_ams.read("PESScan", "PES")).reshape(*ret.npoints) * constants.HA2KCALMOL + + if ret.nscan_coords == 1: + ret.scan_coord_name = ret.scan_coord_name[0] + ret.scan_coord = ret.scan_coord[0] + ret.npoints = ret.npoints[0] + + return ret
+ + + +
+[docs] +def get_history(calc_dir: str) -> Result: + """ + Function to get history variables. The type of variables read depends on the type of calculation. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Dictionary containing information about the calculation status: + + - ``number_of_entries`` **(int)** – number of steps in the history. + - ``{variable}`` **(list[Any])** – variable read from the history section. The number of variables and type of variables depend on the nature of the calculation. + + Common variables: + | ``Molecule`` **(list[plams.Molecule])** – list of molecules from the history, for example from a geometry optimization or PES scan. + | ``energy`` **(list[float])** – list of energies associated with each geometry step. + | ``gradient`` **(list[list[float]])** – array of gradients for each geometry step and each atom. + """ + # read history mols + files = get_calc_files(calc_dir) + # all info is stored in reader_ams + reader_ams = cache.get(files["ams.rkf"]) + + ret = Result() + + # read general info + atnums = ensure_list(reader_ams.read("InputMolecule", "AtomicNumbers")) # type: ignore plams does not include type hints. Returns list[int] + natoms = len(atnums) + + if ("History", "nEntries") in reader_ams: + # the number of elements per history variable (e.g. number of steps in a geometry optimization) + ret.number_of_entries = reader_ams.read("History", "nEntries") + # for history we read the other variables in the rkf file + # the variables are given in ('History', f'ItemName({index})') so we have to find all of those + index = 1 # tracks the current index of the variable. Will be set to False to stop the search + items = [] + while index: + # try to access ItemName, if it cannot find it stop iteration + try: + item_name = reader_ams.read("History", f"ItemName({index})") + items.append(item_name) + index += 1 + except KeyError: + index = False + + if "Coords" in items: + items.append("Molecule") + + # create variable in result for each variable found + for item in items: + ret[item.lower()] = [] + + # collect the elements for each history variable + for i in range(ret.number_of_entries): + for item in items: + # Molecule are special, because we will convert them to plams.Molecule objects first + if item == "Molecule": + mol = plams.Molecule() + coords = np.array(reader_ams.read("History", f"Coords({i+1})")).reshape(natoms, 3) * 0.529177 + for atnum, coord in zip(atnums, coords): + mol.add_atom(plams.Atom(atnum=atnum, coords=coord)) + mol.guess_bonds() + ret.molecule.append(mol) + # other variables are just added as-is + else: + val = reader_ams.read("History", f"{item}({i+1})") + ret[item.lower()].append(val) + + if "converged" not in ret.keys() and ("PESScan", "HistoryIndices") in reader_ams: + ret["converged"] = [False] * ret.number_of_entries + for idx in ensure_list(reader_ams.read("PESScan", "HistoryIndices")): + ret["converged"][idx - 1] = True + + return ret
+ + + +
+[docs] +def get_input_blocks(): + """ + This function reads input_blocks and decomposes its content into a list of blocks and a list of non-standard blocks + The general format is as follows: + + parentblock + - subblock + - - subsubblock + - subblock !nonstandard + parentblock + - subblock + - - subsubblock + - - - subsubsubblock + - - - subsubsubblock !nonstandard + + Each subblock has to be defined within its parent block. !nonstandard indicates that the block is a non-standard block + These blocks are special in that they can contain multiple of the same entry + """ + blocks = [] + nonstandard_blocks = [] + parent_blocks = [] # this list tracks the parent blocks of the current block + with open(j(os.path.split(__file__)[0], "input_blocks")) as inpblx: + lines = inpblx.readlines() + + for line in lines: + line = line.strip().lower() + # we can ignore some lines + if line == "" or line.startswith("#"): + continue + + # block_depth indicates how many parents the block has + block_depth = line.count("- ") + # we reduce the amount of parent_blocks using block_depth + # if we move from a subsubblock to a subblock we remove the last-added block + parent_blocks = parent_blocks[:block_depth] + + # remove the "- " substrings + block = line.split("- ")[-1].strip().lower() + # check if the block is non-standard. If it is, remove the !nonstandard substring + # and add it to the nonstandard_blocks list + if block.endswith("!nonstandard"): + block = block.split()[0] + nonstandard_blocks.append(parent_blocks.copy() + [block]) + # in both standard and nonstandard cases add the block to blocks list + blocks.append(parent_blocks.copy() + [block]) + # add the current block to parent_blocks for the next line + parent_blocks.append(block.lower()) + + return blocks, nonstandard_blocks
+ + + +
+[docs] +def get_ams_input(inp: str) -> Result: + def get_possible_blocks(): + # check which blocks are openable given the current open blocks + # we start by considering all blocks + possible_blocks = blocks + # we iterate through the open blocks and check if the first element in the possible_blocks is the same. + # this way we move down through the blocks + for open_block in open_blocks: + possible_blocks = [block[1:] for block in possible_blocks if len(block) > 0 and block[0].lower() == open_block.lower()] + # we want only the first element in the possible blocks, not the tails + possible_blocks = set([block[0] for block in possible_blocks if len(block) > 0]) + return possible_blocks + + sett = Result() + + blocks, nonstandard_blocks = get_input_blocks() + + open_blocks = ["ams"] + for line in inp.splitlines(): + line = line.strip() + + # we remove comments from the line + # comments can be either at the start of a line or after a real statement + # so we have to search the line for comment starters and remove the part after it + for comment_start in ["#", "!", "::"]: + if comment_start in line: + idx = line.index(comment_start) + line = line[:idx] + + # skip empty lines + if not line: + continue + + # if we encounter an end statement we can close the last openblock + if line.lower().startswith("end"): + open_blocks.pop(-1) + continue + + # check if we are opening a block + # We have to store the parts of a compact block (if it is compact) + # it will be a list of tuples of key-value pairs + compact_parts = None + skip = False + # check if the current line corresponds to a possible block + for possible_block in get_possible_blocks(): + if line.lower().startswith(possible_block.lower()): + # a block opening can either span multiple lines or can be use with compact notation + # compact notation will always have = signs + if "=" in line: + # split the key-values using some regex magic + compact = line[len(possible_block) :].strip() # remove the block name + compact_parts = re.findall(r"""(\S+)=['"]{0,1}([^'"\n]*)['"]{0,1}""", compact) + else: + skip = True + # add the new block to the open_blocks + open_blocks.append(possible_block) + + # if we are not in a compact block we can just skip + if skip: + continue + + # get the sett to the correct level + # first check if the block is nonstandard + is_nonstandard = [block.lower() for block in open_blocks] in nonstandard_blocks + sett_ = sett + # go to the layer one above the lowest + for open_block in open_blocks[:-1]: + sett_ = sett_[open_block] + # at the lowest level we have to check if the block is nonstandard. If it is, we add the whole line to the settings object + if is_nonstandard and not sett_[open_blocks[-1]]: + sett_[open_blocks[-1]] = [] + # then finally go to the lowest sett layer + sett_ = sett_[open_blocks[-1]] + + # if we are in a compact block we just add all the key-value pairs + if compact_parts: + for key, val in compact_parts: + sett_[key] = val + # compact blocks do not have end statements, so we can remove it again from the open_blocks + open_blocks.pop(-1) + # in a normal block we split the line and add them to the settings + else: + # for nonstandard blocks we add the line to the list + if is_nonstandard: + sett_.append(line.strip()) + # for normal blocks we split the line and set it as a key, the rest of the line is the value + else: + sett_[line.split()[0]] = line[len(line.split()[0]) :].strip() + + for engine_block in ["engine adf", "engine dftb", "engine band"]: + if engine_block not in sett["ams"]: + continue + sett["ams"][engine_block.split()[1]] = sett["ams"][engine_block] + del sett["ams"][engine_block] + + return sett["ams"]
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results/cache.html b/docs/_build/html/_modules/tcutility/results/cache.html new file mode 100644 index 00000000..c0b7bf54 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results/cache.html @@ -0,0 +1,429 @@ + + + + + + + + + + tcutility.results.cache — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results.cache

+"""
+Tiny module that handles caching rkf files.
+rkf files take a long time to open (especially {engine}.rkf), so it is better to open them once and cache them for later use
+"""
+from typing import Any, Union
+
+from scm import plams
+
+# the actual cache is stored in this dict
+_cache = {}
+
+
+
+[docs] +class TrackKFReader(plams.KFReader): + """Subclass of plams.KFReader that also tracks the variables that were read. This class can be useful to figure out which variables are important. + For example, we can then trim rkf files to reduce their filesizes.""" + + def __init__(self, *args, **kwargs): + self.tracker = [] + super().__init__(*args, **kwargs) + +
+[docs] + def read(self, section: str, variable: str) -> Any: + """Read a variable from a section of an rkf file and store the accessed section and variable in the tracker. + + Args: + section: Name of the section to read from. + variable: Name of the variable inside the section. + + Returns: + Any value returned will be automatically converted into the correct type. E.g. text-based data will be converted to a string, numbers to floats or integers, etc.""" + + self.tracker.append((section, variable)) + return super().read(section, variable)
+
+ + + +
+[docs] +def store(reader: plams.KFReader) -> None: + """Store an rkf reader in the cache. It can later be indexed by its path. + + Args: + reader: An rkf file reader object.""" + path = reader.path + _cache[path] = reader
+ + + +
+[docs] +def get(path: str) -> plams.KFReader: + """Retrieve an rkf reader from storage using its path. If the file was not opened yet, open it first and then store and return the new object. + + Args: + path: path to the rkf file location. + + Returns: + An rkf file reader that can be used for reading data from a calculation. + """ + if not path: + return None + + # if the path is already in the cache, simply return it + if path in _cache: + return _cache[path] + # else we will load the rkf file and store it in the cache + reader = TrackKFReader(path) + store(reader) + return reader
+ + + +
+[docs] +def unload(arg: Union[str, plams.KFReader]): + """Delete an rkf reader from storage. Since rkf files can be quite large, we should not forget to unload them after we have finished reading from them, lest we run into memory issues. + + Args: + arg: Either a path pointing to the rkf file location or the reader itself.""" + # if the arg is a key in the cache we will delete the key + if arg in _cache: + del _cache[arg] + return + # if it is not a key, find the key corresponding to the value and delete it + if arg in _cache.values(): + key = [key for key, val in _cache.items() if val == arg][0] + del _cache[key] + return
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results/dftb.html b/docs/_build/html/_modules/tcutility/results/dftb.html new file mode 100644 index 00000000..a0c188b3 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results/dftb.html @@ -0,0 +1,430 @@ + + + + + + + + + + tcutility.results.dftb — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results.dftb

+from tcutility.results import cache, Result
+from tcutility import ensure_list, constants
+
+
+
+[docs] +def get_calc_settings(info: Result) -> Result: + """ + Function to read useful calculation settings from kf reader + """ + + assert info.engine == "dftb", f"This function reads DFTB data, not {info.engine} data" + + if info.input.task == 'PESScan': + return Result() + + assert "dftb.rkf" in info.files, f'Missing dftb.rkf file, [{", ".join([": ".join(item) for item in info.files.items()])}]' + + ret = Result() + + # set the calculation task at a higher level + ret.task = info.input.task + + return ret
+ + + +
+[docs] +def get_properties(info: Result) -> Result: + """Function to get properties from an DFTB calculation. + + Args: + info: Result object containing DFTB properties. + + Returns: + :Result object containing properties from the DFTB calculation: + + - **energy.bond (float)** – bonding energy (|kcal/mol|). + """ + + assert info.engine == "dftb", f"This function reads DFTB data, not {info.engine} data" + + if info.input.task == 'PESScan': + return Result() + + assert "dftb.rkf" in info.files, f'Missing dftb.rkf file, [{", ".join([": ".join(item) for item in info.files.items()])}]' + + reader_dftb = cache.get(info.files["dftb.rkf"]) + ret = Result() + + # properties are not given as in ADF. Instead you must first know which index each key is at. For example we might have: + # (Properties, SubType(k)) == Coulomb + # therefore, to get the Coulomb energy we first have to know the index k + # we therefore first loop through every subtype entry and store the substypes in order in a list + # we also store the main type (e.g. 'Energy', 'Gradient', ...) and the value + number_of_properties = reader_dftb.read("Properties", "nEntries") + subtypes = [] + types = [] + values = [] + for i in range(1, number_of_properties + 1): + subtypes.append(reader_dftb.read("Properties", f"Subtype({i})").strip()) + types.append(reader_dftb.read("Properties", f"Type({i})").strip()) + if types[-1] == 'Energy': + values.append(reader_dftb.read("Properties", f"Value({i})") * constants.HA2KCALMOL) + else: + values.append(reader_dftb.read("Properties", f"Value({i})")) + + # then simply add the properties to ret + for typ, subtyp, value in zip(types, subtypes, values): + ret[typ.replace(" ", "_")][subtyp] = value + + if ret.energy['DFTB Final Energy']: + ret.energy.bond = ret.energy['DFTB Final Energy'] + + # we also read vibrations + if ('Vibrations', 'nNormalModes') in reader_dftb: + ret.vibrations.number_of_modes = reader_dftb.read("Vibrations", "nNormalModes") + ret.vibrations.frequencies = ensure_list(reader_dftb.read("Vibrations", "Frequencies[cm-1]")) + if ("Vibrations", "Intensities[km/mol]") in reader_dftb: + ret.vibrations.intensities = ensure_list(reader_dftb.read("Vibrations", "Intensities[km/mol]")) + ret.vibrations.number_of_imag_modes = len([freq for freq in ret.vibrations.frequencies if freq < 0]) + ret.vibrations.character = "minimum" if ret.vibrations.number_of_imag_modes == 0 else "transitionstate" + ret.vibrations.modes = [] + for i in range(ret.vibrations.number_of_modes): + ret.vibrations.modes.append(reader_dftb.read("Vibrations", f"NoWeightNormalMode({i+1})")) + + if ("Thermodynamics", "Gibbs free Energy") in reader_dftb: + ret.energy.gibbs = reader_dftb.read("Thermodynamics", "Gibbs free Energy") * constants.HA2KCALMOL + ret.energy.enthalpy = reader_dftb.read("Thermodynamics", "Enthalpy") * constants.HA2KCALMOL + ret.energy.nuclear_internal = reader_dftb.read("Thermodynamics", "Internal Energy total") * constants.HA2KCALMOL + + return ret
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results/orca.html b/docs/_build/html/_modules/tcutility/results/orca.html new file mode 100644 index 00000000..32434df3 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results/orca.html @@ -0,0 +1,928 @@ + + + + + + + + + + tcutility.results.orca — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results.orca

+from tcutility.results import Result
+from tcutility import constants, slurm
+import os
+from scm import plams
+import numpy as np
+
+
+j = os.path.join
+
+
+
+[docs] +def get_calc_files(calc_dir: str) -> Result: + """Function that returns files relevant to ORCA calculations stored in ``calc_dir``. + + Args: + calc_dir: path pointing to the desired calculation + + Returns: + Result object containing filenames and paths + """ + # collect all files in the current directory and subdirectories + files = [] + for root, _, files_ in os.walk(calc_dir): + files.extend([j(root, file) for file in files_]) + + # we now go through all the files and check their nature + ret = Result() + ret.root = os.path.abspath(calc_dir) + for file in files: + with open(file, errors='ignore') as f: + lines = f.readlines() + # detect the output file + if any(["* O R C A *" in line for line in lines]): + ret.out = os.path.abspath(file) + continue + + # detect the input file + # there should be lines starting with ! and also the system line, starting with * xyz, * xyzfile, * gzmtfile or * int + if any([line.startswith('!') for line in lines]) and any([(len(line.split()) > 2 and line.split()[0] == '*' and line.split()[1] in ['xyz', 'xyzfile', 'gzmtfile', 'int']) for line in lines]): + ret.inp = os.path.abspath(file) + continue + + return ret
+ + + +
+[docs] +def get_version(info: Result) -> Result: + """Function to get the ORCA version used in the calculation. + + Args: + info: Result object containing ORCA calculation settings. + + Returns: + :Result object containing results about the ORCA version: + + - **full (str)** – the full version string as written by ORCA. + - **major (str)** – major ORCA version. + - **minor (str)** – minor ORCA version. + - **micro (str)** – micro ORCA version. + """ + ret = Result() + with open(info.files.out) as out: + for line in out.readlines(): + line = line.strip() + if "Program Version" not in line: + continue + version = line.split()[2] + ret.full = version + ret.major = version.split(".")[0] + ret.minor = version.split(".")[1] + ret.micro = version.split(".")[2] + return ret
+ + + +
+[docs] +def get_input(info: Result) -> Result: + """Function that parses the input file for this ORCA calculation. + + Args: + info: Result object containing ORCA calculation settings. + + Returns: + :Result object containing information about the calculation input: + + - **main (list[str])** - the main inputs for the calculation. These are the lines that start with a "!". + - **sections (Result)** - extra settings added to the calculation. These are the lines that start with a "%" and optionally end with "END" clause. + - **system (Result)** - settings related to the molecular system. This includes charge, multiplicity and the coordinates. + - **task (str)** - the task that was performed by the calculation, e.g. "SinglePoint", "TransitionStateSearch". + """ + ret = Result() + + # we read the input file first + if 'inp' in info.files: + with open(info.files.inp) as inp: + lines = inp.readlines() + # if we don't have it we read the output file, which contains the input as a block + else: + with open(info.files.out) as out: + start_reading = False + lines = [] + for line in out.readlines(): + line = line.strip() + if start_reading: + lines.append(line) + + if "INPUT FILE" in line: + start_reading = True + continue + + if "****END OF INPUT****" in line: + break + + lines = [line.split(">")[1] for line in lines[2:-1] if line.split(">")[1].strip()] + + ret.main = [] + curr_section = None + read_system = False + system_lines = [] + coordinates = None + for line in lines: + line = line.strip() + + if line.startswith("!"): + ret.main.extend(line.strip("!").split()) + + if curr_section: + if line.lower() == "end": + curr_section = None + continue + + var, val = line.split() + ret.sections[curr_section][var] = val + + if line.startswith("%"): + curr_section = line.split()[0][1:] + if len(line.split()) == 2: + ret.sections[curr_section] = line.split()[1] + curr_section = None + + if read_system: + if line == "*": + read_system = False + continue + + system_lines.append(line) + + if line.startswith("*"): + read_system = True + _, coordinates, charge, multiplicity = line.split()[:4] + if coordinates == "xyz": + ret.system.coordinate_system = "cartesian" + elif coordinates == "int": + ret.system.coordinate_system = "internal" + elif coordinates == "xyzfile": + ret.system.coordinate_system = "cartesian" + read_system = False + ret.system.charge = charge + ret.system.multiplicity = multiplicity + continue + + if coordinates in ["xyz", "int"]: + ret.system.molecule = plams.Molecule() + for line in system_lines: + line = line.replace(':', '') + ret.system.molecule.add_atom(plams.Atom(symbol=line.split()[0], coords=[float(x) for x in line.split()[1:4]])) + + ret.task = "SinglePoint" + if "optts" in [x.lower() for x in ret.main]: + ret.task = "TransitionStateSearch" + elif "opt" in [x.lower() for x in ret.main]: + ret.task = "GeometryOptimization" + + return ret
+ + + +
+[docs] +def get_level_of_theory(info: Result) -> Result: + """Function to get the level-of-theory from an input-file. + + Args: + info: Result object containing ORCA calculation settings. + + Returns: + :Result object containing information about the level-of-theory: + + - **summary (str)** - a summary string that gives the level-of-theory in a human-readable format. + - **basis.type (str)** - the size/type of the basis-set. + - **UsedQROs (bool)** - whether QROs were used. + """ + sett = info.input + ret = Result() + main = [x.lower() for x in sett.main] + ret.method = 'HF' + for method in ["MP2", "CCSD", "CCSD(T)", "CCSDT"]: + if method.lower() in main: + ret.method = method + break + + ret.basis.type = 'def2-SVP' + for bs in ["cc-pVDZ", "cc-pVTZ", "cc-pVQZ", "cc-pV5Z", "aug-cc-pVDZ", "aug-cc-pVTZ", "aug-cc-pVQZ", "aug-cc-pV5Z"]: + if bs.lower() in main: + ret.basis.type = bs + + used_qros = sett.sections.mdci.UseQROs and sett.sections.mdci.UseQROs.lower() == "true" + ret.summary = f'{"QRO-" if used_qros else ""}{method}/{ret.basis.type}' + + return ret
+ + + +
+[docs] +def get_calc_settings(info: Result) -> Result: + """Function to read calculation settings for an ORCA calculation. + + Args: + info: Result object containing ORCA calculation settings. + + Returns: + :Result object containing properties from the ORCA calculation: + + - **task (str)** – the task that was set for the calculation. + - **unrestricted (bool)** – whether or not the wavefunction is treated in an unrestricted manner. + - **used_qros (bool)** - whether the reference wavefunction is transformed to a QRO wavefunction. + - **frequencies (bool)** - whether vibrational frequencies were calculated. + - **charge (int)** - the charge of the molecular system. + - **spin_polarization (int)** - the spin-polarization of the molecular system. + - **multiplicity (int)** - the multiplicity of the molecular system. + """ + + assert info.engine == "orca", f"This function reads ORCA data, not {info.engine} data" + + ret = Result() + + # set the calculation task at a higher level + ret.task = info.input.task + + main = [x.lower() for x in info.input.main] + # determine if the wavefunction are unrestricted or not + ret.unrestricted = any(tag in main for tag in ["uhf", "uno"]) + ret.used_qros = info.input.sections.mdci.UseQROs and info.input.sections.mdci.UseQROs.lower() == "true" + ret.frequencies = "freq" in main or 'numfreq' in main + ret.charge = int(info.input.system.charge) + ret.spin_polarization = int(info.input.system.multiplicity) - 1 + ret.multiplicity = int(info.input.system.multiplicity) + return ret
+ + + +
+[docs] +def get_calculation_status(info: Result) -> Result: + """Function that returns the status of the ORCA calculation described in reader. In case of non-succes it will also give possible reasons for the errors/warnings. + + Args: + info: Result object containing ORCA calculation information. + + Returns: + :Result object containing information about the calculation status: + + - **fatal (bool)** – True if calculation cannot be analysed correctly, False otherwise + - **reasons (list[str])** – list of reasons to explain the status, they can be errors, warnings, etc. + - **name (str)** – calculation status written as a string, one of ("SUCCESS", "RUNNING", "UNKNOWN", "SUCCESS(W)", "FAILED") + - **code (str)** – calculation status written as a single character, one of ("S", "R", "U", "W" "F") + """ + ret = Result() + ret.fatal = True + ret.name = None + ret.code = None + ret.reasons = [] + + # if we do not have an output file the calculation failed + if "out" not in info.files.out: + ret.reasons.append("Calculation status unknown") + ret.name = "UNKNOWN" + ret.code = "U" + return ret + + # try to read if the calculation succeeded + with open(info.files.out) as out: + lines = out.readlines() + if any(["ORCA TERMINATED NORMALLY" in line for line in lines]): + ret.fatal = False + ret.name = "SUCCESS" + ret.code = "S" + return ret + + # if it didnt we default to failed + ret.name = "FAILED" + ret.code = "F" + + # otherwise we check if the job is being managed by slurm + if not slurm.workdir_info(os.path.abspath(info.files.root)): + return ret + + # get the statuscode from the workdir + state = slurm.workdir_info(os.path.abspath(info.files.root)).statuscode + state_name = { + 'CG': 'COMPLETING', + 'CF': 'CONFIGURING', + 'PD': 'PENDING', + 'R': 'RUNNING' + }.get(state, 'UNKNOWN') + + ret.fatal = False + ret.name = state_name + ret.code = state + ret.reasons = [] + + return ret
+ + + +
+[docs] +def get_molecules(info: Result) -> Result: + """Function that returns information about the molecules for this calculation. + + Args: + info: Result object containing ORCA calculation information. + + Returns: + :Result object containing properties from the ORCA calculation: + + - **input (plams.Molecule)** - the input molecule for this calculation. + - **output (plams.Molecule)** - the output molecule for this calculation, for example the optimized structure after a geometry optimization. + - **number_of_atoms (int)** - the number of atoms in the molecular system. + """ + ret = Result() + ret.input = info.input.system.molecule + ret.number_of_atoms = len(ret.input.atoms) + + with open(info.files.out) as out: + lines = out.readlines() + lines = [line.strip() for line in lines] + + start_reading = False + look_for_coords = False + coords = [] + for line in lines: + if start_reading: + if len(line) == 0: + start_reading = False + break + + coords.append(line) + + if "THE OPTIMIZATION HAS CONVERGED" in line: + look_for_coords = True + + if look_for_coords and "CARTESIAN COORDINATES (ANGSTROEM)" in line: + look_for_coords = False + start_reading = True + + ret.output = plams.Molecule() + for coord in coords[1:]: + sym, x, y, z = coord.split() + ret.output.add_atom(plams.Atom(symbol=sym, coords=[float(x), float(y), float(z)])) + + if len(ret.output.atoms) == 0: + ret.output = ret.input.copy() + return ret
+ + + +
+[docs] +def get_info(calc_dir: str) -> Result: + """Function to read useful info about the calculation in ``calc_dir``. Returned information will depend on the type of file that is provided. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Result object containing results about the calculation and AMS: + + - **version (Result)** – information about the AMS version used, see :func:`get_version`. + - **files (Result)** - paths to files that are important for this calculation. + - **input (Result)** - information about the input of this calculation, see :func:`get_input`. + - **level (Result)** - information about the level of theory used for this calculation, see :func:`get_level_of_theory`. + - **engine (str)** – the engine that was used to perform the calculation, for example 'adf', 'dftb', ... + - **status (Result)** – information about calculation status, see :func:`get_calculation_status`. + - **molecule (Result)** – information about the input and output molecules and the molecular system in general, see :func:`get_molecules`. + """ + ret = Result() + + ret.engine = "orca" + ret.files = get_calc_files(calc_dir) + + # store the input of the calculation + ret.input = get_input(ret) + + ret.level = get_level_of_theory(ret) + + # store information about the version of AMS + ret.version = get_version(ret) + + # store the calculation status + ret.status = get_calculation_status(ret) + + # read molecules + ret.molecule = get_molecules(ret) + + return ret
+ + + +
+[docs] +def get_vibrations(lines): + """Function to read vibrational data of an ORCA calculation. + + Args: + lines: Lines in the output file of the ORCA calculation. + + Returns: + :Result object containing vibrational properties from the ORCA calculation: + + - **number_of_modes (int)** – number of vibrational modes for this molecule, 3N-5 for non-linear molecules and 3N-6 for linear molecules, where N is the number of atoms. + - **number_of_imaginary_modes (int)** – number of imaginary vibrational modes for this molecule. + - **frequencies (list[float])** – vibrational frequencies associated with the vibrational modes, sorted from low to high (|cm-1|). + - **intensities (list[float])** – vibrational intensities associated with the vibrational modes (|km/mol|). In ORCA, intensities of imaginary modes are set to 0. + - **modes (list[float])** – list of vibrational modes sorted from low frequency to high frequency. + - **character (str)** – the PES character of the molecular system. Either "minimum", "transitionstate" or "saddlepoint(n_imag)", for 0, 1, n_imag number of imaginary frequencies. + """ + ret = Result() + start_reading = False + start_reading_idx = 0 + freq_lines = [] + for i, line in enumerate(lines): + if start_reading: + if len(line) == 0 and (i - start_reading_idx) > 4: + break + if ":" in line: + freq_lines.append(line) + + if "VIBRATIONAL FREQUENCIES" in line: + start_reading = True + start_reading_idx = i + + ret.number_of_modes = len(freq_lines) + frequencies = [float(line.split()[1]) for line in freq_lines] + nrotranslational = sum([freq == 0 for freq in frequencies]) + ret.frequencies = frequencies[nrotranslational:] + ret.number_of_imaginary_modes = len([freq for freq in ret.frequencies if freq < 0]) + ret.character = "minimum" if ret.number_of_imaginary_modes == 0 else "transitionstate" if ret.number_of_imaginary_modes == 1 else f"saddlepoint({ret.number_of_imaginary_modes})" + + start_reading = False + mode_lines = [] + for i, line in enumerate(lines): + if "NORMAL MODES" in line: + start_reading = True + continue + + if "IR SPECTRUM" in line: + start_reading = False + break + + if start_reading: + mode_lines.append(line) + + mode_lines = mode_lines[6:-3] + mode_lines = [[float(x) for x in line.split()[1:]] for i, line in enumerate(mode_lines) if i % (ret.number_of_modes + 1) != 0] + + nblocks = len(mode_lines) // ret.number_of_modes + blocks = [] + for block in range(nblocks): + blocks.append(np.array(mode_lines[block * ret.number_of_modes : (block + 1) * ret.number_of_modes])) + ret.modes = np.hstack(blocks).T.tolist()[nrotranslational:] + + start_reading = False + int_lines = [] + for i, line in enumerate(lines): + if "IR SPECTRUM" in line: + start_reading = True + continue + + if "The epsilon (eps) is given for a Dirac delta lineshape." in line: + start_reading = False + break + + if start_reading: + int_lines.append(line) + + ints = [float(line.split()[3]) for line in int_lines[5:-1]] + ret.intensities = [0] * ret.number_of_imaginary_modes + ints + return ret
+ + + +
+[docs] +def get_properties(info: Result) -> Result: + """Function to get properties from an ORCA calculation. + + Args: + info: Result object containing ORCA properties. + + Returns: + :Result object containing properties from the ORCA calculation: + + - **energy.bond (float)** – total bonding energy (|kcal/mol|). + - **energy.enthalpy (float)** – enthalpy (|kcal/mol|). Only obtained if vibrational modes were calculated. + - **energy.entropy (float)** – entropy (|kcal/mol|). Only obtained if vibrational modes were calculated. + - **energy.gibbs (float)** – Gibb's free energy (|kcal/mol|). Only obtained if vibrational modes were calculated. + - **energy.[method] (float)** - total energy (|kcal/mol|) at a certain level (HF, MP2, CCSD, ...). This is the sum of energy.HF and energy.[method]_corr. + - **energy.[method]_corr (float)** - electron correlation energy (|kcal/mol|) at a certain level (HF, MP2, CCSD, ...). + - **vibrations.number_of_modes (int)** – number of vibrational modes for this molecule, 3N-5 for non-linear molecules and 3N-6 for linear molecules, where N is the number of atoms. + - **vibrations.number_of_imaginary_modes (int)** – number of imaginary vibrational modes for this molecule. + - **vibrations.frequencies (list[float])** – vibrational frequencies associated with the vibrational modes, sorted from low to high (|cm-1|). + - **vibrations.intensities (list[float])** – vibrational intensities associated with the vibrational modes (|km/mol|). In ORCA, intensities of imaginary modes are set to 0. + - **vibrations.modes (list[float])** – list of vibrational modes sorted from low frequency to high frequency. + - **vibrations.character (str)** – the PES character of the molecular system. Either "minimum", "transitionstate" or "saddlepoint(n_imag)", for 0, 1, n_imag number of imaginary frequencies. + - **t1** - T1 diagnostic for the highest level of correlation chosen. Used to check the validity of the reference wavefunction. + - **s2** - expectation value of the :math:`S^2` operator. + - **s2_expected** - ideal expectation value of the :math:`S^2` operator. + - **spin_contamination** - the amount of spin-contamination observed in this calculation. It is equal to (s2 - s2_expected) / (s2_expected). Ideally this value should be below 0.1. + """ + ret = Result() + + with open(info.files.out) as out: + lines = [line.strip() for line in out.readlines()] + + if info.orca.frequencies: + ret.vibrations = get_vibrations(lines) + + # read some important info about the calculation + for line in lines: + if "FINAL SINGLE POINT ENERGY" in line: + ret.energy.bond = float(line.split()[4]) * constants.HA2KCALMOL + continue + + if "E(0)" in line: + ret.energy.HF = float(line.split()[-1]) * constants.HA2KCALMOL + continue + + if "Final correlation energy" in line: + ret.energy.corr = float(line.split()[-1]) * constants.HA2KCALMOL + continue + + if "E(MP2)" in line: + ret.energy.MP2 = float(line.split()[-1]) * constants.HA2KCALMOL + ret.energy.HF + ret.energy.MP2_corr = float(line.split()[-1]) * constants.HA2KCALMOL + continue + + if "E(CCSD) " in line: + ret.energy.CCSD = float(line.split()[-1]) * constants.HA2KCALMOL + ret.energy.CCSD_corr = float(line.split()[-1]) * constants.HA2KCALMOL - ret.energy.HF + continue + + if "E(CCSD(T))" in line: + ret.energy.CCSD_T = float(line.split()[-1]) * constants.HA2KCALMOL + ret.energy.CCSD_T_corr = float(line.split()[-1]) * constants.HA2KCALMOL - ret.energy.HF + continue + + if "Final Gibbs free energy" in line: + ret.energy.gibbs = float(line.split()[-2]) * constants.HA2KCALMOL + continue + + if "Total enthalpy" in line: + ret.energy.enthalpy = float(line.split()[-2]) * constants.HA2KCALMOL + continue + + if "Final entropy term" in line: + ret.energy.entropy = float(line.split()[-2]) + continue + + if "T1 diagnostic" in line: + ret.t1 = float(line.split()[3]) + continue + + if "Expectation value of <S**2>" in line: + ret.s2 = float(line.split()[-1]) + continue + + if "Ideal value" in line: + ret.s2_expected = float(line.split()[-1]) + continue + + if ret.s2 and ret.s2_expected: + ret.spin_contamination = (ret.s2 - ret.s2_expected) / ret.s2_expected + + return ret
+ + +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results/result.html b/docs/_build/html/_modules/tcutility/results/result.html new file mode 100644 index 00000000..8a971268 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results/result.html @@ -0,0 +1,570 @@ + + + + + + + + + + tcutility.results.result — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results.result

+'''Module containing the TCutility.results.result.Result class.'''
+import dictfunc
+import sys
+
+
+
+[docs] +class Result(dict): + '''Class used for storing results from AMS calculations. The class is functionally a dictionary, but allows dot notation to access variables in the dictionary. + The class works case-insensitively, but will retain the case of the key when it was first set.''' + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # if we are casting an object to a Result object + # we will copy all data to this one and all dictionaries will be turned into Result object + # turn every value into a Result object if possible + for key, value in self.items(): + if isinstance(value, dict): + self[key] = Result(value) + else: + self[key] = value + + def __call__(self): + '''Calling of a dictionary subclass should not be possible, instead we raise an error with information about the key and method that were attempted to be called.''' + head, method = '.'.join(self.get_parent_tree().split('.')[:-1]), self.get_parent_tree().split('.')[-1] + raise AttributeError(f'Tried to call method "{method}" from {head}, but {head} is empty') + + def __str__(self): + '''Override str method to prevent printing of hidden keys. You can still print them if you call repr instead of str.''' + return '{' + ', '.join([f'{key}: {str(val)}' for key, val in self.items()]) + '}' + +
+[docs] + def items(self): + '''We override the items method from dict in order to skip certain keys. We want to hide keys starting and ending + with dunders, as they should not be exposed to the user. + ''' + return [(key, self[key]) for key in self.keys()]
+ + +
+[docs] + def keys(self): + original_keys = super().keys() + return [key for key in original_keys if not (key.startswith('__') and key.endswith('__'))]
+ + +
+[docs] + def multi_keys(self): + ''' + Return multi_keys for this Result object. These are unnested keys that can be used if you want a flattened Result object. + ''' + def dict_to_list(a): + ''' + Return a nested dictionary as a list of keys and values. + ''' + lst = [] + if not isinstance(a, dict): + return [[a]] + for k, v in a.items(): + if isinstance(v, dict): + if v == {}: + lst.append([k, {}]) + else: + [lst.append([k, *x]) for x in dict_to_list(v)] + else: + lst.append([k, v]) + return lst + + # cast this object to a list of keys and values + mks = dict_to_list(self) + # write the multi-keys separated with dots + mks = ['.'.join(mk[:-1]) for mk in mks] + return mks
+ + + def __getitem__(self, key): + if key.startswith('__') and key.endswith('__'): + return None + self.__set_empty(key) + val = super().__getitem__(self.__get_case(key)) + return val + + def __getattr__(self, key): + return self.__getitem__(key) + + def __setitem__(self, key, val): + # we set the item, but if it is a dict we convert the dict to a Result first + if isinstance(val, dict): + val = Result(val) + super().__setitem__(self.__get_case(key), val) + + def __setattr__(self, key, val): + self.__setitem__(key, val) + + def __contains__(self, key): + # Custom method to check if the key is defined in this object and is also non-empty, case-insensitive. + return key.lower() in [key_.lower() for key_ in self.keys()] and self[key] + + def __hash__(self): + '''Hashing of a dictionary subclass should not be possible, instead we should raise an error to let the user know + that they made a mistake. Also give information of which key was being read. + ''' + raise KeyError(f'Tried to hash {self.get_parent_tree()}, but it is empty') + + def __reduce__(self): + return 'TCutility.results.result.Result' + + def __bool__(self): + '''Make sure that keys starting and ending in "__" are skipped''' + return len([key for key in self.keys() if not (key.startswith('__') and key.endswith('__'))]) > 0 + + def __sizeof__(self): + ''' + Magic method used by `sys.getsizeof <https://docs.python.org/3/library/sys.html#sys.getsizeof>`_ to determine the memory footprint of this object. + ''' + s = super().__sizeof__() + for key in self.multi_keys(): + s += sys.getsizeof(self.get_multi_key(key)) + return s + +
+[docs] + def getsizeof(self): + ''' + Return the size of this object in bytes. + ''' + return self.__sizeof__()
+ + +
+[docs] + def get_parent_tree(self): + '''Method to get the path from this object to the parent object. The result is presented in a formatted string''' + # every parent except the top-most parent has defined a __parent__ attribute + if '__parent__' not in self: + return 'Head' + # iteratively build the tree using the __name__ attribute. + parent_names = self.__parent__.get_parent_tree() + parent_names += '.' + self.__name__ + return parent_names
+ + + def __set_empty(self, key): + # This function checks if the key has been set. + # If it has not, we create a new Result object and set it at the desired key + if self.__get_case(key) not in self.keys(): + val = Result() + # we also keep track of the parent of this object and also the name it was assigned to for later bookkeeping + val.__parent__ = self + val.__name__ = key + self.__setitem__(key, val) + + def __get_case(self, key): + # Get the case of the key as it has been set in this object. + # The first time a key-value pair has been assigned the case of the key will be set. + for key_ in self: + if key_.lower() == key.lower(): + return key_ + return key + +
+[docs] + def prune(self): + '''Remove empty paths of this object. + ''' + items = list(self.items()) + for key, value in items: + try: + value.prune() + except AttributeError: + pass + + if not value: + del self[key]
+ + +
+[docs] + def get_multi_key(self, key: str): + ''' + Method that returns the value of a "multikey". The multikey is multiple keys joined by dots. + E.g. res.properties.energy.bond can be gotten by calling res.get_multi_key("properties.energy.bond") + ''' + data = self + for keypart in key.split('.'): + data = data[keypart] + return data
+ + +
+[docs] + def as_plams_settings(self): + ''' + Returns this Result object as a plams.Settings object. + ''' + from scm import plams + import dictfunc + + clean_dict = dictfunc.list_to_dict(dictfunc.dict_to_list(self)) + return plams.Settings(clean_dict)
+ + +
+[docs] + def copy(self): + import copy + + # cast this object to a list of keys and values + lsts = dictfunc.dict_to_list(self) + # copy everthing in the lists + lsts = [[copy.copy(x) for x in lst] for lst in lsts] + # and return a new result object + return Result(dictfunc.list_to_dict(lsts))
+
+ + + +if __name__ == '__main__': + ret = Result() + # print(ret.adf) + # print(dict(ret.adf)) + # print(bool(ret.adf)) + ret.adf.x = {'a': 1, 'b': 2} + # ret.adf.system.atoms = [] + # ret.adf.system.atoms.append('test 1 2 3') + + # test_dict[ret.adf.y] = 20 + # ret.adf.y.join() + # {ret.test: 123} + # ret.__name__ = 'testname' + # print(ret.__name__) + print(repr(ret)) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/results/xtb.html b/docs/_build/html/_modules/tcutility/results/xtb.html new file mode 100644 index 00000000..9f9a5a01 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/results/xtb.html @@ -0,0 +1,797 @@ + + + + + + + + + + tcutility.results.xtb — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.results.xtb

+import os
+
+import numpy as np
+
+from tcutility import constants, molecule
+from tcutility.results import Result
+
+j = os.path.join
+
+
+
+[docs] +def get_calc_files(calc_dir: str) -> Result: + """Function that returns files relevant to AMS calculations stored in ``calc_dir``. + + Args: + calc_dir: path pointing to the desired calculation + + Returns: + Result object containing filenames and paths + """ + # collect all files in the current directory and subdirectories + files = [] + for root, _, files_ in os.walk(calc_dir): + files.extend([j(root, file) for file in files_]) + + # parse the filenames + ret = Result() + ret.extra = [] + ret.root = os.path.abspath(calc_dir) + for file in files: + if file.endswith(".out") and not file.endswith("g98.out"): + ret.out = os.path.abspath(file) + continue + if file.endswith("xtbopt.xyz"): + ret.opt_out = os.path.abspath(file) + continue + if file.endswith("xtbopt.log"): + ret.opt_history = os.path.abspath(file) + continue + if file.endswith("xtbscan.log"): + ret.scan_out = os.path.abspath(file) + continue + if file.endswith("vibspectrum"): + ret.vibspectrum = os.path.abspath(file) + continue + if file.endswith("hessian"): + ret.hessian = os.path.abspath(file) + continue + + ret.extra.append(os.path.abspath(file)) + + return ret
+ + + +
+[docs] +def get_version(info: Result) -> Result: + """Function to get the ORCA version used in the calculation. + + Args: + info: Result object containing ORCA calculation settings. + + Returns: + :Result object containing results about the ORCA version: + + - **full (str)** – the full version string as written by ORCA. + - **major (str)** – major ORCA version. + - **minor (str)** – minor ORCA version. + - **micro (str)** – micro ORCA version. + """ + ret = Result() + with open(info.files.out) as out: + for line in out.readlines(): + line = line.strip() + if "* xtb version" not in line: + continue + version = line.split()[3] + ret.full = version + ret.major = version.split(".")[0] + ret.minor = version.split(".")[1] + ret.micro = version.split(".")[2] + return ret
+ + + +
+[docs] +def get_input(info: Result) -> Result: + """Function that parses the input file for this ORCA calculation. + + Args: + info: Result object containing ORCA calculation settings. + + Returns: + :Result object containing information about the calculation input: + + - **main (list[str])** - the main inputs for the calculation. These are the lines that start with a "!". + - **sections (Result)** - extra settings added to the calculation. These are the lines that start with a "%" and optionally end with "END" clause. + - **system (Result)** - settings related to the molecular system. This includes charge, multiplicity and the coordinates. + - **task (str)** - the task that was performed by the calculation, e.g. "SinglePoint", "TransitionStateSearch". + """ + ret = Result() + with open(info.files.out) as out: + for line in out.readlines(): + line = line.strip() + if line.startswith("program call"): + call = line.split(":")[1].strip().split() + if line.startswith("coordinate file"): + ret.coord_file = line.split(":")[1].strip() + + ret.call = " ".join(call) + + ### TASK + ret.task = "SinglePoint" + for option in ["--opt", "--ohess"]: + # check if we used the option in our call + if option not in call: + continue + + # if we used it we did a geo-opt + ret.task = "GeometrOptimization" + # check if we did a PESScan, it also requires using the --opt option + if "scan_out" in info.files: + ret.task = "PESScan" + + # check if we gave convergence criteria + ret.geometry_convergence = "Normal" + option_idx = call.index(option) + if not call[option_idx + 1].startswith("-"): + ret.geometry_convergence = call[option_idx + 1] + + ### CHARGE + ret.charge = 0 + for option in ["--charge", "-c"]: + # check if we used the option in our call + if option not in call: + continue + # read the next position in the call + option_idx = call.index(option) + ret.charge = int(call[option_idx + 1]) + + ### SPIN-POLARIZATION + ret.spin_polarization = 0 + for option in ["--uhf", "-u"]: + # check if we used the option in our call + if option not in call: + continue + # read the next position in the call + option_idx = call.index(option) + ret.spin_polarization = int(call[option_idx + 1]) + + ### SOLVATION + ret.solvent = None + ret.solvation_model = None + + if "--alpb" in call: + option_idx = call.index("--alpb") + ret.solvent = call[option_idx + 1] + ret.solvation_model = "ALPB" + + for option in ["-g", "--gbsa"]: + if option not in call: + continue + option_idx = call.index(option) + ret.solvent = call[option_idx + 1] + ret.solvation_model = "GBSA" + + ### DETAILED INPUT + ret.detailed = None + if "--input" in call: + ret.detailed = Result() + option_idx = call.index("--input") + inp_file = call[option_idx + 1] + for file in info.files.extra: + if file.endswith(inp_file): + ret.detailed.file = file + break + + with open(ret.detailed.file) as infile: + content = infile.readlines() + + for line in content: + line = line.strip() + if line.startswith("$"): + curr_section = line[1:] + continue + + if ":" in line: + key, val = line.split(":") + ret.detailed[curr_section].setdefault(key, []) + ret.detailed[curr_section][key].append(val.strip()) + + elif "=" in line: + key, val = line.split("=") + ret.detailed[curr_section][key] = val.strip() + + ### MODEL HAMILTONIAN + ret.model = "GFN2-xTB" + if "--gfn" in call: + option_idx = call.index("--gfn") + version = call[option_idx + 1] + ret.model = f"GFN{version}-xTB" + + if "--gfnff" in call: + ret.model = "GFNFF" + + return ret
+ + + +
+[docs] +def get_calculation_status(info: Result) -> Result: + """Function that returns the status of the ORCA calculation described in reader. In case of non-succes it will also give possible reasons for the errors/warnings. + + Args: + info: Result object containing ORCA calculation information. + + Returns: + :Result object containing information about the calculation status: + + - **fatal (bool)** – True if calculation cannot be analysed correctly, False otherwise + - **reasons (list[str])** – list of reasons to explain the status, they can be errors, warnings, etc. + - **name (str)** – calculation status written as a string, one of ("SUCCESS", "RUNNING", "UNKNOWN", "SUCCESS(W)", "FAILED") + - **code (str)** – calculation status written as a single character, one of ("S", "R", "U", "W" "F") + """ + ret = Result() + ret.fatal = True + ret.name = None + ret.code = None + ret.reasons = [] + + if "out" not in info.files: + ret.reasons.append("Calculation status unknown") + ret.name = "UNKNOWN" + ret.code = "U" + return ret + + with open(info.files.out) as out: + lines = out.readlines() + if any(["[WARNING] Runtime exception occurred" in line for line in lines]): + ret.fatal = True + ret.name = "FAILED" + ret.code = "F" + + line_index = [i for i, line in enumerate(lines) if "[WARNING] Runtime exception occurred" in line][0] + for line in lines[line_index + 1 :]: + if "##########" in line: + break + ret.reasons.append(line.strip()) + return ret + + if any(["* finished run" in line for line in lines]): + ret.fatal = False + ret.name = "SUCCESS" + ret.code = "S" + return ret + + ret.name = "FAILED" + ret.code = "F" + return ret
+ + + +
+[docs] +def get_molecules(info: Result) -> Result: + """Function that returns information about the molecules for this calculation. + + Args: + info: Result object containing ORCA calculation information. + + Returns: + :Result object containing properties from the ORCA calculation: + + - **input (plams.Molecule)** - the input molecule for this calculation. + - **output (plams.Molecule)** - the output molecule for this calculation, for example the optimized structure after a geometry optimization. + - **number_of_atoms (int)** - the number of atoms in the molecular system. + """ + ret = Result() + for file in info.files.extra: + if file.endswith(info.input.coord_file): + coord_file = file + break + + ret.input = molecule.load(coord_file) + ret.output = ret.input.copy() + + if "opt_out" in info.files: + ret.output = molecule.load(info.files.opt_out) + + return ret
+ + + +
+[docs] +def get_info(calc_dir: str) -> Result: + """Function to read useful info about the calculation in ``calc_dir``. Returned information will depend on the type of file that is provided. + + Args: + calc_dir: path pointing to the desired calculation. + + Returns: + :Result object containing results about the calculation and AMS: + + - **version (Result)** – information about the AMS version used, see :func:`get_version`. + - **files (Result)** - paths to files that are important for this calculation. + - **input (Result)** - information about the input of this calculation, see :func:`get_input`. + - **level (Result)** - information about the level of theory used for this calculation, see :func:`get_level_of_theory`. + - **engine (str)** – the engine that was used to perform the calculation, for example 'adf', 'dftb', ... + - **status (Result)** – information about calculation status, see :func:`get_calculation_status`. + - **molecule (Result)** – information about the input and output molecules and the molecular system in general, see :func:`get_molecules`. + """ + ret = Result() + + ret.engine = "xtb" + ret.files = get_calc_files(calc_dir) + + # store the input of the calculation + ret.input = get_input(ret) + + # store information about the version of AMS + ret.version = get_version(ret) + + # # store the calculation status + ret.status = get_calculation_status(ret) + + # # read molecules + ret.molecule = get_molecules(ret) + + return ret
+ + + +
+[docs] +def get_properties(info: Result) -> Result: + """Function to get properties from an ORCA calculation. + + Args: + info: Result object containing ORCA properties. + + Returns: + :Result object containing properties from the ORCA calculation: + + - **energy.bond (float)** – total bonding energy (|kcal/mol|). + - **energy.enthalpy (float)** – enthalpy (|kcal/mol|). Only obtained if vibrational modes were calculated. + - **energy.entropy (float)** – entropy (|kcal/mol|). Only obtained if vibrational modes were calculated. + - **energy.gibbs (float)** – Gibb's free energy (|kcal/mol|). Only obtained if vibrational modes were calculated. + - **energy.[method] (float)** - total energy (|kcal/mol|) at a certain level (HF, MP2, CCSD, ...). This is the sum of energy.HF and energy.[method]_corr. + - **energy.[method]_corr (float)** - electron correlation energy (|kcal/mol|) at a certain level (HF, MP2, CCSD, ...). + - **vibrations.number_of_modes (int)** – number of vibrational modes for this molecule, 3N-5 for non-linear molecules and 3N-6 for linear molecules, where N is the number of atoms. + - **vibrations.number_of_imaginary_modes (int)** – number of imaginary vibrational modes for this molecule. + - **vibrations.frequencies (list[float])** – vibrational frequencies associated with the vibrational modes, sorted from low to high (|cm-1|). + - **vibrations.intensities (list[float])** – vibrational intensities associated with the vibrational modes (|km/mol|). In ORCA, intensities of imaginary modes are set to 0. + - **vibrations.modes (list[float])** – list of vibrational modes sorted from low frequency to high frequency. + - **vibrations.character (str)** – the PES character of the molecular system. Either "minimum", "transitionstate" or "saddlepoint(n_imag)", for 0, 1, n_imag number of imaginary frequencies. + - **t1** - T1 diagnostic for the highest level of correlation chosen. Used to check the validity of the reference wavefunction. + - **s2** - expectation value of the :math:`S^2` operator. + - **s2_expected** - ideal expectation value of the :math:`S^2` operator. + - **spin_contamination** - the amount of spin-contamination observed in this calculation. It is equal to (s2 - s2_expected) / (s2_expected). Ideally this value should be below 0.1. + """ + ret = Result() + + with open(info.files.out) as out: + lines = [line.strip() for line in out.readlines()] + + # read some important info about the calculation + for line in lines: + if "TOTAL ENERGY" in line: + ret.energy.bond = float(line.split()[3]) * constants.HA2KCALMOL + continue + + if "TOTAL FREE ENERGY" in line: + ret.energy.gibbs = float(line.split()[4]) * constants.HA2KCALMOL + continue + + if "TOTAL ENTHALPY" in line: + ret.energy.enthalpy = float(line.split()[3]) * constants.HA2KCALMOL + continue + + if "# frequencies" in line: + ret.vibrations.number_of_modes = int(line.split()[3]) + continue + + if "# imaginary freq." in line: + ret.vibrations.number_of_imaginary_modes = int(line.split()[4]) + continue + + if "vibrational frequencies" in line: + ret.vibrations.frequencies = [] + continue + + if "eigval :" in line: + ret.vibrations.frequencies.extend([float(freq) for freq in line.split()[2:]]) + + if ret.vibrations.frequencies: + # get the number of the first vibrational mode, so without the translations and rotations + first_mode = len(ret.vibrations.frequencies) - ret.vibrations.number_of_modes + 1 + # we have to remove the first 5 or 6 frequencies, because they are translation+rotation + ret.vibrations.frequencies = ret.vibrations.frequencies[first_mode - 1 :] + + # read in the vibspectrum file to get the vibrational intensities: + ret.vibrations.intensities = [] + if info.files.vibspectrum: + with open(info.files.vibspectrum) as spec: + for line in spec.readlines()[3:-1]: + if line.startswith("$"): + continue + + if int(line.split()[0]) < first_mode: + continue + + ret.vibrations.intensities.append(float(line.split()[3])) + + # read in the hessian file to get the normal modes: + if info.files.hessian: + hessian = [] + with open(info.files.hessian) as hess: + for line in hess.readlines()[1:]: + hessian.extend([float(x) for x in line.split()]) + + # number of modes: + N = int(np.sqrt(len(hessian))) + # square hessian: + H = np.reshape(hessian, (N, N)) + + # get the atomic masses + mol = molecule.load(info.files.opt_out) + masses = np.atleast_2d([atom.mass for atom in mol.atoms for _ in range(3)]) + + # make the reduced mass matrix + mu = np.sqrt(masses * masses.T) + # and reduced mass Hessian + F = H / mu + + # diagonalize it to get frequencies and modes + freqs, modes = np.linalg.eigh(F) + # print(modes) + + # from yviewer import viewer + # mol.guess_bonds() + # viewer.show(mol, molinfo=[{'normalmode': modes[0].reshape(-1, 3)}]) + + return ret
+ + + +if __name__ == "__main__": + from tcutility import log + + ret = get_info("/Users/yumanhordijk/PhD/ganesh_project/calculations/AlCl3_xtb/opt_1") + log.log(ret.files) + props = get_properties(ret) + print(props) + + # ret = get_info("/Users/yumanhordijk/PhD/ganesh_project/calculations/AlCl3_xtb/scan_1") + # print(ret) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/slurm.html b/docs/_build/html/_modules/tcutility/slurm.html new file mode 100644 index 00000000..4a4f78fd --- /dev/null +++ b/docs/_build/html/_modules/tcutility/slurm.html @@ -0,0 +1,502 @@ + + + + + + + + + + tcutility.slurm — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.slurm

+import os
+import platform
+import subprocess as sp
+import time
+
+from tcutility import cache, log, results
+
+
+
+[docs] +@cache.cache +def has_slurm() -> bool: + """ + Function to check if the current platform uses slurm. + + Returns: + Whether slurm is available on this platform. + """ + try: + # Determine the appropriate command based on the OS + command = ["which", "sbatch"] if platform.system() != "Windows" else ["where", "sbatch"] + + # we do not want this function to print anything when it does not find sbatch + with open(os.devnull, "wb") as devnull: + sp.check_output(command, stderr=devnull).decode() + # if it runs without error, we have access to slurm + return True + # if an error is raised we do not have slurm + except (sp.CalledProcessError, FileNotFoundError): + return False
+ + + +
+[docs] +@cache.timed_cache(3) +def squeue() -> results.Result: + """ + Get information about jobs managed by slurm using squeue. + + Returns: + : A :class:`Result <tcutility.results.result.Result>` object containing information about the calculation status: + + - ``directory`` **(list[str])** – path to slurm directories. + - ``id`` **(list[str])** – slurm job id's. + - ``status`` **(list[str])** – slurm job status name. See squeue documentation. + - ``statuscode`` **(list[str])** – slurm job status codes. See squeue documentation + + .. note:: + + By default this function uses a timed cache (see :func:`timed_cache <tcutility.cache.timed_cache>`) with a 3 second delay to lessen the load on HPC systems. + """ + ret = results.Result() + + if not has_slurm(): + return ret + + # specify the columns to get here + columns = ["directory", "id", "statuscode", "status"] + options = ["%Z", "%A", "%t", "%T"] # these are the squeue format codes + + # set each column as an empty list in the return object + for col in columns: + ret[col] = [] + + # run the squeue command with the formatting options + output = sp.check_output(["squeue", "--me", "--format", "" + " ".join(options) + ""]).decode() + output = [line for line in output.splitlines()[1:] if line.strip()] + + # then add the data to the return object's lists + for line in output: + [ret[col].append(val) for col, val in zip(columns, line.split())] + + return ret
+ + + +
+[docs] +def sbatch(runfile: str, **options: dict) -> results.Result: + """ + Submit a job to slurm using sbatch. + + Args: + runfile: the path to the filename to be submitted. + options: options to be used for sbatch. + + Returns: + : A :class:`Result <tcutility.results.result.Result>` object containing information about the newly submitted slurm job + + - ``id`` **(str)** - the ID for the submitted slurm job. + - ``command`` **(str)** - the command used to submit the job. + """ + cmd = "sbatch " + for key, val in options.items(): + key = key.replace("_", "-") + + if val is True: + if len(key) > 1: + cmd += f"--{key} " + else: + cmd += f"-{key} " + else: + if len(key) > 1: + cmd += f"--{key}={val} " + else: + cmd += f"-{key} {val} " + + cmd = cmd + runfile + + ret = results.Result() + ret.command = cmd + + # run the job + sbatch_out = sp.check_output(cmd.split(), stderr=sp.STDOUT).decode() + # get the slurm job id from the output + for line in sbatch_out.splitlines(): + if "Submitted batch job" in line: + # set the slurm job id for this calculation, we use this in order to set dependencies between jobs. + ret.id = line.strip().split()[-1] + break + + return ret
+ + + +
+[docs] +def workdir_info(workdir: str) -> results.Result: + """ + Function that gets squeue information given a working directory. This will return None if the directory is not being actively referenced by slurm. + + Returns: + :Result object containing information about the calculation status, see :func:`squeue`. + """ + if not has_slurm(): + return None + + sq = squeue() + if workdir not in sq.directory: + return None + + workdir_index = sq.directory.index(workdir) + ret = results.Result() + for key, vals in sq.items(): + ret[key] = vals[workdir_index] + + return ret
+ + + +
+[docs] +def wait_for_job(slurmid: int, check_every: int = 3): + """ + Wait for a slurm job to finish. We check every `check_every` seconds if the slurm job id is still present in squeue. + + Args: + slurmid: the ID of the slurm job we are waiting for. + check_every: the amount of seconds to wait before checking squeue again. Don't put this too high, or you will anger the cluster people. + """ + while slurmid in squeue().id: + time.sleep(check_every)
+ + + +if __name__ == "__main__": + if has_slurm(): + log.info("This platform has SLURM.") + else: + log.info("This platform does not have SLURM.") +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/spell_check.html b/docs/_build/html/_modules/tcutility/spell_check.html new file mode 100644 index 00000000..bd6819d9 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/spell_check.html @@ -0,0 +1,520 @@ + + + + + + + + + + tcutility.spell_check — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.spell_check

+import numpy as np
+from tcutility import log
+from typing import List
+
+
+
+[docs] +def naive_recursive(a: str, b: str) -> float: + ''' + The naïve recursive algorithm to obtain the Levenshtein distance between two strings. + We do not recommend using this algorithm as it is quite slow and faster alternatives exist. + + Args: + a, b: strings to compare. + + Returns: + The Levenshtein distance between the strings ``a`` and ``b``. + + .. seealso:: + :func:`wagner_fischer` + A more efficient algorithm to obtain the Levenshtein distance (up to 25x faster). + ''' + if len(b) == 0: + return len(a) + if len(a) == 0: + return len(b) + + def tail(s): + return s[1:] + + if a[0] == b[0]: + return naive_recursive(tail(a), tail(b)) + + d = 1 + min(naive_recursive(tail(a), b), naive_recursive(a, tail(b)), naive_recursive(tail(a), tail(b))) + return d
+ + + +
+[docs] +def wagner_fischer(a: str, b: str, substitution_cost: float = 1, case_missmatch_cost: float = 1, insertion_cost: float = 1) -> float: + ''' + Return the Levenshtein distance using the Wagner-Fischer algorithm. + You can also change the penalty for various errors for this algorithm. + By default, all types of errors incur a penalty of 1. + + Args: + a, b: strings to compare. + substitution_cost: the penalty for the erroneous substitution of a character. + case_missmatch_cost: the penalty for miss-matching the case of a character. + insertion_cost: the cost for the erroneous insertion or deletion of a character. + + Returns: + The Levenshtein distance between the strings ``a`` and ``b``. + + Example: + .. code-block:: python + + >>> wagner_fischer('kitten', 'sitting') + 3 + + .. seealso:: + :func:`naive_recursive` + An alternative (and slower) algorithm to obtain the Levenshtein distance. + ''' + # initialize an empty matrix + d = np.zeros((len(a)+1, len(b)+1)).astype(float) + + # the top row and left column are always the same + for i in range(len(a)): + d[i+1, 0] = i+1 + for i in range(len(b)): + d[0, i+1] = i+1 + + # iteratively build the matrix + for i in range(1, len(a)+1): + for j in range(1, len(b)+1): + # if the two characters are the same the cost is 0 + if a[i-1] == b[j-1]: + cost = 0 + # case miss-match + elif a[i-1].lower() == b[j-1].lower(): + cost = case_missmatch_cost + # substitution + else: + cost = substitution_cost + + # here determine if the substitution/miss-match cost is greater than the insertion or deletion cost + d[i, j] = min(d[i-1, j] + insertion_cost, d[i, j-1] + insertion_cost, d[i-1, j-1] + cost) + + # return the bottom-right element, this is the final edit-distance + return d[-1, -1]
+ + + +
+[docs] +def get_closest(a: str, others: List[str], compare_func=wagner_fischer, ignore_case: bool = False, ignore_chars: str = '', maximum_distance: int = None, **kwargs) -> List[str]: + ''' + Return strings that are similar to an input string using the Levenshtein distance. + + Args: + a: the string to compare the rest to. + others: a collection of strings to compare to a. The returned strings will be taken from this collection. + compare_func: the function to use to compare the strings. Defaults to the efficient :func:`wagner_fischer` algorithm. + ignore_case: whether the case of the strings is taken into account. If enabled, all strings are turned to lower-case before comparison. + ignore_chars: a strings specifying characters that should be ignored. + maximum_distance: the maximum Levenshtein distance to allow. + If it is lower than the lowest distance for the collection of strings, we return the strings with the lowest distance. + If set to ``None`` we return the lowest distance strings. + + Returns: + A collection of strings that have a Levenshtein distance to ``a`` below ``maximum_distance`` + or have the lowest distance to ``a`` if all strings have a distance greater than ``maximum_distance``. + If the lowest distance is ``0``, return an empty list instead. + + Example: + .. code-block:: python + + >>> closest = get_closest('kitten', ['mitten', 'bitten', 'sitting']) + >>> print(closest) + ['mitten', 'bitten'] + ''' + if ignore_case: + a = a.lower() + + for char in ignore_chars: + a = a.replace(char, '') + + dists = [] + for other in others: + if ignore_case: + other = other.lower() + + for char in ignore_chars: + other = other.replace(char, '') + + dists.append(compare_func(a, other, **kwargs)) + + if maximum_distance is None: + maximum_distance = -1 + lowest_strs = [other for dist, other in zip(dists, others) if 0 < dist <= max(maximum_distance, min(dists))] + return lowest_strs
+ + + +
+[docs] +def make_suggestion(a: str, others: List[str], **kwargs): + ''' + Print a warning that gives suggestions for strings that are close to a given string. + + Example: + .. code-block:: python + + >>> make_suggestion('kitten', ['mitten', 'bitten', 'sitting']) + [2024/01/30 15:26:35] [WARNING](main): Could not find "kitten". Did you mean mitten or bitten? + + .. seealso:: + :func:`get_closest` for a description of the function arguments. + ''' + closest = get_closest(a, others, **kwargs) + + if len(closest) > 1: + closest_string = " or ".join([", ".join(closest[:-1]), closest[-1]]) + else: + closest_string = closest[0] + + # write a warning message + log.warn(f'Could not find "{a}". Did you mean {closest_string}?', caller_level=3)
+ + + +
+[docs] +def check(a: str, others: List[str], caller_level=2, **kwargs): + closest = get_closest(a, others, **kwargs) + if len(closest) == 0: + return + + if len(closest) > 1: + closest_string = " or ".join([", ".join(closest[:-1]), closest[-1]]) + else: + closest_string = closest[0] + + # write a warning message + msg = f"({log.caller_name(caller_level)}): " + f'Could not find "{a}". Did you mean {closest_string}?' + raise ValueError(msg)
+ +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_modules/tcutility/timer.html b/docs/_build/html/_modules/tcutility/timer.html new file mode 100644 index 00000000..27bc3286 --- /dev/null +++ b/docs/_build/html/_modules/tcutility/timer.html @@ -0,0 +1,465 @@ + + + + + + + + + + tcutility.timer — TCutility v0.14.4 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
+
+
+ +
+ +
+ + + + + +
+
+ + + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + + + +
+ +
+ + +
+
+ + + + + +
+ +

Source code for tcutility.timer

+from time import perf_counter
+import numpy as np
+from tcutility import log
+from types import FunctionType
+import listfunc
+import atexit
+'''
+Implements a decorator and context manager that records and stores the number of times a function
+has been called and also the amount of time taken in total/per call
+'''
+times = {}
+exec_start = perf_counter()
+
+enabled: bool = True
+
+
+
+[docs] +class timer: + ''' + The main timer class. It acts both as a context-manager and decorator. + ''' + def __init__(self, name=None): + if isinstance(name, FunctionType): + self.function = name + times.setdefault(name.__qualname__, {'calls': 0, 'timings': []}) + else: + self.name = name + times.setdefault(self.name, {'calls': 0, 'timings': []}) + + def __enter__(self): + self.start = perf_counter() + return self + + def __exit__(self, *args, **kwargs): + times[self.name]['calls'] += 1 + times[self.name]['timings'].append(perf_counter() - self.start) + + def __call__(self, *args, **kwargs): + times.setdefault(self.function.__qualname__, {'calls': 0, 'timings': []}) + + if enabled and __debug__: + start = perf_counter() + ret = self.function(*args, **kwargs) + times[self.function.__qualname__]['calls'] += 1 + times[self.function.__qualname__]['timings'].append(perf_counter() - start) + return ret + else: + return self.function(*args, **kwargs)
+ + + + + + + +# this makes sure that the timings are printed when Python quits running +atexit.register(print_timings) +
+ +
+ + + + + +
+ +
+
+
+ +
+ + + + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/docs/_build/html/_sources/analysis/analysis.rst.txt b/docs/_build/html/_sources/analysis/analysis.rst.txt new file mode 100644 index 00000000..2a6f1922 --- /dev/null +++ b/docs/_build/html/_sources/analysis/analysis.rst.txt @@ -0,0 +1,10 @@ +tcutility.analysis +================================ + +This chapter contains description of all analysis functionalities including examples of usage. +Below is the list of all available analysis modules: + +.. toctree:: + + transition_state_analysis + vdd_charge_analysis \ No newline at end of file diff --git a/docs/_build/html/_sources/analysis/transition_state_analysis.rst.txt b/docs/_build/html/_sources/analysis/transition_state_analysis.rst.txt new file mode 100644 index 00000000..ad7f82d4 --- /dev/null +++ b/docs/_build/html/_sources/analysis/transition_state_analysis.rst.txt @@ -0,0 +1,8 @@ +Transition State Analysis module +================================ + +This module contains the code and examples for the transition state analysis. + +.. note:: + + This documentation is still under construction. \ No newline at end of file diff --git a/docs/_build/html/_sources/analysis/vdd_charge_analysis.rst.txt b/docs/_build/html/_sources/analysis/vdd_charge_analysis.rst.txt new file mode 100644 index 00000000..48cec4e5 --- /dev/null +++ b/docs/_build/html/_sources/analysis/vdd_charge_analysis.rst.txt @@ -0,0 +1,128 @@ +VDD Charge Analysis module +=========================== + +When a calculation is performed and has succesfully finished, the VDD charge analysis module can be used to extract the Voronoi Deformation Density (`VDD `_) charges. +The VDD charges measure the charge flow between atoms (officially Voronoi cells) from non-interacting atoms ("promolecule") to atoms feeling the environment of other atoms (molecular enviroment). +If symmetry is used, the VDD charges can be decomposed into contributions of seperate irreducible representations. + +Requirements +------------ + +* A finished calculation using the ADF engine. +* Location to the calculation directory with ams.rkf and adf.rkf files + + +Example +-------- + +First, relevant modules need to be loaded. These include pathlib for handling paths and tcutility.results for loading the results of the calculation. +In addition, the VDD manager module needs to be loaded which is the interface to performing VDD analyses. + +.. note:: + + For this example we use calculations found in the `VDD test directory`_ of the tcutility package. + We assume that the you place the VDD test directory in the same directory as this script. + See the `example python script <../../../../examples/vdd_analysis.py>`_ for a direct implementation + +.. code-block:: python + + import pathlib as pl + import tcutility.results as results + from tcutility.analysis.vdd import manager + +Now, the calculation directory needs to be specified and the calculation results can be loaded via the |read| function. +The next step is to create a |VDDmanager| object which is the interface to performing VDD analyses. + + +.. code-block:: python + + DIRS = {0: "fa_acid_amide_cs", 1: "fa_squaramide_se_cs", 2: "fa_donor_acceptor_nosym", 3: "geo_nosym"} + + # Specify the calculation directory + base_dir = pl.Path(__file__).parent + base_dir = base_dir / "VDD" + calc_dir = base_dir / DIRS[1] + + calc_res = results.read(calc_dir) + vdd_manager = manager.create_vdd_charge_manager(name=calc_dir.name, results=calc_res) + +The |VDDmanager| object contains the total VDD charges, as well as the VDD charges for each irreducible representation. +To see the contents of the |VDDmanager|, simply print it. The charges are formatted as a table in the unit of milli electrons [me]. +You can always change the unit of the charges by using the |change_unit| method. + +.. code-block:: python + + vdd_manager.change_unit("me") # Change the unit to electrons "e" (electrons) or "me" (milli electrons) + + # Print the VDD charges to standard output + print(vdd_manager) + + # Output: + fa_squaramide_se_cs + VDD charges (in unit me): + Frag Atom Total AA AAA + 1 1C -40 -10 -30 + 1 2Se -165 -30 -134 + 1 3C -40 -10 -30 + 1 4Se -165 -30 -134 + 1 5C +26 +122 -96 + 1 6C +26 +122 -96 + 2 7N +62 -88 +150 + 2 8H +53 -2 +55 + 2 9H +63 +7 +56 + 2 10N +62 -88 +150 + 2 11H +63 +7 +56 + 2 12H +53 -2 +55 + + Summed VDD charges (in unit me): + Frag Total AA AAA + 1 -357 +164 -521 + 2 +357 -164 +521 + +See? It is that easy. The charges sum up to the total charge of the molecule (in this case 0). Also, the sum of irrep charges is equal to the total charge, as it should be. +It is possible to print the charges to both a text file (.txt) as well as a Excel (.xlsx) file. The Excel file is formatted as a table and can be used for further analysis. + +.. code-block:: python + + output_dir = base_dir / "output" + + # Write the VDD charges to a text file (static method because multiple managers can be written to the same file) + manager.VDDChargeManager.write_to_txt(output_dir, vdd_manager) + + # Write the VDD charges to an excel file + vdd_manager.write_to_excel(output_dir) + +To visualize the VDD charges further, the charge for each atom can be plotted in a bar graph using matplotlib. The plot is saved as a .png file.: + +.. code-block:: python + + # Plot the VDD charges per atom in a bar graph + vdd_manager.plot_vdd_charges_per_atom(output_dir) + +.. image:: ../_static/analysis/VDD/VDD_charges_per_atom.png + :align: center + + +Finally, multiple |VDDmanager| objects can be made and written to a single .txt file. This is useful when comparing multiple calculations. + +.. code-block:: python + + # Multiple calculations can be combined into a single file + calc_dirs = [base_dir / calc for calc in DIRS.values()] + calc_res = [results.read(calc_dir) for calc_dir in calc_dirs] + vdd_managers = [manager.create_vdd_charge_manager(name=calc_dir.name, results=res) for calc_dir, res in zip(calc_dirs, calc_res)] + manager.VDDChargeManager.write_to_txt(output_dir, vdd_managers) + +.. literalinclude:: ../_static/analysis/VDD/VDD_charges_per_atom.txt + :language: python + :lines: 1- + + +VDD analysis API +----------------- + +Here is the implementation of the |VDDmanager| and |VDDcharge| classes. The central information contained in the |VDDmanager| is a dictionary containing the total charge, and irreps (if present) as keys and the a list of |VDDcharge| as value. +A |VDDcharge| does not only contain the charge itself, but also to which atom and frag index it belongs. + + +.. _VDD test directory: https://github.com/TheoChem-VU/TCutility/tree/VDD-charge-implementation-and-pathlib-rewrite/test/fixtures/VDD diff --git a/docs/_build/html/_sources/api/modules.rst.txt b/docs/_build/html/_sources/api/modules.rst.txt new file mode 100644 index 00000000..8708b821 --- /dev/null +++ b/docs/_build/html/_sources/api/modules.rst.txt @@ -0,0 +1,7 @@ +tcutility +========= + +.. toctree:: + :maxdepth: 4 + + tcutility diff --git a/docs/_build/html/_sources/api/tcutility.analysis.rst.txt b/docs/_build/html/_sources/api/tcutility.analysis.rst.txt new file mode 100644 index 00000000..83b1d6a8 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.analysis.rst.txt @@ -0,0 +1,19 @@ +tcutility.analysis package +========================== + +Subpackages +----------- + +.. toctree:: + :maxdepth: 4 + + tcutility.analysis.vdd + tcutility.analysis.vibration + +Module contents +--------------- + +.. automodule:: tcutility.analysis + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.analysis.vdd.rst.txt b/docs/_build/html/_sources/api/tcutility.analysis.vdd.rst.txt new file mode 100644 index 00000000..a8a27614 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.analysis.vdd.rst.txt @@ -0,0 +1,29 @@ +tcutility.analysis.vdd package +============================== + +Submodules +---------- + +tcutility.analysis.vdd.charge module +------------------------------------ + +.. automodule:: tcutility.analysis.vdd.charge + :members: + :undoc-members: + :show-inheritance: + +tcutility.analysis.vdd.manager module +------------------------------------- + +.. automodule:: tcutility.analysis.vdd.manager + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.analysis.vdd + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.analysis.vibration.rst.txt b/docs/_build/html/_sources/api/tcutility.analysis.vibration.rst.txt new file mode 100644 index 00000000..b42854c1 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.analysis.vibration.rst.txt @@ -0,0 +1,21 @@ +tcutility.analysis.vibration package +==================================== + +Submodules +---------- + +tcutility.analysis.vibration.ts\_vibration module +------------------------------------------------- + +.. automodule:: tcutility.analysis.vibration.ts_vibration + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.analysis.vibration + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.data.rst.txt b/docs/_build/html/_sources/api/tcutility.data.rst.txt new file mode 100644 index 00000000..3fb5b4e8 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.data.rst.txt @@ -0,0 +1,53 @@ +tcutility.data package +====================== + +Submodules +---------- + +tcutility.data.atom module +-------------------------- + +.. automodule:: tcutility.data.atom + :members: + :undoc-members: + :show-inheritance: + +tcutility.data.basis\_sets module +--------------------------------- + +.. automodule:: tcutility.data.basis_sets + :members: + :undoc-members: + :show-inheritance: + +tcutility.data.cosmo module +--------------------------- + +.. automodule:: tcutility.data.cosmo + :members: + :undoc-members: + :show-inheritance: + +tcutility.data.functionals module +--------------------------------- + +.. automodule:: tcutility.data.functionals + :members: + :undoc-members: + :show-inheritance: + +tcutility.data.molecules module +------------------------------- + +.. automodule:: tcutility.data.molecules + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.data + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.job.postscripts.rst.txt b/docs/_build/html/_sources/api/tcutility.job.postscripts.rst.txt new file mode 100644 index 00000000..6ee5a03e --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.job.postscripts.rst.txt @@ -0,0 +1,37 @@ +tcutility.job.postscripts package +================================= + +Submodules +---------- + +tcutility.job.postscripts.clean\_workdir module +----------------------------------------------- + +.. automodule:: tcutility.job.postscripts.clean_workdir + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.postscripts.split\_crest\_xyz module +-------------------------------------------------- + +.. automodule:: tcutility.job.postscripts.split_crest_xyz + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.postscripts.write\_converged\_geoms module +-------------------------------------------------------- + +.. automodule:: tcutility.job.postscripts.write_converged_geoms + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.job.postscripts + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.job.rst.txt b/docs/_build/html/_sources/api/tcutility.job.rst.txt new file mode 100644 index 00000000..4d48d67e --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.job.rst.txt @@ -0,0 +1,85 @@ +tcutility.job package +===================== + +Subpackages +----------- + +.. toctree:: + :maxdepth: 4 + + tcutility.job.postscripts + +Submodules +---------- + +tcutility.job.adf module +------------------------ + +.. automodule:: tcutility.job.adf + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.ams module +------------------------ + +.. automodule:: tcutility.job.ams + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.crest module +-------------------------- + +.. automodule:: tcutility.job.crest + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.dftb module +------------------------- + +.. automodule:: tcutility.job.dftb + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.generic module +---------------------------- + +.. automodule:: tcutility.job.generic + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.nmr module +------------------------ + +.. automodule:: tcutility.job.nmr + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.orca module +------------------------- + +.. automodule:: tcutility.job.orca + :members: + :undoc-members: + :show-inheritance: + +tcutility.job.xtb module +------------------------ + +.. automodule:: tcutility.job.xtb + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.job + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.report.rst.txt b/docs/_build/html/_sources/api/tcutility.report.rst.txt new file mode 100644 index 00000000..928060c0 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.report.rst.txt @@ -0,0 +1,21 @@ +tcutility.report package +======================== + +Submodules +---------- + +tcutility.report.character module +--------------------------------- + +.. automodule:: tcutility.report.character + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.report + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.results.rst.txt b/docs/_build/html/_sources/api/tcutility.results.rst.txt new file mode 100644 index 00000000..8d81565b --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.results.rst.txt @@ -0,0 +1,69 @@ +tcutility.results package +========================= + +Submodules +---------- + +tcutility.results.adf module +---------------------------- + +.. automodule:: tcutility.results.adf + :members: + :undoc-members: + :show-inheritance: + +tcutility.results.ams module +---------------------------- + +.. automodule:: tcutility.results.ams + :members: + :undoc-members: + :show-inheritance: + +tcutility.results.cache module +------------------------------ + +.. automodule:: tcutility.results.cache + :members: + :undoc-members: + :show-inheritance: + +tcutility.results.dftb module +----------------------------- + +.. automodule:: tcutility.results.dftb + :members: + :undoc-members: + :show-inheritance: + +tcutility.results.orca module +----------------------------- + +.. automodule:: tcutility.results.orca + :members: + :undoc-members: + :show-inheritance: + +tcutility.results.result module +------------------------------- + +.. automodule:: tcutility.results.result + :members: + :undoc-members: + :show-inheritance: + +tcutility.results.xtb module +---------------------------- + +.. automodule:: tcutility.results.xtb + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.results + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.rst.txt b/docs/_build/html/_sources/api/tcutility.rst.txt new file mode 100644 index 00000000..1e46faa6 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.rst.txt @@ -0,0 +1,138 @@ +tcutility package +================= + +Subpackages +----------- + +.. toctree:: + :maxdepth: 4 + + tcutility.analysis + tcutility.data + tcutility.job + tcutility.report + tcutility.results + tcutility.tc_typing + +Submodules +---------- + +tcutility.cache module +---------------------- + +.. automodule:: tcutility.cache + :members: + :undoc-members: + :show-inheritance: + +tcutility.cite module +--------------------- + +.. automodule:: tcutility.cite + :members: + :undoc-members: + :show-inheritance: + +tcutility.constants module +-------------------------- + +.. automodule:: tcutility.constants + :members: + :undoc-members: + :show-inheritance: + +tcutility.environment module +---------------------------- + +.. automodule:: tcutility.environment + :members: + :undoc-members: + :show-inheritance: + +tcutility.errors module +----------------------- + +.. automodule:: tcutility.errors + :members: + :undoc-members: + :show-inheritance: + +tcutility.formula module +------------------------ + +.. automodule:: tcutility.formula + :members: + :undoc-members: + :show-inheritance: + +tcutility.geometry module +------------------------- + +.. automodule:: tcutility.geometry + :members: + :undoc-members: + :show-inheritance: + +tcutility.log module +-------------------- + +.. automodule:: tcutility.log + :members: + :undoc-members: + :show-inheritance: + +tcutility.molecule module +------------------------- + +.. automodule:: tcutility.molecule + :members: + :undoc-members: + :show-inheritance: + +tcutility.pathfunc module +------------------------- + +.. automodule:: tcutility.pathfunc + :members: + :undoc-members: + :show-inheritance: + +tcutility.report module +----------------------- + +.. automodule:: tcutility.report + :members: + :undoc-members: + :show-inheritance: + +tcutility.slurm module +---------------------- + +.. automodule:: tcutility.slurm + :members: + :undoc-members: + :show-inheritance: + +tcutility.spell\_check module +----------------------------- + +.. automodule:: tcutility.spell_check + :members: + :undoc-members: + :show-inheritance: + +tcutility.timer module +---------------------- + +.. automodule:: tcutility.timer + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.tc_typing.rst.txt b/docs/_build/html/_sources/api/tcutility.tc_typing.rst.txt new file mode 100644 index 00000000..81fe1106 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.tc_typing.rst.txt @@ -0,0 +1,21 @@ +tcutility.tc\_typing package +============================ + +Submodules +---------- + +tcutility.tc\_typing.arrays module +---------------------------------- + +.. automodule:: tcutility.tc_typing.arrays + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.tc_typing + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/api/tcutility.typing.rst.txt b/docs/_build/html/_sources/api/tcutility.typing.rst.txt new file mode 100644 index 00000000..dd981e68 --- /dev/null +++ b/docs/_build/html/_sources/api/tcutility.typing.rst.txt @@ -0,0 +1,21 @@ +tcutility.typing package +======================== + +Submodules +---------- + +tcutility.typing.arrays module +------------------------------ + +.. automodule:: tcutility.typing.arrays + :members: + :undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: tcutility.typing + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_build/html/_sources/cli_scripts/main.rst.txt b/docs/_build/html/_sources/cli_scripts/main.rst.txt new file mode 100644 index 00000000..ab2b7208 --- /dev/null +++ b/docs/_build/html/_sources/cli_scripts/main.rst.txt @@ -0,0 +1,15 @@ +Command-line interface (CLI) scripts +==================================== + +TCutility comes with some helpful CLI scripts for you to use. Please find an overview and examples here. You can also access information by using the ``tc -h`` command. This will show you an overview of the available CLI scripts. More detailed descriptions can be accessed using the ``tc {program name} -h`` commands. + +Overview +-------- + +CLI scripts are invoked using the parent ``tc`` command followed by the sub-program (see below). If you have suggestions for useful scripts please contact the developers or `open an issue `_ on our GitHub page. + +.. argparse:: + :filename: ../src/tcutility/cli_scripts/tcparser.py + :func: create_parser + :prog: tc + diff --git a/docs/_build/html/_sources/index.rst.txt b/docs/_build/html/_sources/index.rst.txt new file mode 100644 index 00000000..667e4e08 --- /dev/null +++ b/docs/_build/html/_sources/index.rst.txt @@ -0,0 +1,51 @@ +.. TCutility documentation master file, created by + sphinx-quickstart on Sun Aug 27 13:58:34 2023. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +TCutility |ProjectVersion| documentation +======================================== + +**TCutility** is a Python library containing many helper functions and classes for use in programs written in the TheoCheM group. + +.. toctree:: + :maxdepth: 3 + :caption: Main modules + + results/results + tcutility.job + analysis/analysis + cli_scripts/main + +.. toctree:: + :maxdepth: 2 + :caption: Utility modules + + api/tcutility.constants + api/tcutility.data + api/tcutility.log + api/tcutility.slurm + api/tcutility.molecule + api/tcutility.formula + api/tcutility.cache + api/tcutility.geometry + api/tcutility.report + +.. toctree:: + :maxdepth: 2 + :caption: Full API + + api/modules + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + + +.. note:: + + This library is under heavy development, so there are no guarantees that older code will work with newer versions. diff --git a/docs/_build/html/_sources/results/results.rst.txt b/docs/_build/html/_sources/results/results.rst.txt new file mode 100644 index 00000000..4cdf624e --- /dev/null +++ b/docs/_build/html/_sources/results/results.rst.txt @@ -0,0 +1,46 @@ +tcutility.results +================= + +Overview +-------- + +The ``tcutility.results`` package allows you to easily retrieve information and results from a calculation performed using AMS, ORCA or CREST. +This includes results and settings from AMS as well as the calculation engine used (e.g. ADF, BAND, DFTB, ...). +Recommended usage is to use the |read| function to read the information. +One can also access specific information by calling one the functions in the submodules below. +Information will be given as |result| objects and can be used just like a `dict`_. + +.. code-block:: python + + >>> import TCutility.results + >>> calc_dir = '../../test/fixtures/ethanol' + >>> info = TCutility.results.read(calc_dir) + >>> info.engine + adf + >>> info.ams_version.full + 2022.103 r104886 (2022-06-17) + >>> info.adf.symmetry + {'group': 'C(S)', 'labels': ['AA', 'AAA']} + >>> info.properties.energy.orbint + {'AA': -2738.644830445246, + 'AAA': -1056.9706925183411, + 'total': -3795.615522963587} + >>> info.properties.vibrations.number_of_imag_modes + 0 + + +Available keys present in the |result| object +---------------------------------------------- + +After reading a calculation, different keys may be present in the |result| object depending on the engine used. Think of reading an adf calculation, or an orca calculation. +Below you can find a list of keys that are present in the |result| object for each type of calculation. + +ADF calculation +*************** + +.. literalinclude:: ../_static/result/adf_multikeys.txt + :language: text + + + +.. _dict: https://docs.python.org/3.12/library/stdtypes.html#dict diff --git a/docs/_build/html/_sources/tcutility.job.rst.txt b/docs/_build/html/_sources/tcutility.job.rst.txt new file mode 100644 index 00000000..a769e5a1 --- /dev/null +++ b/docs/_build/html/_sources/tcutility.job.rst.txt @@ -0,0 +1,227 @@ +tcutility.job +============== + +Overview +-------- + +This module offers you the tools to efficiently and easily build computational workflows with various engines. +The module defines usefull classes that do all the heavy lifting (input and runscript preparation) in the background, while ensuring correctness of the generated inputs + +Job classes +*********** + +Jobs are run using subclasses of the |Job| class. The base |Job| class handles setting up directories and running the calculations. + +The |Job| subclasses are also context-managers, which results in cleaner and more error-proof code: + +.. code-block:: python + :linenos: + + from tcutility.job import ADFJob + + # job classes are also context-managers + # when exiting the context-manager the job will automatically be run + # this ensures you won't forget to start the job + with ADFJob() as job: + job.molecule('example.xyz') + + # you can also not use the context-manager + # in that case, don't forget to run the job + job = ADFJob() + job.molecule('example.xyz') + job.run() + +You can control where a calculation is run by changing the ``job.name`` and ``job.rundir`` properties. + +.. code-block:: python + :linenos: + + from tcutility.job import ADFJob + + with ADFJob() as job: + job.molecule('example.xyz') + job.rundir = './calc_dir/molecule_1' + job.name = 'ADF_calculation' + + print(job.workdir) + +This script will run a single point calculation using ADF in the working directory ``./calc_dir/molecule_1/ADF_calculation``. You can access the full path to the working directory using the ``job.workdir`` property. + + +Slurm support +************* + +One usefull feature is that the |Job| class detects if slurm is able to be used on the platform the script is running on. If slurm is available, jobs will be submitted using ``sbatch`` instead of ran locally. It is possible to set any ``sbatch`` option you would like. + +.. code-block:: python + :linenos: + + from tcutility.job import ADFJob + + with ADFJob() as job: + job.molecule('example.xyz') + # we can set any sbatch settings using the job.sbatch() method + # in this case, we set the partition to 'tc' and the number of cores to 32 + job.sbatch(p='tc', n=32) + +Job dependencies +**************** + +It is possible to setup dependencies between jobs. This allows you to use the results of one calculation as input for a different calculation. + +.. code-block:: python + :linenos: + + from tcutility.job import ADFJob, CRESTJob + + # submit and run a CREST calculation + with CRESTJob() as crest_job: + crest_job.molecule('input.xyz') + crest_job.sbatch(p='tc', n=32) + + crest_job.rundir = './calculations/molecule_1' + crest_job.name = 'CREST' + + # get the 10 lowest conformers using the crest_job.get_conformer_xyz() method + for i, conformer_xyz in enumerate(crest_job.get_conformer_xyz(10)): + # set up the ADF calculation + with ADFJob() as opt_job: + # make the ADFJob depend on the CRESTJob + # slurm will wait for the CRESTJob to finish before starting the ADFJob + opt_job.dependency(crest_job) + # you can set a file to an xyz-file + # that does not exist yet as the molecule + opt_job.molecule(conformer_xyz) + opt_job.sbatch(p='tc', n=16) + + opt_job.functional('OLYP-D3(BJ)') + opt_job.basis_set('TZ2P') + opt_job.quality('Good') + opt_job.optimization() + + opt_job.rundir = './calculations/molecule_1' + opt_job.name = f'conformer_{i}' + +This script will first setup and submit a |CRESTJob| calculation to generate conformers for the structure in ``input.xyz``. It will then submit geometry optimizations for the 10 lowest conformers using |ADFJob| at the ``OLYP-D3(BJ)/TZ2P`` level of theory. Slurm will first wait for the |CRESTJob| calculation to finish before starting the |ADFJob| calculations. + + +Rerun prevention +**************** + +Before submitting a calculation :mod:`tcutility.job` will check if the calculation has already been run or is currently being managed by slurm. This way you can be sure that you are not wasting time rerunning your calculation when you run a script you have run before. + +For example, we can write a script that performs optimizations using |ADFJob| on structures stored in a directory: + +.. code-block:: python + :linenos: + + + from tcutility.job import ADFJob + import os + + + input_xyz_directory = 'molecules' + + # get the xyz files we want to optimize + xyz_files = [os.path.join(input_xyz_directory, file) for file in os.listdir(input_xyz_directory) if file.endswith('.xyz')] + + for xyz_file in xyz_files: + with ADFJob() as job: + job.molecule(xyz_file) + job.sbatch(p='tc', n=16) + + job.functional('OLYP-D3(BJ)') + job.basis_set('TZ2P') + job.quality('Good') + job.optimization() + + job.rundir = './calculations' + job.name = os.path.split(file)[1].removesuffix('.xyz') + +Everytime this script is run it will loop through the molecules stored in the ``molecules`` directory. If you add new molecules to this directory and then rerun it, the script will detect which molecules were previously optimized and skip those. This way you can easily reuse the script multiple times without manually checking/implementing rerun prevention. + + +Supported engines +***************** + +We currently support the following engines and job classes: + +* `Amsterdam Density Functional (ADF) `_ + + * |ADFJob|, regular ADF calculations + * |ADFFragmentJob|, fragment based calculations + * |NMRJob|, Nuclear Magnetic Resonance (NMR) calculations using ADF + + +* `Density Functional with Tight Binding (DFTB) `_ + + * |DFTBJob|, regular DFTB calculations + +* `ORCA `_ + + * |ORCAJob|, regular ORCA calculations + +* `Conformer rotamer ensemble sampling tool (CREST) `_ including `Quantum Cluster Growth (QCG) `_ + + * |CRESTJob|, CREST conformational search + * |QCGJob|, QCG explicit solvation search + +See the `API Documentation <./api/tcutility.job.html>`_ for an overview of the Job classes offered by tcutility.job module. + +.. note:: + + If you want support for new engines/classes, please open an issue on our GitHub page, or let one of the developers know! + +Requirements +------------ + +To run calculations related to the Amsterdam Modelling Suite (AMS) you will require a license. + +For ORCA calculations you will need to add the ORCA executable to your PATH. + + +Examples +-------- +A few typical use-cases are given below. Click `here <./examples.html>`_ for a full overview of all examples. Of course, the scripts shown above are also valid example uses of :mod:`tcutility.job`! + +Geometry optimization using ADF +******************************* + +It is quite easy to set up calculations using the :mod:`tcutility.job` package. +For example, if we want to run a simple geometry optimization using ADF we can use the |ADFJob| class. + +In this case we are optimizing the water dimer at the ``BP86-D3(BJ)/TZ2P`` level. +To handle the ADF settings you can refer to the GUI. For example, to use a specific functional simply enter the name of the functional as it appears in the ADF GUI. The same applies to pretty much all settings. The |ADFJob| class will handle everything in the background for you. + +The job will be run in the ``./calculations/GO_water_dimer`` directory. The :mod:`tcutility.job` package will handle running of the calculation as well. It will detect if your platform supports slurm and if it does, will use ``sbatch`` to run your calculations. Otherwise, it will simply run the calculation locally. + +.. tabs:: + + .. group-tab:: Runscript (:download:`󠀠download <../examples/job/GO_water_dimer.py>`) + + .. literalinclude:: ../examples/job/GO_water_dimer.py + :language: python + :linenos: + + .. group-tab:: XYZ-file (:download:`󠀠download <../examples/job/water_dimer.xyz>`) + + .. literalinclude:: ../examples/job/water_dimer.xyz + +Fragment calculation using ADF +****************************** + +Another common usage of ADF is running a fragment calculation. This calculation requires setting up three different ADF jobs. Using the :mod:`tcutility.job` package allows you to set up and run these kinds of calculations in as little as 8 lines of code. + +In this case we make use of a special xyz file format (see :func:`tcutility.molecule.guess_fragments`) which specifies the fragments. This saves us some work in setting up the calculations. + +.. tabs:: + + .. group-tab:: Runscript (:download:`󠀠download <../examples/job/frag_NH3BH3.py>`) + + .. literalinclude:: ../examples/job/frag_NH3BH3.py + :language: python + :linenos: + + .. group-tab:: XYZ-file (:download:`󠀠download <../examples/job/NH3BH3.xyz>`) + + .. literalinclude:: ../examples/job/NH3BH3.xyz diff --git a/docs/_build/html/_static/analysis/VDD/VDD_charges_per_atom.txt b/docs/_build/html/_static/analysis/VDD/VDD_charges_per_atom.txt new file mode 100644 index 00000000..683b999a --- /dev/null +++ b/docs/_build/html/_static/analysis/VDD/VDD_charges_per_atom.txt @@ -0,0 +1,79 @@ +VDD charges (in unit me): +fa_acid_amide_cs + Frag Atom Total AA AAA + 1 1C +19 +1 +18 + 1 2O -8 -49 +41 + 1 3Se -68 -5 -63 + 2 4O -34 +27 -61 + 2 5C +10 +3 +8 + 2 6H +6 +5 +1 + 2 7H +2 -2 +4 + 2 8H +44 +41 +3 + 2 9N -4 -46 +42 + 1 10H +32 +31 +1 + 1 11H +1 -6 +6 + +fa_squaramide_se_cs + Frag Atom Total AA AAA + 1 1C -40 -10 -30 + 1 2Se -165 -30 -134 + 1 3C -40 -10 -30 + 1 4Se -165 -30 -134 + 1 5C +26 +122 -96 + 1 6C +26 +122 -96 + 2 7N +62 -88 +150 + 2 8H +53 -2 +55 + 2 9H +63 +7 +56 + 2 10N +62 -88 +150 + 2 11H +63 +7 +56 + 2 12H +53 -2 +55 + +fa_donor_acceptor_nosym + Frag Atom Total + 1 1C +0 + 1 2C +0 + 1 3C -0 + 1 4C -0 + 1 5H +1 + 1 6H +1 + 1 7H +1 + 1 8H +0 + 1 9H +1 + 1 10H +2 + 1 11H +1 + 2 12O -1 + 1 13O -2 + 1 14N -13 + 2 15H +6 + 2 16H -7 + 2 17H -9 + 1 18H +20 + +geo_nosym + Frag Atom Total + 1 1C -105 + 5 2H +67 + 11 3H +68 + 16 4H +55 + 17 5C +166 + 18 6O -291 + 19 7N -116 + 20 8H +158 + 21 9N -84 + 2 10H +165 + 3 11C +213 + 4 12O -253 + 8 13N -235 + 10 14H +54 + 14 15H +59 + 15 16C +45 + 22 17C -68 + 23 18C -50 + 24 19C -59 + 25 20C -53 + 6 21C -64 + 12 22H +65 + 7 23H +52 + 9 24H +48 + 13 25H +164 + diff --git a/docs/_build/html/_static/analysis/VDD/vdd_charges_per_atom.png b/docs/_build/html/_static/analysis/VDD/vdd_charges_per_atom.png new file mode 100644 index 00000000..26643dc6 Binary files /dev/null and b/docs/_build/html/_static/analysis/VDD/vdd_charges_per_atom.png differ diff --git a/docs/_build/html/_static/basic.css b/docs/_build/html/_static/basic.css new file mode 100644 index 00000000..2af6139e --- /dev/null +++ b/docs/_build/html/_static/basic.css @@ -0,0 +1,925 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 270px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li p.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 360px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +a:visited { + color: #551A8B; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, figure.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, figure.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, figure.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, figure.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar, +aside.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} + +nav.contents, +aside.topic, +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ + +nav.contents, +aside.topic, +div.topic { + border: 1px solid #ccc; + padding: 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +aside.sidebar > :last-child, +nav.contents > :last-child, +aside.topic > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +aside.sidebar::after, +nav.contents::after, +aside.topic::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure, figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption, figcaption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number, +figcaption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text, +figcaption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + +/* -- object description styles --------------------------------------------- */ + +.sig { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; +} + +.sig-name, code.descname { + background-color: transparent; + font-weight: bold; +} + +.sig-name { + font-size: 1.1em; +} + +code.descname { + font-size: 1.2em; +} + +.sig-prename, code.descclassname { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.sig-param.n { + font-style: italic; +} + +/* C++ specific styling */ + +.sig-inline.c-texpr, +.sig-inline.cpp-texpr { + font-family: unset; +} + +.sig.c .k, .sig.c .kt, +.sig.cpp .k, .sig.cpp .kt { + color: #0033B3; +} + +.sig.c .m, +.sig.cpp .m { + color: #1750EB; +} + +.sig.c .s, .sig.c .sc, +.sig.cpp .s, .sig.cpp .sc { + color: #067D17; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +aside.footnote > span, +div.citation > span { + float: left; +} +aside.footnote > span:last-of-type, +div.citation > span:last-of-type { + padding-right: 0.5em; +} +aside.footnote > p { + margin-left: 2em; +} +div.citation > p { + margin-left: 4em; +} +aside.footnote > p:last-of-type, +div.citation > p:last-of-type { + margin-bottom: 0em; +} +aside.footnote > p:last-of-type:after, +div.citation > p:last-of-type:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +.sig dd { + margin-top: 0px; + margin-bottom: 0px; +} + +.sig dl { + margin-top: 0px; + margin-bottom: 0px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0 0.5em; + content: ":"; + display: inline-block; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +.translated { + background-color: rgba(207, 255, 207, 0.2) +} + +.untranslated { + background-color: rgba(255, 207, 207, 0.2) +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; + white-space: nowrap; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; + -webkit-user-select: text; /* Safari fallback only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10+ */ +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + margin: 1em 0; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/docs/_build/html/_static/check-solid.svg b/docs/_build/html/_static/check-solid.svg new file mode 100644 index 00000000..92fad4b5 --- /dev/null +++ b/docs/_build/html/_static/check-solid.svg @@ -0,0 +1,4 @@ + + + + diff --git a/docs/_build/html/_static/clipboard.min.js b/docs/_build/html/_static/clipboard.min.js new file mode 100644 index 00000000..54b3c463 --- /dev/null +++ b/docs/_build/html/_static/clipboard.min.js @@ -0,0 +1,7 @@ +/*! + * clipboard.js v2.0.8 + * https://clipboardjs.com/ + * + * Licensed MIT © Zeno Rocha + */ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ClipboardJS=e():t.ClipboardJS=e()}(this,function(){return n={686:function(t,e,n){"use strict";n.d(e,{default:function(){return o}});var e=n(279),i=n.n(e),e=n(370),u=n.n(e),e=n(817),c=n.n(e);function a(t){try{return document.execCommand(t)}catch(t){return}}var f=function(t){t=c()(t);return a("cut"),t};var l=function(t){var e,n,o,r=1 + + + + diff --git a/docs/_build/html/_static/copybutton.css b/docs/_build/html/_static/copybutton.css new file mode 100644 index 00000000..f1916ec7 --- /dev/null +++ b/docs/_build/html/_static/copybutton.css @@ -0,0 +1,94 @@ +/* Copy buttons */ +button.copybtn { + position: absolute; + display: flex; + top: .3em; + right: .3em; + width: 1.7em; + height: 1.7em; + opacity: 0; + transition: opacity 0.3s, border .3s, background-color .3s; + user-select: none; + padding: 0; + border: none; + outline: none; + border-radius: 0.4em; + /* The colors that GitHub uses */ + border: #1b1f2426 1px solid; + background-color: #f6f8fa; + color: #57606a; +} + +button.copybtn.success { + border-color: #22863a; + color: #22863a; +} + +button.copybtn svg { + stroke: currentColor; + width: 1.5em; + height: 1.5em; + padding: 0.1em; +} + +div.highlight { + position: relative; +} + +/* Show the copybutton */ +.highlight:hover button.copybtn, button.copybtn.success { + opacity: 1; +} + +.highlight button.copybtn:hover { + background-color: rgb(235, 235, 235); +} + +.highlight button.copybtn:active { + background-color: rgb(187, 187, 187); +} + +/** + * A minimal CSS-only tooltip copied from: + * https://codepen.io/mildrenben/pen/rVBrpK + * + * To use, write HTML like the following: + * + *

Short

+ */ + .o-tooltip--left { + position: relative; + } + + .o-tooltip--left:after { + opacity: 0; + visibility: hidden; + position: absolute; + content: attr(data-tooltip); + padding: .2em; + font-size: .8em; + left: -.2em; + background: grey; + color: white; + white-space: nowrap; + z-index: 2; + border-radius: 2px; + transform: translateX(-102%) translateY(0); + transition: opacity 0.2s cubic-bezier(0.64, 0.09, 0.08, 1), transform 0.2s cubic-bezier(0.64, 0.09, 0.08, 1); +} + +.o-tooltip--left:hover:after { + display: block; + opacity: 1; + visibility: visible; + transform: translateX(-100%) translateY(0); + transition: opacity 0.2s cubic-bezier(0.64, 0.09, 0.08, 1), transform 0.2s cubic-bezier(0.64, 0.09, 0.08, 1); + transition-delay: .5s; +} + +/* By default the copy button shouldn't show up when printing a page */ +@media print { + button.copybtn { + display: none; + } +} diff --git a/docs/_build/html/_static/copybutton.js b/docs/_build/html/_static/copybutton.js new file mode 100644 index 00000000..2ea7ff3e --- /dev/null +++ b/docs/_build/html/_static/copybutton.js @@ -0,0 +1,248 @@ +// Localization support +const messages = { + 'en': { + 'copy': 'Copy', + 'copy_to_clipboard': 'Copy to clipboard', + 'copy_success': 'Copied!', + 'copy_failure': 'Failed to copy', + }, + 'es' : { + 'copy': 'Copiar', + 'copy_to_clipboard': 'Copiar al portapapeles', + 'copy_success': '¡Copiado!', + 'copy_failure': 'Error al copiar', + }, + 'de' : { + 'copy': 'Kopieren', + 'copy_to_clipboard': 'In die Zwischenablage kopieren', + 'copy_success': 'Kopiert!', + 'copy_failure': 'Fehler beim Kopieren', + }, + 'fr' : { + 'copy': 'Copier', + 'copy_to_clipboard': 'Copier dans le presse-papier', + 'copy_success': 'Copié !', + 'copy_failure': 'Échec de la copie', + }, + 'ru': { + 'copy': 'Скопировать', + 'copy_to_clipboard': 'Скопировать в буфер', + 'copy_success': 'Скопировано!', + 'copy_failure': 'Не удалось скопировать', + }, + 'zh-CN': { + 'copy': '复制', + 'copy_to_clipboard': '复制到剪贴板', + 'copy_success': '复制成功!', + 'copy_failure': '复制失败', + }, + 'it' : { + 'copy': 'Copiare', + 'copy_to_clipboard': 'Copiato negli appunti', + 'copy_success': 'Copiato!', + 'copy_failure': 'Errore durante la copia', + } +} + +let locale = 'en' +if( document.documentElement.lang !== undefined + && messages[document.documentElement.lang] !== undefined ) { + locale = document.documentElement.lang +} + +let doc_url_root = DOCUMENTATION_OPTIONS.URL_ROOT; +if (doc_url_root == '#') { + doc_url_root = ''; +} + +/** + * SVG files for our copy buttons + */ +let iconCheck = ` + ${messages[locale]['copy_success']} + + +` + +// If the user specified their own SVG use that, otherwise use the default +let iconCopy = ``; +if (!iconCopy) { + iconCopy = ` + ${messages[locale]['copy_to_clipboard']} + + + +` +} + +/** + * Set up copy/paste for code blocks + */ + +const runWhenDOMLoaded = cb => { + if (document.readyState != 'loading') { + cb() + } else if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', cb) + } else { + document.attachEvent('onreadystatechange', function() { + if (document.readyState == 'complete') cb() + }) + } +} + +const codeCellId = index => `codecell${index}` + +// Clears selected text since ClipboardJS will select the text when copying +const clearSelection = () => { + if (window.getSelection) { + window.getSelection().removeAllRanges() + } else if (document.selection) { + document.selection.empty() + } +} + +// Changes tooltip text for a moment, then changes it back +// We want the timeout of our `success` class to be a bit shorter than the +// tooltip and icon change, so that we can hide the icon before changing back. +var timeoutIcon = 2000; +var timeoutSuccessClass = 1500; + +const temporarilyChangeTooltip = (el, oldText, newText) => { + el.setAttribute('data-tooltip', newText) + el.classList.add('success') + // Remove success a little bit sooner than we change the tooltip + // So that we can use CSS to hide the copybutton first + setTimeout(() => el.classList.remove('success'), timeoutSuccessClass) + setTimeout(() => el.setAttribute('data-tooltip', oldText), timeoutIcon) +} + +// Changes the copy button icon for two seconds, then changes it back +const temporarilyChangeIcon = (el) => { + el.innerHTML = iconCheck; + setTimeout(() => {el.innerHTML = iconCopy}, timeoutIcon) +} + +const addCopyButtonToCodeCells = () => { + // If ClipboardJS hasn't loaded, wait a bit and try again. This + // happens because we load ClipboardJS asynchronously. + if (window.ClipboardJS === undefined) { + setTimeout(addCopyButtonToCodeCells, 250) + return + } + + // Add copybuttons to all of our code cells + const COPYBUTTON_SELECTOR = 'div.highlight pre'; + const codeCells = document.querySelectorAll(COPYBUTTON_SELECTOR) + codeCells.forEach((codeCell, index) => { + const id = codeCellId(index) + codeCell.setAttribute('id', id) + + const clipboardButton = id => + `` + codeCell.insertAdjacentHTML('afterend', clipboardButton(id)) + }) + +function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} + +/** + * Removes excluded text from a Node. + * + * @param {Node} target Node to filter. + * @param {string} exclude CSS selector of nodes to exclude. + * @returns {DOMString} Text from `target` with text removed. + */ +function filterText(target, exclude) { + const clone = target.cloneNode(true); // clone as to not modify the live DOM + if (exclude) { + // remove excluded nodes + clone.querySelectorAll(exclude).forEach(node => node.remove()); + } + return clone.innerText; +} + +// Callback when a copy button is clicked. Will be passed the node that was clicked +// should then grab the text and replace pieces of text that shouldn't be used in output +function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true, copyEmptyLines = true, lineContinuationChar = "", hereDocDelim = "") { + var regexp; + var match; + + // Do we check for line continuation characters and "HERE-documents"? + var useLineCont = !!lineContinuationChar + var useHereDoc = !!hereDocDelim + + // create regexp to capture prompt and remaining line + if (isRegexp) { + regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)') + } else { + regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)') + } + + const outputLines = []; + var promptFound = false; + var gotLineCont = false; + var gotHereDoc = false; + const lineGotPrompt = []; + for (const line of textContent.split('\n')) { + match = line.match(regexp) + if (match || gotLineCont || gotHereDoc) { + promptFound = regexp.test(line) + lineGotPrompt.push(promptFound) + if (removePrompts && promptFound) { + outputLines.push(match[2]) + } else { + outputLines.push(line) + } + gotLineCont = line.endsWith(lineContinuationChar) & useLineCont + if (line.includes(hereDocDelim) & useHereDoc) + gotHereDoc = !gotHereDoc + } else if (!onlyCopyPromptLines) { + outputLines.push(line) + } else if (copyEmptyLines && line.trim() === '') { + outputLines.push(line) + } + } + + // If no lines with the prompt were found then just use original lines + if (lineGotPrompt.some(v => v === true)) { + textContent = outputLines.join('\n'); + } + + // Remove a trailing newline to avoid auto-running when pasting + if (textContent.endsWith("\n")) { + textContent = textContent.slice(0, -1) + } + return textContent +} + + +var copyTargetText = (trigger) => { + var target = document.querySelector(trigger.attributes['data-clipboard-target'].value); + + // get filtered text + let exclude = '.linenos'; + + let text = filterText(target, exclude); + return formatCopyText(text, '', false, true, true, true, '', '') +} + + // Initialize with a callback so we can modify the text before copy + const clipboard = new ClipboardJS('.copybtn', {text: copyTargetText}) + + // Update UI with error/success messages + clipboard.on('success', event => { + clearSelection() + temporarilyChangeTooltip(event.trigger, messages[locale]['copy'], messages[locale]['copy_success']) + temporarilyChangeIcon(event.trigger) + }) + + clipboard.on('error', event => { + temporarilyChangeTooltip(event.trigger, messages[locale]['copy'], messages[locale]['copy_failure']) + }) +} + +runWhenDOMLoaded(addCopyButtonToCodeCells) \ No newline at end of file diff --git a/docs/_build/html/_static/copybutton_funcs.js b/docs/_build/html/_static/copybutton_funcs.js new file mode 100644 index 00000000..dbe1aaad --- /dev/null +++ b/docs/_build/html/_static/copybutton_funcs.js @@ -0,0 +1,73 @@ +function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} + +/** + * Removes excluded text from a Node. + * + * @param {Node} target Node to filter. + * @param {string} exclude CSS selector of nodes to exclude. + * @returns {DOMString} Text from `target` with text removed. + */ +export function filterText(target, exclude) { + const clone = target.cloneNode(true); // clone as to not modify the live DOM + if (exclude) { + // remove excluded nodes + clone.querySelectorAll(exclude).forEach(node => node.remove()); + } + return clone.innerText; +} + +// Callback when a copy button is clicked. Will be passed the node that was clicked +// should then grab the text and replace pieces of text that shouldn't be used in output +export function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true, copyEmptyLines = true, lineContinuationChar = "", hereDocDelim = "") { + var regexp; + var match; + + // Do we check for line continuation characters and "HERE-documents"? + var useLineCont = !!lineContinuationChar + var useHereDoc = !!hereDocDelim + + // create regexp to capture prompt and remaining line + if (isRegexp) { + regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)') + } else { + regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)') + } + + const outputLines = []; + var promptFound = false; + var gotLineCont = false; + var gotHereDoc = false; + const lineGotPrompt = []; + for (const line of textContent.split('\n')) { + match = line.match(regexp) + if (match || gotLineCont || gotHereDoc) { + promptFound = regexp.test(line) + lineGotPrompt.push(promptFound) + if (removePrompts && promptFound) { + outputLines.push(match[2]) + } else { + outputLines.push(line) + } + gotLineCont = line.endsWith(lineContinuationChar) & useLineCont + if (line.includes(hereDocDelim) & useHereDoc) + gotHereDoc = !gotHereDoc + } else if (!onlyCopyPromptLines) { + outputLines.push(line) + } else if (copyEmptyLines && line.trim() === '') { + outputLines.push(line) + } + } + + // If no lines with the prompt were found then just use original lines + if (lineGotPrompt.some(v => v === true)) { + textContent = outputLines.join('\n'); + } + + // Remove a trailing newline to avoid auto-running when pasting + if (textContent.endsWith("\n")) { + textContent = textContent.slice(0, -1) + } + return textContent +} diff --git a/docs/_build/html/_static/doctools.js b/docs/_build/html/_static/doctools.js new file mode 100644 index 00000000..4d67807d --- /dev/null +++ b/docs/_build/html/_static/doctools.js @@ -0,0 +1,156 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Base JavaScript utilities for all Sphinx HTML documentation. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ +"use strict"; + +const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([ + "TEXTAREA", + "INPUT", + "SELECT", + "BUTTON", +]); + +const _ready = (callback) => { + if (document.readyState !== "loading") { + callback(); + } else { + document.addEventListener("DOMContentLoaded", callback); + } +}; + +/** + * Small JavaScript module for the documentation. + */ +const Documentation = { + init: () => { + Documentation.initDomainIndexTable(); + Documentation.initOnKeyListeners(); + }, + + /** + * i18n support + */ + TRANSLATIONS: {}, + PLURAL_EXPR: (n) => (n === 1 ? 0 : 1), + LOCALE: "unknown", + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext: (string) => { + const translated = Documentation.TRANSLATIONS[string]; + switch (typeof translated) { + case "undefined": + return string; // no translation + case "string": + return translated; // translation exists + default: + return translated[0]; // (singular, plural) translation tuple exists + } + }, + + ngettext: (singular, plural, n) => { + const translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated !== "undefined") + return translated[Documentation.PLURAL_EXPR(n)]; + return n === 1 ? singular : plural; + }, + + addTranslations: (catalog) => { + Object.assign(Documentation.TRANSLATIONS, catalog.messages); + Documentation.PLURAL_EXPR = new Function( + "n", + `return (${catalog.plural_expr})` + ); + Documentation.LOCALE = catalog.locale; + }, + + /** + * helper function to focus on search bar + */ + focusSearchBar: () => { + document.querySelectorAll("input[name=q]")[0]?.focus(); + }, + + /** + * Initialise the domain index toggle buttons + */ + initDomainIndexTable: () => { + const toggler = (el) => { + const idNumber = el.id.substr(7); + const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`); + if (el.src.substr(-9) === "minus.png") { + el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`; + toggledRows.forEach((el) => (el.style.display = "none")); + } else { + el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`; + toggledRows.forEach((el) => (el.style.display = "")); + } + }; + + const togglerElements = document.querySelectorAll("img.toggler"); + togglerElements.forEach((el) => + el.addEventListener("click", (event) => toggler(event.currentTarget)) + ); + togglerElements.forEach((el) => (el.style.display = "")); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler); + }, + + initOnKeyListeners: () => { + // only install a listener if it is really needed + if ( + !DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS && + !DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS + ) + return; + + document.addEventListener("keydown", (event) => { + // bail for input elements + if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; + // bail with special keys + if (event.altKey || event.ctrlKey || event.metaKey) return; + + if (!event.shiftKey) { + switch (event.key) { + case "ArrowLeft": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const prevLink = document.querySelector('link[rel="prev"]'); + if (prevLink && prevLink.href) { + window.location.href = prevLink.href; + event.preventDefault(); + } + break; + case "ArrowRight": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const nextLink = document.querySelector('link[rel="next"]'); + if (nextLink && nextLink.href) { + window.location.href = nextLink.href; + event.preventDefault(); + } + break; + } + } + + // some keyboard layouts may need Shift to get / + switch (event.key) { + case "/": + if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break; + Documentation.focusSearchBar(); + event.preventDefault(); + } + }); + }, +}; + +// quick alias for translations +const _ = Documentation.gettext; + +_ready(Documentation.init); diff --git a/docs/_build/html/_static/documentation_options.js b/docs/_build/html/_static/documentation_options.js new file mode 100644 index 00000000..ccad2234 --- /dev/null +++ b/docs/_build/html/_static/documentation_options.js @@ -0,0 +1,13 @@ +const DOCUMENTATION_OPTIONS = { + VERSION: 'v0.14.4', + LANGUAGE: 'en', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false, + SHOW_SEARCH_SUMMARY: true, + ENABLE_SEARCH_SHORTCUTS: true, +}; \ No newline at end of file diff --git a/docs/_build/html/_static/file.png b/docs/_build/html/_static/file.png new file mode 100644 index 00000000..a858a410 Binary files /dev/null and b/docs/_build/html/_static/file.png differ diff --git a/docs/_build/html/_static/language_data.js b/docs/_build/html/_static/language_data.js new file mode 100644 index 00000000..367b8ed8 --- /dev/null +++ b/docs/_build/html/_static/language_data.js @@ -0,0 +1,199 @@ +/* + * language_data.js + * ~~~~~~~~~~~~~~~~ + * + * This script contains the language-specific data used by searchtools.js, + * namely the list of stopwords, stemmer, scorer and splitter. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +var stopwords = ["a", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "near", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"]; + + +/* Non-minified version is copied as a separate JS file, if available */ + +/** + * Porter Stemmer + */ +var Stemmer = function() { + + var step2list = { + ational: 'ate', + tional: 'tion', + enci: 'ence', + anci: 'ance', + izer: 'ize', + bli: 'ble', + alli: 'al', + entli: 'ent', + eli: 'e', + ousli: 'ous', + ization: 'ize', + ation: 'ate', + ator: 'ate', + alism: 'al', + iveness: 'ive', + fulness: 'ful', + ousness: 'ous', + aliti: 'al', + iviti: 'ive', + biliti: 'ble', + logi: 'log' + }; + + var step3list = { + icate: 'ic', + ative: '', + alize: 'al', + iciti: 'ic', + ical: 'ic', + ful: '', + ness: '' + }; + + var c = "[^aeiou]"; // consonant + var v = "[aeiouy]"; // vowel + var C = c + "[^aeiouy]*"; // consonant sequence + var V = v + "[aeiou]*"; // vowel sequence + + var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 + var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 + var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 + var s_v = "^(" + C + ")?" + v; // vowel in stem + + this.stemWord = function (w) { + var stem; + var suffix; + var firstch; + var origword = w; + + if (w.length < 3) + return w; + + var re; + var re2; + var re3; + var re4; + + firstch = w.substr(0,1); + if (firstch == "y") + w = firstch.toUpperCase() + w.substr(1); + + // Step 1a + re = /^(.+?)(ss|i)es$/; + re2 = /^(.+?)([^s])s$/; + + if (re.test(w)) + w = w.replace(re,"$1$2"); + else if (re2.test(w)) + w = w.replace(re2,"$1$2"); + + // Step 1b + re = /^(.+?)eed$/; + re2 = /^(.+?)(ed|ing)$/; + if (re.test(w)) { + var fp = re.exec(w); + re = new RegExp(mgr0); + if (re.test(fp[1])) { + re = /.$/; + w = w.replace(re,""); + } + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1]; + re2 = new RegExp(s_v); + if (re2.test(stem)) { + w = stem; + re2 = /(at|bl|iz)$/; + re3 = new RegExp("([^aeiouylsz])\\1$"); + re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re2.test(w)) + w = w + "e"; + else if (re3.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + else if (re4.test(w)) + w = w + "e"; + } + } + + // Step 1c + re = /^(.+?)y$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(s_v); + if (re.test(stem)) + w = stem + "i"; + } + + // Step 2 + re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step2list[suffix]; + } + + // Step 3 + re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step3list[suffix]; + } + + // Step 4 + re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; + re2 = /^(.+?)(s|t)(ion)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + if (re.test(stem)) + w = stem; + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1] + fp[2]; + re2 = new RegExp(mgr1); + if (re2.test(stem)) + w = stem; + } + + // Step 5 + re = /^(.+?)e$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + re2 = new RegExp(meq1); + re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) + w = stem; + } + re = /ll$/; + re2 = new RegExp(mgr1); + if (re.test(w) && re2.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + + // and turn initial Y back to y + if (firstch == "y") + w = firstch.toLowerCase() + w.substr(1); + return w; + } +} + diff --git a/docs/_build/html/_static/minus.png b/docs/_build/html/_static/minus.png new file mode 100644 index 00000000..d96755fd Binary files /dev/null and b/docs/_build/html/_static/minus.png differ diff --git a/docs/_build/html/_static/plus.png b/docs/_build/html/_static/plus.png new file mode 100644 index 00000000..7107cec9 Binary files /dev/null and b/docs/_build/html/_static/plus.png differ diff --git a/docs/_build/html/_static/pygments.css b/docs/_build/html/_static/pygments.css new file mode 100644 index 00000000..012e6a00 --- /dev/null +++ b/docs/_build/html/_static/pygments.css @@ -0,0 +1,152 @@ +html[data-theme="light"] .highlight pre { line-height: 125%; } +html[data-theme="light"] .highlight td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +html[data-theme="light"] .highlight span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +html[data-theme="light"] .highlight td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +html[data-theme="light"] .highlight span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +html[data-theme="light"] .highlight .hll { background-color: #fae4c2 } +html[data-theme="light"] .highlight { background: #fefefe; color: #080808 } +html[data-theme="light"] .highlight .c { color: #515151 } /* Comment */ +html[data-theme="light"] .highlight .err { color: #a12236 } /* Error */ +html[data-theme="light"] .highlight .k { color: #6730c5 } /* Keyword */ +html[data-theme="light"] .highlight .l { color: #7f4707 } /* Literal */ +html[data-theme="light"] .highlight .n { color: #080808 } /* Name */ +html[data-theme="light"] .highlight .o { color: #00622f } /* Operator */ +html[data-theme="light"] .highlight .p { color: #080808 } /* Punctuation */ +html[data-theme="light"] .highlight .ch { color: #515151 } /* Comment.Hashbang */ +html[data-theme="light"] .highlight .cm { color: #515151 } /* Comment.Multiline */ +html[data-theme="light"] .highlight .cp { color: #515151 } /* Comment.Preproc */ +html[data-theme="light"] .highlight .cpf { color: #515151 } /* Comment.PreprocFile */ +html[data-theme="light"] .highlight .c1 { color: #515151 } /* Comment.Single */ +html[data-theme="light"] .highlight .cs { color: #515151 } /* Comment.Special */ +html[data-theme="light"] .highlight .gd { color: #005b82 } /* Generic.Deleted */ +html[data-theme="light"] .highlight .ge { font-style: italic } /* Generic.Emph */ +html[data-theme="light"] .highlight .gh { color: #005b82 } /* Generic.Heading */ +html[data-theme="light"] .highlight .gs { font-weight: bold } /* Generic.Strong */ +html[data-theme="light"] .highlight .gu { color: #005b82 } /* Generic.Subheading */ +html[data-theme="light"] .highlight .kc { color: #6730c5 } /* Keyword.Constant */ +html[data-theme="light"] .highlight .kd { color: #6730c5 } /* Keyword.Declaration */ +html[data-theme="light"] .highlight .kn { color: #6730c5 } /* Keyword.Namespace */ +html[data-theme="light"] .highlight .kp { color: #6730c5 } /* Keyword.Pseudo */ +html[data-theme="light"] .highlight .kr { color: #6730c5 } /* Keyword.Reserved */ +html[data-theme="light"] .highlight .kt { color: #7f4707 } /* Keyword.Type */ +html[data-theme="light"] .highlight .ld { color: #7f4707 } /* Literal.Date */ +html[data-theme="light"] .highlight .m { color: #7f4707 } /* Literal.Number */ +html[data-theme="light"] .highlight .s { color: #00622f } /* Literal.String */ +html[data-theme="light"] .highlight .na { color: #912583 } /* Name.Attribute */ +html[data-theme="light"] .highlight .nb { color: #7f4707 } /* Name.Builtin */ +html[data-theme="light"] .highlight .nc { color: #005b82 } /* Name.Class */ +html[data-theme="light"] .highlight .no { color: #005b82 } /* Name.Constant */ +html[data-theme="light"] .highlight .nd { color: #7f4707 } /* Name.Decorator */ +html[data-theme="light"] .highlight .ni { color: #00622f } /* Name.Entity */ +html[data-theme="light"] .highlight .ne { color: #6730c5 } /* Name.Exception */ +html[data-theme="light"] .highlight .nf { color: #005b82 } /* Name.Function */ +html[data-theme="light"] .highlight .nl { color: #7f4707 } /* Name.Label */ +html[data-theme="light"] .highlight .nn { color: #080808 } /* Name.Namespace */ +html[data-theme="light"] .highlight .nx { color: #080808 } /* Name.Other */ +html[data-theme="light"] .highlight .py { color: #005b82 } /* Name.Property */ +html[data-theme="light"] .highlight .nt { color: #005b82 } /* Name.Tag */ +html[data-theme="light"] .highlight .nv { color: #a12236 } /* Name.Variable */ +html[data-theme="light"] .highlight .ow { color: #6730c5 } /* Operator.Word */ +html[data-theme="light"] .highlight .pm { color: #080808 } /* Punctuation.Marker */ +html[data-theme="light"] .highlight .w { color: #080808 } /* Text.Whitespace */ +html[data-theme="light"] .highlight .mb { color: #7f4707 } /* Literal.Number.Bin */ +html[data-theme="light"] .highlight .mf { color: #7f4707 } /* Literal.Number.Float */ +html[data-theme="light"] .highlight .mh { color: #7f4707 } /* Literal.Number.Hex */ +html[data-theme="light"] .highlight .mi { color: #7f4707 } /* Literal.Number.Integer */ +html[data-theme="light"] .highlight .mo { color: #7f4707 } /* Literal.Number.Oct */ +html[data-theme="light"] .highlight .sa { color: #00622f } /* Literal.String.Affix */ +html[data-theme="light"] .highlight .sb { color: #00622f } /* Literal.String.Backtick */ +html[data-theme="light"] .highlight .sc { color: #00622f } /* Literal.String.Char */ +html[data-theme="light"] .highlight .dl { color: #00622f } /* Literal.String.Delimiter */ +html[data-theme="light"] .highlight .sd { color: #00622f } /* Literal.String.Doc */ +html[data-theme="light"] .highlight .s2 { color: #00622f } /* Literal.String.Double */ +html[data-theme="light"] .highlight .se { color: #00622f } /* Literal.String.Escape */ +html[data-theme="light"] .highlight .sh { color: #00622f } /* Literal.String.Heredoc */ +html[data-theme="light"] .highlight .si { color: #00622f } /* Literal.String.Interpol */ +html[data-theme="light"] .highlight .sx { color: #00622f } /* Literal.String.Other */ +html[data-theme="light"] .highlight .sr { color: #a12236 } /* Literal.String.Regex */ +html[data-theme="light"] .highlight .s1 { color: #00622f } /* Literal.String.Single */ +html[data-theme="light"] .highlight .ss { color: #005b82 } /* Literal.String.Symbol */ +html[data-theme="light"] .highlight .bp { color: #7f4707 } /* Name.Builtin.Pseudo */ +html[data-theme="light"] .highlight .fm { color: #005b82 } /* Name.Function.Magic */ +html[data-theme="light"] .highlight .vc { color: #a12236 } /* Name.Variable.Class */ +html[data-theme="light"] .highlight .vg { color: #a12236 } /* Name.Variable.Global */ +html[data-theme="light"] .highlight .vi { color: #a12236 } /* Name.Variable.Instance */ +html[data-theme="light"] .highlight .vm { color: #7f4707 } /* Name.Variable.Magic */ +html[data-theme="light"] .highlight .il { color: #7f4707 } /* Literal.Number.Integer.Long */ +html[data-theme="dark"] .highlight pre { line-height: 125%; } +html[data-theme="dark"] .highlight td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +html[data-theme="dark"] .highlight span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +html[data-theme="dark"] .highlight td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +html[data-theme="dark"] .highlight span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +html[data-theme="dark"] .highlight .hll { background-color: #ffd9002e } +html[data-theme="dark"] .highlight { background: #2b2b2b; color: #f8f8f2 } +html[data-theme="dark"] .highlight .c { color: #ffd900 } /* Comment */ +html[data-theme="dark"] .highlight .err { color: #ffa07a } /* Error */ +html[data-theme="dark"] .highlight .k { color: #dcc6e0 } /* Keyword */ +html[data-theme="dark"] .highlight .l { color: #ffd900 } /* Literal */ +html[data-theme="dark"] .highlight .n { color: #f8f8f2 } /* Name */ +html[data-theme="dark"] .highlight .o { color: #abe338 } /* Operator */ +html[data-theme="dark"] .highlight .p { color: #f8f8f2 } /* Punctuation */ +html[data-theme="dark"] .highlight .ch { color: #ffd900 } /* Comment.Hashbang */ +html[data-theme="dark"] .highlight .cm { color: #ffd900 } /* Comment.Multiline */ +html[data-theme="dark"] .highlight .cp { color: #ffd900 } /* Comment.Preproc */ +html[data-theme="dark"] .highlight .cpf { color: #ffd900 } /* Comment.PreprocFile */ +html[data-theme="dark"] .highlight .c1 { color: #ffd900 } /* Comment.Single */ +html[data-theme="dark"] .highlight .cs { color: #ffd900 } /* Comment.Special */ +html[data-theme="dark"] .highlight .gd { color: #00e0e0 } /* Generic.Deleted */ +html[data-theme="dark"] .highlight .ge { font-style: italic } /* Generic.Emph */ +html[data-theme="dark"] .highlight .gh { color: #00e0e0 } /* Generic.Heading */ +html[data-theme="dark"] .highlight .gs { font-weight: bold } /* Generic.Strong */ +html[data-theme="dark"] .highlight .gu { color: #00e0e0 } /* Generic.Subheading */ +html[data-theme="dark"] .highlight .kc { color: #dcc6e0 } /* Keyword.Constant */ +html[data-theme="dark"] .highlight .kd { color: #dcc6e0 } /* Keyword.Declaration */ +html[data-theme="dark"] .highlight .kn { color: #dcc6e0 } /* Keyword.Namespace */ +html[data-theme="dark"] .highlight .kp { color: #dcc6e0 } /* Keyword.Pseudo */ +html[data-theme="dark"] .highlight .kr { color: #dcc6e0 } /* Keyword.Reserved */ +html[data-theme="dark"] .highlight .kt { color: #ffd900 } /* Keyword.Type */ +html[data-theme="dark"] .highlight .ld { color: #ffd900 } /* Literal.Date */ +html[data-theme="dark"] .highlight .m { color: #ffd900 } /* Literal.Number */ +html[data-theme="dark"] .highlight .s { color: #abe338 } /* Literal.String */ +html[data-theme="dark"] .highlight .na { color: #ffd900 } /* Name.Attribute */ +html[data-theme="dark"] .highlight .nb { color: #ffd900 } /* Name.Builtin */ +html[data-theme="dark"] .highlight .nc { color: #00e0e0 } /* Name.Class */ +html[data-theme="dark"] .highlight .no { color: #00e0e0 } /* Name.Constant */ +html[data-theme="dark"] .highlight .nd { color: #ffd900 } /* Name.Decorator */ +html[data-theme="dark"] .highlight .ni { color: #abe338 } /* Name.Entity */ +html[data-theme="dark"] .highlight .ne { color: #dcc6e0 } /* Name.Exception */ +html[data-theme="dark"] .highlight .nf { color: #00e0e0 } /* Name.Function */ +html[data-theme="dark"] .highlight .nl { color: #ffd900 } /* Name.Label */ +html[data-theme="dark"] .highlight .nn { color: #f8f8f2 } /* Name.Namespace */ +html[data-theme="dark"] .highlight .nx { color: #f8f8f2 } /* Name.Other */ +html[data-theme="dark"] .highlight .py { color: #00e0e0 } /* Name.Property */ +html[data-theme="dark"] .highlight .nt { color: #00e0e0 } /* Name.Tag */ +html[data-theme="dark"] .highlight .nv { color: #ffa07a } /* Name.Variable */ +html[data-theme="dark"] .highlight .ow { color: #dcc6e0 } /* Operator.Word */ +html[data-theme="dark"] .highlight .pm { color: #f8f8f2 } /* Punctuation.Marker */ +html[data-theme="dark"] .highlight .w { color: #f8f8f2 } /* Text.Whitespace */ +html[data-theme="dark"] .highlight .mb { color: #ffd900 } /* Literal.Number.Bin */ +html[data-theme="dark"] .highlight .mf { color: #ffd900 } /* Literal.Number.Float */ +html[data-theme="dark"] .highlight .mh { color: #ffd900 } /* Literal.Number.Hex */ +html[data-theme="dark"] .highlight .mi { color: #ffd900 } /* Literal.Number.Integer */ +html[data-theme="dark"] .highlight .mo { color: #ffd900 } /* Literal.Number.Oct */ +html[data-theme="dark"] .highlight .sa { color: #abe338 } /* Literal.String.Affix */ +html[data-theme="dark"] .highlight .sb { color: #abe338 } /* Literal.String.Backtick */ +html[data-theme="dark"] .highlight .sc { color: #abe338 } /* Literal.String.Char */ +html[data-theme="dark"] .highlight .dl { color: #abe338 } /* Literal.String.Delimiter */ +html[data-theme="dark"] .highlight .sd { color: #abe338 } /* Literal.String.Doc */ +html[data-theme="dark"] .highlight .s2 { color: #abe338 } /* Literal.String.Double */ +html[data-theme="dark"] .highlight .se { color: #abe338 } /* Literal.String.Escape */ +html[data-theme="dark"] .highlight .sh { color: #abe338 } /* Literal.String.Heredoc */ +html[data-theme="dark"] .highlight .si { color: #abe338 } /* Literal.String.Interpol */ +html[data-theme="dark"] .highlight .sx { color: #abe338 } /* Literal.String.Other */ +html[data-theme="dark"] .highlight .sr { color: #ffa07a } /* Literal.String.Regex */ +html[data-theme="dark"] .highlight .s1 { color: #abe338 } /* Literal.String.Single */ +html[data-theme="dark"] .highlight .ss { color: #00e0e0 } /* Literal.String.Symbol */ +html[data-theme="dark"] .highlight .bp { color: #ffd900 } /* Name.Builtin.Pseudo */ +html[data-theme="dark"] .highlight .fm { color: #00e0e0 } /* Name.Function.Magic */ +html[data-theme="dark"] .highlight .vc { color: #ffa07a } /* Name.Variable.Class */ +html[data-theme="dark"] .highlight .vg { color: #ffa07a } /* Name.Variable.Global */ +html[data-theme="dark"] .highlight .vi { color: #ffa07a } /* Name.Variable.Instance */ +html[data-theme="dark"] .highlight .vm { color: #ffd900 } /* Name.Variable.Magic */ +html[data-theme="dark"] .highlight .il { color: #ffd900 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/docs/_build/html/_static/result/adf_multikeys.txt b/docs/_build/html/_static/result/adf_multikeys.txt new file mode 100644 index 00000000..1b2d86ad --- /dev/null +++ b/docs/_build/html/_static/result/adf_multikeys.txt @@ -0,0 +1,88 @@ +files.root +files.out +files.log +files.err +files.adf.rkf +files.ams.rkf +engine +input.Task +input.properties.NormalModes +input.system.atoms +input.system.bondorders +input.adf.basis.Type +input.adf.basis.Core +input.adf.xc.GGA +input.adf.NumericalQuality +job_id +ams_version.full +ams_version.major +ams_version.minor +ams_version.micro +ams_version.date +timing.cpu +timing.sys +timing.total +status.fatal +status.name +status.code +status.reasons +is_multijob +molecule.number_of_atoms +molecule.atom_numbers +molecule.atom_symbols +molecule.atom_masses +molecule.input +molecule.output +molecule.frag_indices +molecule.mol_charge +history.number_of_entries +history.coords +history.energy +history.gradients +history.maxgrad +history.rmsgrad +history.maxstep +history.rmsstep +history.molecule +pes +adf.task +adf.relativistic +adf.relativistic_type +adf.unrestricted_mos +adf.unrestricted_sfos +adf.symmetry.group +adf.symmetry.labels +adf.used_regions +adf.charge +adf.spin_polarization +adf.multiplicity +properties.energy.bond +properties.energy.elstat.total +properties.energy.orbint.total +properties.energy.orbint.correction +properties.energy.orbint.AA +properties.energy.orbint.AAA +properties.energy.pauli.total +properties.energy.dispersion +properties.energy.gibbs +properties.energy.enthalpy +properties.energy.nuclear_internal +properties.vibrations.number_of_modes +properties.vibrations.frequencies +properties.vibrations.intensities +properties.vibrations.number_of_imag_modes +properties.vibrations.character +properties.vibrations.modes +properties.vdd.charges +properties.s2_expected +properties.s2 +properties.spin_contamination +level.xc.functional +level.xc.category +level.xc.dispersion +level.xc.empirical_scaling +level.xc.summary +level.basis.type +level.basis.core +level.quality +level.summary \ No newline at end of file diff --git a/docs/_build/html/_static/scripts/bootstrap.js b/docs/_build/html/_static/scripts/bootstrap.js new file mode 100644 index 00000000..c8178deb --- /dev/null +++ b/docs/_build/html/_static/scripts/bootstrap.js @@ -0,0 +1,3 @@ +/*! For license information please see bootstrap.js.LICENSE.txt */ +(()=>{"use strict";var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{afterMain:()=>E,afterRead:()=>v,afterWrite:()=>C,applyStyles:()=>$,arrow:()=>J,auto:()=>a,basePlacements:()=>l,beforeMain:()=>y,beforeRead:()=>_,beforeWrite:()=>A,bottom:()=>s,clippingParents:()=>d,computeStyles:()=>it,createPopper:()=>Dt,createPopperBase:()=>St,createPopperLite:()=>$t,detectOverflow:()=>_t,end:()=>h,eventListeners:()=>st,flip:()=>bt,hide:()=>wt,left:()=>r,main:()=>w,modifierPhases:()=>O,offset:()=>Et,placements:()=>g,popper:()=>f,popperGenerator:()=>Lt,popperOffsets:()=>At,preventOverflow:()=>Tt,read:()=>b,reference:()=>p,right:()=>o,start:()=>c,top:()=>n,variationPlacements:()=>m,viewport:()=>u,write:()=>T});var i={};t.r(i),t.d(i,{Alert:()=>Oe,Button:()=>ke,Carousel:()=>li,Collapse:()=>Ei,Dropdown:()=>Ki,Modal:()=>Ln,Offcanvas:()=>Kn,Popover:()=>bs,ScrollSpy:()=>Ls,Tab:()=>Js,Toast:()=>po,Tooltip:()=>fs});var n="top",s="bottom",o="right",r="left",a="auto",l=[n,s,o,r],c="start",h="end",d="clippingParents",u="viewport",f="popper",p="reference",m=l.reduce((function(t,e){return t.concat([e+"-"+c,e+"-"+h])}),[]),g=[].concat(l,[a]).reduce((function(t,e){return t.concat([e,e+"-"+c,e+"-"+h])}),[]),_="beforeRead",b="read",v="afterRead",y="beforeMain",w="main",E="afterMain",A="beforeWrite",T="write",C="afterWrite",O=[_,b,v,y,w,E,A,T,C];function x(t){return t?(t.nodeName||"").toLowerCase():null}function k(t){if(null==t)return window;if("[object Window]"!==t.toString()){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function L(t){return t instanceof k(t).Element||t instanceof Element}function S(t){return t instanceof k(t).HTMLElement||t instanceof HTMLElement}function D(t){return"undefined"!=typeof ShadowRoot&&(t instanceof k(t).ShadowRoot||t instanceof ShadowRoot)}const $={name:"applyStyles",enabled:!0,phase:"write",fn:function(t){var e=t.state;Object.keys(e.elements).forEach((function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];S(s)&&x(s)&&(Object.assign(s.style,i),Object.keys(n).forEach((function(t){var e=n[t];!1===e?s.removeAttribute(t):s.setAttribute(t,!0===e?"":e)})))}))},effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow),function(){Object.keys(e.elements).forEach((function(t){var n=e.elements[t],s=e.attributes[t]||{},o=Object.keys(e.styles.hasOwnProperty(t)?e.styles[t]:i[t]).reduce((function(t,e){return t[e]="",t}),{});S(n)&&x(n)&&(Object.assign(n.style,o),Object.keys(s).forEach((function(t){n.removeAttribute(t)})))}))}},requires:["computeStyles"]};function I(t){return t.split("-")[0]}var N=Math.max,P=Math.min,M=Math.round;function j(){var t=navigator.userAgentData;return null!=t&&t.brands&&Array.isArray(t.brands)?t.brands.map((function(t){return t.brand+"/"+t.version})).join(" "):navigator.userAgent}function F(){return!/^((?!chrome|android).)*safari/i.test(j())}function H(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=t.getBoundingClientRect(),s=1,o=1;e&&S(t)&&(s=t.offsetWidth>0&&M(n.width)/t.offsetWidth||1,o=t.offsetHeight>0&&M(n.height)/t.offsetHeight||1);var r=(L(t)?k(t):window).visualViewport,a=!F()&&i,l=(n.left+(a&&r?r.offsetLeft:0))/s,c=(n.top+(a&&r?r.offsetTop:0))/o,h=n.width/s,d=n.height/o;return{width:h,height:d,top:c,right:l+h,bottom:c+d,left:l,x:l,y:c}}function B(t){var e=H(t),i=t.offsetWidth,n=t.offsetHeight;return Math.abs(e.width-i)<=1&&(i=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:t.offsetLeft,y:t.offsetTop,width:i,height:n}}function W(t,e){var i=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(i&&D(i)){var n=e;do{if(n&&t.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function z(t){return k(t).getComputedStyle(t)}function R(t){return["table","td","th"].indexOf(x(t))>=0}function q(t){return((L(t)?t.ownerDocument:t.document)||window.document).documentElement}function V(t){return"html"===x(t)?t:t.assignedSlot||t.parentNode||(D(t)?t.host:null)||q(t)}function Y(t){return S(t)&&"fixed"!==z(t).position?t.offsetParent:null}function K(t){for(var e=k(t),i=Y(t);i&&R(i)&&"static"===z(i).position;)i=Y(i);return i&&("html"===x(i)||"body"===x(i)&&"static"===z(i).position)?e:i||function(t){var e=/firefox/i.test(j());if(/Trident/i.test(j())&&S(t)&&"fixed"===z(t).position)return null;var i=V(t);for(D(i)&&(i=i.host);S(i)&&["html","body"].indexOf(x(i))<0;){var n=z(i);if("none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||-1!==["transform","perspective"].indexOf(n.willChange)||e&&"filter"===n.willChange||e&&n.filter&&"none"!==n.filter)return i;i=i.parentNode}return null}(t)||e}function Q(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}function X(t,e,i){return N(t,P(e,i))}function U(t){return Object.assign({},{top:0,right:0,bottom:0,left:0},t)}function G(t,e){return e.reduce((function(e,i){return e[i]=t,e}),{})}const J={name:"arrow",enabled:!0,phase:"main",fn:function(t){var e,i=t.state,a=t.name,c=t.options,h=i.elements.arrow,d=i.modifiersData.popperOffsets,u=I(i.placement),f=Q(u),p=[r,o].indexOf(u)>=0?"height":"width";if(h&&d){var m=function(t,e){return U("number"!=typeof(t="function"==typeof t?t(Object.assign({},e.rects,{placement:e.placement})):t)?t:G(t,l))}(c.padding,i),g=B(h),_="y"===f?n:r,b="y"===f?s:o,v=i.rects.reference[p]+i.rects.reference[f]-d[f]-i.rects.popper[p],y=d[f]-i.rects.reference[f],w=K(h),E=w?"y"===f?w.clientHeight||0:w.clientWidth||0:0,A=v/2-y/2,T=m[_],C=E-g[p]-m[b],O=E/2-g[p]/2+A,x=X(T,O,C),k=f;i.modifiersData[a]=((e={})[k]=x,e.centerOffset=x-O,e)}},effect:function(t){var e=t.state,i=t.options.element,n=void 0===i?"[data-popper-arrow]":i;null!=n&&("string"!=typeof n||(n=e.elements.popper.querySelector(n)))&&W(e.elements.popper,n)&&(e.elements.arrow=n)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Z(t){return t.split("-")[1]}var tt={top:"auto",right:"auto",bottom:"auto",left:"auto"};function et(t){var e,i=t.popper,a=t.popperRect,l=t.placement,c=t.variation,d=t.offsets,u=t.position,f=t.gpuAcceleration,p=t.adaptive,m=t.roundOffsets,g=t.isFixed,_=d.x,b=void 0===_?0:_,v=d.y,y=void 0===v?0:v,w="function"==typeof m?m({x:b,y}):{x:b,y};b=w.x,y=w.y;var E=d.hasOwnProperty("x"),A=d.hasOwnProperty("y"),T=r,C=n,O=window;if(p){var x=K(i),L="clientHeight",S="clientWidth";x===k(i)&&"static"!==z(x=q(i)).position&&"absolute"===u&&(L="scrollHeight",S="scrollWidth"),(l===n||(l===r||l===o)&&c===h)&&(C=s,y-=(g&&x===O&&O.visualViewport?O.visualViewport.height:x[L])-a.height,y*=f?1:-1),l!==r&&(l!==n&&l!==s||c!==h)||(T=o,b-=(g&&x===O&&O.visualViewport?O.visualViewport.width:x[S])-a.width,b*=f?1:-1)}var D,$=Object.assign({position:u},p&&tt),I=!0===m?function(t,e){var i=t.x,n=t.y,s=e.devicePixelRatio||1;return{x:M(i*s)/s||0,y:M(n*s)/s||0}}({x:b,y},k(i)):{x:b,y};return b=I.x,y=I.y,f?Object.assign({},$,((D={})[C]=A?"0":"",D[T]=E?"0":"",D.transform=(O.devicePixelRatio||1)<=1?"translate("+b+"px, "+y+"px)":"translate3d("+b+"px, "+y+"px, 0)",D)):Object.assign({},$,((e={})[C]=A?y+"px":"",e[T]=E?b+"px":"",e.transform="",e))}const it={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(t){var e=t.state,i=t.options,n=i.gpuAcceleration,s=void 0===n||n,o=i.adaptive,r=void 0===o||o,a=i.roundOffsets,l=void 0===a||a,c={placement:I(e.placement),variation:Z(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s,isFixed:"fixed"===e.options.strategy};null!=e.modifiersData.popperOffsets&&(e.styles.popper=Object.assign({},e.styles.popper,et(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:r,roundOffsets:l})))),null!=e.modifiersData.arrow&&(e.styles.arrow=Object.assign({},e.styles.arrow,et(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})},data:{}};var nt={passive:!0};const st={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(t){var e=t.state,i=t.instance,n=t.options,s=n.scroll,o=void 0===s||s,r=n.resize,a=void 0===r||r,l=k(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach((function(t){t.addEventListener("scroll",i.update,nt)})),a&&l.addEventListener("resize",i.update,nt),function(){o&&c.forEach((function(t){t.removeEventListener("scroll",i.update,nt)})),a&&l.removeEventListener("resize",i.update,nt)}},data:{}};var ot={left:"right",right:"left",bottom:"top",top:"bottom"};function rt(t){return t.replace(/left|right|bottom|top/g,(function(t){return ot[t]}))}var at={start:"end",end:"start"};function lt(t){return t.replace(/start|end/g,(function(t){return at[t]}))}function ct(t){var e=k(t);return{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function ht(t){return H(q(t)).left+ct(t).scrollLeft}function dt(t){var e=z(t),i=e.overflow,n=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(i+s+n)}function ut(t){return["html","body","#document"].indexOf(x(t))>=0?t.ownerDocument.body:S(t)&&dt(t)?t:ut(V(t))}function ft(t,e){var i;void 0===e&&(e=[]);var n=ut(t),s=n===(null==(i=t.ownerDocument)?void 0:i.body),o=k(n),r=s?[o].concat(o.visualViewport||[],dt(n)?n:[]):n,a=e.concat(r);return s?a:a.concat(ft(V(r)))}function pt(t){return Object.assign({},t,{left:t.x,top:t.y,right:t.x+t.width,bottom:t.y+t.height})}function mt(t,e,i){return e===u?pt(function(t,e){var i=k(t),n=q(t),s=i.visualViewport,o=n.clientWidth,r=n.clientHeight,a=0,l=0;if(s){o=s.width,r=s.height;var c=F();(c||!c&&"fixed"===e)&&(a=s.offsetLeft,l=s.offsetTop)}return{width:o,height:r,x:a+ht(t),y:l}}(t,i)):L(e)?function(t,e){var i=H(t,!1,"fixed"===e);return i.top=i.top+t.clientTop,i.left=i.left+t.clientLeft,i.bottom=i.top+t.clientHeight,i.right=i.left+t.clientWidth,i.width=t.clientWidth,i.height=t.clientHeight,i.x=i.left,i.y=i.top,i}(e,i):pt(function(t){var e,i=q(t),n=ct(t),s=null==(e=t.ownerDocument)?void 0:e.body,o=N(i.scrollWidth,i.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),r=N(i.scrollHeight,i.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-n.scrollLeft+ht(t),l=-n.scrollTop;return"rtl"===z(s||i).direction&&(a+=N(i.clientWidth,s?s.clientWidth:0)-o),{width:o,height:r,x:a,y:l}}(q(t)))}function gt(t){var e,i=t.reference,a=t.element,l=t.placement,d=l?I(l):null,u=l?Z(l):null,f=i.x+i.width/2-a.width/2,p=i.y+i.height/2-a.height/2;switch(d){case n:e={x:f,y:i.y-a.height};break;case s:e={x:f,y:i.y+i.height};break;case o:e={x:i.x+i.width,y:p};break;case r:e={x:i.x-a.width,y:p};break;default:e={x:i.x,y:i.y}}var m=d?Q(d):null;if(null!=m){var g="y"===m?"height":"width";switch(u){case c:e[m]=e[m]-(i[g]/2-a[g]/2);break;case h:e[m]=e[m]+(i[g]/2-a[g]/2)}}return e}function _t(t,e){void 0===e&&(e={});var i=e,r=i.placement,a=void 0===r?t.placement:r,c=i.strategy,h=void 0===c?t.strategy:c,m=i.boundary,g=void 0===m?d:m,_=i.rootBoundary,b=void 0===_?u:_,v=i.elementContext,y=void 0===v?f:v,w=i.altBoundary,E=void 0!==w&&w,A=i.padding,T=void 0===A?0:A,C=U("number"!=typeof T?T:G(T,l)),O=y===f?p:f,k=t.rects.popper,D=t.elements[E?O:y],$=function(t,e,i,n){var s="clippingParents"===e?function(t){var e=ft(V(t)),i=["absolute","fixed"].indexOf(z(t).position)>=0&&S(t)?K(t):t;return L(i)?e.filter((function(t){return L(t)&&W(t,i)&&"body"!==x(t)})):[]}(t):[].concat(e),o=[].concat(s,[i]),r=o[0],a=o.reduce((function(e,i){var s=mt(t,i,n);return e.top=N(s.top,e.top),e.right=P(s.right,e.right),e.bottom=P(s.bottom,e.bottom),e.left=N(s.left,e.left),e}),mt(t,r,n));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}(L(D)?D:D.contextElement||q(t.elements.popper),g,b,h),I=H(t.elements.reference),M=gt({reference:I,element:k,strategy:"absolute",placement:a}),j=pt(Object.assign({},k,M)),F=y===f?j:I,B={top:$.top-F.top+C.top,bottom:F.bottom-$.bottom+C.bottom,left:$.left-F.left+C.left,right:F.right-$.right+C.right},R=t.modifiersData.offset;if(y===f&&R){var Y=R[a];Object.keys(B).forEach((function(t){var e=[o,s].indexOf(t)>=0?1:-1,i=[n,s].indexOf(t)>=0?"y":"x";B[t]+=Y[i]*e}))}return B}const bt={name:"flip",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,h=t.name;if(!e.modifiersData[h]._skip){for(var d=i.mainAxis,u=void 0===d||d,f=i.altAxis,p=void 0===f||f,_=i.fallbackPlacements,b=i.padding,v=i.boundary,y=i.rootBoundary,w=i.altBoundary,E=i.flipVariations,A=void 0===E||E,T=i.allowedAutoPlacements,C=e.options.placement,O=I(C),x=_||(O!==C&&A?function(t){if(I(t)===a)return[];var e=rt(t);return[lt(t),e,lt(e)]}(C):[rt(C)]),k=[C].concat(x).reduce((function(t,i){return t.concat(I(i)===a?function(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=i.boundary,o=i.rootBoundary,r=i.padding,a=i.flipVariations,c=i.allowedAutoPlacements,h=void 0===c?g:c,d=Z(n),u=d?a?m:m.filter((function(t){return Z(t)===d})):l,f=u.filter((function(t){return h.indexOf(t)>=0}));0===f.length&&(f=u);var p=f.reduce((function(e,i){return e[i]=_t(t,{placement:i,boundary:s,rootBoundary:o,padding:r})[I(i)],e}),{});return Object.keys(p).sort((function(t,e){return p[t]-p[e]}))}(e,{placement:i,boundary:v,rootBoundary:y,padding:b,flipVariations:A,allowedAutoPlacements:T}):i)}),[]),L=e.rects.reference,S=e.rects.popper,D=new Map,$=!0,N=k[0],P=0;P=0,B=H?"width":"height",W=_t(e,{placement:M,boundary:v,rootBoundary:y,altBoundary:w,padding:b}),z=H?F?o:r:F?s:n;L[B]>S[B]&&(z=rt(z));var R=rt(z),q=[];if(u&&q.push(W[j]<=0),p&&q.push(W[z]<=0,W[R]<=0),q.every((function(t){return t}))){N=M,$=!1;break}D.set(M,q)}if($)for(var V=function(t){var e=k.find((function(e){var i=D.get(e);if(i)return i.slice(0,t).every((function(t){return t}))}));if(e)return N=e,"break"},Y=A?3:1;Y>0&&"break"!==V(Y);Y--);e.placement!==N&&(e.modifiersData[h]._skip=!0,e.placement=N,e.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function vt(t,e,i){return void 0===i&&(i={x:0,y:0}),{top:t.top-e.height-i.y,right:t.right-e.width+i.x,bottom:t.bottom-e.height+i.y,left:t.left-e.width-i.x}}function yt(t){return[n,o,s,r].some((function(e){return t[e]>=0}))}const wt={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(t){var e=t.state,i=t.name,n=e.rects.reference,s=e.rects.popper,o=e.modifiersData.preventOverflow,r=_t(e,{elementContext:"reference"}),a=_t(e,{altBoundary:!0}),l=vt(r,n),c=vt(a,s,o),h=yt(l),d=yt(c);e.modifiersData[i]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:h,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":h,"data-popper-escaped":d})}},Et={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(t){var e=t.state,i=t.options,s=t.name,a=i.offset,l=void 0===a?[0,0]:a,c=g.reduce((function(t,i){return t[i]=function(t,e,i){var s=I(t),a=[r,n].indexOf(s)>=0?-1:1,l="function"==typeof i?i(Object.assign({},e,{placement:t})):i,c=l[0],h=l[1];return c=c||0,h=(h||0)*a,[r,o].indexOf(s)>=0?{x:h,y:c}:{x:c,y:h}}(i,e.rects,l),t}),{}),h=c[e.placement],d=h.x,u=h.y;null!=e.modifiersData.popperOffsets&&(e.modifiersData.popperOffsets.x+=d,e.modifiersData.popperOffsets.y+=u),e.modifiersData[s]=c}},At={name:"popperOffsets",enabled:!0,phase:"read",fn:function(t){var e=t.state,i=t.name;e.modifiersData[i]=gt({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})},data:{}},Tt={name:"preventOverflow",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,a=t.name,l=i.mainAxis,h=void 0===l||l,d=i.altAxis,u=void 0!==d&&d,f=i.boundary,p=i.rootBoundary,m=i.altBoundary,g=i.padding,_=i.tether,b=void 0===_||_,v=i.tetherOffset,y=void 0===v?0:v,w=_t(e,{boundary:f,rootBoundary:p,padding:g,altBoundary:m}),E=I(e.placement),A=Z(e.placement),T=!A,C=Q(E),O="x"===C?"y":"x",x=e.modifiersData.popperOffsets,k=e.rects.reference,L=e.rects.popper,S="function"==typeof y?y(Object.assign({},e.rects,{placement:e.placement})):y,D="number"==typeof S?{mainAxis:S,altAxis:S}:Object.assign({mainAxis:0,altAxis:0},S),$=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,M={x:0,y:0};if(x){if(h){var j,F="y"===C?n:r,H="y"===C?s:o,W="y"===C?"height":"width",z=x[C],R=z+w[F],q=z-w[H],V=b?-L[W]/2:0,Y=A===c?k[W]:L[W],U=A===c?-L[W]:-k[W],G=e.elements.arrow,J=b&&G?B(G):{width:0,height:0},tt=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},et=tt[F],it=tt[H],nt=X(0,k[W],J[W]),st=T?k[W]/2-V-nt-et-D.mainAxis:Y-nt-et-D.mainAxis,ot=T?-k[W]/2+V+nt+it+D.mainAxis:U+nt+it+D.mainAxis,rt=e.elements.arrow&&K(e.elements.arrow),at=rt?"y"===C?rt.clientTop||0:rt.clientLeft||0:0,lt=null!=(j=null==$?void 0:$[C])?j:0,ct=z+ot-lt,ht=X(b?P(R,z+st-lt-at):R,z,b?N(q,ct):q);x[C]=ht,M[C]=ht-z}if(u){var dt,ut="x"===C?n:r,ft="x"===C?s:o,pt=x[O],mt="y"===O?"height":"width",gt=pt+w[ut],bt=pt-w[ft],vt=-1!==[n,r].indexOf(E),yt=null!=(dt=null==$?void 0:$[O])?dt:0,wt=vt?gt:pt-k[mt]-L[mt]-yt+D.altAxis,Et=vt?pt+k[mt]+L[mt]-yt-D.altAxis:bt,At=b&&vt?function(t,e,i){var n=X(t,e,i);return n>i?i:n}(wt,pt,Et):X(b?wt:gt,pt,b?Et:bt);x[O]=At,M[O]=At-pt}e.modifiersData[a]=M}},requiresIfExists:["offset"]};function Ct(t,e,i){void 0===i&&(i=!1);var n,s,o=S(e),r=S(e)&&function(t){var e=t.getBoundingClientRect(),i=M(e.width)/t.offsetWidth||1,n=M(e.height)/t.offsetHeight||1;return 1!==i||1!==n}(e),a=q(e),l=H(t,r,i),c={scrollLeft:0,scrollTop:0},h={x:0,y:0};return(o||!o&&!i)&&(("body"!==x(e)||dt(a))&&(c=(n=e)!==k(n)&&S(n)?{scrollLeft:(s=n).scrollLeft,scrollTop:s.scrollTop}:ct(n)),S(e)?((h=H(e,!0)).x+=e.clientLeft,h.y+=e.clientTop):a&&(h.x=ht(a))),{x:l.left+c.scrollLeft-h.x,y:l.top+c.scrollTop-h.y,width:l.width,height:l.height}}function Ot(t){var e=new Map,i=new Set,n=[];function s(t){i.add(t.name),[].concat(t.requires||[],t.requiresIfExists||[]).forEach((function(t){if(!i.has(t)){var n=e.get(t);n&&s(n)}})),n.push(t)}return t.forEach((function(t){e.set(t.name,t)})),t.forEach((function(t){i.has(t.name)||s(t)})),n}var xt={placement:"bottom",modifiers:[],strategy:"absolute"};function kt(){for(var t=arguments.length,e=new Array(t),i=0;iIt.has(t)&&It.get(t).get(e)||null,remove(t,e){if(!It.has(t))return;const i=It.get(t);i.delete(e),0===i.size&&It.delete(t)}},Pt="transitionend",Mt=t=>(t&&window.CSS&&window.CSS.escape&&(t=t.replace(/#([^\s"#']+)/g,((t,e)=>`#${CSS.escape(e)}`))),t),jt=t=>{t.dispatchEvent(new Event(Pt))},Ft=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),Ht=t=>Ft(t)?t.jquery?t[0]:t:"string"==typeof t&&t.length>0?document.querySelector(Mt(t)):null,Bt=t=>{if(!Ft(t)||0===t.getClientRects().length)return!1;const e="visible"===getComputedStyle(t).getPropertyValue("visibility"),i=t.closest("details:not([open])");if(!i)return e;if(i!==t){const e=t.closest("summary");if(e&&e.parentNode!==i)return!1;if(null===e)return!1}return e},Wt=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),zt=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?zt(t.parentNode):null},Rt=()=>{},qt=t=>{t.offsetHeight},Vt=()=>window.jQuery&&!document.body.hasAttribute("data-bs-no-jquery")?window.jQuery:null,Yt=[],Kt=()=>"rtl"===document.documentElement.dir,Qt=t=>{var e;e=()=>{const e=Vt();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?(Yt.length||document.addEventListener("DOMContentLoaded",(()=>{for(const t of Yt)t()})),Yt.push(e)):e()},Xt=(t,e=[],i=t)=>"function"==typeof t?t(...e):i,Ut=(t,e,i=!0)=>{if(!i)return void Xt(t);const n=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let s=!1;const o=({target:i})=>{i===e&&(s=!0,e.removeEventListener(Pt,o),Xt(t))};e.addEventListener(Pt,o),setTimeout((()=>{s||jt(e)}),n)},Gt=(t,e,i,n)=>{const s=t.length;let o=t.indexOf(e);return-1===o?!i&&n?t[s-1]:t[0]:(o+=i?1:-1,n&&(o=(o+s)%s),t[Math.max(0,Math.min(o,s-1))])},Jt=/[^.]*(?=\..*)\.|.*/,Zt=/\..*/,te=/::\d+$/,ee={};let ie=1;const ne={mouseenter:"mouseover",mouseleave:"mouseout"},se=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function oe(t,e){return e&&`${e}::${ie++}`||t.uidEvent||ie++}function re(t){const e=oe(t);return t.uidEvent=e,ee[e]=ee[e]||{},ee[e]}function ae(t,e,i=null){return Object.values(t).find((t=>t.callable===e&&t.delegationSelector===i))}function le(t,e,i){const n="string"==typeof e,s=n?i:e||i;let o=ue(t);return se.has(o)||(o=t),[n,s,o]}function ce(t,e,i,n,s){if("string"!=typeof e||!t)return;let[o,r,a]=le(e,i,n);if(e in ne){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};r=t(r)}const l=re(t),c=l[a]||(l[a]={}),h=ae(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&s);const d=oe(r,e.replace(Jt,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(const a of o)if(a===r)return pe(s,{delegateTarget:r}),n.oneOff&&fe.off(t,s.type,e,i),i.apply(r,[s])}}(t,i,r):function(t,e){return function i(n){return pe(n,{delegateTarget:t}),i.oneOff&&fe.off(t,n.type,e),e.apply(t,[n])}}(t,r);u.delegationSelector=o?i:null,u.callable=r,u.oneOff=s,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function he(t,e,i,n,s){const o=ae(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function de(t,e,i,n){const s=e[i]||{};for(const[o,r]of Object.entries(s))o.includes(n)&&he(t,e,i,r.callable,r.delegationSelector)}function ue(t){return t=t.replace(Zt,""),ne[t]||t}const fe={on(t,e,i,n){ce(t,e,i,n,!1)},one(t,e,i,n){ce(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=le(e,i,n),a=r!==e,l=re(t),c=l[r]||{},h=e.startsWith(".");if(void 0===o){if(h)for(const i of Object.keys(l))de(t,l,i,e.slice(1));for(const[i,n]of Object.entries(c)){const s=i.replace(te,"");a&&!e.includes(s)||he(t,l,r,n.callable,n.delegationSelector)}}else{if(!Object.keys(c).length)return;he(t,l,r,o,s?i:null)}},trigger(t,e,i){if("string"!=typeof e||!t)return null;const n=Vt();let s=null,o=!0,r=!0,a=!1;e!==ue(e)&&n&&(s=n.Event(e,i),n(t).trigger(s),o=!s.isPropagationStopped(),r=!s.isImmediatePropagationStopped(),a=s.isDefaultPrevented());const l=pe(new Event(e,{bubbles:o,cancelable:!0}),i);return a&&l.preventDefault(),r&&t.dispatchEvent(l),l.defaultPrevented&&s&&s.preventDefault(),l}};function pe(t,e={}){for(const[i,n]of Object.entries(e))try{t[i]=n}catch(e){Object.defineProperty(t,i,{configurable:!0,get:()=>n})}return t}function me(t){if("true"===t)return!0;if("false"===t)return!1;if(t===Number(t).toString())return Number(t);if(""===t||"null"===t)return null;if("string"!=typeof t)return t;try{return JSON.parse(decodeURIComponent(t))}catch(e){return t}}function ge(t){return t.replace(/[A-Z]/g,(t=>`-${t.toLowerCase()}`))}const _e={setDataAttribute(t,e,i){t.setAttribute(`data-bs-${ge(e)}`,i)},removeDataAttribute(t,e){t.removeAttribute(`data-bs-${ge(e)}`)},getDataAttributes(t){if(!t)return{};const e={},i=Object.keys(t.dataset).filter((t=>t.startsWith("bs")&&!t.startsWith("bsConfig")));for(const n of i){let i=n.replace(/^bs/,"");i=i.charAt(0).toLowerCase()+i.slice(1,i.length),e[i]=me(t.dataset[n])}return e},getDataAttribute:(t,e)=>me(t.getAttribute(`data-bs-${ge(e)}`))};class be{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}_getConfig(t){return t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t}_mergeConfigObj(t,e){const i=Ft(e)?_e.getDataAttribute(e,"config"):{};return{...this.constructor.Default,..."object"==typeof i?i:{},...Ft(e)?_e.getDataAttributes(e):{},..."object"==typeof t?t:{}}}_typeCheckConfig(t,e=this.constructor.DefaultType){for(const[n,s]of Object.entries(e)){const e=t[n],o=Ft(e)?"element":null==(i=e)?`${i}`:Object.prototype.toString.call(i).match(/\s([a-z]+)/i)[1].toLowerCase();if(!new RegExp(s).test(o))throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${n}" provided type "${o}" but expected type "${s}".`)}var i}}class ve extends be{constructor(t,e){super(),(t=Ht(t))&&(this._element=t,this._config=this._getConfig(e),Nt.set(this._element,this.constructor.DATA_KEY,this))}dispose(){Nt.remove(this._element,this.constructor.DATA_KEY),fe.off(this._element,this.constructor.EVENT_KEY);for(const t of Object.getOwnPropertyNames(this))this[t]=null}_queueCallback(t,e,i=!0){Ut(t,e,i)}_getConfig(t){return t=this._mergeConfigObj(t,this._element),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}static getInstance(t){return Nt.get(Ht(t),this.DATA_KEY)}static getOrCreateInstance(t,e={}){return this.getInstance(t)||new this(t,"object"==typeof e?e:null)}static get VERSION(){return"5.3.3"}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(t){return`${t}${this.EVENT_KEY}`}}const ye=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i=`#${i.split("#")[1]}`),e=i&&"#"!==i?i.trim():null}return e?e.split(",").map((t=>Mt(t))).join(","):null},we={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter((t=>t.matches(e))),parents(t,e){const i=[];let n=t.parentNode.closest(e);for(;n;)i.push(n),n=n.parentNode.closest(e);return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]},focusableChildren(t){const e=["a","button","input","textarea","select","details","[tabindex]",'[contenteditable="true"]'].map((t=>`${t}:not([tabindex^="-"])`)).join(",");return this.find(e,t).filter((t=>!Wt(t)&&Bt(t)))},getSelectorFromElement(t){const e=ye(t);return e&&we.findOne(e)?e:null},getElementFromSelector(t){const e=ye(t);return e?we.findOne(e):null},getMultipleElementsFromSelector(t){const e=ye(t);return e?we.find(e):[]}},Ee=(t,e="hide")=>{const i=`click.dismiss${t.EVENT_KEY}`,n=t.NAME;fe.on(document,i,`[data-bs-dismiss="${n}"]`,(function(i){if(["A","AREA"].includes(this.tagName)&&i.preventDefault(),Wt(this))return;const s=we.getElementFromSelector(this)||this.closest(`.${n}`);t.getOrCreateInstance(s)[e]()}))},Ae=".bs.alert",Te=`close${Ae}`,Ce=`closed${Ae}`;class Oe extends ve{static get NAME(){return"alert"}close(){if(fe.trigger(this._element,Te).defaultPrevented)return;this._element.classList.remove("show");const t=this._element.classList.contains("fade");this._queueCallback((()=>this._destroyElement()),this._element,t)}_destroyElement(){this._element.remove(),fe.trigger(this._element,Ce),this.dispose()}static jQueryInterface(t){return this.each((function(){const e=Oe.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}Ee(Oe,"close"),Qt(Oe);const xe='[data-bs-toggle="button"]';class ke extends ve{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){const e=ke.getOrCreateInstance(this);"toggle"===t&&e[t]()}))}}fe.on(document,"click.bs.button.data-api",xe,(t=>{t.preventDefault();const e=t.target.closest(xe);ke.getOrCreateInstance(e).toggle()})),Qt(ke);const Le=".bs.swipe",Se=`touchstart${Le}`,De=`touchmove${Le}`,$e=`touchend${Le}`,Ie=`pointerdown${Le}`,Ne=`pointerup${Le}`,Pe={endCallback:null,leftCallback:null,rightCallback:null},Me={endCallback:"(function|null)",leftCallback:"(function|null)",rightCallback:"(function|null)"};class je extends be{constructor(t,e){super(),this._element=t,t&&je.isSupported()&&(this._config=this._getConfig(e),this._deltaX=0,this._supportPointerEvents=Boolean(window.PointerEvent),this._initEvents())}static get Default(){return Pe}static get DefaultType(){return Me}static get NAME(){return"swipe"}dispose(){fe.off(this._element,Le)}_start(t){this._supportPointerEvents?this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX):this._deltaX=t.touches[0].clientX}_end(t){this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX-this._deltaX),this._handleSwipe(),Xt(this._config.endCallback)}_move(t){this._deltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this._deltaX}_handleSwipe(){const t=Math.abs(this._deltaX);if(t<=40)return;const e=t/this._deltaX;this._deltaX=0,e&&Xt(e>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?(fe.on(this._element,Ie,(t=>this._start(t))),fe.on(this._element,Ne,(t=>this._end(t))),this._element.classList.add("pointer-event")):(fe.on(this._element,Se,(t=>this._start(t))),fe.on(this._element,De,(t=>this._move(t))),fe.on(this._element,$e,(t=>this._end(t))))}_eventIsPointerPenTouch(t){return this._supportPointerEvents&&("pen"===t.pointerType||"touch"===t.pointerType)}static isSupported(){return"ontouchstart"in document.documentElement||navigator.maxTouchPoints>0}}const Fe=".bs.carousel",He=".data-api",Be="ArrowLeft",We="ArrowRight",ze="next",Re="prev",qe="left",Ve="right",Ye=`slide${Fe}`,Ke=`slid${Fe}`,Qe=`keydown${Fe}`,Xe=`mouseenter${Fe}`,Ue=`mouseleave${Fe}`,Ge=`dragstart${Fe}`,Je=`load${Fe}${He}`,Ze=`click${Fe}${He}`,ti="carousel",ei="active",ii=".active",ni=".carousel-item",si=ii+ni,oi={[Be]:Ve,[We]:qe},ri={interval:5e3,keyboard:!0,pause:"hover",ride:!1,touch:!0,wrap:!0},ai={interval:"(number|boolean)",keyboard:"boolean",pause:"(string|boolean)",ride:"(boolean|string)",touch:"boolean",wrap:"boolean"};class li extends ve{constructor(t,e){super(t,e),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=we.findOne(".carousel-indicators",this._element),this._addEventListeners(),this._config.ride===ti&&this.cycle()}static get Default(){return ri}static get DefaultType(){return ai}static get NAME(){return"carousel"}next(){this._slide(ze)}nextWhenVisible(){!document.hidden&&Bt(this._element)&&this.next()}prev(){this._slide(Re)}pause(){this._isSliding&&jt(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval((()=>this.nextWhenVisible()),this._config.interval)}_maybeEnableCycle(){this._config.ride&&(this._isSliding?fe.one(this._element,Ke,(()=>this.cycle())):this.cycle())}to(t){const e=this._getItems();if(t>e.length-1||t<0)return;if(this._isSliding)return void fe.one(this._element,Ke,(()=>this.to(t)));const i=this._getItemIndex(this._getActive());if(i===t)return;const n=t>i?ze:Re;this._slide(n,e[t])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(t){return t.defaultInterval=t.interval,t}_addEventListeners(){this._config.keyboard&&fe.on(this._element,Qe,(t=>this._keydown(t))),"hover"===this._config.pause&&(fe.on(this._element,Xe,(()=>this.pause())),fe.on(this._element,Ue,(()=>this._maybeEnableCycle()))),this._config.touch&&je.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(const t of we.find(".carousel-item img",this._element))fe.on(t,Ge,(t=>t.preventDefault()));const t={leftCallback:()=>this._slide(this._directionToOrder(qe)),rightCallback:()=>this._slide(this._directionToOrder(Ve)),endCallback:()=>{"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout((()=>this._maybeEnableCycle()),500+this._config.interval))}};this._swipeHelper=new je(this._element,t)}_keydown(t){if(/input|textarea/i.test(t.target.tagName))return;const e=oi[t.key];e&&(t.preventDefault(),this._slide(this._directionToOrder(e)))}_getItemIndex(t){return this._getItems().indexOf(t)}_setActiveIndicatorElement(t){if(!this._indicatorsElement)return;const e=we.findOne(ii,this._indicatorsElement);e.classList.remove(ei),e.removeAttribute("aria-current");const i=we.findOne(`[data-bs-slide-to="${t}"]`,this._indicatorsElement);i&&(i.classList.add(ei),i.setAttribute("aria-current","true"))}_updateInterval(){const t=this._activeElement||this._getActive();if(!t)return;const e=Number.parseInt(t.getAttribute("data-bs-interval"),10);this._config.interval=e||this._config.defaultInterval}_slide(t,e=null){if(this._isSliding)return;const i=this._getActive(),n=t===ze,s=e||Gt(this._getItems(),i,n,this._config.wrap);if(s===i)return;const o=this._getItemIndex(s),r=e=>fe.trigger(this._element,e,{relatedTarget:s,direction:this._orderToDirection(t),from:this._getItemIndex(i),to:o});if(r(Ye).defaultPrevented)return;if(!i||!s)return;const a=Boolean(this._interval);this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(o),this._activeElement=s;const l=n?"carousel-item-start":"carousel-item-end",c=n?"carousel-item-next":"carousel-item-prev";s.classList.add(c),qt(s),i.classList.add(l),s.classList.add(l),this._queueCallback((()=>{s.classList.remove(l,c),s.classList.add(ei),i.classList.remove(ei,c,l),this._isSliding=!1,r(Ke)}),i,this._isAnimated()),a&&this.cycle()}_isAnimated(){return this._element.classList.contains("slide")}_getActive(){return we.findOne(si,this._element)}_getItems(){return we.find(ni,this._element)}_clearInterval(){this._interval&&(clearInterval(this._interval),this._interval=null)}_directionToOrder(t){return Kt()?t===qe?Re:ze:t===qe?ze:Re}_orderToDirection(t){return Kt()?t===Re?qe:Ve:t===Re?Ve:qe}static jQueryInterface(t){return this.each((function(){const e=li.getOrCreateInstance(this,t);if("number"!=typeof t){if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}else e.to(t)}))}}fe.on(document,Ze,"[data-bs-slide], [data-bs-slide-to]",(function(t){const e=we.getElementFromSelector(this);if(!e||!e.classList.contains(ti))return;t.preventDefault();const i=li.getOrCreateInstance(e),n=this.getAttribute("data-bs-slide-to");return n?(i.to(n),void i._maybeEnableCycle()):"next"===_e.getDataAttribute(this,"slide")?(i.next(),void i._maybeEnableCycle()):(i.prev(),void i._maybeEnableCycle())})),fe.on(window,Je,(()=>{const t=we.find('[data-bs-ride="carousel"]');for(const e of t)li.getOrCreateInstance(e)})),Qt(li);const ci=".bs.collapse",hi=`show${ci}`,di=`shown${ci}`,ui=`hide${ci}`,fi=`hidden${ci}`,pi=`click${ci}.data-api`,mi="show",gi="collapse",_i="collapsing",bi=`:scope .${gi} .${gi}`,vi='[data-bs-toggle="collapse"]',yi={parent:null,toggle:!0},wi={parent:"(null|element)",toggle:"boolean"};class Ei extends ve{constructor(t,e){super(t,e),this._isTransitioning=!1,this._triggerArray=[];const i=we.find(vi);for(const t of i){const e=we.getSelectorFromElement(t),i=we.find(e).filter((t=>t===this._element));null!==e&&i.length&&this._triggerArray.push(t)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return yi}static get DefaultType(){return wi}static get NAME(){return"collapse"}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(".collapse.show, .collapse.collapsing").filter((t=>t!==this._element)).map((t=>Ei.getOrCreateInstance(t,{toggle:!1})))),t.length&&t[0]._isTransitioning)return;if(fe.trigger(this._element,hi).defaultPrevented)return;for(const e of t)e.hide();const e=this._getDimension();this._element.classList.remove(gi),this._element.classList.add(_i),this._element.style[e]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;const i=`scroll${e[0].toUpperCase()+e.slice(1)}`;this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(_i),this._element.classList.add(gi,mi),this._element.style[e]="",fe.trigger(this._element,di)}),this._element,!0),this._element.style[e]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown())return;if(fe.trigger(this._element,ui).defaultPrevented)return;const t=this._getDimension();this._element.style[t]=`${this._element.getBoundingClientRect()[t]}px`,qt(this._element),this._element.classList.add(_i),this._element.classList.remove(gi,mi);for(const t of this._triggerArray){const e=we.getElementFromSelector(t);e&&!this._isShown(e)&&this._addAriaAndCollapsedClass([t],!1)}this._isTransitioning=!0,this._element.style[t]="",this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(_i),this._element.classList.add(gi),fe.trigger(this._element,fi)}),this._element,!0)}_isShown(t=this._element){return t.classList.contains(mi)}_configAfterMerge(t){return t.toggle=Boolean(t.toggle),t.parent=Ht(t.parent),t}_getDimension(){return this._element.classList.contains("collapse-horizontal")?"width":"height"}_initializeChildren(){if(!this._config.parent)return;const t=this._getFirstLevelChildren(vi);for(const e of t){const t=we.getElementFromSelector(e);t&&this._addAriaAndCollapsedClass([e],this._isShown(t))}}_getFirstLevelChildren(t){const e=we.find(bi,this._config.parent);return we.find(t,this._config.parent).filter((t=>!e.includes(t)))}_addAriaAndCollapsedClass(t,e){if(t.length)for(const i of t)i.classList.toggle("collapsed",!e),i.setAttribute("aria-expanded",e)}static jQueryInterface(t){const e={};return"string"==typeof t&&/show|hide/.test(t)&&(e.toggle=!1),this.each((function(){const i=Ei.getOrCreateInstance(this,e);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t]()}}))}}fe.on(document,pi,vi,(function(t){("A"===t.target.tagName||t.delegateTarget&&"A"===t.delegateTarget.tagName)&&t.preventDefault();for(const t of we.getMultipleElementsFromSelector(this))Ei.getOrCreateInstance(t,{toggle:!1}).toggle()})),Qt(Ei);const Ai="dropdown",Ti=".bs.dropdown",Ci=".data-api",Oi="ArrowUp",xi="ArrowDown",ki=`hide${Ti}`,Li=`hidden${Ti}`,Si=`show${Ti}`,Di=`shown${Ti}`,$i=`click${Ti}${Ci}`,Ii=`keydown${Ti}${Ci}`,Ni=`keyup${Ti}${Ci}`,Pi="show",Mi='[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)',ji=`${Mi}.${Pi}`,Fi=".dropdown-menu",Hi=Kt()?"top-end":"top-start",Bi=Kt()?"top-start":"top-end",Wi=Kt()?"bottom-end":"bottom-start",zi=Kt()?"bottom-start":"bottom-end",Ri=Kt()?"left-start":"right-start",qi=Kt()?"right-start":"left-start",Vi={autoClose:!0,boundary:"clippingParents",display:"dynamic",offset:[0,2],popperConfig:null,reference:"toggle"},Yi={autoClose:"(boolean|string)",boundary:"(string|element)",display:"string",offset:"(array|string|function)",popperConfig:"(null|object|function)",reference:"(string|element|object)"};class Ki extends ve{constructor(t,e){super(t,e),this._popper=null,this._parent=this._element.parentNode,this._menu=we.next(this._element,Fi)[0]||we.prev(this._element,Fi)[0]||we.findOne(Fi,this._parent),this._inNavbar=this._detectNavbar()}static get Default(){return Vi}static get DefaultType(){return Yi}static get NAME(){return Ai}toggle(){return this._isShown()?this.hide():this.show()}show(){if(Wt(this._element)||this._isShown())return;const t={relatedTarget:this._element};if(!fe.trigger(this._element,Si,t).defaultPrevented){if(this._createPopper(),"ontouchstart"in document.documentElement&&!this._parent.closest(".navbar-nav"))for(const t of[].concat(...document.body.children))fe.on(t,"mouseover",Rt);this._element.focus(),this._element.setAttribute("aria-expanded",!0),this._menu.classList.add(Pi),this._element.classList.add(Pi),fe.trigger(this._element,Di,t)}}hide(){if(Wt(this._element)||!this._isShown())return;const t={relatedTarget:this._element};this._completeHide(t)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_completeHide(t){if(!fe.trigger(this._element,ki,t).defaultPrevented){if("ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))fe.off(t,"mouseover",Rt);this._popper&&this._popper.destroy(),this._menu.classList.remove(Pi),this._element.classList.remove(Pi),this._element.setAttribute("aria-expanded","false"),_e.removeDataAttribute(this._menu,"popper"),fe.trigger(this._element,Li,t)}}_getConfig(t){if("object"==typeof(t=super._getConfig(t)).reference&&!Ft(t.reference)&&"function"!=typeof t.reference.getBoundingClientRect)throw new TypeError(`${Ai.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);return t}_createPopper(){if(void 0===e)throw new TypeError("Bootstrap's dropdowns require Popper (https://popper.js.org)");let t=this._element;"parent"===this._config.reference?t=this._parent:Ft(this._config.reference)?t=Ht(this._config.reference):"object"==typeof this._config.reference&&(t=this._config.reference);const i=this._getPopperConfig();this._popper=Dt(t,this._menu,i)}_isShown(){return this._menu.classList.contains(Pi)}_getPlacement(){const t=this._parent;if(t.classList.contains("dropend"))return Ri;if(t.classList.contains("dropstart"))return qi;if(t.classList.contains("dropup-center"))return"top";if(t.classList.contains("dropdown-center"))return"bottom";const e="end"===getComputedStyle(this._menu).getPropertyValue("--bs-position").trim();return t.classList.contains("dropup")?e?Bi:Hi:e?zi:Wi}_detectNavbar(){return null!==this._element.closest(".navbar")}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return(this._inNavbar||"static"===this._config.display)&&(_e.setDataAttribute(this._menu,"popper","static"),t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,...Xt(this._config.popperConfig,[t])}}_selectMenuItem({key:t,target:e}){const i=we.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter((t=>Bt(t)));i.length&&Gt(i,e,t===xi,!i.includes(e)).focus()}static jQueryInterface(t){return this.each((function(){const e=Ki.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}static clearMenus(t){if(2===t.button||"keyup"===t.type&&"Tab"!==t.key)return;const e=we.find(ji);for(const i of e){const e=Ki.getInstance(i);if(!e||!1===e._config.autoClose)continue;const n=t.composedPath(),s=n.includes(e._menu);if(n.includes(e._element)||"inside"===e._config.autoClose&&!s||"outside"===e._config.autoClose&&s)continue;if(e._menu.contains(t.target)&&("keyup"===t.type&&"Tab"===t.key||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;const o={relatedTarget:e._element};"click"===t.type&&(o.clickEvent=t),e._completeHide(o)}}static dataApiKeydownHandler(t){const e=/input|textarea/i.test(t.target.tagName),i="Escape"===t.key,n=[Oi,xi].includes(t.key);if(!n&&!i)return;if(e&&!i)return;t.preventDefault();const s=this.matches(Mi)?this:we.prev(this,Mi)[0]||we.next(this,Mi)[0]||we.findOne(Mi,t.delegateTarget.parentNode),o=Ki.getOrCreateInstance(s);if(n)return t.stopPropagation(),o.show(),void o._selectMenuItem(t);o._isShown()&&(t.stopPropagation(),o.hide(),s.focus())}}fe.on(document,Ii,Mi,Ki.dataApiKeydownHandler),fe.on(document,Ii,Fi,Ki.dataApiKeydownHandler),fe.on(document,$i,Ki.clearMenus),fe.on(document,Ni,Ki.clearMenus),fe.on(document,$i,Mi,(function(t){t.preventDefault(),Ki.getOrCreateInstance(this).toggle()})),Qt(Ki);const Qi="backdrop",Xi="show",Ui=`mousedown.bs.${Qi}`,Gi={className:"modal-backdrop",clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:"body"},Ji={className:"string",clickCallback:"(function|null)",isAnimated:"boolean",isVisible:"boolean",rootElement:"(element|string)"};class Zi extends be{constructor(t){super(),this._config=this._getConfig(t),this._isAppended=!1,this._element=null}static get Default(){return Gi}static get DefaultType(){return Ji}static get NAME(){return Qi}show(t){if(!this._config.isVisible)return void Xt(t);this._append();const e=this._getElement();this._config.isAnimated&&qt(e),e.classList.add(Xi),this._emulateAnimation((()=>{Xt(t)}))}hide(t){this._config.isVisible?(this._getElement().classList.remove(Xi),this._emulateAnimation((()=>{this.dispose(),Xt(t)}))):Xt(t)}dispose(){this._isAppended&&(fe.off(this._element,Ui),this._element.remove(),this._isAppended=!1)}_getElement(){if(!this._element){const t=document.createElement("div");t.className=this._config.className,this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_configAfterMerge(t){return t.rootElement=Ht(t.rootElement),t}_append(){if(this._isAppended)return;const t=this._getElement();this._config.rootElement.append(t),fe.on(t,Ui,(()=>{Xt(this._config.clickCallback)})),this._isAppended=!0}_emulateAnimation(t){Ut(t,this._getElement(),this._config.isAnimated)}}const tn=".bs.focustrap",en=`focusin${tn}`,nn=`keydown.tab${tn}`,sn="backward",on={autofocus:!0,trapElement:null},rn={autofocus:"boolean",trapElement:"element"};class an extends be{constructor(t){super(),this._config=this._getConfig(t),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return on}static get DefaultType(){return rn}static get NAME(){return"focustrap"}activate(){this._isActive||(this._config.autofocus&&this._config.trapElement.focus(),fe.off(document,tn),fe.on(document,en,(t=>this._handleFocusin(t))),fe.on(document,nn,(t=>this._handleKeydown(t))),this._isActive=!0)}deactivate(){this._isActive&&(this._isActive=!1,fe.off(document,tn))}_handleFocusin(t){const{trapElement:e}=this._config;if(t.target===document||t.target===e||e.contains(t.target))return;const i=we.focusableChildren(e);0===i.length?e.focus():this._lastTabNavDirection===sn?i[i.length-1].focus():i[0].focus()}_handleKeydown(t){"Tab"===t.key&&(this._lastTabNavDirection=t.shiftKey?sn:"forward")}}const ln=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",cn=".sticky-top",hn="padding-right",dn="margin-right";class un{constructor(){this._element=document.body}getWidth(){const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)}hide(){const t=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,hn,(e=>e+t)),this._setElementAttributes(ln,hn,(e=>e+t)),this._setElementAttributes(cn,dn,(e=>e-t))}reset(){this._resetElementAttributes(this._element,"overflow"),this._resetElementAttributes(this._element,hn),this._resetElementAttributes(ln,hn),this._resetElementAttributes(cn,dn)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,"overflow"),this._element.style.overflow="hidden"}_setElementAttributes(t,e,i){const n=this.getWidth();this._applyManipulationCallback(t,(t=>{if(t!==this._element&&window.innerWidth>t.clientWidth+n)return;this._saveInitialAttribute(t,e);const s=window.getComputedStyle(t).getPropertyValue(e);t.style.setProperty(e,`${i(Number.parseFloat(s))}px`)}))}_saveInitialAttribute(t,e){const i=t.style.getPropertyValue(e);i&&_e.setDataAttribute(t,e,i)}_resetElementAttributes(t,e){this._applyManipulationCallback(t,(t=>{const i=_e.getDataAttribute(t,e);null!==i?(_e.removeDataAttribute(t,e),t.style.setProperty(e,i)):t.style.removeProperty(e)}))}_applyManipulationCallback(t,e){if(Ft(t))e(t);else for(const i of we.find(t,this._element))e(i)}}const fn=".bs.modal",pn=`hide${fn}`,mn=`hidePrevented${fn}`,gn=`hidden${fn}`,_n=`show${fn}`,bn=`shown${fn}`,vn=`resize${fn}`,yn=`click.dismiss${fn}`,wn=`mousedown.dismiss${fn}`,En=`keydown.dismiss${fn}`,An=`click${fn}.data-api`,Tn="modal-open",Cn="show",On="modal-static",xn={backdrop:!0,focus:!0,keyboard:!0},kn={backdrop:"(boolean|string)",focus:"boolean",keyboard:"boolean"};class Ln extends ve{constructor(t,e){super(t,e),this._dialog=we.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new un,this._addEventListeners()}static get Default(){return xn}static get DefaultType(){return kn}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||this._isTransitioning||fe.trigger(this._element,_n,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(Tn),this._adjustDialog(),this._backdrop.show((()=>this._showElement(t))))}hide(){this._isShown&&!this._isTransitioning&&(fe.trigger(this._element,pn).defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(Cn),this._queueCallback((()=>this._hideModal()),this._element,this._isAnimated())))}dispose(){fe.off(window,fn),fe.off(this._dialog,fn),this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Zi({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new an({trapElement:this._element})}_showElement(t){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0;const e=we.findOne(".modal-body",this._dialog);e&&(e.scrollTop=0),qt(this._element),this._element.classList.add(Cn),this._queueCallback((()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,fe.trigger(this._element,bn,{relatedTarget:t})}),this._dialog,this._isAnimated())}_addEventListeners(){fe.on(this._element,En,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():this._triggerBackdropTransition())})),fe.on(window,vn,(()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()})),fe.on(this._element,wn,(t=>{fe.one(this._element,yn,(e=>{this._element===t.target&&this._element===e.target&&("static"!==this._config.backdrop?this._config.backdrop&&this.hide():this._triggerBackdropTransition())}))}))}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide((()=>{document.body.classList.remove(Tn),this._resetAdjustments(),this._scrollBar.reset(),fe.trigger(this._element,gn)}))}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if(fe.trigger(this._element,mn).defaultPrevented)return;const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._element.style.overflowY;"hidden"===e||this._element.classList.contains(On)||(t||(this._element.style.overflowY="hidden"),this._element.classList.add(On),this._queueCallback((()=>{this._element.classList.remove(On),this._queueCallback((()=>{this._element.style.overflowY=e}),this._dialog)}),this._dialog),this._element.focus())}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._scrollBar.getWidth(),i=e>0;if(i&&!t){const t=Kt()?"paddingLeft":"paddingRight";this._element.style[t]=`${e}px`}if(!i&&t){const t=Kt()?"paddingRight":"paddingLeft";this._element.style[t]=`${e}px`}}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=Ln.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}fe.on(document,An,'[data-bs-toggle="modal"]',(function(t){const e=we.getElementFromSelector(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),fe.one(e,_n,(t=>{t.defaultPrevented||fe.one(e,gn,(()=>{Bt(this)&&this.focus()}))}));const i=we.findOne(".modal.show");i&&Ln.getInstance(i).hide(),Ln.getOrCreateInstance(e).toggle(this)})),Ee(Ln),Qt(Ln);const Sn=".bs.offcanvas",Dn=".data-api",$n=`load${Sn}${Dn}`,In="show",Nn="showing",Pn="hiding",Mn=".offcanvas.show",jn=`show${Sn}`,Fn=`shown${Sn}`,Hn=`hide${Sn}`,Bn=`hidePrevented${Sn}`,Wn=`hidden${Sn}`,zn=`resize${Sn}`,Rn=`click${Sn}${Dn}`,qn=`keydown.dismiss${Sn}`,Vn={backdrop:!0,keyboard:!0,scroll:!1},Yn={backdrop:"(boolean|string)",keyboard:"boolean",scroll:"boolean"};class Kn extends ve{constructor(t,e){super(t,e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return Vn}static get DefaultType(){return Yn}static get NAME(){return"offcanvas"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||fe.trigger(this._element,jn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||(new un).hide(),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add(Nn),this._queueCallback((()=>{this._config.scroll&&!this._config.backdrop||this._focustrap.activate(),this._element.classList.add(In),this._element.classList.remove(Nn),fe.trigger(this._element,Fn,{relatedTarget:t})}),this._element,!0))}hide(){this._isShown&&(fe.trigger(this._element,Hn).defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add(Pn),this._backdrop.hide(),this._queueCallback((()=>{this._element.classList.remove(In,Pn),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._config.scroll||(new un).reset(),fe.trigger(this._element,Wn)}),this._element,!0)))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){const t=Boolean(this._config.backdrop);return new Zi({className:"offcanvas-backdrop",isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?()=>{"static"!==this._config.backdrop?this.hide():fe.trigger(this._element,Bn)}:null})}_initializeFocusTrap(){return new an({trapElement:this._element})}_addEventListeners(){fe.on(this._element,qn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():fe.trigger(this._element,Bn))}))}static jQueryInterface(t){return this.each((function(){const e=Kn.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}fe.on(document,Rn,'[data-bs-toggle="offcanvas"]',(function(t){const e=we.getElementFromSelector(this);if(["A","AREA"].includes(this.tagName)&&t.preventDefault(),Wt(this))return;fe.one(e,Wn,(()=>{Bt(this)&&this.focus()}));const i=we.findOne(Mn);i&&i!==e&&Kn.getInstance(i).hide(),Kn.getOrCreateInstance(e).toggle(this)})),fe.on(window,$n,(()=>{for(const t of we.find(Mn))Kn.getOrCreateInstance(t).show()})),fe.on(window,zn,(()=>{for(const t of we.find("[aria-modal][class*=show][class*=offcanvas-]"))"fixed"!==getComputedStyle(t).position&&Kn.getOrCreateInstance(t).hide()})),Ee(Kn),Qt(Kn);const Qn={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],dd:[],div:[],dl:[],dt:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},Xn=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),Un=/^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i,Gn=(t,e)=>{const i=t.nodeName.toLowerCase();return e.includes(i)?!Xn.has(i)||Boolean(Un.test(t.nodeValue)):e.filter((t=>t instanceof RegExp)).some((t=>t.test(i)))},Jn={allowList:Qn,content:{},extraClass:"",html:!1,sanitize:!0,sanitizeFn:null,template:"
"},Zn={allowList:"object",content:"object",extraClass:"(string|function)",html:"boolean",sanitize:"boolean",sanitizeFn:"(null|function)",template:"string"},ts={entry:"(string|element|function|null)",selector:"(string|element)"};class es extends be{constructor(t){super(),this._config=this._getConfig(t)}static get Default(){return Jn}static get DefaultType(){return Zn}static get NAME(){return"TemplateFactory"}getContent(){return Object.values(this._config.content).map((t=>this._resolvePossibleFunction(t))).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(t){return this._checkContent(t),this._config.content={...this._config.content,...t},this}toHtml(){const t=document.createElement("div");t.innerHTML=this._maybeSanitize(this._config.template);for(const[e,i]of Object.entries(this._config.content))this._setContent(t,i,e);const e=t.children[0],i=this._resolvePossibleFunction(this._config.extraClass);return i&&e.classList.add(...i.split(" ")),e}_typeCheckConfig(t){super._typeCheckConfig(t),this._checkContent(t.content)}_checkContent(t){for(const[e,i]of Object.entries(t))super._typeCheckConfig({selector:e,entry:i},ts)}_setContent(t,e,i){const n=we.findOne(i,t);n&&((e=this._resolvePossibleFunction(e))?Ft(e)?this._putElementInTemplate(Ht(e),n):this._config.html?n.innerHTML=this._maybeSanitize(e):n.textContent=e:n.remove())}_maybeSanitize(t){return this._config.sanitize?function(t,e,i){if(!t.length)return t;if(i&&"function"==typeof i)return i(t);const n=(new window.DOMParser).parseFromString(t,"text/html"),s=[].concat(...n.body.querySelectorAll("*"));for(const t of s){const i=t.nodeName.toLowerCase();if(!Object.keys(e).includes(i)){t.remove();continue}const n=[].concat(...t.attributes),s=[].concat(e["*"]||[],e[i]||[]);for(const e of n)Gn(e,s)||t.removeAttribute(e.nodeName)}return n.body.innerHTML}(t,this._config.allowList,this._config.sanitizeFn):t}_resolvePossibleFunction(t){return Xt(t,[this])}_putElementInTemplate(t,e){if(this._config.html)return e.innerHTML="",void e.append(t);e.textContent=t.textContent}}const is=new Set(["sanitize","allowList","sanitizeFn"]),ns="fade",ss="show",os=".tooltip-inner",rs=".modal",as="hide.bs.modal",ls="hover",cs="focus",hs={AUTO:"auto",TOP:"top",RIGHT:Kt()?"left":"right",BOTTOM:"bottom",LEFT:Kt()?"right":"left"},ds={allowList:Qn,animation:!0,boundary:"clippingParents",container:!1,customClass:"",delay:0,fallbackPlacements:["top","right","bottom","left"],html:!1,offset:[0,6],placement:"top",popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:'',title:"",trigger:"hover focus"},us={allowList:"object",animation:"boolean",boundary:"(string|element)",container:"(string|element|boolean)",customClass:"(string|function)",delay:"(number|object)",fallbackPlacements:"array",html:"boolean",offset:"(array|string|function)",placement:"(string|function)",popperConfig:"(null|object|function)",sanitize:"boolean",sanitizeFn:"(null|function)",selector:"(string|boolean)",template:"string",title:"(string|element|function)",trigger:"string"};class fs extends ve{constructor(t,i){if(void 0===e)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t,i),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return ds}static get DefaultType(){return us}static get NAME(){return"tooltip"}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){this._isEnabled&&(this._activeTrigger.click=!this._activeTrigger.click,this._isShown()?this._leave():this._enter())}dispose(){clearTimeout(this._timeout),fe.off(this._element.closest(rs),as,this._hideModalHandler),this._element.getAttribute("data-bs-original-title")&&this._element.setAttribute("title",this._element.getAttribute("data-bs-original-title")),this._disposePopper(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this._isWithContent()||!this._isEnabled)return;const t=fe.trigger(this._element,this.constructor.eventName("show")),e=(zt(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(t.defaultPrevented||!e)return;this._disposePopper();const i=this._getTipElement();this._element.setAttribute("aria-describedby",i.getAttribute("id"));const{container:n}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(n.append(i),fe.trigger(this._element,this.constructor.eventName("inserted"))),this._popper=this._createPopper(i),i.classList.add(ss),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))fe.on(t,"mouseover",Rt);this._queueCallback((()=>{fe.trigger(this._element,this.constructor.eventName("shown")),!1===this._isHovered&&this._leave(),this._isHovered=!1}),this.tip,this._isAnimated())}hide(){if(this._isShown()&&!fe.trigger(this._element,this.constructor.eventName("hide")).defaultPrevented){if(this._getTipElement().classList.remove(ss),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))fe.off(t,"mouseover",Rt);this._activeTrigger.click=!1,this._activeTrigger[cs]=!1,this._activeTrigger[ls]=!1,this._isHovered=null,this._queueCallback((()=>{this._isWithActiveTrigger()||(this._isHovered||this._disposePopper(),this._element.removeAttribute("aria-describedby"),fe.trigger(this._element,this.constructor.eventName("hidden")))}),this.tip,this._isAnimated())}}update(){this._popper&&this._popper.update()}_isWithContent(){return Boolean(this._getTitle())}_getTipElement(){return this.tip||(this.tip=this._createTipElement(this._newContent||this._getContentForTemplate())),this.tip}_createTipElement(t){const e=this._getTemplateFactory(t).toHtml();if(!e)return null;e.classList.remove(ns,ss),e.classList.add(`bs-${this.constructor.NAME}-auto`);const i=(t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t})(this.constructor.NAME).toString();return e.setAttribute("id",i),this._isAnimated()&&e.classList.add(ns),e}setContent(t){this._newContent=t,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(t){return this._templateFactory?this._templateFactory.changeContent(t):this._templateFactory=new es({...this._config,content:t,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{[os]:this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute("data-bs-original-title")}_initializeOnDelegatedTarget(t){return this.constructor.getOrCreateInstance(t.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(ns)}_isShown(){return this.tip&&this.tip.classList.contains(ss)}_createPopper(t){const e=Xt(this._config.placement,[this,t,this._element]),i=hs[e.toUpperCase()];return Dt(this._element,t,this._getPopperConfig(i))}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_resolvePossibleFunction(t){return Xt(t,[this._element])}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"preSetPlacement",enabled:!0,phase:"beforeMain",fn:t=>{this._getTipElement().setAttribute("data-popper-placement",t.state.placement)}}]};return{...e,...Xt(this._config.popperConfig,[e])}}_setListeners(){const t=this._config.trigger.split(" ");for(const e of t)if("click"===e)fe.on(this._element,this.constructor.eventName("click"),this._config.selector,(t=>{this._initializeOnDelegatedTarget(t).toggle()}));else if("manual"!==e){const t=e===ls?this.constructor.eventName("mouseenter"):this.constructor.eventName("focusin"),i=e===ls?this.constructor.eventName("mouseleave"):this.constructor.eventName("focusout");fe.on(this._element,t,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusin"===t.type?cs:ls]=!0,e._enter()})),fe.on(this._element,i,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusout"===t.type?cs:ls]=e._element.contains(t.relatedTarget),e._leave()}))}this._hideModalHandler=()=>{this._element&&this.hide()},fe.on(this._element.closest(rs),as,this._hideModalHandler)}_fixTitle(){const t=this._element.getAttribute("title");t&&(this._element.getAttribute("aria-label")||this._element.textContent.trim()||this._element.setAttribute("aria-label",t),this._element.setAttribute("data-bs-original-title",t),this._element.removeAttribute("title"))}_enter(){this._isShown()||this._isHovered?this._isHovered=!0:(this._isHovered=!0,this._setTimeout((()=>{this._isHovered&&this.show()}),this._config.delay.show))}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout((()=>{this._isHovered||this.hide()}),this._config.delay.hide))}_setTimeout(t,e){clearTimeout(this._timeout),this._timeout=setTimeout(t,e)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(t){const e=_e.getDataAttributes(this._element);for(const t of Object.keys(e))is.has(t)&&delete e[t];return t={...e,..."object"==typeof t&&t?t:{}},t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t.container=!1===t.container?document.body:Ht(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),t}_getDelegateConfig(){const t={};for(const[e,i]of Object.entries(this._config))this.constructor.Default[e]!==i&&(t[e]=i);return t.selector=!1,t.trigger="manual",t}_disposePopper(){this._popper&&(this._popper.destroy(),this._popper=null),this.tip&&(this.tip.remove(),this.tip=null)}static jQueryInterface(t){return this.each((function(){const e=fs.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}Qt(fs);const ps=".popover-header",ms=".popover-body",gs={...fs.Default,content:"",offset:[0,8],placement:"right",template:'',trigger:"click"},_s={...fs.DefaultType,content:"(null|string|element|function)"};class bs extends fs{static get Default(){return gs}static get DefaultType(){return _s}static get NAME(){return"popover"}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{[ps]:this._getTitle(),[ms]:this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each((function(){const e=bs.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}Qt(bs);const vs=".bs.scrollspy",ys=`activate${vs}`,ws=`click${vs}`,Es=`load${vs}.data-api`,As="active",Ts="[href]",Cs=".nav-link",Os=`${Cs}, .nav-item > ${Cs}, .list-group-item`,xs={offset:null,rootMargin:"0px 0px -25%",smoothScroll:!1,target:null,threshold:[.1,.5,1]},ks={offset:"(number|null)",rootMargin:"string",smoothScroll:"boolean",target:"element",threshold:"array"};class Ls extends ve{constructor(t,e){super(t,e),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement="visible"===getComputedStyle(this._element).overflowY?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return xs}static get DefaultType(){return ks}static get NAME(){return"scrollspy"}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(const t of this._observableSections.values())this._observer.observe(t)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(t){return t.target=Ht(t.target)||document.body,t.rootMargin=t.offset?`${t.offset}px 0px -30%`:t.rootMargin,"string"==typeof t.threshold&&(t.threshold=t.threshold.split(",").map((t=>Number.parseFloat(t)))),t}_maybeEnableSmoothScroll(){this._config.smoothScroll&&(fe.off(this._config.target,ws),fe.on(this._config.target,ws,Ts,(t=>{const e=this._observableSections.get(t.target.hash);if(e){t.preventDefault();const i=this._rootElement||window,n=e.offsetTop-this._element.offsetTop;if(i.scrollTo)return void i.scrollTo({top:n,behavior:"smooth"});i.scrollTop=n}})))}_getNewObserver(){const t={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver((t=>this._observerCallback(t)),t)}_observerCallback(t){const e=t=>this._targetLinks.get(`#${t.target.id}`),i=t=>{this._previousScrollData.visibleEntryTop=t.target.offsetTop,this._process(e(t))},n=(this._rootElement||document.documentElement).scrollTop,s=n>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=n;for(const o of t){if(!o.isIntersecting){this._activeTarget=null,this._clearActiveClass(e(o));continue}const t=o.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(s&&t){if(i(o),!n)return}else s||t||i(o)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;const t=we.find(Ts,this._config.target);for(const e of t){if(!e.hash||Wt(e))continue;const t=we.findOne(decodeURI(e.hash),this._element);Bt(t)&&(this._targetLinks.set(decodeURI(e.hash),e),this._observableSections.set(e.hash,t))}}_process(t){this._activeTarget!==t&&(this._clearActiveClass(this._config.target),this._activeTarget=t,t.classList.add(As),this._activateParents(t),fe.trigger(this._element,ys,{relatedTarget:t}))}_activateParents(t){if(t.classList.contains("dropdown-item"))we.findOne(".dropdown-toggle",t.closest(".dropdown")).classList.add(As);else for(const e of we.parents(t,".nav, .list-group"))for(const t of we.prev(e,Os))t.classList.add(As)}_clearActiveClass(t){t.classList.remove(As);const e=we.find(`${Ts}.${As}`,t);for(const t of e)t.classList.remove(As)}static jQueryInterface(t){return this.each((function(){const e=Ls.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}fe.on(window,Es,(()=>{for(const t of we.find('[data-bs-spy="scroll"]'))Ls.getOrCreateInstance(t)})),Qt(Ls);const Ss=".bs.tab",Ds=`hide${Ss}`,$s=`hidden${Ss}`,Is=`show${Ss}`,Ns=`shown${Ss}`,Ps=`click${Ss}`,Ms=`keydown${Ss}`,js=`load${Ss}`,Fs="ArrowLeft",Hs="ArrowRight",Bs="ArrowUp",Ws="ArrowDown",zs="Home",Rs="End",qs="active",Vs="fade",Ys="show",Ks=".dropdown-toggle",Qs=`:not(${Ks})`,Xs='[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',Us=`.nav-link${Qs}, .list-group-item${Qs}, [role="tab"]${Qs}, ${Xs}`,Gs=`.${qs}[data-bs-toggle="tab"], .${qs}[data-bs-toggle="pill"], .${qs}[data-bs-toggle="list"]`;class Js extends ve{constructor(t){super(t),this._parent=this._element.closest('.list-group, .nav, [role="tablist"]'),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),fe.on(this._element,Ms,(t=>this._keydown(t))))}static get NAME(){return"tab"}show(){const t=this._element;if(this._elemIsActive(t))return;const e=this._getActiveElem(),i=e?fe.trigger(e,Ds,{relatedTarget:t}):null;fe.trigger(t,Is,{relatedTarget:e}).defaultPrevented||i&&i.defaultPrevented||(this._deactivate(e,t),this._activate(t,e))}_activate(t,e){t&&(t.classList.add(qs),this._activate(we.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.removeAttribute("tabindex"),t.setAttribute("aria-selected",!0),this._toggleDropDown(t,!0),fe.trigger(t,Ns,{relatedTarget:e})):t.classList.add(Ys)}),t,t.classList.contains(Vs)))}_deactivate(t,e){t&&(t.classList.remove(qs),t.blur(),this._deactivate(we.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.setAttribute("aria-selected",!1),t.setAttribute("tabindex","-1"),this._toggleDropDown(t,!1),fe.trigger(t,$s,{relatedTarget:e})):t.classList.remove(Ys)}),t,t.classList.contains(Vs)))}_keydown(t){if(![Fs,Hs,Bs,Ws,zs,Rs].includes(t.key))return;t.stopPropagation(),t.preventDefault();const e=this._getChildren().filter((t=>!Wt(t)));let i;if([zs,Rs].includes(t.key))i=e[t.key===zs?0:e.length-1];else{const n=[Hs,Ws].includes(t.key);i=Gt(e,t.target,n,!0)}i&&(i.focus({preventScroll:!0}),Js.getOrCreateInstance(i).show())}_getChildren(){return we.find(Us,this._parent)}_getActiveElem(){return this._getChildren().find((t=>this._elemIsActive(t)))||null}_setInitialAttributes(t,e){this._setAttributeIfNotExists(t,"role","tablist");for(const t of e)this._setInitialAttributesOnChild(t)}_setInitialAttributesOnChild(t){t=this._getInnerElement(t);const e=this._elemIsActive(t),i=this._getOuterElement(t);t.setAttribute("aria-selected",e),i!==t&&this._setAttributeIfNotExists(i,"role","presentation"),e||t.setAttribute("tabindex","-1"),this._setAttributeIfNotExists(t,"role","tab"),this._setInitialAttributesOnTargetPanel(t)}_setInitialAttributesOnTargetPanel(t){const e=we.getElementFromSelector(t);e&&(this._setAttributeIfNotExists(e,"role","tabpanel"),t.id&&this._setAttributeIfNotExists(e,"aria-labelledby",`${t.id}`))}_toggleDropDown(t,e){const i=this._getOuterElement(t);if(!i.classList.contains("dropdown"))return;const n=(t,n)=>{const s=we.findOne(t,i);s&&s.classList.toggle(n,e)};n(Ks,qs),n(".dropdown-menu",Ys),i.setAttribute("aria-expanded",e)}_setAttributeIfNotExists(t,e,i){t.hasAttribute(e)||t.setAttribute(e,i)}_elemIsActive(t){return t.classList.contains(qs)}_getInnerElement(t){return t.matches(Us)?t:we.findOne(Us,t)}_getOuterElement(t){return t.closest(".nav-item, .list-group-item")||t}static jQueryInterface(t){return this.each((function(){const e=Js.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}fe.on(document,Ps,Xs,(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),Wt(this)||Js.getOrCreateInstance(this).show()})),fe.on(window,js,(()=>{for(const t of we.find(Gs))Js.getOrCreateInstance(t)})),Qt(Js);const Zs=".bs.toast",to=`mouseover${Zs}`,eo=`mouseout${Zs}`,io=`focusin${Zs}`,no=`focusout${Zs}`,so=`hide${Zs}`,oo=`hidden${Zs}`,ro=`show${Zs}`,ao=`shown${Zs}`,lo="hide",co="show",ho="showing",uo={animation:"boolean",autohide:"boolean",delay:"number"},fo={animation:!0,autohide:!0,delay:5e3};class po extends ve{constructor(t,e){super(t,e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return fo}static get DefaultType(){return uo}static get NAME(){return"toast"}show(){fe.trigger(this._element,ro).defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove(lo),qt(this._element),this._element.classList.add(co,ho),this._queueCallback((()=>{this._element.classList.remove(ho),fe.trigger(this._element,ao),this._maybeScheduleHide()}),this._element,this._config.animation))}hide(){this.isShown()&&(fe.trigger(this._element,so).defaultPrevented||(this._element.classList.add(ho),this._queueCallback((()=>{this._element.classList.add(lo),this._element.classList.remove(ho,co),fe.trigger(this._element,oo)}),this._element,this._config.animation)))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(co),super.dispose()}isShown(){return this._element.classList.contains(co)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout((()=>{this.hide()}),this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){fe.on(this._element,to,(t=>this._onInteraction(t,!0))),fe.on(this._element,eo,(t=>this._onInteraction(t,!1))),fe.on(this._element,io,(t=>this._onInteraction(t,!0))),fe.on(this._element,no,(t=>this._onInteraction(t,!1)))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){const e=po.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}function mo(t){"loading"!=document.readyState?t():document.addEventListener("DOMContentLoaded",t)}Ee(po),Qt(po),mo((function(){[].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')).map((function(t){return new fs(t,{delay:{show:500,hide:100}})}))})),mo((function(){document.getElementById("pst-back-to-top").addEventListener("click",(function(){document.body.scrollTop=0,document.documentElement.scrollTop=0}))})),mo((function(){var t=document.getElementById("pst-back-to-top"),e=document.getElementsByClassName("bd-header")[0].getBoundingClientRect();window.addEventListener("scroll",(function(){this.oldScroll>this.scrollY&&this.scrollY>e.bottom?t.style.display="block":t.style.display="none",this.oldScroll=this.scrollY}))})),window.bootstrap=i})(); +//# sourceMappingURL=bootstrap.js.map \ No newline at end of file diff --git a/docs/_build/html/_static/scripts/bootstrap.js.LICENSE.txt b/docs/_build/html/_static/scripts/bootstrap.js.LICENSE.txt new file mode 100644 index 00000000..28755c2c --- /dev/null +++ b/docs/_build/html/_static/scripts/bootstrap.js.LICENSE.txt @@ -0,0 +1,5 @@ +/*! + * Bootstrap v5.3.3 (https://getbootstrap.com/) + * Copyright 2011-2024 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + */ diff --git a/docs/_build/html/_static/scripts/bootstrap.js.map b/docs/_build/html/_static/scripts/bootstrap.js.map new file mode 100644 index 00000000..e9e81589 --- /dev/null +++ b/docs/_build/html/_static/scripts/bootstrap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scripts/bootstrap.js","mappings":";mBACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFV,EAAyBC,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeL,EAAS,aAAc,CAAEe,OAAO,GAAO,01BCLvD,IAAI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,EAAKyZ,GAAQ9D,KACf,CACF,GACF,ECr0IK,SAAS0qB,GAAcruB,GACD,WAAvBhX,SAASuX,WAAyBP,IACjChX,SAASyF,iBAAiB,mBAAoBuR,EACrD,CDy0IAwK,GAAqBqjB,IAMrB/tB,GAAmB+tB,IEpyInBQ,IAzCA,WAC2B,GAAGt4B,MAAM5U,KAChC6H,SAAS+a,iBAAiB,+BAETtd,KAAI,SAAU6nC,GAC/B,OAAO,IAAI,GAAkBA,EAAkB,CAC7CpK,MAAO,CAAE1Q,KAAM,IAAKD,KAAM,MAE9B,GACF,IAiCA8a,IA5BA,WACYrlC,SAASm9B,eAAe,mBAC9B13B,iBAAiB,SAAS,WAC5BzF,SAAS6G,KAAKT,UAAY,EAC1BpG,SAASC,gBAAgBmG,UAAY,CACvC,GACF,IAuBAi/B,IArBA,WACE,IAAIE,EAAMvlC,SAASm9B,eAAe,mBAC9BqI,EAASxlC,SACVylC,uBAAuB,aAAa,GACpCxnC,wBACH1D,OAAOkL,iBAAiB,UAAU,WAC5BkV,KAAK+qB,UAAY/qB,KAAKgrB,SAAWhrB,KAAKgrB,QAAUH,EAAOjtC,OACzDgtC,EAAI7pC,MAAMgxB,QAAU,QAEpB6Y,EAAI7pC,MAAMgxB,QAAU,OAEtB/R,KAAK+qB,UAAY/qB,KAAKgrB,OACxB,GACF,IAUAprC,OAAOqrC,UAAY","sources":["webpack://pydata_sphinx_theme/webpack/bootstrap","webpack://pydata_sphinx_theme/webpack/runtime/define property getters","webpack://pydata_sphinx_theme/webpack/runtime/hasOwnProperty shorthand","webpack://pydata_sphinx_theme/webpack/runtime/make namespace object","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/enums.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getWindow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/applyStyles.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getBasePlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/math.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/userAgent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/contains.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/within.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/expandToHashMap.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/arrow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getVariation.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/computeStyles.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/eventListeners.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/rectToClientRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/computeOffsets.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/detectOverflow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/flip.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/hide.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/offset.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getAltAxis.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/orderModifiers.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/createPopper.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/debounce.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/mergeByName.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/popper.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/popper-lite.js","webpack://pydata_sphinx_theme/./node_modules/bootstrap/dist/js/bootstrap.esm.js","webpack://pydata_sphinx_theme/./src/pydata_sphinx_theme/assets/scripts/mixin.js","webpack://pydata_sphinx_theme/./src/pydata_sphinx_theme/assets/scripts/bootstrap.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export var top = 'top';\nexport var bottom = 'bottom';\nexport var right = 'right';\nexport var left = 'left';\nexport var auto = 'auto';\nexport var basePlacements = [top, bottom, right, left];\nexport var start = 'start';\nexport var end = 'end';\nexport var clippingParents = 'clippingParents';\nexport var viewport = 'viewport';\nexport var popper = 'popper';\nexport var reference = 'reference';\nexport var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {\n return acc.concat([placement + \"-\" + start, placement + \"-\" + end]);\n}, []);\nexport var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {\n return acc.concat([placement, placement + \"-\" + start, placement + \"-\" + end]);\n}, []); // modifiers that need to read the DOM\n\nexport var beforeRead = 'beforeRead';\nexport var read = 'read';\nexport var afterRead = 'afterRead'; // pure-logic modifiers\n\nexport var beforeMain = 'beforeMain';\nexport var main = 'main';\nexport var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)\n\nexport var beforeWrite = 'beforeWrite';\nexport var write = 'write';\nexport var afterWrite = 'afterWrite';\nexport var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];","export default function getNodeName(element) {\n return element ? (element.nodeName || '').toLowerCase() : null;\n}","export default function getWindow(node) {\n if (node == null) {\n return window;\n }\n\n if (node.toString() !== '[object Window]') {\n var ownerDocument = node.ownerDocument;\n return ownerDocument ? ownerDocument.defaultView || window : window;\n }\n\n return node;\n}","import getWindow from \"./getWindow.js\";\n\nfunction isElement(node) {\n var OwnElement = getWindow(node).Element;\n return node instanceof OwnElement || node instanceof Element;\n}\n\nfunction isHTMLElement(node) {\n var OwnElement = getWindow(node).HTMLElement;\n return node instanceof OwnElement || node instanceof HTMLElement;\n}\n\nfunction isShadowRoot(node) {\n // IE 11 has no ShadowRoot\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n\n var OwnElement = getWindow(node).ShadowRoot;\n return node instanceof OwnElement || node instanceof ShadowRoot;\n}\n\nexport { isElement, isHTMLElement, isShadowRoot };","import getNodeName from \"../dom-utils/getNodeName.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // This modifier takes the styles prepared by the `computeStyles` modifier\n// and applies them to the HTMLElements such as popper and arrow\n\nfunction applyStyles(_ref) {\n var state = _ref.state;\n Object.keys(state.elements).forEach(function (name) {\n var style = state.styles[name] || {};\n var attributes = state.attributes[name] || {};\n var element = state.elements[name]; // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n } // Flow doesn't support to extend this property, but it's the most\n // effective way to apply styles to an HTMLElement\n // $FlowFixMe[cannot-write]\n\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (name) {\n var value = attributes[name];\n\n if (value === false) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, value === true ? '' : value);\n }\n });\n });\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state;\n var initialStyles = {\n popper: {\n position: state.options.strategy,\n left: '0',\n top: '0',\n margin: '0'\n },\n arrow: {\n position: 'absolute'\n },\n reference: {}\n };\n Object.assign(state.elements.popper.style, initialStyles.popper);\n state.styles = initialStyles;\n\n if (state.elements.arrow) {\n Object.assign(state.elements.arrow.style, initialStyles.arrow);\n }\n\n return function () {\n Object.keys(state.elements).forEach(function (name) {\n var element = state.elements[name];\n var attributes = state.attributes[name] || {};\n var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them\n\n var style = styleProperties.reduce(function (style, property) {\n style[property] = '';\n return style;\n }, {}); // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n }\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (attribute) {\n element.removeAttribute(attribute);\n });\n });\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'applyStyles',\n enabled: true,\n phase: 'write',\n fn: applyStyles,\n effect: effect,\n requires: ['computeStyles']\n};","import { auto } from \"../enums.js\";\nexport default function getBasePlacement(placement) {\n return placement.split('-')[0];\n}","export var max = Math.max;\nexport var min = Math.min;\nexport var round = Math.round;","export default function getUAString() {\n var uaData = navigator.userAgentData;\n\n if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {\n return uaData.brands.map(function (item) {\n return item.brand + \"/\" + item.version;\n }).join(' ');\n }\n\n return navigator.userAgent;\n}","import getUAString from \"../utils/userAgent.js\";\nexport default function isLayoutViewport() {\n return !/^((?!chrome|android).)*safari/i.test(getUAString());\n}","import { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport { round } from \"../utils/math.js\";\nimport getWindow from \"./getWindow.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getBoundingClientRect(element, includeScale, isFixedStrategy) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n\n var clientRect = element.getBoundingClientRect();\n var scaleX = 1;\n var scaleY = 1;\n\n if (includeScale && isHTMLElement(element)) {\n scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;\n scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;\n }\n\n var _ref = isElement(element) ? getWindow(element) : window,\n visualViewport = _ref.visualViewport;\n\n var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;\n var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;\n var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;\n var width = clientRect.width / scaleX;\n var height = clientRect.height / scaleY;\n return {\n width: width,\n height: height,\n top: y,\n right: x + width,\n bottom: y + height,\n left: x,\n x: x,\n y: y\n };\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\"; // Returns the layout rect of an element relative to its offsetParent. Layout\n// means it doesn't take into account transforms.\n\nexport default function getLayoutRect(element) {\n var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.\n // Fixes https://github.com/popperjs/popper-core/issues/1223\n\n var width = element.offsetWidth;\n var height = element.offsetHeight;\n\n if (Math.abs(clientRect.width - width) <= 1) {\n width = clientRect.width;\n }\n\n if (Math.abs(clientRect.height - height) <= 1) {\n height = clientRect.height;\n }\n\n return {\n x: element.offsetLeft,\n y: element.offsetTop,\n width: width,\n height: height\n };\n}","import { isShadowRoot } from \"./instanceOf.js\";\nexport default function contains(parent, child) {\n var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method\n\n if (parent.contains(child)) {\n return true;\n } // then fallback to custom implementation with Shadow DOM support\n else if (rootNode && isShadowRoot(rootNode)) {\n var next = child;\n\n do {\n if (next && parent.isSameNode(next)) {\n return true;\n } // $FlowFixMe[prop-missing]: need a better way to handle this...\n\n\n next = next.parentNode || next.host;\n } while (next);\n } // Give up, the result is false\n\n\n return false;\n}","import getWindow from \"./getWindow.js\";\nexport default function getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}","import getNodeName from \"./getNodeName.js\";\nexport default function isTableElement(element) {\n return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;\n}","import { isElement } from \"./instanceOf.js\";\nexport default function getDocumentElement(element) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]\n element.document) || window.document).documentElement;\n}","import getNodeName from \"./getNodeName.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport { isShadowRoot } from \"./instanceOf.js\";\nexport default function getParentNode(element) {\n if (getNodeName(element) === 'html') {\n return element;\n }\n\n return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle\n // $FlowFixMe[incompatible-return]\n // $FlowFixMe[prop-missing]\n element.assignedSlot || // step into the shadow DOM of the parent of a slotted node\n element.parentNode || ( // DOM Element detected\n isShadowRoot(element) ? element.host : null) || // ShadowRoot detected\n // $FlowFixMe[incompatible-call]: HTMLElement is a Node\n getDocumentElement(element) // fallback\n\n );\n}","import getWindow from \"./getWindow.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isHTMLElement, isShadowRoot } from \"./instanceOf.js\";\nimport isTableElement from \"./isTableElement.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getUAString from \"../utils/userAgent.js\";\n\nfunction getTrueOffsetParent(element) {\n if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837\n getComputedStyle(element).position === 'fixed') {\n return null;\n }\n\n return element.offsetParent;\n} // `.offsetParent` reports `null` for fixed elements, while absolute elements\n// return the containing block\n\n\nfunction getContainingBlock(element) {\n var isFirefox = /firefox/i.test(getUAString());\n var isIE = /Trident/i.test(getUAString());\n\n if (isIE && isHTMLElement(element)) {\n // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport\n var elementCss = getComputedStyle(element);\n\n if (elementCss.position === 'fixed') {\n return null;\n }\n }\n\n var currentNode = getParentNode(element);\n\n if (isShadowRoot(currentNode)) {\n currentNode = currentNode.host;\n }\n\n while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {\n var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that\n // create a containing block.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n\n if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {\n return currentNode;\n } else {\n currentNode = currentNode.parentNode;\n }\n }\n\n return null;\n} // Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\n\n\nexport default function getOffsetParent(element) {\n var window = getWindow(element);\n var offsetParent = getTrueOffsetParent(element);\n\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent);\n }\n\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {\n return window;\n }\n\n return offsetParent || getContainingBlock(element) || window;\n}","export default function getMainAxisFromPlacement(placement) {\n return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';\n}","import { max as mathMax, min as mathMin } from \"./math.js\";\nexport function within(min, value, max) {\n return mathMax(min, mathMin(value, max));\n}\nexport function withinMaxClamp(min, value, max) {\n var v = within(min, value, max);\n return v > max ? max : v;\n}","import getFreshSideObject from \"./getFreshSideObject.js\";\nexport default function mergePaddingObject(paddingObject) {\n return Object.assign({}, getFreshSideObject(), paddingObject);\n}","export default function getFreshSideObject() {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n };\n}","export default function expandToHashMap(value, keys) {\n return keys.reduce(function (hashMap, key) {\n hashMap[key] = value;\n return hashMap;\n }, {});\n}","import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport contains from \"../dom-utils/contains.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport { within } from \"../utils/within.js\";\nimport mergePaddingObject from \"../utils/mergePaddingObject.js\";\nimport expandToHashMap from \"../utils/expandToHashMap.js\";\nimport { left, right, basePlacements, top, bottom } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar toPaddingObject = function toPaddingObject(padding, state) {\n padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {\n placement: state.placement\n })) : padding;\n return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n};\n\nfunction arrow(_ref) {\n var _state$modifiersData$;\n\n var state = _ref.state,\n name = _ref.name,\n options = _ref.options;\n var arrowElement = state.elements.arrow;\n var popperOffsets = state.modifiersData.popperOffsets;\n var basePlacement = getBasePlacement(state.placement);\n var axis = getMainAxisFromPlacement(basePlacement);\n var isVertical = [left, right].indexOf(basePlacement) >= 0;\n var len = isVertical ? 'height' : 'width';\n\n if (!arrowElement || !popperOffsets) {\n return;\n }\n\n var paddingObject = toPaddingObject(options.padding, state);\n var arrowRect = getLayoutRect(arrowElement);\n var minProp = axis === 'y' ? top : left;\n var maxProp = axis === 'y' ? bottom : right;\n var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];\n var startDiff = popperOffsets[axis] - state.rects.reference[axis];\n var arrowOffsetParent = getOffsetParent(arrowElement);\n var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;\n var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is\n // outside of the popper bounds\n\n var min = paddingObject[minProp];\n var max = clientSize - arrowRect[len] - paddingObject[maxProp];\n var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;\n var offset = within(min, center, max); // Prevents breaking syntax highlighting...\n\n var axisProp = axis;\n state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state,\n options = _ref2.options;\n var _options$element = options.element,\n arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;\n\n if (arrowElement == null) {\n return;\n } // CSS selector\n\n\n if (typeof arrowElement === 'string') {\n arrowElement = state.elements.popper.querySelector(arrowElement);\n\n if (!arrowElement) {\n return;\n }\n }\n\n if (!contains(state.elements.popper, arrowElement)) {\n return;\n }\n\n state.elements.arrow = arrowElement;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'arrow',\n enabled: true,\n phase: 'main',\n fn: arrow,\n effect: effect,\n requires: ['popperOffsets'],\n requiresIfExists: ['preventOverflow']\n};","export default function getVariation(placement) {\n return placement.split('-')[1];\n}","import { top, left, right, bottom, end } from \"../enums.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getWindow from \"../dom-utils/getWindow.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getComputedStyle from \"../dom-utils/getComputedStyle.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport { round } from \"../utils/math.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar unsetSides = {\n top: 'auto',\n right: 'auto',\n bottom: 'auto',\n left: 'auto'\n}; // Round the offsets to the nearest suitable subpixel based on the DPR.\n// Zooming can change the DPR, but it seems to report a value that will\n// cleanly divide the values into the appropriate subpixels.\n\nfunction roundOffsetsByDPR(_ref, win) {\n var x = _ref.x,\n y = _ref.y;\n var dpr = win.devicePixelRatio || 1;\n return {\n x: round(x * dpr) / dpr || 0,\n y: round(y * dpr) / dpr || 0\n };\n}\n\nexport function mapToStyles(_ref2) {\n var _Object$assign2;\n\n var popper = _ref2.popper,\n popperRect = _ref2.popperRect,\n placement = _ref2.placement,\n variation = _ref2.variation,\n offsets = _ref2.offsets,\n position = _ref2.position,\n gpuAcceleration = _ref2.gpuAcceleration,\n adaptive = _ref2.adaptive,\n roundOffsets = _ref2.roundOffsets,\n isFixed = _ref2.isFixed;\n var _offsets$x = offsets.x,\n x = _offsets$x === void 0 ? 0 : _offsets$x,\n _offsets$y = offsets.y,\n y = _offsets$y === void 0 ? 0 : _offsets$y;\n\n var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({\n x: x,\n y: y\n }) : {\n x: x,\n y: y\n };\n\n x = _ref3.x;\n y = _ref3.y;\n var hasX = offsets.hasOwnProperty('x');\n var hasY = offsets.hasOwnProperty('y');\n var sideX = left;\n var sideY = top;\n var win = window;\n\n if (adaptive) {\n var offsetParent = getOffsetParent(popper);\n var heightProp = 'clientHeight';\n var widthProp = 'clientWidth';\n\n if (offsetParent === getWindow(popper)) {\n offsetParent = getDocumentElement(popper);\n\n if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {\n heightProp = 'scrollHeight';\n widthProp = 'scrollWidth';\n }\n } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it\n\n\n offsetParent = offsetParent;\n\n if (placement === top || (placement === left || placement === right) && variation === end) {\n sideY = bottom;\n var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]\n offsetParent[heightProp];\n y -= offsetY - popperRect.height;\n y *= gpuAcceleration ? 1 : -1;\n }\n\n if (placement === left || (placement === top || placement === bottom) && variation === end) {\n sideX = right;\n var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]\n offsetParent[widthProp];\n x -= offsetX - popperRect.width;\n x *= gpuAcceleration ? 1 : -1;\n }\n }\n\n var commonStyles = Object.assign({\n position: position\n }, adaptive && unsetSides);\n\n var _ref4 = roundOffsets === true ? roundOffsetsByDPR({\n x: x,\n y: y\n }, getWindow(popper)) : {\n x: x,\n y: y\n };\n\n x = _ref4.x;\n y = _ref4.y;\n\n if (gpuAcceleration) {\n var _Object$assign;\n\n return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? \"translate(\" + x + \"px, \" + y + \"px)\" : \"translate3d(\" + x + \"px, \" + y + \"px, 0)\", _Object$assign));\n }\n\n return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + \"px\" : '', _Object$assign2[sideX] = hasX ? x + \"px\" : '', _Object$assign2.transform = '', _Object$assign2));\n}\n\nfunction computeStyles(_ref5) {\n var state = _ref5.state,\n options = _ref5.options;\n var _options$gpuAccelerat = options.gpuAcceleration,\n gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,\n _options$adaptive = options.adaptive,\n adaptive = _options$adaptive === void 0 ? true : _options$adaptive,\n _options$roundOffsets = options.roundOffsets,\n roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;\n var commonStyles = {\n placement: getBasePlacement(state.placement),\n variation: getVariation(state.placement),\n popper: state.elements.popper,\n popperRect: state.rects.popper,\n gpuAcceleration: gpuAcceleration,\n isFixed: state.options.strategy === 'fixed'\n };\n\n if (state.modifiersData.popperOffsets != null) {\n state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.popperOffsets,\n position: state.options.strategy,\n adaptive: adaptive,\n roundOffsets: roundOffsets\n })));\n }\n\n if (state.modifiersData.arrow != null) {\n state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.arrow,\n position: 'absolute',\n adaptive: false,\n roundOffsets: roundOffsets\n })));\n }\n\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-placement': state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'computeStyles',\n enabled: true,\n phase: 'beforeWrite',\n fn: computeStyles,\n data: {}\n};","import getWindow from \"../dom-utils/getWindow.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar passive = {\n passive: true\n};\n\nfunction effect(_ref) {\n var state = _ref.state,\n instance = _ref.instance,\n options = _ref.options;\n var _options$scroll = options.scroll,\n scroll = _options$scroll === void 0 ? true : _options$scroll,\n _options$resize = options.resize,\n resize = _options$resize === void 0 ? true : _options$resize;\n var window = getWindow(state.elements.popper);\n var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);\n\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.addEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.addEventListener('resize', instance.update, passive);\n }\n\n return function () {\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.removeEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.removeEventListener('resize', instance.update, passive);\n }\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'eventListeners',\n enabled: true,\n phase: 'write',\n fn: function fn() {},\n effect: effect,\n data: {}\n};","var hash = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nexport default function getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, function (matched) {\n return hash[matched];\n });\n}","var hash = {\n start: 'end',\n end: 'start'\n};\nexport default function getOppositeVariationPlacement(placement) {\n return placement.replace(/start|end/g, function (matched) {\n return hash[matched];\n });\n}","import getWindow from \"./getWindow.js\";\nexport default function getWindowScroll(node) {\n var win = getWindow(node);\n var scrollLeft = win.pageXOffset;\n var scrollTop = win.pageYOffset;\n return {\n scrollLeft: scrollLeft,\n scrollTop: scrollTop\n };\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nexport default function getWindowScrollBarX(element) {\n // If has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n // Popper 1 is broken in this case and never had a bug report so let's assume\n // it's not an issue. I don't think anyone ever specifies width on \n // anyway.\n // Browsers where the left scrollbar doesn't cause an issue report `0` for\n // this (e.g. Edge 2019, IE11, Safari)\n return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;\n}","import getComputedStyle from \"./getComputedStyle.js\";\nexport default function isScrollParent(element) {\n // Firefox wants us to check `-x` and `-y` variations as well\n var _getComputedStyle = getComputedStyle(element),\n overflow = _getComputedStyle.overflow,\n overflowX = _getComputedStyle.overflowX,\n overflowY = _getComputedStyle.overflowY;\n\n return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);\n}","import getParentNode from \"./getParentNode.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nexport default function getScrollParent(node) {\n if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return node.ownerDocument.body;\n }\n\n if (isHTMLElement(node) && isScrollParent(node)) {\n return node;\n }\n\n return getScrollParent(getParentNode(node));\n}","import getScrollParent from \"./getScrollParent.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getWindow from \"./getWindow.js\";\nimport isScrollParent from \"./isScrollParent.js\";\n/*\ngiven a DOM element, return the list of all scroll parents, up the list of ancesors\nuntil we get to the top window object. This list is what we attach scroll listeners\nto, because if any of these parent elements scroll, we'll need to re-calculate the\nreference element's position.\n*/\n\nexport default function listScrollParents(element, list) {\n var _element$ownerDocumen;\n\n if (list === void 0) {\n list = [];\n }\n\n var scrollParent = getScrollParent(element);\n var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);\n var win = getWindow(scrollParent);\n var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;\n var updatedList = list.concat(target);\n return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here\n updatedList.concat(listScrollParents(getParentNode(target)));\n}","export default function rectToClientRect(rect) {\n return Object.assign({}, rect, {\n left: rect.x,\n top: rect.y,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n });\n}","import { viewport } from \"../enums.js\";\nimport getViewportRect from \"./getViewportRect.js\";\nimport getDocumentRect from \"./getDocumentRect.js\";\nimport listScrollParents from \"./listScrollParents.js\";\nimport getOffsetParent from \"./getOffsetParent.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport contains from \"./contains.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport rectToClientRect from \"../utils/rectToClientRect.js\";\nimport { max, min } from \"../utils/math.js\";\n\nfunction getInnerBoundingClientRect(element, strategy) {\n var rect = getBoundingClientRect(element, false, strategy === 'fixed');\n rect.top = rect.top + element.clientTop;\n rect.left = rect.left + element.clientLeft;\n rect.bottom = rect.top + element.clientHeight;\n rect.right = rect.left + element.clientWidth;\n rect.width = element.clientWidth;\n rect.height = element.clientHeight;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\n\nfunction getClientRectFromMixedType(element, clippingParent, strategy) {\n return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));\n} // A \"clipping parent\" is an overflowable container with the characteristic of\n// clipping (or hiding) overflowing elements with a position different from\n// `initial`\n\n\nfunction getClippingParents(element) {\n var clippingParents = listScrollParents(getParentNode(element));\n var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;\n var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;\n\n if (!isElement(clipperElement)) {\n return [];\n } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414\n\n\n return clippingParents.filter(function (clippingParent) {\n return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';\n });\n} // Gets the maximum area that the element is visible in due to any number of\n// clipping parents\n\n\nexport default function getClippingRect(element, boundary, rootBoundary, strategy) {\n var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);\n var clippingParents = [].concat(mainClippingParents, [rootBoundary]);\n var firstClippingParent = clippingParents[0];\n var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {\n var rect = getClientRectFromMixedType(element, clippingParent, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromMixedType(element, firstClippingParent, strategy));\n clippingRect.width = clippingRect.right - clippingRect.left;\n clippingRect.height = clippingRect.bottom - clippingRect.top;\n clippingRect.x = clippingRect.left;\n clippingRect.y = clippingRect.top;\n return clippingRect;\n}","import getWindow from \"./getWindow.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getViewportRect(element, strategy) {\n var win = getWindow(element);\n var html = getDocumentElement(element);\n var visualViewport = win.visualViewport;\n var width = html.clientWidth;\n var height = html.clientHeight;\n var x = 0;\n var y = 0;\n\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n var layoutViewport = isLayoutViewport();\n\n if (layoutViewport || !layoutViewport && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n\n return {\n width: width,\n height: height,\n x: x + getWindowScrollBarX(element),\n y: y\n };\n}","import getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nimport { max } from \"../utils/math.js\"; // Gets the entire size of the scrollable document area, even extending outside\n// of the `` and `` rect bounds if horizontally scrollable\n\nexport default function getDocumentRect(element) {\n var _element$ownerDocumen;\n\n var html = getDocumentElement(element);\n var winScroll = getWindowScroll(element);\n var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;\n var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);\n var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);\n var x = -winScroll.scrollLeft + getWindowScrollBarX(element);\n var y = -winScroll.scrollTop;\n\n if (getComputedStyle(body || html).direction === 'rtl') {\n x += max(html.clientWidth, body ? body.clientWidth : 0) - width;\n }\n\n return {\n width: width,\n height: height,\n x: x,\n y: y\n };\n}","import getBasePlacement from \"./getBasePlacement.js\";\nimport getVariation from \"./getVariation.js\";\nimport getMainAxisFromPlacement from \"./getMainAxisFromPlacement.js\";\nimport { top, right, bottom, left, start, end } from \"../enums.js\";\nexport default function computeOffsets(_ref) {\n var reference = _ref.reference,\n element = _ref.element,\n placement = _ref.placement;\n var basePlacement = placement ? getBasePlacement(placement) : null;\n var variation = placement ? getVariation(placement) : null;\n var commonX = reference.x + reference.width / 2 - element.width / 2;\n var commonY = reference.y + reference.height / 2 - element.height / 2;\n var offsets;\n\n switch (basePlacement) {\n case top:\n offsets = {\n x: commonX,\n y: reference.y - element.height\n };\n break;\n\n case bottom:\n offsets = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n\n case right:\n offsets = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n\n case left:\n offsets = {\n x: reference.x - element.width,\n y: commonY\n };\n break;\n\n default:\n offsets = {\n x: reference.x,\n y: reference.y\n };\n }\n\n var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;\n\n if (mainAxis != null) {\n var len = mainAxis === 'y' ? 'height' : 'width';\n\n switch (variation) {\n case start:\n offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);\n break;\n\n case end:\n offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);\n break;\n\n default:\n }\n }\n\n return offsets;\n}","import getClippingRect from \"../dom-utils/getClippingRect.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getBoundingClientRect from \"../dom-utils/getBoundingClientRect.js\";\nimport computeOffsets from \"./computeOffsets.js\";\nimport rectToClientRect from \"./rectToClientRect.js\";\nimport { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from \"../enums.js\";\nimport { isElement } from \"../dom-utils/instanceOf.js\";\nimport mergePaddingObject from \"./mergePaddingObject.js\";\nimport expandToHashMap from \"./expandToHashMap.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport default function detectOverflow(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$placement = _options.placement,\n placement = _options$placement === void 0 ? state.placement : _options$placement,\n _options$strategy = _options.strategy,\n strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,\n _options$boundary = _options.boundary,\n boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,\n _options$rootBoundary = _options.rootBoundary,\n rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,\n _options$elementConte = _options.elementContext,\n elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,\n _options$altBoundary = _options.altBoundary,\n altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,\n _options$padding = _options.padding,\n padding = _options$padding === void 0 ? 0 : _options$padding;\n var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n var altContext = elementContext === popper ? reference : popper;\n var popperRect = state.rects.popper;\n var element = state.elements[altBoundary ? altContext : elementContext];\n var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);\n var referenceClientRect = getBoundingClientRect(state.elements.reference);\n var popperOffsets = computeOffsets({\n reference: referenceClientRect,\n element: popperRect,\n strategy: 'absolute',\n placement: placement\n });\n var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));\n var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect\n // 0 or negative = within the clipping rect\n\n var overflowOffsets = {\n top: clippingClientRect.top - elementClientRect.top + paddingObject.top,\n bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,\n left: clippingClientRect.left - elementClientRect.left + paddingObject.left,\n right: elementClientRect.right - clippingClientRect.right + paddingObject.right\n };\n var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element\n\n if (elementContext === popper && offsetData) {\n var offset = offsetData[placement];\n Object.keys(overflowOffsets).forEach(function (key) {\n var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;\n var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';\n overflowOffsets[key] += offset[axis] * multiply;\n });\n }\n\n return overflowOffsets;\n}","import getOppositePlacement from \"../utils/getOppositePlacement.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getOppositeVariationPlacement from \"../utils/getOppositeVariationPlacement.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport computeAutoPlacement from \"../utils/computeAutoPlacement.js\";\nimport { bottom, top, start, right, left, auto } from \"../enums.js\";\nimport getVariation from \"../utils/getVariation.js\"; // eslint-disable-next-line import/no-unused-modules\n\nfunction getExpandedFallbackPlacements(placement) {\n if (getBasePlacement(placement) === auto) {\n return [];\n }\n\n var oppositePlacement = getOppositePlacement(placement);\n return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];\n}\n\nfunction flip(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n\n if (state.modifiersData[name]._skip) {\n return;\n }\n\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,\n specifiedFallbackPlacements = options.fallbackPlacements,\n padding = options.padding,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n _options$flipVariatio = options.flipVariations,\n flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,\n allowedAutoPlacements = options.allowedAutoPlacements;\n var preferredPlacement = state.options.placement;\n var basePlacement = getBasePlacement(preferredPlacement);\n var isBasePlacement = basePlacement === preferredPlacement;\n var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));\n var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {\n return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n flipVariations: flipVariations,\n allowedAutoPlacements: allowedAutoPlacements\n }) : placement);\n }, []);\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var checksMap = new Map();\n var makeFallbackChecks = true;\n var firstFittingPlacement = placements[0];\n\n for (var i = 0; i < placements.length; i++) {\n var placement = placements[i];\n\n var _basePlacement = getBasePlacement(placement);\n\n var isStartVariation = getVariation(placement) === start;\n var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;\n var len = isVertical ? 'width' : 'height';\n var overflow = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n altBoundary: altBoundary,\n padding: padding\n });\n var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;\n\n if (referenceRect[len] > popperRect[len]) {\n mainVariationSide = getOppositePlacement(mainVariationSide);\n }\n\n var altVariationSide = getOppositePlacement(mainVariationSide);\n var checks = [];\n\n if (checkMainAxis) {\n checks.push(overflow[_basePlacement] <= 0);\n }\n\n if (checkAltAxis) {\n checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);\n }\n\n if (checks.every(function (check) {\n return check;\n })) {\n firstFittingPlacement = placement;\n makeFallbackChecks = false;\n break;\n }\n\n checksMap.set(placement, checks);\n }\n\n if (makeFallbackChecks) {\n // `2` may be desired in some cases – research later\n var numberOfChecks = flipVariations ? 3 : 1;\n\n var _loop = function _loop(_i) {\n var fittingPlacement = placements.find(function (placement) {\n var checks = checksMap.get(placement);\n\n if (checks) {\n return checks.slice(0, _i).every(function (check) {\n return check;\n });\n }\n });\n\n if (fittingPlacement) {\n firstFittingPlacement = fittingPlacement;\n return \"break\";\n }\n };\n\n for (var _i = numberOfChecks; _i > 0; _i--) {\n var _ret = _loop(_i);\n\n if (_ret === \"break\") break;\n }\n }\n\n if (state.placement !== firstFittingPlacement) {\n state.modifiersData[name]._skip = true;\n state.placement = firstFittingPlacement;\n state.reset = true;\n }\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'flip',\n enabled: true,\n phase: 'main',\n fn: flip,\n requiresIfExists: ['offset'],\n data: {\n _skip: false\n }\n};","import getVariation from \"./getVariation.js\";\nimport { variationPlacements, basePlacements, placements as allPlacements } from \"../enums.js\";\nimport detectOverflow from \"./detectOverflow.js\";\nimport getBasePlacement from \"./getBasePlacement.js\";\nexport default function computeAutoPlacement(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n placement = _options.placement,\n boundary = _options.boundary,\n rootBoundary = _options.rootBoundary,\n padding = _options.padding,\n flipVariations = _options.flipVariations,\n _options$allowedAutoP = _options.allowedAutoPlacements,\n allowedAutoPlacements = _options$allowedAutoP === void 0 ? allPlacements : _options$allowedAutoP;\n var variation = getVariation(placement);\n var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {\n return getVariation(placement) === variation;\n }) : basePlacements;\n var allowedPlacements = placements.filter(function (placement) {\n return allowedAutoPlacements.indexOf(placement) >= 0;\n });\n\n if (allowedPlacements.length === 0) {\n allowedPlacements = placements;\n } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...\n\n\n var overflows = allowedPlacements.reduce(function (acc, placement) {\n acc[placement] = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding\n })[getBasePlacement(placement)];\n return acc;\n }, {});\n return Object.keys(overflows).sort(function (a, b) {\n return overflows[a] - overflows[b];\n });\n}","import { top, bottom, left, right } from \"../enums.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\n\nfunction getSideOffsets(overflow, rect, preventedOffsets) {\n if (preventedOffsets === void 0) {\n preventedOffsets = {\n x: 0,\n y: 0\n };\n }\n\n return {\n top: overflow.top - rect.height - preventedOffsets.y,\n right: overflow.right - rect.width + preventedOffsets.x,\n bottom: overflow.bottom - rect.height + preventedOffsets.y,\n left: overflow.left - rect.width - preventedOffsets.x\n };\n}\n\nfunction isAnySideFullyClipped(overflow) {\n return [top, right, bottom, left].some(function (side) {\n return overflow[side] >= 0;\n });\n}\n\nfunction hide(_ref) {\n var state = _ref.state,\n name = _ref.name;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var preventedOffsets = state.modifiersData.preventOverflow;\n var referenceOverflow = detectOverflow(state, {\n elementContext: 'reference'\n });\n var popperAltOverflow = detectOverflow(state, {\n altBoundary: true\n });\n var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);\n var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);\n var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);\n var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);\n state.modifiersData[name] = {\n referenceClippingOffsets: referenceClippingOffsets,\n popperEscapeOffsets: popperEscapeOffsets,\n isReferenceHidden: isReferenceHidden,\n hasPopperEscaped: hasPopperEscaped\n };\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-reference-hidden': isReferenceHidden,\n 'data-popper-escaped': hasPopperEscaped\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'hide',\n enabled: true,\n phase: 'main',\n requiresIfExists: ['preventOverflow'],\n fn: hide\n};","import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport { top, left, right, placements } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport function distanceAndSkiddingToXY(placement, rects, offset) {\n var basePlacement = getBasePlacement(placement);\n var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;\n\n var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {\n placement: placement\n })) : offset,\n skidding = _ref[0],\n distance = _ref[1];\n\n skidding = skidding || 0;\n distance = (distance || 0) * invertDistance;\n return [left, right].indexOf(basePlacement) >= 0 ? {\n x: distance,\n y: skidding\n } : {\n x: skidding,\n y: distance\n };\n}\n\nfunction offset(_ref2) {\n var state = _ref2.state,\n options = _ref2.options,\n name = _ref2.name;\n var _options$offset = options.offset,\n offset = _options$offset === void 0 ? [0, 0] : _options$offset;\n var data = placements.reduce(function (acc, placement) {\n acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);\n return acc;\n }, {});\n var _data$state$placement = data[state.placement],\n x = _data$state$placement.x,\n y = _data$state$placement.y;\n\n if (state.modifiersData.popperOffsets != null) {\n state.modifiersData.popperOffsets.x += x;\n state.modifiersData.popperOffsets.y += y;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'offset',\n enabled: true,\n phase: 'main',\n requires: ['popperOffsets'],\n fn: offset\n};","import computeOffsets from \"../utils/computeOffsets.js\";\n\nfunction popperOffsets(_ref) {\n var state = _ref.state,\n name = _ref.name;\n // Offsets are the actual position the popper needs to have to be\n // properly positioned near its reference element\n // This is the most basic placement, and will be adjusted by\n // the modifiers in the next step\n state.modifiersData[name] = computeOffsets({\n reference: state.rects.reference,\n element: state.rects.popper,\n strategy: 'absolute',\n placement: state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'popperOffsets',\n enabled: true,\n phase: 'read',\n fn: popperOffsets,\n data: {}\n};","import { top, left, right, bottom, start } from \"../enums.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport getAltAxis from \"../utils/getAltAxis.js\";\nimport { within, withinMaxClamp } from \"../utils/within.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport getFreshSideObject from \"../utils/getFreshSideObject.js\";\nimport { min as mathMin, max as mathMax } from \"../utils/math.js\";\n\nfunction preventOverflow(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n padding = options.padding,\n _options$tether = options.tether,\n tether = _options$tether === void 0 ? true : _options$tether,\n _options$tetherOffset = options.tetherOffset,\n tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;\n var overflow = detectOverflow(state, {\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n altBoundary: altBoundary\n });\n var basePlacement = getBasePlacement(state.placement);\n var variation = getVariation(state.placement);\n var isBasePlacement = !variation;\n var mainAxis = getMainAxisFromPlacement(basePlacement);\n var altAxis = getAltAxis(mainAxis);\n var popperOffsets = state.modifiersData.popperOffsets;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {\n placement: state.placement\n })) : tetherOffset;\n var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {\n mainAxis: tetherOffsetValue,\n altAxis: tetherOffsetValue\n } : Object.assign({\n mainAxis: 0,\n altAxis: 0\n }, tetherOffsetValue);\n var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;\n var data = {\n x: 0,\n y: 0\n };\n\n if (!popperOffsets) {\n return;\n }\n\n if (checkMainAxis) {\n var _offsetModifierState$;\n\n var mainSide = mainAxis === 'y' ? top : left;\n var altSide = mainAxis === 'y' ? bottom : right;\n var len = mainAxis === 'y' ? 'height' : 'width';\n var offset = popperOffsets[mainAxis];\n var min = offset + overflow[mainSide];\n var max = offset - overflow[altSide];\n var additive = tether ? -popperRect[len] / 2 : 0;\n var minLen = variation === start ? referenceRect[len] : popperRect[len];\n var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go\n // outside the reference bounds\n\n var arrowElement = state.elements.arrow;\n var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {\n width: 0,\n height: 0\n };\n var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();\n var arrowPaddingMin = arrowPaddingObject[mainSide];\n var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want\n // to include its full size in the calculation. If the reference is small\n // and near the edge of a boundary, the popper can overflow even if the\n // reference is not overflowing as well (e.g. virtual elements with no\n // width or height)\n\n var arrowLen = within(0, referenceRect[len], arrowRect[len]);\n var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;\n var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;\n var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);\n var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;\n var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;\n var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;\n var tetherMax = offset + maxOffset - offsetModifierValue;\n var preventedOffset = within(tether ? mathMin(min, tetherMin) : min, offset, tether ? mathMax(max, tetherMax) : max);\n popperOffsets[mainAxis] = preventedOffset;\n data[mainAxis] = preventedOffset - offset;\n }\n\n if (checkAltAxis) {\n var _offsetModifierState$2;\n\n var _mainSide = mainAxis === 'x' ? top : left;\n\n var _altSide = mainAxis === 'x' ? bottom : right;\n\n var _offset = popperOffsets[altAxis];\n\n var _len = altAxis === 'y' ? 'height' : 'width';\n\n var _min = _offset + overflow[_mainSide];\n\n var _max = _offset - overflow[_altSide];\n\n var isOriginSide = [top, left].indexOf(basePlacement) !== -1;\n\n var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;\n\n var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;\n\n var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;\n\n var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);\n\n popperOffsets[altAxis] = _preventedOffset;\n data[altAxis] = _preventedOffset - _offset;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'preventOverflow',\n enabled: true,\n phase: 'main',\n fn: preventOverflow,\n requiresIfExists: ['offset']\n};","export default function getAltAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getNodeScroll from \"./getNodeScroll.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport { round } from \"../utils/math.js\";\n\nfunction isElementScaled(element) {\n var rect = element.getBoundingClientRect();\n var scaleX = round(rect.width) / element.offsetWidth || 1;\n var scaleY = round(rect.height) / element.offsetHeight || 1;\n return scaleX !== 1 || scaleY !== 1;\n} // Returns the composite rect of an element relative to its offsetParent.\n// Composite means it takes into account transforms as well as layout.\n\n\nexport default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n\n var isOffsetParentAnElement = isHTMLElement(offsetParent);\n var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);\n var documentElement = getDocumentElement(offsetParent);\n var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);\n var scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n var offsets = {\n x: 0,\n y: 0\n };\n\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078\n isScrollParent(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n\n if (isHTMLElement(offsetParent)) {\n offsets = getBoundingClientRect(offsetParent, true);\n offsets.x += offsetParent.clientLeft;\n offsets.y += offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n\n return {\n x: rect.left + scroll.scrollLeft - offsets.x,\n y: rect.top + scroll.scrollTop - offsets.y,\n width: rect.width,\n height: rect.height\n };\n}","import getWindowScroll from \"./getWindowScroll.js\";\nimport getWindow from \"./getWindow.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getHTMLElementScroll from \"./getHTMLElementScroll.js\";\nexport default function getNodeScroll(node) {\n if (node === getWindow(node) || !isHTMLElement(node)) {\n return getWindowScroll(node);\n } else {\n return getHTMLElementScroll(node);\n }\n}","export default function getHTMLElementScroll(element) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n}","import { modifierPhases } from \"../enums.js\"; // source: https://stackoverflow.com/questions/49875255\n\nfunction order(modifiers) {\n var map = new Map();\n var visited = new Set();\n var result = [];\n modifiers.forEach(function (modifier) {\n map.set(modifier.name, modifier);\n }); // On visiting object, check for its dependencies and visit them recursively\n\n function sort(modifier) {\n visited.add(modifier.name);\n var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);\n requires.forEach(function (dep) {\n if (!visited.has(dep)) {\n var depModifier = map.get(dep);\n\n if (depModifier) {\n sort(depModifier);\n }\n }\n });\n result.push(modifier);\n }\n\n modifiers.forEach(function (modifier) {\n if (!visited.has(modifier.name)) {\n // check for visited object\n sort(modifier);\n }\n });\n return result;\n}\n\nexport default function orderModifiers(modifiers) {\n // order based on dependencies\n var orderedModifiers = order(modifiers); // order based on phase\n\n return modifierPhases.reduce(function (acc, phase) {\n return acc.concat(orderedModifiers.filter(function (modifier) {\n return modifier.phase === phase;\n }));\n }, []);\n}","import getCompositeRect from \"./dom-utils/getCompositeRect.js\";\nimport getLayoutRect from \"./dom-utils/getLayoutRect.js\";\nimport listScrollParents from \"./dom-utils/listScrollParents.js\";\nimport getOffsetParent from \"./dom-utils/getOffsetParent.js\";\nimport orderModifiers from \"./utils/orderModifiers.js\";\nimport debounce from \"./utils/debounce.js\";\nimport mergeByName from \"./utils/mergeByName.js\";\nimport detectOverflow from \"./utils/detectOverflow.js\";\nimport { isElement } from \"./dom-utils/instanceOf.js\";\nvar DEFAULT_OPTIONS = {\n placement: 'bottom',\n modifiers: [],\n strategy: 'absolute'\n};\n\nfunction areValidElements() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return !args.some(function (element) {\n return !(element && typeof element.getBoundingClientRect === 'function');\n });\n}\n\nexport function popperGenerator(generatorOptions) {\n if (generatorOptions === void 0) {\n generatorOptions = {};\n }\n\n var _generatorOptions = generatorOptions,\n _generatorOptions$def = _generatorOptions.defaultModifiers,\n defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,\n _generatorOptions$def2 = _generatorOptions.defaultOptions,\n defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;\n return function createPopper(reference, popper, options) {\n if (options === void 0) {\n options = defaultOptions;\n }\n\n var state = {\n placement: 'bottom',\n orderedModifiers: [],\n options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),\n modifiersData: {},\n elements: {\n reference: reference,\n popper: popper\n },\n attributes: {},\n styles: {}\n };\n var effectCleanupFns = [];\n var isDestroyed = false;\n var instance = {\n state: state,\n setOptions: function setOptions(setOptionsAction) {\n var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;\n cleanupModifierEffects();\n state.options = Object.assign({}, defaultOptions, state.options, options);\n state.scrollParents = {\n reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],\n popper: listScrollParents(popper)\n }; // Orders the modifiers based on their dependencies and `phase`\n // properties\n\n var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers\n\n state.orderedModifiers = orderedModifiers.filter(function (m) {\n return m.enabled;\n });\n runModifierEffects();\n return instance.update();\n },\n // Sync update – it will always be executed, even if not necessary. This\n // is useful for low frequency updates where sync behavior simplifies the\n // logic.\n // For high frequency updates (e.g. `resize` and `scroll` events), always\n // prefer the async Popper#update method\n forceUpdate: function forceUpdate() {\n if (isDestroyed) {\n return;\n }\n\n var _state$elements = state.elements,\n reference = _state$elements.reference,\n popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements\n // anymore\n\n if (!areValidElements(reference, popper)) {\n return;\n } // Store the reference and popper rects to be read by modifiers\n\n\n state.rects = {\n reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),\n popper: getLayoutRect(popper)\n }; // Modifiers have the ability to reset the current update cycle. The\n // most common use case for this is the `flip` modifier changing the\n // placement, which then needs to re-run all the modifiers, because the\n // logic was previously ran for the previous placement and is therefore\n // stale/incorrect\n\n state.reset = false;\n state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier\n // is filled with the initial data specified by the modifier. This means\n // it doesn't persist and is fresh on each update.\n // To ensure persistent data, use `${name}#persistent`\n\n state.orderedModifiers.forEach(function (modifier) {\n return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);\n });\n\n for (var index = 0; index < state.orderedModifiers.length; index++) {\n if (state.reset === true) {\n state.reset = false;\n index = -1;\n continue;\n }\n\n var _state$orderedModifie = state.orderedModifiers[index],\n fn = _state$orderedModifie.fn,\n _state$orderedModifie2 = _state$orderedModifie.options,\n _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,\n name = _state$orderedModifie.name;\n\n if (typeof fn === 'function') {\n state = fn({\n state: state,\n options: _options,\n name: name,\n instance: instance\n }) || state;\n }\n }\n },\n // Async and optimistically optimized update – it will not be executed if\n // not necessary (debounced to run at most once-per-tick)\n update: debounce(function () {\n return new Promise(function (resolve) {\n instance.forceUpdate();\n resolve(state);\n });\n }),\n destroy: function destroy() {\n cleanupModifierEffects();\n isDestroyed = true;\n }\n };\n\n if (!areValidElements(reference, popper)) {\n return instance;\n }\n\n instance.setOptions(options).then(function (state) {\n if (!isDestroyed && options.onFirstUpdate) {\n options.onFirstUpdate(state);\n }\n }); // Modifiers have the ability to execute arbitrary code before the first\n // update cycle runs. They will be executed in the same order as the update\n // cycle. This is useful when a modifier adds some persistent data that\n // other modifiers need to use, but the modifier is run after the dependent\n // one.\n\n function runModifierEffects() {\n state.orderedModifiers.forEach(function (_ref) {\n var name = _ref.name,\n _ref$options = _ref.options,\n options = _ref$options === void 0 ? {} : _ref$options,\n effect = _ref.effect;\n\n if (typeof effect === 'function') {\n var cleanupFn = effect({\n state: state,\n name: name,\n instance: instance,\n options: options\n });\n\n var noopFn = function noopFn() {};\n\n effectCleanupFns.push(cleanupFn || noopFn);\n }\n });\n }\n\n function cleanupModifierEffects() {\n effectCleanupFns.forEach(function (fn) {\n return fn();\n });\n effectCleanupFns = [];\n }\n\n return instance;\n };\n}\nexport var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules\n\nexport { detectOverflow };","export default function debounce(fn) {\n var pending;\n return function () {\n if (!pending) {\n pending = new Promise(function (resolve) {\n Promise.resolve().then(function () {\n pending = undefined;\n resolve(fn());\n });\n });\n }\n\n return pending;\n };\n}","export default function mergeByName(modifiers) {\n var merged = modifiers.reduce(function (merged, current) {\n var existing = merged[current.name];\n merged[current.name] = existing ? Object.assign({}, existing, current, {\n options: Object.assign({}, existing.options, current.options),\n data: Object.assign({}, existing.data, current.data)\n }) : current;\n return merged;\n }, {}); // IE11 does not support Object.values\n\n return Object.keys(merged).map(function (key) {\n return merged[key];\n });\n}","import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nimport offset from \"./modifiers/offset.js\";\nimport flip from \"./modifiers/flip.js\";\nimport preventOverflow from \"./modifiers/preventOverflow.js\";\nimport arrow from \"./modifiers/arrow.js\";\nimport hide from \"./modifiers/hide.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles, offset, flip, preventOverflow, arrow, hide];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow }; // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper as createPopperLite } from \"./popper-lite.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport * from \"./modifiers/index.js\";","import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow };","/*!\n * Bootstrap v5.3.3 (https://getbootstrap.com/)\n * Copyright 2011-2024 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n */\nimport * as Popper from '@popperjs/core';\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/data.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n/**\n * Constants\n */\n\nconst elementMap = new Map();\nconst Data = {\n set(element, key, instance) {\n if (!elementMap.has(element)) {\n elementMap.set(element, new Map());\n }\n const instanceMap = elementMap.get(element);\n\n // make it clear we only want one instance per element\n // can be removed later when multiple key/instances are fine to be used\n if (!instanceMap.has(key) && instanceMap.size !== 0) {\n // eslint-disable-next-line no-console\n console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`);\n return;\n }\n instanceMap.set(key, instance);\n },\n get(element, key) {\n if (elementMap.has(element)) {\n return elementMap.get(element).get(key) || null;\n }\n return null;\n },\n remove(element, key) {\n if (!elementMap.has(element)) {\n return;\n }\n const instanceMap = elementMap.get(element);\n instanceMap.delete(key);\n\n // free up element references if there are no instances left for an element\n if (instanceMap.size === 0) {\n elementMap.delete(element);\n }\n }\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/index.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nconst MAX_UID = 1000000;\nconst MILLISECONDS_MULTIPLIER = 1000;\nconst TRANSITION_END = 'transitionend';\n\n/**\n * Properly escape IDs selectors to handle weird IDs\n * @param {string} selector\n * @returns {string}\n */\nconst parseSelector = selector => {\n if (selector && window.CSS && window.CSS.escape) {\n // document.querySelector needs escaping to handle IDs (html5+) containing for instance /\n selector = selector.replace(/#([^\\s\"#']+)/g, (match, id) => `#${CSS.escape(id)}`);\n }\n return selector;\n};\n\n// Shout-out Angus Croll (https://goo.gl/pxwQGp)\nconst toType = object => {\n if (object === null || object === undefined) {\n return `${object}`;\n }\n return Object.prototype.toString.call(object).match(/\\s([a-z]+)/i)[1].toLowerCase();\n};\n\n/**\n * Public Util API\n */\n\nconst getUID = prefix => {\n do {\n prefix += Math.floor(Math.random() * MAX_UID);\n } while (document.getElementById(prefix));\n return prefix;\n};\nconst getTransitionDurationFromElement = element => {\n if (!element) {\n return 0;\n }\n\n // Get transition-duration of the element\n let {\n transitionDuration,\n transitionDelay\n } = window.getComputedStyle(element);\n const floatTransitionDuration = Number.parseFloat(transitionDuration);\n const floatTransitionDelay = Number.parseFloat(transitionDelay);\n\n // Return 0 if element or transition duration is not found\n if (!floatTransitionDuration && !floatTransitionDelay) {\n return 0;\n }\n\n // If multiple durations are defined, take the first\n transitionDuration = transitionDuration.split(',')[0];\n transitionDelay = transitionDelay.split(',')[0];\n return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;\n};\nconst triggerTransitionEnd = element => {\n element.dispatchEvent(new Event(TRANSITION_END));\n};\nconst isElement = object => {\n if (!object || typeof object !== 'object') {\n return false;\n }\n if (typeof object.jquery !== 'undefined') {\n object = object[0];\n }\n return typeof object.nodeType !== 'undefined';\n};\nconst getElement = object => {\n // it's a jQuery object or a node element\n if (isElement(object)) {\n return object.jquery ? object[0] : object;\n }\n if (typeof object === 'string' && object.length > 0) {\n return document.querySelector(parseSelector(object));\n }\n return null;\n};\nconst isVisible = element => {\n if (!isElement(element) || element.getClientRects().length === 0) {\n return false;\n }\n const elementIsVisible = getComputedStyle(element).getPropertyValue('visibility') === 'visible';\n // Handle `details` element as its content may falsie appear visible when it is closed\n const closedDetails = element.closest('details:not([open])');\n if (!closedDetails) {\n return elementIsVisible;\n }\n if (closedDetails !== element) {\n const summary = element.closest('summary');\n if (summary && summary.parentNode !== closedDetails) {\n return false;\n }\n if (summary === null) {\n return false;\n }\n }\n return elementIsVisible;\n};\nconst isDisabled = element => {\n if (!element || element.nodeType !== Node.ELEMENT_NODE) {\n return true;\n }\n if (element.classList.contains('disabled')) {\n return true;\n }\n if (typeof element.disabled !== 'undefined') {\n return element.disabled;\n }\n return element.hasAttribute('disabled') && element.getAttribute('disabled') !== 'false';\n};\nconst findShadowRoot = element => {\n if (!document.documentElement.attachShadow) {\n return null;\n }\n\n // Can find the shadow root otherwise it'll return the document\n if (typeof element.getRootNode === 'function') {\n const root = element.getRootNode();\n return root instanceof ShadowRoot ? root : null;\n }\n if (element instanceof ShadowRoot) {\n return element;\n }\n\n // when we don't find a shadow root\n if (!element.parentNode) {\n return null;\n }\n return findShadowRoot(element.parentNode);\n};\nconst noop = () => {};\n\n/**\n * Trick to restart an element's animation\n *\n * @param {HTMLElement} element\n * @return void\n *\n * @see https://www.charistheo.io/blog/2021/02/restart-a-css-animation-with-javascript/#restarting-a-css-animation\n */\nconst reflow = element => {\n element.offsetHeight; // eslint-disable-line no-unused-expressions\n};\nconst getjQuery = () => {\n if (window.jQuery && !document.body.hasAttribute('data-bs-no-jquery')) {\n return window.jQuery;\n }\n return null;\n};\nconst DOMContentLoadedCallbacks = [];\nconst onDOMContentLoaded = callback => {\n if (document.readyState === 'loading') {\n // add listener on the first call when the document is in loading state\n if (!DOMContentLoadedCallbacks.length) {\n document.addEventListener('DOMContentLoaded', () => {\n for (const callback of DOMContentLoadedCallbacks) {\n callback();\n }\n });\n }\n DOMContentLoadedCallbacks.push(callback);\n } else {\n callback();\n }\n};\nconst isRTL = () => document.documentElement.dir === 'rtl';\nconst defineJQueryPlugin = plugin => {\n onDOMContentLoaded(() => {\n const $ = getjQuery();\n /* istanbul ignore if */\n if ($) {\n const name = plugin.NAME;\n const JQUERY_NO_CONFLICT = $.fn[name];\n $.fn[name] = plugin.jQueryInterface;\n $.fn[name].Constructor = plugin;\n $.fn[name].noConflict = () => {\n $.fn[name] = JQUERY_NO_CONFLICT;\n return plugin.jQueryInterface;\n };\n }\n });\n};\nconst execute = (possibleCallback, args = [], defaultValue = possibleCallback) => {\n return typeof possibleCallback === 'function' ? possibleCallback(...args) : defaultValue;\n};\nconst executeAfterTransition = (callback, transitionElement, waitForTransition = true) => {\n if (!waitForTransition) {\n execute(callback);\n return;\n }\n const durationPadding = 5;\n const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding;\n let called = false;\n const handler = ({\n target\n }) => {\n if (target !== transitionElement) {\n return;\n }\n called = true;\n transitionElement.removeEventListener(TRANSITION_END, handler);\n execute(callback);\n };\n transitionElement.addEventListener(TRANSITION_END, handler);\n setTimeout(() => {\n if (!called) {\n triggerTransitionEnd(transitionElement);\n }\n }, emulatedDuration);\n};\n\n/**\n * Return the previous/next element of a list.\n *\n * @param {array} list The list of elements\n * @param activeElement The active element\n * @param shouldGetNext Choose to get next or previous element\n * @param isCycleAllowed\n * @return {Element|elem} The proper element\n */\nconst getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => {\n const listLength = list.length;\n let index = list.indexOf(activeElement);\n\n // if the element does not exist in the list return an element\n // depending on the direction and if cycle is allowed\n if (index === -1) {\n return !shouldGetNext && isCycleAllowed ? list[listLength - 1] : list[0];\n }\n index += shouldGetNext ? 1 : -1;\n if (isCycleAllowed) {\n index = (index + listLength) % listLength;\n }\n return list[Math.max(0, Math.min(index, listLength - 1))];\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/event-handler.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst namespaceRegex = /[^.]*(?=\\..*)\\.|.*/;\nconst stripNameRegex = /\\..*/;\nconst stripUidRegex = /::\\d+$/;\nconst eventRegistry = {}; // Events storage\nlet uidEvent = 1;\nconst customEvents = {\n mouseenter: 'mouseover',\n mouseleave: 'mouseout'\n};\nconst nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout', 'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange', 'error', 'abort', 'scroll']);\n\n/**\n * Private methods\n */\n\nfunction makeEventUid(element, uid) {\n return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++;\n}\nfunction getElementEvents(element) {\n const uid = makeEventUid(element);\n element.uidEvent = uid;\n eventRegistry[uid] = eventRegistry[uid] || {};\n return eventRegistry[uid];\n}\nfunction bootstrapHandler(element, fn) {\n return function handler(event) {\n hydrateObj(event, {\n delegateTarget: element\n });\n if (handler.oneOff) {\n EventHandler.off(element, event.type, fn);\n }\n return fn.apply(element, [event]);\n };\n}\nfunction bootstrapDelegationHandler(element, selector, fn) {\n return function handler(event) {\n const domElements = element.querySelectorAll(selector);\n for (let {\n target\n } = event; target && target !== this; target = target.parentNode) {\n for (const domElement of domElements) {\n if (domElement !== target) {\n continue;\n }\n hydrateObj(event, {\n delegateTarget: target\n });\n if (handler.oneOff) {\n EventHandler.off(element, event.type, selector, fn);\n }\n return fn.apply(target, [event]);\n }\n }\n };\n}\nfunction findHandler(events, callable, delegationSelector = null) {\n return Object.values(events).find(event => event.callable === callable && event.delegationSelector === delegationSelector);\n}\nfunction normalizeParameters(originalTypeEvent, handler, delegationFunction) {\n const isDelegated = typeof handler === 'string';\n // TODO: tooltip passes `false` instead of selector, so we need to check\n const callable = isDelegated ? delegationFunction : handler || delegationFunction;\n let typeEvent = getTypeEvent(originalTypeEvent);\n if (!nativeEvents.has(typeEvent)) {\n typeEvent = originalTypeEvent;\n }\n return [isDelegated, callable, typeEvent];\n}\nfunction addHandler(element, originalTypeEvent, handler, delegationFunction, oneOff) {\n if (typeof originalTypeEvent !== 'string' || !element) {\n return;\n }\n let [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction);\n\n // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position\n // this prevents the handler from being dispatched the same way as mouseover or mouseout does\n if (originalTypeEvent in customEvents) {\n const wrapFunction = fn => {\n return function (event) {\n if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) {\n return fn.call(this, event);\n }\n };\n };\n callable = wrapFunction(callable);\n }\n const events = getElementEvents(element);\n const handlers = events[typeEvent] || (events[typeEvent] = {});\n const previousFunction = findHandler(handlers, callable, isDelegated ? handler : null);\n if (previousFunction) {\n previousFunction.oneOff = previousFunction.oneOff && oneOff;\n return;\n }\n const uid = makeEventUid(callable, originalTypeEvent.replace(namespaceRegex, ''));\n const fn = isDelegated ? bootstrapDelegationHandler(element, handler, callable) : bootstrapHandler(element, callable);\n fn.delegationSelector = isDelegated ? handler : null;\n fn.callable = callable;\n fn.oneOff = oneOff;\n fn.uidEvent = uid;\n handlers[uid] = fn;\n element.addEventListener(typeEvent, fn, isDelegated);\n}\nfunction removeHandler(element, events, typeEvent, handler, delegationSelector) {\n const fn = findHandler(events[typeEvent], handler, delegationSelector);\n if (!fn) {\n return;\n }\n element.removeEventListener(typeEvent, fn, Boolean(delegationSelector));\n delete events[typeEvent][fn.uidEvent];\n}\nfunction removeNamespacedHandlers(element, events, typeEvent, namespace) {\n const storeElementEvent = events[typeEvent] || {};\n for (const [handlerKey, event] of Object.entries(storeElementEvent)) {\n if (handlerKey.includes(namespace)) {\n removeHandler(element, events, typeEvent, event.callable, event.delegationSelector);\n }\n }\n}\nfunction getTypeEvent(event) {\n // allow to get the native events from namespaced events ('click.bs.button' --> 'click')\n event = event.replace(stripNameRegex, '');\n return customEvents[event] || event;\n}\nconst EventHandler = {\n on(element, event, handler, delegationFunction) {\n addHandler(element, event, handler, delegationFunction, false);\n },\n one(element, event, handler, delegationFunction) {\n addHandler(element, event, handler, delegationFunction, true);\n },\n off(element, originalTypeEvent, handler, delegationFunction) {\n if (typeof originalTypeEvent !== 'string' || !element) {\n return;\n }\n const [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction);\n const inNamespace = typeEvent !== originalTypeEvent;\n const events = getElementEvents(element);\n const storeElementEvent = events[typeEvent] || {};\n const isNamespace = originalTypeEvent.startsWith('.');\n if (typeof callable !== 'undefined') {\n // Simplest case: handler is passed, remove that listener ONLY.\n if (!Object.keys(storeElementEvent).length) {\n return;\n }\n removeHandler(element, events, typeEvent, callable, isDelegated ? handler : null);\n return;\n }\n if (isNamespace) {\n for (const elementEvent of Object.keys(events)) {\n removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1));\n }\n }\n for (const [keyHandlers, event] of Object.entries(storeElementEvent)) {\n const handlerKey = keyHandlers.replace(stripUidRegex, '');\n if (!inNamespace || originalTypeEvent.includes(handlerKey)) {\n removeHandler(element, events, typeEvent, event.callable, event.delegationSelector);\n }\n }\n },\n trigger(element, event, args) {\n if (typeof event !== 'string' || !element) {\n return null;\n }\n const $ = getjQuery();\n const typeEvent = getTypeEvent(event);\n const inNamespace = event !== typeEvent;\n let jQueryEvent = null;\n let bubbles = true;\n let nativeDispatch = true;\n let defaultPrevented = false;\n if (inNamespace && $) {\n jQueryEvent = $.Event(event, args);\n $(element).trigger(jQueryEvent);\n bubbles = !jQueryEvent.isPropagationStopped();\n nativeDispatch = !jQueryEvent.isImmediatePropagationStopped();\n defaultPrevented = jQueryEvent.isDefaultPrevented();\n }\n const evt = hydrateObj(new Event(event, {\n bubbles,\n cancelable: true\n }), args);\n if (defaultPrevented) {\n evt.preventDefault();\n }\n if (nativeDispatch) {\n element.dispatchEvent(evt);\n }\n if (evt.defaultPrevented && jQueryEvent) {\n jQueryEvent.preventDefault();\n }\n return evt;\n }\n};\nfunction hydrateObj(obj, meta = {}) {\n for (const [key, value] of Object.entries(meta)) {\n try {\n obj[key] = value;\n } catch (_unused) {\n Object.defineProperty(obj, key, {\n configurable: true,\n get() {\n return value;\n }\n });\n }\n }\n return obj;\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/manipulator.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nfunction normalizeData(value) {\n if (value === 'true') {\n return true;\n }\n if (value === 'false') {\n return false;\n }\n if (value === Number(value).toString()) {\n return Number(value);\n }\n if (value === '' || value === 'null') {\n return null;\n }\n if (typeof value !== 'string') {\n return value;\n }\n try {\n return JSON.parse(decodeURIComponent(value));\n } catch (_unused) {\n return value;\n }\n}\nfunction normalizeDataKey(key) {\n return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`);\n}\nconst Manipulator = {\n setDataAttribute(element, key, value) {\n element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value);\n },\n removeDataAttribute(element, key) {\n element.removeAttribute(`data-bs-${normalizeDataKey(key)}`);\n },\n getDataAttributes(element) {\n if (!element) {\n return {};\n }\n const attributes = {};\n const bsKeys = Object.keys(element.dataset).filter(key => key.startsWith('bs') && !key.startsWith('bsConfig'));\n for (const key of bsKeys) {\n let pureKey = key.replace(/^bs/, '');\n pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);\n attributes[pureKey] = normalizeData(element.dataset[key]);\n }\n return attributes;\n },\n getDataAttribute(element, key) {\n return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`));\n }\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/config.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Class definition\n */\n\nclass Config {\n // Getters\n static get Default() {\n return {};\n }\n static get DefaultType() {\n return {};\n }\n static get NAME() {\n throw new Error('You have to implement the static method \"NAME\", for each component!');\n }\n _getConfig(config) {\n config = this._mergeConfigObj(config);\n config = this._configAfterMerge(config);\n this._typeCheckConfig(config);\n return config;\n }\n _configAfterMerge(config) {\n return config;\n }\n _mergeConfigObj(config, element) {\n const jsonConfig = isElement(element) ? Manipulator.getDataAttribute(element, 'config') : {}; // try to parse\n\n return {\n ...this.constructor.Default,\n ...(typeof jsonConfig === 'object' ? jsonConfig : {}),\n ...(isElement(element) ? Manipulator.getDataAttributes(element) : {}),\n ...(typeof config === 'object' ? config : {})\n };\n }\n _typeCheckConfig(config, configTypes = this.constructor.DefaultType) {\n for (const [property, expectedTypes] of Object.entries(configTypes)) {\n const value = config[property];\n const valueType = isElement(value) ? 'element' : toType(value);\n if (!new RegExp(expectedTypes).test(valueType)) {\n throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option \"${property}\" provided type \"${valueType}\" but expected type \"${expectedTypes}\".`);\n }\n }\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap base-component.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst VERSION = '5.3.3';\n\n/**\n * Class definition\n */\n\nclass BaseComponent extends Config {\n constructor(element, config) {\n super();\n element = getElement(element);\n if (!element) {\n return;\n }\n this._element = element;\n this._config = this._getConfig(config);\n Data.set(this._element, this.constructor.DATA_KEY, this);\n }\n\n // Public\n dispose() {\n Data.remove(this._element, this.constructor.DATA_KEY);\n EventHandler.off(this._element, this.constructor.EVENT_KEY);\n for (const propertyName of Object.getOwnPropertyNames(this)) {\n this[propertyName] = null;\n }\n }\n _queueCallback(callback, element, isAnimated = true) {\n executeAfterTransition(callback, element, isAnimated);\n }\n _getConfig(config) {\n config = this._mergeConfigObj(config, this._element);\n config = this._configAfterMerge(config);\n this._typeCheckConfig(config);\n return config;\n }\n\n // Static\n static getInstance(element) {\n return Data.get(getElement(element), this.DATA_KEY);\n }\n static getOrCreateInstance(element, config = {}) {\n return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null);\n }\n static get VERSION() {\n return VERSION;\n }\n static get DATA_KEY() {\n return `bs.${this.NAME}`;\n }\n static get EVENT_KEY() {\n return `.${this.DATA_KEY}`;\n }\n static eventName(name) {\n return `${name}${this.EVENT_KEY}`;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/selector-engine.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nconst getSelector = element => {\n let selector = element.getAttribute('data-bs-target');\n if (!selector || selector === '#') {\n let hrefAttribute = element.getAttribute('href');\n\n // The only valid content that could double as a selector are IDs or classes,\n // so everything starting with `#` or `.`. If a \"real\" URL is used as the selector,\n // `document.querySelector` will rightfully complain it is invalid.\n // See https://github.com/twbs/bootstrap/issues/32273\n if (!hrefAttribute || !hrefAttribute.includes('#') && !hrefAttribute.startsWith('.')) {\n return null;\n }\n\n // Just in case some CMS puts out a full URL with the anchor appended\n if (hrefAttribute.includes('#') && !hrefAttribute.startsWith('#')) {\n hrefAttribute = `#${hrefAttribute.split('#')[1]}`;\n }\n selector = hrefAttribute && hrefAttribute !== '#' ? hrefAttribute.trim() : null;\n }\n return selector ? selector.split(',').map(sel => parseSelector(sel)).join(',') : null;\n};\nconst SelectorEngine = {\n find(selector, element = document.documentElement) {\n return [].concat(...Element.prototype.querySelectorAll.call(element, selector));\n },\n findOne(selector, element = document.documentElement) {\n return Element.prototype.querySelector.call(element, selector);\n },\n children(element, selector) {\n return [].concat(...element.children).filter(child => child.matches(selector));\n },\n parents(element, selector) {\n const parents = [];\n let ancestor = element.parentNode.closest(selector);\n while (ancestor) {\n parents.push(ancestor);\n ancestor = ancestor.parentNode.closest(selector);\n }\n return parents;\n },\n prev(element, selector) {\n let previous = element.previousElementSibling;\n while (previous) {\n if (previous.matches(selector)) {\n return [previous];\n }\n previous = previous.previousElementSibling;\n }\n return [];\n },\n // TODO: this is now unused; remove later along with prev()\n next(element, selector) {\n let next = element.nextElementSibling;\n while (next) {\n if (next.matches(selector)) {\n return [next];\n }\n next = next.nextElementSibling;\n }\n return [];\n },\n focusableChildren(element) {\n const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable=\"true\"]'].map(selector => `${selector}:not([tabindex^=\"-\"])`).join(',');\n return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el));\n },\n getSelectorFromElement(element) {\n const selector = getSelector(element);\n if (selector) {\n return SelectorEngine.findOne(selector) ? selector : null;\n }\n return null;\n },\n getElementFromSelector(element) {\n const selector = getSelector(element);\n return selector ? SelectorEngine.findOne(selector) : null;\n },\n getMultipleElementsFromSelector(element) {\n const selector = getSelector(element);\n return selector ? SelectorEngine.find(selector) : [];\n }\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/component-functions.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nconst enableDismissTrigger = (component, method = 'hide') => {\n const clickEvent = `click.dismiss${component.EVENT_KEY}`;\n const name = component.NAME;\n EventHandler.on(document, clickEvent, `[data-bs-dismiss=\"${name}\"]`, function (event) {\n if (['A', 'AREA'].includes(this.tagName)) {\n event.preventDefault();\n }\n if (isDisabled(this)) {\n return;\n }\n const target = SelectorEngine.getElementFromSelector(this) || this.closest(`.${name}`);\n const instance = component.getOrCreateInstance(target);\n\n // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method\n instance[method]();\n });\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap alert.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$f = 'alert';\nconst DATA_KEY$a = 'bs.alert';\nconst EVENT_KEY$b = `.${DATA_KEY$a}`;\nconst EVENT_CLOSE = `close${EVENT_KEY$b}`;\nconst EVENT_CLOSED = `closed${EVENT_KEY$b}`;\nconst CLASS_NAME_FADE$5 = 'fade';\nconst CLASS_NAME_SHOW$8 = 'show';\n\n/**\n * Class definition\n */\n\nclass Alert extends BaseComponent {\n // Getters\n static get NAME() {\n return NAME$f;\n }\n\n // Public\n close() {\n const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE);\n if (closeEvent.defaultPrevented) {\n return;\n }\n this._element.classList.remove(CLASS_NAME_SHOW$8);\n const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5);\n this._queueCallback(() => this._destroyElement(), this._element, isAnimated);\n }\n\n // Private\n _destroyElement() {\n this._element.remove();\n EventHandler.trigger(this._element, EVENT_CLOSED);\n this.dispose();\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Alert.getOrCreateInstance(this);\n if (typeof config !== 'string') {\n return;\n }\n if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config](this);\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nenableDismissTrigger(Alert, 'close');\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Alert);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap button.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$e = 'button';\nconst DATA_KEY$9 = 'bs.button';\nconst EVENT_KEY$a = `.${DATA_KEY$9}`;\nconst DATA_API_KEY$6 = '.data-api';\nconst CLASS_NAME_ACTIVE$3 = 'active';\nconst SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle=\"button\"]';\nconst EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`;\n\n/**\n * Class definition\n */\n\nclass Button extends BaseComponent {\n // Getters\n static get NAME() {\n return NAME$e;\n }\n\n // Public\n toggle() {\n // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method\n this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3));\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Button.getOrCreateInstance(this);\n if (config === 'toggle') {\n data[config]();\n }\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => {\n event.preventDefault();\n const button = event.target.closest(SELECTOR_DATA_TOGGLE$5);\n const data = Button.getOrCreateInstance(button);\n data.toggle();\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Button);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/swipe.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$d = 'swipe';\nconst EVENT_KEY$9 = '.bs.swipe';\nconst EVENT_TOUCHSTART = `touchstart${EVENT_KEY$9}`;\nconst EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$9}`;\nconst EVENT_TOUCHEND = `touchend${EVENT_KEY$9}`;\nconst EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$9}`;\nconst EVENT_POINTERUP = `pointerup${EVENT_KEY$9}`;\nconst POINTER_TYPE_TOUCH = 'touch';\nconst POINTER_TYPE_PEN = 'pen';\nconst CLASS_NAME_POINTER_EVENT = 'pointer-event';\nconst SWIPE_THRESHOLD = 40;\nconst Default$c = {\n endCallback: null,\n leftCallback: null,\n rightCallback: null\n};\nconst DefaultType$c = {\n endCallback: '(function|null)',\n leftCallback: '(function|null)',\n rightCallback: '(function|null)'\n};\n\n/**\n * Class definition\n */\n\nclass Swipe extends Config {\n constructor(element, config) {\n super();\n this._element = element;\n if (!element || !Swipe.isSupported()) {\n return;\n }\n this._config = this._getConfig(config);\n this._deltaX = 0;\n this._supportPointerEvents = Boolean(window.PointerEvent);\n this._initEvents();\n }\n\n // Getters\n static get Default() {\n return Default$c;\n }\n static get DefaultType() {\n return DefaultType$c;\n }\n static get NAME() {\n return NAME$d;\n }\n\n // Public\n dispose() {\n EventHandler.off(this._element, EVENT_KEY$9);\n }\n\n // Private\n _start(event) {\n if (!this._supportPointerEvents) {\n this._deltaX = event.touches[0].clientX;\n return;\n }\n if (this._eventIsPointerPenTouch(event)) {\n this._deltaX = event.clientX;\n }\n }\n _end(event) {\n if (this._eventIsPointerPenTouch(event)) {\n this._deltaX = event.clientX - this._deltaX;\n }\n this._handleSwipe();\n execute(this._config.endCallback);\n }\n _move(event) {\n this._deltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this._deltaX;\n }\n _handleSwipe() {\n const absDeltaX = Math.abs(this._deltaX);\n if (absDeltaX <= SWIPE_THRESHOLD) {\n return;\n }\n const direction = absDeltaX / this._deltaX;\n this._deltaX = 0;\n if (!direction) {\n return;\n }\n execute(direction > 0 ? this._config.rightCallback : this._config.leftCallback);\n }\n _initEvents() {\n if (this._supportPointerEvents) {\n EventHandler.on(this._element, EVENT_POINTERDOWN, event => this._start(event));\n EventHandler.on(this._element, EVENT_POINTERUP, event => this._end(event));\n this._element.classList.add(CLASS_NAME_POINTER_EVENT);\n } else {\n EventHandler.on(this._element, EVENT_TOUCHSTART, event => this._start(event));\n EventHandler.on(this._element, EVENT_TOUCHMOVE, event => this._move(event));\n EventHandler.on(this._element, EVENT_TOUCHEND, event => this._end(event));\n }\n }\n _eventIsPointerPenTouch(event) {\n return this._supportPointerEvents && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH);\n }\n\n // Static\n static isSupported() {\n return 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap carousel.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$c = 'carousel';\nconst DATA_KEY$8 = 'bs.carousel';\nconst EVENT_KEY$8 = `.${DATA_KEY$8}`;\nconst DATA_API_KEY$5 = '.data-api';\nconst ARROW_LEFT_KEY$1 = 'ArrowLeft';\nconst ARROW_RIGHT_KEY$1 = 'ArrowRight';\nconst TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch\n\nconst ORDER_NEXT = 'next';\nconst ORDER_PREV = 'prev';\nconst DIRECTION_LEFT = 'left';\nconst DIRECTION_RIGHT = 'right';\nconst EVENT_SLIDE = `slide${EVENT_KEY$8}`;\nconst EVENT_SLID = `slid${EVENT_KEY$8}`;\nconst EVENT_KEYDOWN$1 = `keydown${EVENT_KEY$8}`;\nconst EVENT_MOUSEENTER$1 = `mouseenter${EVENT_KEY$8}`;\nconst EVENT_MOUSELEAVE$1 = `mouseleave${EVENT_KEY$8}`;\nconst EVENT_DRAG_START = `dragstart${EVENT_KEY$8}`;\nconst EVENT_LOAD_DATA_API$3 = `load${EVENT_KEY$8}${DATA_API_KEY$5}`;\nconst EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$8}${DATA_API_KEY$5}`;\nconst CLASS_NAME_CAROUSEL = 'carousel';\nconst CLASS_NAME_ACTIVE$2 = 'active';\nconst CLASS_NAME_SLIDE = 'slide';\nconst CLASS_NAME_END = 'carousel-item-end';\nconst CLASS_NAME_START = 'carousel-item-start';\nconst CLASS_NAME_NEXT = 'carousel-item-next';\nconst CLASS_NAME_PREV = 'carousel-item-prev';\nconst SELECTOR_ACTIVE = '.active';\nconst SELECTOR_ITEM = '.carousel-item';\nconst SELECTOR_ACTIVE_ITEM = SELECTOR_ACTIVE + SELECTOR_ITEM;\nconst SELECTOR_ITEM_IMG = '.carousel-item img';\nconst SELECTOR_INDICATORS = '.carousel-indicators';\nconst SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]';\nconst SELECTOR_DATA_RIDE = '[data-bs-ride=\"carousel\"]';\nconst KEY_TO_DIRECTION = {\n [ARROW_LEFT_KEY$1]: DIRECTION_RIGHT,\n [ARROW_RIGHT_KEY$1]: DIRECTION_LEFT\n};\nconst Default$b = {\n interval: 5000,\n keyboard: true,\n pause: 'hover',\n ride: false,\n touch: true,\n wrap: true\n};\nconst DefaultType$b = {\n interval: '(number|boolean)',\n // TODO:v6 remove boolean support\n keyboard: 'boolean',\n pause: '(string|boolean)',\n ride: '(boolean|string)',\n touch: 'boolean',\n wrap: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Carousel extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._interval = null;\n this._activeElement = null;\n this._isSliding = false;\n this.touchTimeout = null;\n this._swipeHelper = null;\n this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element);\n this._addEventListeners();\n if (this._config.ride === CLASS_NAME_CAROUSEL) {\n this.cycle();\n }\n }\n\n // Getters\n static get Default() {\n return Default$b;\n }\n static get DefaultType() {\n return DefaultType$b;\n }\n static get NAME() {\n return NAME$c;\n }\n\n // Public\n next() {\n this._slide(ORDER_NEXT);\n }\n nextWhenVisible() {\n // FIXME TODO use `document.visibilityState`\n // Don't call next when the page isn't visible\n // or the carousel or its parent isn't visible\n if (!document.hidden && isVisible(this._element)) {\n this.next();\n }\n }\n prev() {\n this._slide(ORDER_PREV);\n }\n pause() {\n if (this._isSliding) {\n triggerTransitionEnd(this._element);\n }\n this._clearInterval();\n }\n cycle() {\n this._clearInterval();\n this._updateInterval();\n this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval);\n }\n _maybeEnableCycle() {\n if (!this._config.ride) {\n return;\n }\n if (this._isSliding) {\n EventHandler.one(this._element, EVENT_SLID, () => this.cycle());\n return;\n }\n this.cycle();\n }\n to(index) {\n const items = this._getItems();\n if (index > items.length - 1 || index < 0) {\n return;\n }\n if (this._isSliding) {\n EventHandler.one(this._element, EVENT_SLID, () => this.to(index));\n return;\n }\n const activeIndex = this._getItemIndex(this._getActive());\n if (activeIndex === index) {\n return;\n }\n const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV;\n this._slide(order, items[index]);\n }\n dispose() {\n if (this._swipeHelper) {\n this._swipeHelper.dispose();\n }\n super.dispose();\n }\n\n // Private\n _configAfterMerge(config) {\n config.defaultInterval = config.interval;\n return config;\n }\n _addEventListeners() {\n if (this._config.keyboard) {\n EventHandler.on(this._element, EVENT_KEYDOWN$1, event => this._keydown(event));\n }\n if (this._config.pause === 'hover') {\n EventHandler.on(this._element, EVENT_MOUSEENTER$1, () => this.pause());\n EventHandler.on(this._element, EVENT_MOUSELEAVE$1, () => this._maybeEnableCycle());\n }\n if (this._config.touch && Swipe.isSupported()) {\n this._addTouchEventListeners();\n }\n }\n _addTouchEventListeners() {\n for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) {\n EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault());\n }\n const endCallBack = () => {\n if (this._config.pause !== 'hover') {\n return;\n }\n\n // If it's a touch-enabled device, mouseenter/leave are fired as\n // part of the mouse compatibility events on first tap - the carousel\n // would stop cycling until user tapped out of it;\n // here, we listen for touchend, explicitly pause the carousel\n // (as if it's the second time we tap on it, mouseenter compat event\n // is NOT fired) and after a timeout (to allow for mouse compatibility\n // events to fire) we explicitly restart cycling\n\n this.pause();\n if (this.touchTimeout) {\n clearTimeout(this.touchTimeout);\n }\n this.touchTimeout = setTimeout(() => this._maybeEnableCycle(), TOUCHEVENT_COMPAT_WAIT + this._config.interval);\n };\n const swipeConfig = {\n leftCallback: () => this._slide(this._directionToOrder(DIRECTION_LEFT)),\n rightCallback: () => this._slide(this._directionToOrder(DIRECTION_RIGHT)),\n endCallback: endCallBack\n };\n this._swipeHelper = new Swipe(this._element, swipeConfig);\n }\n _keydown(event) {\n if (/input|textarea/i.test(event.target.tagName)) {\n return;\n }\n const direction = KEY_TO_DIRECTION[event.key];\n if (direction) {\n event.preventDefault();\n this._slide(this._directionToOrder(direction));\n }\n }\n _getItemIndex(element) {\n return this._getItems().indexOf(element);\n }\n _setActiveIndicatorElement(index) {\n if (!this._indicatorsElement) {\n return;\n }\n const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement);\n activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2);\n activeIndicator.removeAttribute('aria-current');\n const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to=\"${index}\"]`, this._indicatorsElement);\n if (newActiveIndicator) {\n newActiveIndicator.classList.add(CLASS_NAME_ACTIVE$2);\n newActiveIndicator.setAttribute('aria-current', 'true');\n }\n }\n _updateInterval() {\n const element = this._activeElement || this._getActive();\n if (!element) {\n return;\n }\n const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10);\n this._config.interval = elementInterval || this._config.defaultInterval;\n }\n _slide(order, element = null) {\n if (this._isSliding) {\n return;\n }\n const activeElement = this._getActive();\n const isNext = order === ORDER_NEXT;\n const nextElement = element || getNextActiveElement(this._getItems(), activeElement, isNext, this._config.wrap);\n if (nextElement === activeElement) {\n return;\n }\n const nextElementIndex = this._getItemIndex(nextElement);\n const triggerEvent = eventName => {\n return EventHandler.trigger(this._element, eventName, {\n relatedTarget: nextElement,\n direction: this._orderToDirection(order),\n from: this._getItemIndex(activeElement),\n to: nextElementIndex\n });\n };\n const slideEvent = triggerEvent(EVENT_SLIDE);\n if (slideEvent.defaultPrevented) {\n return;\n }\n if (!activeElement || !nextElement) {\n // Some weirdness is happening, so we bail\n // TODO: change tests that use empty divs to avoid this check\n return;\n }\n const isCycling = Boolean(this._interval);\n this.pause();\n this._isSliding = true;\n this._setActiveIndicatorElement(nextElementIndex);\n this._activeElement = nextElement;\n const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END;\n const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV;\n nextElement.classList.add(orderClassName);\n reflow(nextElement);\n activeElement.classList.add(directionalClassName);\n nextElement.classList.add(directionalClassName);\n const completeCallBack = () => {\n nextElement.classList.remove(directionalClassName, orderClassName);\n nextElement.classList.add(CLASS_NAME_ACTIVE$2);\n activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName);\n this._isSliding = false;\n triggerEvent(EVENT_SLID);\n };\n this._queueCallback(completeCallBack, activeElement, this._isAnimated());\n if (isCycling) {\n this.cycle();\n }\n }\n _isAnimated() {\n return this._element.classList.contains(CLASS_NAME_SLIDE);\n }\n _getActive() {\n return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);\n }\n _getItems() {\n return SelectorEngine.find(SELECTOR_ITEM, this._element);\n }\n _clearInterval() {\n if (this._interval) {\n clearInterval(this._interval);\n this._interval = null;\n }\n }\n _directionToOrder(direction) {\n if (isRTL()) {\n return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT;\n }\n return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV;\n }\n _orderToDirection(order) {\n if (isRTL()) {\n return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT;\n }\n return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT;\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Carousel.getOrCreateInstance(this, config);\n if (typeof config === 'number') {\n data.to(config);\n return;\n }\n if (typeof config === 'string') {\n if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n }\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, function (event) {\n const target = SelectorEngine.getElementFromSelector(this);\n if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {\n return;\n }\n event.preventDefault();\n const carousel = Carousel.getOrCreateInstance(target);\n const slideIndex = this.getAttribute('data-bs-slide-to');\n if (slideIndex) {\n carousel.to(slideIndex);\n carousel._maybeEnableCycle();\n return;\n }\n if (Manipulator.getDataAttribute(this, 'slide') === 'next') {\n carousel.next();\n carousel._maybeEnableCycle();\n return;\n }\n carousel.prev();\n carousel._maybeEnableCycle();\n});\nEventHandler.on(window, EVENT_LOAD_DATA_API$3, () => {\n const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE);\n for (const carousel of carousels) {\n Carousel.getOrCreateInstance(carousel);\n }\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Carousel);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap collapse.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$b = 'collapse';\nconst DATA_KEY$7 = 'bs.collapse';\nconst EVENT_KEY$7 = `.${DATA_KEY$7}`;\nconst DATA_API_KEY$4 = '.data-api';\nconst EVENT_SHOW$6 = `show${EVENT_KEY$7}`;\nconst EVENT_SHOWN$6 = `shown${EVENT_KEY$7}`;\nconst EVENT_HIDE$6 = `hide${EVENT_KEY$7}`;\nconst EVENT_HIDDEN$6 = `hidden${EVENT_KEY$7}`;\nconst EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$7}${DATA_API_KEY$4}`;\nconst CLASS_NAME_SHOW$7 = 'show';\nconst CLASS_NAME_COLLAPSE = 'collapse';\nconst CLASS_NAME_COLLAPSING = 'collapsing';\nconst CLASS_NAME_COLLAPSED = 'collapsed';\nconst CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`;\nconst CLASS_NAME_HORIZONTAL = 'collapse-horizontal';\nconst WIDTH = 'width';\nconst HEIGHT = 'height';\nconst SELECTOR_ACTIVES = '.collapse.show, .collapse.collapsing';\nconst SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle=\"collapse\"]';\nconst Default$a = {\n parent: null,\n toggle: true\n};\nconst DefaultType$a = {\n parent: '(null|element)',\n toggle: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Collapse extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._isTransitioning = false;\n this._triggerArray = [];\n const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4);\n for (const elem of toggleList) {\n const selector = SelectorEngine.getSelectorFromElement(elem);\n const filterElement = SelectorEngine.find(selector).filter(foundElement => foundElement === this._element);\n if (selector !== null && filterElement.length) {\n this._triggerArray.push(elem);\n }\n }\n this._initializeChildren();\n if (!this._config.parent) {\n this._addAriaAndCollapsedClass(this._triggerArray, this._isShown());\n }\n if (this._config.toggle) {\n this.toggle();\n }\n }\n\n // Getters\n static get Default() {\n return Default$a;\n }\n static get DefaultType() {\n return DefaultType$a;\n }\n static get NAME() {\n return NAME$b;\n }\n\n // Public\n toggle() {\n if (this._isShown()) {\n this.hide();\n } else {\n this.show();\n }\n }\n show() {\n if (this._isTransitioning || this._isShown()) {\n return;\n }\n let activeChildren = [];\n\n // find active children\n if (this._config.parent) {\n activeChildren = this._getFirstLevelChildren(SELECTOR_ACTIVES).filter(element => element !== this._element).map(element => Collapse.getOrCreateInstance(element, {\n toggle: false\n }));\n }\n if (activeChildren.length && activeChildren[0]._isTransitioning) {\n return;\n }\n const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$6);\n if (startEvent.defaultPrevented) {\n return;\n }\n for (const activeInstance of activeChildren) {\n activeInstance.hide();\n }\n const dimension = this._getDimension();\n this._element.classList.remove(CLASS_NAME_COLLAPSE);\n this._element.classList.add(CLASS_NAME_COLLAPSING);\n this._element.style[dimension] = 0;\n this._addAriaAndCollapsedClass(this._triggerArray, true);\n this._isTransitioning = true;\n const complete = () => {\n this._isTransitioning = false;\n this._element.classList.remove(CLASS_NAME_COLLAPSING);\n this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7);\n this._element.style[dimension] = '';\n EventHandler.trigger(this._element, EVENT_SHOWN$6);\n };\n const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);\n const scrollSize = `scroll${capitalizedDimension}`;\n this._queueCallback(complete, this._element, true);\n this._element.style[dimension] = `${this._element[scrollSize]}px`;\n }\n hide() {\n if (this._isTransitioning || !this._isShown()) {\n return;\n }\n const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$6);\n if (startEvent.defaultPrevented) {\n return;\n }\n const dimension = this._getDimension();\n this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`;\n reflow(this._element);\n this._element.classList.add(CLASS_NAME_COLLAPSING);\n this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7);\n for (const trigger of this._triggerArray) {\n const element = SelectorEngine.getElementFromSelector(trigger);\n if (element && !this._isShown(element)) {\n this._addAriaAndCollapsedClass([trigger], false);\n }\n }\n this._isTransitioning = true;\n const complete = () => {\n this._isTransitioning = false;\n this._element.classList.remove(CLASS_NAME_COLLAPSING);\n this._element.classList.add(CLASS_NAME_COLLAPSE);\n EventHandler.trigger(this._element, EVENT_HIDDEN$6);\n };\n this._element.style[dimension] = '';\n this._queueCallback(complete, this._element, true);\n }\n _isShown(element = this._element) {\n return element.classList.contains(CLASS_NAME_SHOW$7);\n }\n\n // Private\n _configAfterMerge(config) {\n config.toggle = Boolean(config.toggle); // Coerce string values\n config.parent = getElement(config.parent);\n return config;\n }\n _getDimension() {\n return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT;\n }\n _initializeChildren() {\n if (!this._config.parent) {\n return;\n }\n const children = this._getFirstLevelChildren(SELECTOR_DATA_TOGGLE$4);\n for (const element of children) {\n const selected = SelectorEngine.getElementFromSelector(element);\n if (selected) {\n this._addAriaAndCollapsedClass([element], this._isShown(selected));\n }\n }\n }\n _getFirstLevelChildren(selector) {\n const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent);\n // remove children if greater depth\n return SelectorEngine.find(selector, this._config.parent).filter(element => !children.includes(element));\n }\n _addAriaAndCollapsedClass(triggerArray, isOpen) {\n if (!triggerArray.length) {\n return;\n }\n for (const element of triggerArray) {\n element.classList.toggle(CLASS_NAME_COLLAPSED, !isOpen);\n element.setAttribute('aria-expanded', isOpen);\n }\n }\n\n // Static\n static jQueryInterface(config) {\n const _config = {};\n if (typeof config === 'string' && /show|hide/.test(config)) {\n _config.toggle = false;\n }\n return this.each(function () {\n const data = Collapse.getOrCreateInstance(this, _config);\n if (typeof config === 'string') {\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n }\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function (event) {\n // preventDefault only for elements (which change the URL) not inside the collapsible element\n if (event.target.tagName === 'A' || event.delegateTarget && event.delegateTarget.tagName === 'A') {\n event.preventDefault();\n }\n for (const element of SelectorEngine.getMultipleElementsFromSelector(this)) {\n Collapse.getOrCreateInstance(element, {\n toggle: false\n }).toggle();\n }\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Collapse);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dropdown.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$a = 'dropdown';\nconst DATA_KEY$6 = 'bs.dropdown';\nconst EVENT_KEY$6 = `.${DATA_KEY$6}`;\nconst DATA_API_KEY$3 = '.data-api';\nconst ESCAPE_KEY$2 = 'Escape';\nconst TAB_KEY$1 = 'Tab';\nconst ARROW_UP_KEY$1 = 'ArrowUp';\nconst ARROW_DOWN_KEY$1 = 'ArrowDown';\nconst RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button\n\nconst EVENT_HIDE$5 = `hide${EVENT_KEY$6}`;\nconst EVENT_HIDDEN$5 = `hidden${EVENT_KEY$6}`;\nconst EVENT_SHOW$5 = `show${EVENT_KEY$6}`;\nconst EVENT_SHOWN$5 = `shown${EVENT_KEY$6}`;\nconst EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`;\nconst EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$6}${DATA_API_KEY$3}`;\nconst EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$6}${DATA_API_KEY$3}`;\nconst CLASS_NAME_SHOW$6 = 'show';\nconst CLASS_NAME_DROPUP = 'dropup';\nconst CLASS_NAME_DROPEND = 'dropend';\nconst CLASS_NAME_DROPSTART = 'dropstart';\nconst CLASS_NAME_DROPUP_CENTER = 'dropup-center';\nconst CLASS_NAME_DROPDOWN_CENTER = 'dropdown-center';\nconst SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle=\"dropdown\"]:not(.disabled):not(:disabled)';\nconst SELECTOR_DATA_TOGGLE_SHOWN = `${SELECTOR_DATA_TOGGLE$3}.${CLASS_NAME_SHOW$6}`;\nconst SELECTOR_MENU = '.dropdown-menu';\nconst SELECTOR_NAVBAR = '.navbar';\nconst SELECTOR_NAVBAR_NAV = '.navbar-nav';\nconst SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)';\nconst PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start';\nconst PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end';\nconst PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start';\nconst PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end';\nconst PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start';\nconst PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start';\nconst PLACEMENT_TOPCENTER = 'top';\nconst PLACEMENT_BOTTOMCENTER = 'bottom';\nconst Default$9 = {\n autoClose: true,\n boundary: 'clippingParents',\n display: 'dynamic',\n offset: [0, 2],\n popperConfig: null,\n reference: 'toggle'\n};\nconst DefaultType$9 = {\n autoClose: '(boolean|string)',\n boundary: '(string|element)',\n display: 'string',\n offset: '(array|string|function)',\n popperConfig: '(null|object|function)',\n reference: '(string|element|object)'\n};\n\n/**\n * Class definition\n */\n\nclass Dropdown extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._popper = null;\n this._parent = this._element.parentNode; // dropdown wrapper\n // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/\n this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] || SelectorEngine.prev(this._element, SELECTOR_MENU)[0] || SelectorEngine.findOne(SELECTOR_MENU, this._parent);\n this._inNavbar = this._detectNavbar();\n }\n\n // Getters\n static get Default() {\n return Default$9;\n }\n static get DefaultType() {\n return DefaultType$9;\n }\n static get NAME() {\n return NAME$a;\n }\n\n // Public\n toggle() {\n return this._isShown() ? this.hide() : this.show();\n }\n show() {\n if (isDisabled(this._element) || this._isShown()) {\n return;\n }\n const relatedTarget = {\n relatedTarget: this._element\n };\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$5, relatedTarget);\n if (showEvent.defaultPrevented) {\n return;\n }\n this._createPopper();\n\n // If this is a touch-enabled device we add extra\n // empty mouseover listeners to the body's immediate children;\n // only needed because of broken event delegation on iOS\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\n if ('ontouchstart' in document.documentElement && !this._parent.closest(SELECTOR_NAVBAR_NAV)) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.on(element, 'mouseover', noop);\n }\n }\n this._element.focus();\n this._element.setAttribute('aria-expanded', true);\n this._menu.classList.add(CLASS_NAME_SHOW$6);\n this._element.classList.add(CLASS_NAME_SHOW$6);\n EventHandler.trigger(this._element, EVENT_SHOWN$5, relatedTarget);\n }\n hide() {\n if (isDisabled(this._element) || !this._isShown()) {\n return;\n }\n const relatedTarget = {\n relatedTarget: this._element\n };\n this._completeHide(relatedTarget);\n }\n dispose() {\n if (this._popper) {\n this._popper.destroy();\n }\n super.dispose();\n }\n update() {\n this._inNavbar = this._detectNavbar();\n if (this._popper) {\n this._popper.update();\n }\n }\n\n // Private\n _completeHide(relatedTarget) {\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$5, relatedTarget);\n if (hideEvent.defaultPrevented) {\n return;\n }\n\n // If this is a touch-enabled device we remove the extra\n // empty mouseover listeners we added for iOS support\n if ('ontouchstart' in document.documentElement) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.off(element, 'mouseover', noop);\n }\n }\n if (this._popper) {\n this._popper.destroy();\n }\n this._menu.classList.remove(CLASS_NAME_SHOW$6);\n this._element.classList.remove(CLASS_NAME_SHOW$6);\n this._element.setAttribute('aria-expanded', 'false');\n Manipulator.removeDataAttribute(this._menu, 'popper');\n EventHandler.trigger(this._element, EVENT_HIDDEN$5, relatedTarget);\n }\n _getConfig(config) {\n config = super._getConfig(config);\n if (typeof config.reference === 'object' && !isElement(config.reference) && typeof config.reference.getBoundingClientRect !== 'function') {\n // Popper virtual elements require a getBoundingClientRect method\n throw new TypeError(`${NAME$a.toUpperCase()}: Option \"reference\" provided type \"object\" without a required \"getBoundingClientRect\" method.`);\n }\n return config;\n }\n _createPopper() {\n if (typeof Popper === 'undefined') {\n throw new TypeError('Bootstrap\\'s dropdowns require Popper (https://popper.js.org)');\n }\n let referenceElement = this._element;\n if (this._config.reference === 'parent') {\n referenceElement = this._parent;\n } else if (isElement(this._config.reference)) {\n referenceElement = getElement(this._config.reference);\n } else if (typeof this._config.reference === 'object') {\n referenceElement = this._config.reference;\n }\n const popperConfig = this._getPopperConfig();\n this._popper = Popper.createPopper(referenceElement, this._menu, popperConfig);\n }\n _isShown() {\n return this._menu.classList.contains(CLASS_NAME_SHOW$6);\n }\n _getPlacement() {\n const parentDropdown = this._parent;\n if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) {\n return PLACEMENT_RIGHT;\n }\n if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) {\n return PLACEMENT_LEFT;\n }\n if (parentDropdown.classList.contains(CLASS_NAME_DROPUP_CENTER)) {\n return PLACEMENT_TOPCENTER;\n }\n if (parentDropdown.classList.contains(CLASS_NAME_DROPDOWN_CENTER)) {\n return PLACEMENT_BOTTOMCENTER;\n }\n\n // We need to trim the value because custom properties can also include spaces\n const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end';\n if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) {\n return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP;\n }\n return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM;\n }\n _detectNavbar() {\n return this._element.closest(SELECTOR_NAVBAR) !== null;\n }\n _getOffset() {\n const {\n offset\n } = this._config;\n if (typeof offset === 'string') {\n return offset.split(',').map(value => Number.parseInt(value, 10));\n }\n if (typeof offset === 'function') {\n return popperData => offset(popperData, this._element);\n }\n return offset;\n }\n _getPopperConfig() {\n const defaultBsPopperConfig = {\n placement: this._getPlacement(),\n modifiers: [{\n name: 'preventOverflow',\n options: {\n boundary: this._config.boundary\n }\n }, {\n name: 'offset',\n options: {\n offset: this._getOffset()\n }\n }]\n };\n\n // Disable Popper if we have a static display or Dropdown is in Navbar\n if (this._inNavbar || this._config.display === 'static') {\n Manipulator.setDataAttribute(this._menu, 'popper', 'static'); // TODO: v6 remove\n defaultBsPopperConfig.modifiers = [{\n name: 'applyStyles',\n enabled: false\n }];\n }\n return {\n ...defaultBsPopperConfig,\n ...execute(this._config.popperConfig, [defaultBsPopperConfig])\n };\n }\n _selectMenuItem({\n key,\n target\n }) {\n const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element));\n if (!items.length) {\n return;\n }\n\n // if target isn't included in items (e.g. when expanding the dropdown)\n // allow cycling to get the last item in case key equals ARROW_UP_KEY\n getNextActiveElement(items, target, key === ARROW_DOWN_KEY$1, !items.includes(target)).focus();\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Dropdown.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n });\n }\n static clearMenus(event) {\n if (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1) {\n return;\n }\n const openToggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE_SHOWN);\n for (const toggle of openToggles) {\n const context = Dropdown.getInstance(toggle);\n if (!context || context._config.autoClose === false) {\n continue;\n }\n const composedPath = event.composedPath();\n const isMenuTarget = composedPath.includes(context._menu);\n if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) {\n continue;\n }\n\n // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu\n if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) {\n continue;\n }\n const relatedTarget = {\n relatedTarget: context._element\n };\n if (event.type === 'click') {\n relatedTarget.clickEvent = event;\n }\n context._completeHide(relatedTarget);\n }\n }\n static dataApiKeydownHandler(event) {\n // If not an UP | DOWN | ESCAPE key => not a dropdown command\n // If input/textarea && if key is other than ESCAPE => not a dropdown command\n\n const isInput = /input|textarea/i.test(event.target.tagName);\n const isEscapeEvent = event.key === ESCAPE_KEY$2;\n const isUpOrDownEvent = [ARROW_UP_KEY$1, ARROW_DOWN_KEY$1].includes(event.key);\n if (!isUpOrDownEvent && !isEscapeEvent) {\n return;\n }\n if (isInput && !isEscapeEvent) {\n return;\n }\n event.preventDefault();\n\n // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/\n const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.next(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.findOne(SELECTOR_DATA_TOGGLE$3, event.delegateTarget.parentNode);\n const instance = Dropdown.getOrCreateInstance(getToggleButton);\n if (isUpOrDownEvent) {\n event.stopPropagation();\n instance.show();\n instance._selectMenuItem(event);\n return;\n }\n if (instance._isShown()) {\n // else is escape and we check if it is shown\n event.stopPropagation();\n instance.hide();\n getToggleButton.focus();\n }\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler);\nEventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler);\nEventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus);\nEventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus);\nEventHandler.on(document, EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) {\n event.preventDefault();\n Dropdown.getOrCreateInstance(this).toggle();\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Dropdown);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/backdrop.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$9 = 'backdrop';\nconst CLASS_NAME_FADE$4 = 'fade';\nconst CLASS_NAME_SHOW$5 = 'show';\nconst EVENT_MOUSEDOWN = `mousedown.bs.${NAME$9}`;\nconst Default$8 = {\n className: 'modal-backdrop',\n clickCallback: null,\n isAnimated: false,\n isVisible: true,\n // if false, we use the backdrop helper without adding any element to the dom\n rootElement: 'body' // give the choice to place backdrop under different elements\n};\nconst DefaultType$8 = {\n className: 'string',\n clickCallback: '(function|null)',\n isAnimated: 'boolean',\n isVisible: 'boolean',\n rootElement: '(element|string)'\n};\n\n/**\n * Class definition\n */\n\nclass Backdrop extends Config {\n constructor(config) {\n super();\n this._config = this._getConfig(config);\n this._isAppended = false;\n this._element = null;\n }\n\n // Getters\n static get Default() {\n return Default$8;\n }\n static get DefaultType() {\n return DefaultType$8;\n }\n static get NAME() {\n return NAME$9;\n }\n\n // Public\n show(callback) {\n if (!this._config.isVisible) {\n execute(callback);\n return;\n }\n this._append();\n const element = this._getElement();\n if (this._config.isAnimated) {\n reflow(element);\n }\n element.classList.add(CLASS_NAME_SHOW$5);\n this._emulateAnimation(() => {\n execute(callback);\n });\n }\n hide(callback) {\n if (!this._config.isVisible) {\n execute(callback);\n return;\n }\n this._getElement().classList.remove(CLASS_NAME_SHOW$5);\n this._emulateAnimation(() => {\n this.dispose();\n execute(callback);\n });\n }\n dispose() {\n if (!this._isAppended) {\n return;\n }\n EventHandler.off(this._element, EVENT_MOUSEDOWN);\n this._element.remove();\n this._isAppended = false;\n }\n\n // Private\n _getElement() {\n if (!this._element) {\n const backdrop = document.createElement('div');\n backdrop.className = this._config.className;\n if (this._config.isAnimated) {\n backdrop.classList.add(CLASS_NAME_FADE$4);\n }\n this._element = backdrop;\n }\n return this._element;\n }\n _configAfterMerge(config) {\n // use getElement() with the default \"body\" to get a fresh Element on each instantiation\n config.rootElement = getElement(config.rootElement);\n return config;\n }\n _append() {\n if (this._isAppended) {\n return;\n }\n const element = this._getElement();\n this._config.rootElement.append(element);\n EventHandler.on(element, EVENT_MOUSEDOWN, () => {\n execute(this._config.clickCallback);\n });\n this._isAppended = true;\n }\n _emulateAnimation(callback) {\n executeAfterTransition(callback, this._getElement(), this._config.isAnimated);\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/focustrap.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$8 = 'focustrap';\nconst DATA_KEY$5 = 'bs.focustrap';\nconst EVENT_KEY$5 = `.${DATA_KEY$5}`;\nconst EVENT_FOCUSIN$2 = `focusin${EVENT_KEY$5}`;\nconst EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$5}`;\nconst TAB_KEY = 'Tab';\nconst TAB_NAV_FORWARD = 'forward';\nconst TAB_NAV_BACKWARD = 'backward';\nconst Default$7 = {\n autofocus: true,\n trapElement: null // The element to trap focus inside of\n};\nconst DefaultType$7 = {\n autofocus: 'boolean',\n trapElement: 'element'\n};\n\n/**\n * Class definition\n */\n\nclass FocusTrap extends Config {\n constructor(config) {\n super();\n this._config = this._getConfig(config);\n this._isActive = false;\n this._lastTabNavDirection = null;\n }\n\n // Getters\n static get Default() {\n return Default$7;\n }\n static get DefaultType() {\n return DefaultType$7;\n }\n static get NAME() {\n return NAME$8;\n }\n\n // Public\n activate() {\n if (this._isActive) {\n return;\n }\n if (this._config.autofocus) {\n this._config.trapElement.focus();\n }\n EventHandler.off(document, EVENT_KEY$5); // guard against infinite focus loop\n EventHandler.on(document, EVENT_FOCUSIN$2, event => this._handleFocusin(event));\n EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event));\n this._isActive = true;\n }\n deactivate() {\n if (!this._isActive) {\n return;\n }\n this._isActive = false;\n EventHandler.off(document, EVENT_KEY$5);\n }\n\n // Private\n _handleFocusin(event) {\n const {\n trapElement\n } = this._config;\n if (event.target === document || event.target === trapElement || trapElement.contains(event.target)) {\n return;\n }\n const elements = SelectorEngine.focusableChildren(trapElement);\n if (elements.length === 0) {\n trapElement.focus();\n } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) {\n elements[elements.length - 1].focus();\n } else {\n elements[0].focus();\n }\n }\n _handleKeydown(event) {\n if (event.key !== TAB_KEY) {\n return;\n }\n this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/scrollBar.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top';\nconst SELECTOR_STICKY_CONTENT = '.sticky-top';\nconst PROPERTY_PADDING = 'padding-right';\nconst PROPERTY_MARGIN = 'margin-right';\n\n/**\n * Class definition\n */\n\nclass ScrollBarHelper {\n constructor() {\n this._element = document.body;\n }\n\n // Public\n getWidth() {\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes\n const documentWidth = document.documentElement.clientWidth;\n return Math.abs(window.innerWidth - documentWidth);\n }\n hide() {\n const width = this.getWidth();\n this._disableOverFlow();\n // give padding to element to balance the hidden scrollbar width\n this._setElementAttributes(this._element, PROPERTY_PADDING, calculatedValue => calculatedValue + width);\n // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth\n this._setElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING, calculatedValue => calculatedValue + width);\n this._setElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN, calculatedValue => calculatedValue - width);\n }\n reset() {\n this._resetElementAttributes(this._element, 'overflow');\n this._resetElementAttributes(this._element, PROPERTY_PADDING);\n this._resetElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING);\n this._resetElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN);\n }\n isOverflowing() {\n return this.getWidth() > 0;\n }\n\n // Private\n _disableOverFlow() {\n this._saveInitialAttribute(this._element, 'overflow');\n this._element.style.overflow = 'hidden';\n }\n _setElementAttributes(selector, styleProperty, callback) {\n const scrollbarWidth = this.getWidth();\n const manipulationCallBack = element => {\n if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) {\n return;\n }\n this._saveInitialAttribute(element, styleProperty);\n const calculatedValue = window.getComputedStyle(element).getPropertyValue(styleProperty);\n element.style.setProperty(styleProperty, `${callback(Number.parseFloat(calculatedValue))}px`);\n };\n this._applyManipulationCallback(selector, manipulationCallBack);\n }\n _saveInitialAttribute(element, styleProperty) {\n const actualValue = element.style.getPropertyValue(styleProperty);\n if (actualValue) {\n Manipulator.setDataAttribute(element, styleProperty, actualValue);\n }\n }\n _resetElementAttributes(selector, styleProperty) {\n const manipulationCallBack = element => {\n const value = Manipulator.getDataAttribute(element, styleProperty);\n // We only want to remove the property if the value is `null`; the value can also be zero\n if (value === null) {\n element.style.removeProperty(styleProperty);\n return;\n }\n Manipulator.removeDataAttribute(element, styleProperty);\n element.style.setProperty(styleProperty, value);\n };\n this._applyManipulationCallback(selector, manipulationCallBack);\n }\n _applyManipulationCallback(selector, callBack) {\n if (isElement(selector)) {\n callBack(selector);\n return;\n }\n for (const sel of SelectorEngine.find(selector, this._element)) {\n callBack(sel);\n }\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap modal.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$7 = 'modal';\nconst DATA_KEY$4 = 'bs.modal';\nconst EVENT_KEY$4 = `.${DATA_KEY$4}`;\nconst DATA_API_KEY$2 = '.data-api';\nconst ESCAPE_KEY$1 = 'Escape';\nconst EVENT_HIDE$4 = `hide${EVENT_KEY$4}`;\nconst EVENT_HIDE_PREVENTED$1 = `hidePrevented${EVENT_KEY$4}`;\nconst EVENT_HIDDEN$4 = `hidden${EVENT_KEY$4}`;\nconst EVENT_SHOW$4 = `show${EVENT_KEY$4}`;\nconst EVENT_SHOWN$4 = `shown${EVENT_KEY$4}`;\nconst EVENT_RESIZE$1 = `resize${EVENT_KEY$4}`;\nconst EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$4}`;\nconst EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$4}`;\nconst EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$4}`;\nconst EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$4}${DATA_API_KEY$2}`;\nconst CLASS_NAME_OPEN = 'modal-open';\nconst CLASS_NAME_FADE$3 = 'fade';\nconst CLASS_NAME_SHOW$4 = 'show';\nconst CLASS_NAME_STATIC = 'modal-static';\nconst OPEN_SELECTOR$1 = '.modal.show';\nconst SELECTOR_DIALOG = '.modal-dialog';\nconst SELECTOR_MODAL_BODY = '.modal-body';\nconst SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle=\"modal\"]';\nconst Default$6 = {\n backdrop: true,\n focus: true,\n keyboard: true\n};\nconst DefaultType$6 = {\n backdrop: '(boolean|string)',\n focus: 'boolean',\n keyboard: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Modal extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);\n this._backdrop = this._initializeBackDrop();\n this._focustrap = this._initializeFocusTrap();\n this._isShown = false;\n this._isTransitioning = false;\n this._scrollBar = new ScrollBarHelper();\n this._addEventListeners();\n }\n\n // Getters\n static get Default() {\n return Default$6;\n }\n static get DefaultType() {\n return DefaultType$6;\n }\n static get NAME() {\n return NAME$7;\n }\n\n // Public\n toggle(relatedTarget) {\n return this._isShown ? this.hide() : this.show(relatedTarget);\n }\n show(relatedTarget) {\n if (this._isShown || this._isTransitioning) {\n return;\n }\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, {\n relatedTarget\n });\n if (showEvent.defaultPrevented) {\n return;\n }\n this._isShown = true;\n this._isTransitioning = true;\n this._scrollBar.hide();\n document.body.classList.add(CLASS_NAME_OPEN);\n this._adjustDialog();\n this._backdrop.show(() => this._showElement(relatedTarget));\n }\n hide() {\n if (!this._isShown || this._isTransitioning) {\n return;\n }\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4);\n if (hideEvent.defaultPrevented) {\n return;\n }\n this._isShown = false;\n this._isTransitioning = true;\n this._focustrap.deactivate();\n this._element.classList.remove(CLASS_NAME_SHOW$4);\n this._queueCallback(() => this._hideModal(), this._element, this._isAnimated());\n }\n dispose() {\n EventHandler.off(window, EVENT_KEY$4);\n EventHandler.off(this._dialog, EVENT_KEY$4);\n this._backdrop.dispose();\n this._focustrap.deactivate();\n super.dispose();\n }\n handleUpdate() {\n this._adjustDialog();\n }\n\n // Private\n _initializeBackDrop() {\n return new Backdrop({\n isVisible: Boolean(this._config.backdrop),\n // 'static' option will be translated to true, and booleans will keep their value,\n isAnimated: this._isAnimated()\n });\n }\n _initializeFocusTrap() {\n return new FocusTrap({\n trapElement: this._element\n });\n }\n _showElement(relatedTarget) {\n // try to append dynamic modal\n if (!document.body.contains(this._element)) {\n document.body.append(this._element);\n }\n this._element.style.display = 'block';\n this._element.removeAttribute('aria-hidden');\n this._element.setAttribute('aria-modal', true);\n this._element.setAttribute('role', 'dialog');\n this._element.scrollTop = 0;\n const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog);\n if (modalBody) {\n modalBody.scrollTop = 0;\n }\n reflow(this._element);\n this._element.classList.add(CLASS_NAME_SHOW$4);\n const transitionComplete = () => {\n if (this._config.focus) {\n this._focustrap.activate();\n }\n this._isTransitioning = false;\n EventHandler.trigger(this._element, EVENT_SHOWN$4, {\n relatedTarget\n });\n };\n this._queueCallback(transitionComplete, this._dialog, this._isAnimated());\n }\n _addEventListeners() {\n EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => {\n if (event.key !== ESCAPE_KEY$1) {\n return;\n }\n if (this._config.keyboard) {\n this.hide();\n return;\n }\n this._triggerBackdropTransition();\n });\n EventHandler.on(window, EVENT_RESIZE$1, () => {\n if (this._isShown && !this._isTransitioning) {\n this._adjustDialog();\n }\n });\n EventHandler.on(this._element, EVENT_MOUSEDOWN_DISMISS, event => {\n // a bad trick to segregate clicks that may start inside dialog but end outside, and avoid listen to scrollbar clicks\n EventHandler.one(this._element, EVENT_CLICK_DISMISS, event2 => {\n if (this._element !== event.target || this._element !== event2.target) {\n return;\n }\n if (this._config.backdrop === 'static') {\n this._triggerBackdropTransition();\n return;\n }\n if (this._config.backdrop) {\n this.hide();\n }\n });\n });\n }\n _hideModal() {\n this._element.style.display = 'none';\n this._element.setAttribute('aria-hidden', true);\n this._element.removeAttribute('aria-modal');\n this._element.removeAttribute('role');\n this._isTransitioning = false;\n this._backdrop.hide(() => {\n document.body.classList.remove(CLASS_NAME_OPEN);\n this._resetAdjustments();\n this._scrollBar.reset();\n EventHandler.trigger(this._element, EVENT_HIDDEN$4);\n });\n }\n _isAnimated() {\n return this._element.classList.contains(CLASS_NAME_FADE$3);\n }\n _triggerBackdropTransition() {\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED$1);\n if (hideEvent.defaultPrevented) {\n return;\n }\n const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;\n const initialOverflowY = this._element.style.overflowY;\n // return if the following background transition hasn't yet completed\n if (initialOverflowY === 'hidden' || this._element.classList.contains(CLASS_NAME_STATIC)) {\n return;\n }\n if (!isModalOverflowing) {\n this._element.style.overflowY = 'hidden';\n }\n this._element.classList.add(CLASS_NAME_STATIC);\n this._queueCallback(() => {\n this._element.classList.remove(CLASS_NAME_STATIC);\n this._queueCallback(() => {\n this._element.style.overflowY = initialOverflowY;\n }, this._dialog);\n }, this._dialog);\n this._element.focus();\n }\n\n /**\n * The following methods are used to handle overflowing modals\n */\n\n _adjustDialog() {\n const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;\n const scrollbarWidth = this._scrollBar.getWidth();\n const isBodyOverflowing = scrollbarWidth > 0;\n if (isBodyOverflowing && !isModalOverflowing) {\n const property = isRTL() ? 'paddingLeft' : 'paddingRight';\n this._element.style[property] = `${scrollbarWidth}px`;\n }\n if (!isBodyOverflowing && isModalOverflowing) {\n const property = isRTL() ? 'paddingRight' : 'paddingLeft';\n this._element.style[property] = `${scrollbarWidth}px`;\n }\n }\n _resetAdjustments() {\n this._element.style.paddingLeft = '';\n this._element.style.paddingRight = '';\n }\n\n // Static\n static jQueryInterface(config, relatedTarget) {\n return this.each(function () {\n const data = Modal.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config](relatedTarget);\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) {\n const target = SelectorEngine.getElementFromSelector(this);\n if (['A', 'AREA'].includes(this.tagName)) {\n event.preventDefault();\n }\n EventHandler.one(target, EVENT_SHOW$4, showEvent => {\n if (showEvent.defaultPrevented) {\n // only register focus restorer if modal will actually get shown\n return;\n }\n EventHandler.one(target, EVENT_HIDDEN$4, () => {\n if (isVisible(this)) {\n this.focus();\n }\n });\n });\n\n // avoid conflict when clicking modal toggler while another one is open\n const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1);\n if (alreadyOpen) {\n Modal.getInstance(alreadyOpen).hide();\n }\n const data = Modal.getOrCreateInstance(target);\n data.toggle(this);\n});\nenableDismissTrigger(Modal);\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Modal);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap offcanvas.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$6 = 'offcanvas';\nconst DATA_KEY$3 = 'bs.offcanvas';\nconst EVENT_KEY$3 = `.${DATA_KEY$3}`;\nconst DATA_API_KEY$1 = '.data-api';\nconst EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$3}${DATA_API_KEY$1}`;\nconst ESCAPE_KEY = 'Escape';\nconst CLASS_NAME_SHOW$3 = 'show';\nconst CLASS_NAME_SHOWING$1 = 'showing';\nconst CLASS_NAME_HIDING = 'hiding';\nconst CLASS_NAME_BACKDROP = 'offcanvas-backdrop';\nconst OPEN_SELECTOR = '.offcanvas.show';\nconst EVENT_SHOW$3 = `show${EVENT_KEY$3}`;\nconst EVENT_SHOWN$3 = `shown${EVENT_KEY$3}`;\nconst EVENT_HIDE$3 = `hide${EVENT_KEY$3}`;\nconst EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$3}`;\nconst EVENT_HIDDEN$3 = `hidden${EVENT_KEY$3}`;\nconst EVENT_RESIZE = `resize${EVENT_KEY$3}`;\nconst EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$3}${DATA_API_KEY$1}`;\nconst EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$3}`;\nconst SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle=\"offcanvas\"]';\nconst Default$5 = {\n backdrop: true,\n keyboard: true,\n scroll: false\n};\nconst DefaultType$5 = {\n backdrop: '(boolean|string)',\n keyboard: 'boolean',\n scroll: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Offcanvas extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._isShown = false;\n this._backdrop = this._initializeBackDrop();\n this._focustrap = this._initializeFocusTrap();\n this._addEventListeners();\n }\n\n // Getters\n static get Default() {\n return Default$5;\n }\n static get DefaultType() {\n return DefaultType$5;\n }\n static get NAME() {\n return NAME$6;\n }\n\n // Public\n toggle(relatedTarget) {\n return this._isShown ? this.hide() : this.show(relatedTarget);\n }\n show(relatedTarget) {\n if (this._isShown) {\n return;\n }\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, {\n relatedTarget\n });\n if (showEvent.defaultPrevented) {\n return;\n }\n this._isShown = true;\n this._backdrop.show();\n if (!this._config.scroll) {\n new ScrollBarHelper().hide();\n }\n this._element.setAttribute('aria-modal', true);\n this._element.setAttribute('role', 'dialog');\n this._element.classList.add(CLASS_NAME_SHOWING$1);\n const completeCallBack = () => {\n if (!this._config.scroll || this._config.backdrop) {\n this._focustrap.activate();\n }\n this._element.classList.add(CLASS_NAME_SHOW$3);\n this._element.classList.remove(CLASS_NAME_SHOWING$1);\n EventHandler.trigger(this._element, EVENT_SHOWN$3, {\n relatedTarget\n });\n };\n this._queueCallback(completeCallBack, this._element, true);\n }\n hide() {\n if (!this._isShown) {\n return;\n }\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3);\n if (hideEvent.defaultPrevented) {\n return;\n }\n this._focustrap.deactivate();\n this._element.blur();\n this._isShown = false;\n this._element.classList.add(CLASS_NAME_HIDING);\n this._backdrop.hide();\n const completeCallback = () => {\n this._element.classList.remove(CLASS_NAME_SHOW$3, CLASS_NAME_HIDING);\n this._element.removeAttribute('aria-modal');\n this._element.removeAttribute('role');\n if (!this._config.scroll) {\n new ScrollBarHelper().reset();\n }\n EventHandler.trigger(this._element, EVENT_HIDDEN$3);\n };\n this._queueCallback(completeCallback, this._element, true);\n }\n dispose() {\n this._backdrop.dispose();\n this._focustrap.deactivate();\n super.dispose();\n }\n\n // Private\n _initializeBackDrop() {\n const clickCallback = () => {\n if (this._config.backdrop === 'static') {\n EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED);\n return;\n }\n this.hide();\n };\n\n // 'static' option will be translated to true, and booleans will keep their value\n const isVisible = Boolean(this._config.backdrop);\n return new Backdrop({\n className: CLASS_NAME_BACKDROP,\n isVisible,\n isAnimated: true,\n rootElement: this._element.parentNode,\n clickCallback: isVisible ? clickCallback : null\n });\n }\n _initializeFocusTrap() {\n return new FocusTrap({\n trapElement: this._element\n });\n }\n _addEventListeners() {\n EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => {\n if (event.key !== ESCAPE_KEY) {\n return;\n }\n if (this._config.keyboard) {\n this.hide();\n return;\n }\n EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED);\n });\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Offcanvas.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config](this);\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) {\n const target = SelectorEngine.getElementFromSelector(this);\n if (['A', 'AREA'].includes(this.tagName)) {\n event.preventDefault();\n }\n if (isDisabled(this)) {\n return;\n }\n EventHandler.one(target, EVENT_HIDDEN$3, () => {\n // focus on trigger when it is closed\n if (isVisible(this)) {\n this.focus();\n }\n });\n\n // avoid conflict when clicking a toggler of an offcanvas, while another is open\n const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR);\n if (alreadyOpen && alreadyOpen !== target) {\n Offcanvas.getInstance(alreadyOpen).hide();\n }\n const data = Offcanvas.getOrCreateInstance(target);\n data.toggle(this);\n});\nEventHandler.on(window, EVENT_LOAD_DATA_API$2, () => {\n for (const selector of SelectorEngine.find(OPEN_SELECTOR)) {\n Offcanvas.getOrCreateInstance(selector).show();\n }\n});\nEventHandler.on(window, EVENT_RESIZE, () => {\n for (const element of SelectorEngine.find('[aria-modal][class*=show][class*=offcanvas-]')) {\n if (getComputedStyle(element).position !== 'fixed') {\n Offcanvas.getOrCreateInstance(element).hide();\n }\n }\n});\nenableDismissTrigger(Offcanvas);\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Offcanvas);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/sanitizer.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n// js-docs-start allow-list\nconst ARIA_ATTRIBUTE_PATTERN = /^aria-[\\w-]*$/i;\nconst DefaultAllowlist = {\n // Global attributes allowed on any supplied element below.\n '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],\n a: ['target', 'href', 'title', 'rel'],\n area: [],\n b: [],\n br: [],\n col: [],\n code: [],\n dd: [],\n div: [],\n dl: [],\n dt: [],\n em: [],\n hr: [],\n h1: [],\n h2: [],\n h3: [],\n h4: [],\n h5: [],\n h6: [],\n i: [],\n img: ['src', 'srcset', 'alt', 'title', 'width', 'height'],\n li: [],\n ol: [],\n p: [],\n pre: [],\n s: [],\n small: [],\n span: [],\n sub: [],\n sup: [],\n strong: [],\n u: [],\n ul: []\n};\n// js-docs-end allow-list\n\nconst uriAttributes = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']);\n\n/**\n * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation\n * contexts.\n *\n * Shout-out to Angular https://github.com/angular/angular/blob/15.2.8/packages/core/src/sanitization/url_sanitizer.ts#L38\n */\n// eslint-disable-next-line unicorn/better-regex\nconst SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i;\nconst allowedAttribute = (attribute, allowedAttributeList) => {\n const attributeName = attribute.nodeName.toLowerCase();\n if (allowedAttributeList.includes(attributeName)) {\n if (uriAttributes.has(attributeName)) {\n return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue));\n }\n return true;\n }\n\n // Check if a regular expression validates the attribute.\n return allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp).some(regex => regex.test(attributeName));\n};\nfunction sanitizeHtml(unsafeHtml, allowList, sanitizeFunction) {\n if (!unsafeHtml.length) {\n return unsafeHtml;\n }\n if (sanitizeFunction && typeof sanitizeFunction === 'function') {\n return sanitizeFunction(unsafeHtml);\n }\n const domParser = new window.DOMParser();\n const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html');\n const elements = [].concat(...createdDocument.body.querySelectorAll('*'));\n for (const element of elements) {\n const elementName = element.nodeName.toLowerCase();\n if (!Object.keys(allowList).includes(elementName)) {\n element.remove();\n continue;\n }\n const attributeList = [].concat(...element.attributes);\n const allowedAttributes = [].concat(allowList['*'] || [], allowList[elementName] || []);\n for (const attribute of attributeList) {\n if (!allowedAttribute(attribute, allowedAttributes)) {\n element.removeAttribute(attribute.nodeName);\n }\n }\n }\n return createdDocument.body.innerHTML;\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/template-factory.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$5 = 'TemplateFactory';\nconst Default$4 = {\n allowList: DefaultAllowlist,\n content: {},\n // { selector : text , selector2 : text2 , }\n extraClass: '',\n html: false,\n sanitize: true,\n sanitizeFn: null,\n template: '
'\n};\nconst DefaultType$4 = {\n allowList: 'object',\n content: 'object',\n extraClass: '(string|function)',\n html: 'boolean',\n sanitize: 'boolean',\n sanitizeFn: '(null|function)',\n template: 'string'\n};\nconst DefaultContentType = {\n entry: '(string|element|function|null)',\n selector: '(string|element)'\n};\n\n/**\n * Class definition\n */\n\nclass TemplateFactory extends Config {\n constructor(config) {\n super();\n this._config = this._getConfig(config);\n }\n\n // Getters\n static get Default() {\n return Default$4;\n }\n static get DefaultType() {\n return DefaultType$4;\n }\n static get NAME() {\n return NAME$5;\n }\n\n // Public\n getContent() {\n return Object.values(this._config.content).map(config => this._resolvePossibleFunction(config)).filter(Boolean);\n }\n hasContent() {\n return this.getContent().length > 0;\n }\n changeContent(content) {\n this._checkContent(content);\n this._config.content = {\n ...this._config.content,\n ...content\n };\n return this;\n }\n toHtml() {\n const templateWrapper = document.createElement('div');\n templateWrapper.innerHTML = this._maybeSanitize(this._config.template);\n for (const [selector, text] of Object.entries(this._config.content)) {\n this._setContent(templateWrapper, text, selector);\n }\n const template = templateWrapper.children[0];\n const extraClass = this._resolvePossibleFunction(this._config.extraClass);\n if (extraClass) {\n template.classList.add(...extraClass.split(' '));\n }\n return template;\n }\n\n // Private\n _typeCheckConfig(config) {\n super._typeCheckConfig(config);\n this._checkContent(config.content);\n }\n _checkContent(arg) {\n for (const [selector, content] of Object.entries(arg)) {\n super._typeCheckConfig({\n selector,\n entry: content\n }, DefaultContentType);\n }\n }\n _setContent(template, content, selector) {\n const templateElement = SelectorEngine.findOne(selector, template);\n if (!templateElement) {\n return;\n }\n content = this._resolvePossibleFunction(content);\n if (!content) {\n templateElement.remove();\n return;\n }\n if (isElement(content)) {\n this._putElementInTemplate(getElement(content), templateElement);\n return;\n }\n if (this._config.html) {\n templateElement.innerHTML = this._maybeSanitize(content);\n return;\n }\n templateElement.textContent = content;\n }\n _maybeSanitize(arg) {\n return this._config.sanitize ? sanitizeHtml(arg, this._config.allowList, this._config.sanitizeFn) : arg;\n }\n _resolvePossibleFunction(arg) {\n return execute(arg, [this]);\n }\n _putElementInTemplate(element, templateElement) {\n if (this._config.html) {\n templateElement.innerHTML = '';\n templateElement.append(element);\n return;\n }\n templateElement.textContent = element.textContent;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap tooltip.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$4 = 'tooltip';\nconst DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']);\nconst CLASS_NAME_FADE$2 = 'fade';\nconst CLASS_NAME_MODAL = 'modal';\nconst CLASS_NAME_SHOW$2 = 'show';\nconst SELECTOR_TOOLTIP_INNER = '.tooltip-inner';\nconst SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`;\nconst EVENT_MODAL_HIDE = 'hide.bs.modal';\nconst TRIGGER_HOVER = 'hover';\nconst TRIGGER_FOCUS = 'focus';\nconst TRIGGER_CLICK = 'click';\nconst TRIGGER_MANUAL = 'manual';\nconst EVENT_HIDE$2 = 'hide';\nconst EVENT_HIDDEN$2 = 'hidden';\nconst EVENT_SHOW$2 = 'show';\nconst EVENT_SHOWN$2 = 'shown';\nconst EVENT_INSERTED = 'inserted';\nconst EVENT_CLICK$1 = 'click';\nconst EVENT_FOCUSIN$1 = 'focusin';\nconst EVENT_FOCUSOUT$1 = 'focusout';\nconst EVENT_MOUSEENTER = 'mouseenter';\nconst EVENT_MOUSELEAVE = 'mouseleave';\nconst AttachmentMap = {\n AUTO: 'auto',\n TOP: 'top',\n RIGHT: isRTL() ? 'left' : 'right',\n BOTTOM: 'bottom',\n LEFT: isRTL() ? 'right' : 'left'\n};\nconst Default$3 = {\n allowList: DefaultAllowlist,\n animation: true,\n boundary: 'clippingParents',\n container: false,\n customClass: '',\n delay: 0,\n fallbackPlacements: ['top', 'right', 'bottom', 'left'],\n html: false,\n offset: [0, 6],\n placement: 'top',\n popperConfig: null,\n sanitize: true,\n sanitizeFn: null,\n selector: false,\n template: '
' + '
' + '
' + '
',\n title: '',\n trigger: 'hover focus'\n};\nconst DefaultType$3 = {\n allowList: 'object',\n animation: 'boolean',\n boundary: '(string|element)',\n container: '(string|element|boolean)',\n customClass: '(string|function)',\n delay: '(number|object)',\n fallbackPlacements: 'array',\n html: 'boolean',\n offset: '(array|string|function)',\n placement: '(string|function)',\n popperConfig: '(null|object|function)',\n sanitize: 'boolean',\n sanitizeFn: '(null|function)',\n selector: '(string|boolean)',\n template: 'string',\n title: '(string|element|function)',\n trigger: 'string'\n};\n\n/**\n * Class definition\n */\n\nclass Tooltip extends BaseComponent {\n constructor(element, config) {\n if (typeof Popper === 'undefined') {\n throw new TypeError('Bootstrap\\'s tooltips require Popper (https://popper.js.org)');\n }\n super(element, config);\n\n // Private\n this._isEnabled = true;\n this._timeout = 0;\n this._isHovered = null;\n this._activeTrigger = {};\n this._popper = null;\n this._templateFactory = null;\n this._newContent = null;\n\n // Protected\n this.tip = null;\n this._setListeners();\n if (!this._config.selector) {\n this._fixTitle();\n }\n }\n\n // Getters\n static get Default() {\n return Default$3;\n }\n static get DefaultType() {\n return DefaultType$3;\n }\n static get NAME() {\n return NAME$4;\n }\n\n // Public\n enable() {\n this._isEnabled = true;\n }\n disable() {\n this._isEnabled = false;\n }\n toggleEnabled() {\n this._isEnabled = !this._isEnabled;\n }\n toggle() {\n if (!this._isEnabled) {\n return;\n }\n this._activeTrigger.click = !this._activeTrigger.click;\n if (this._isShown()) {\n this._leave();\n return;\n }\n this._enter();\n }\n dispose() {\n clearTimeout(this._timeout);\n EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler);\n if (this._element.getAttribute('data-bs-original-title')) {\n this._element.setAttribute('title', this._element.getAttribute('data-bs-original-title'));\n }\n this._disposePopper();\n super.dispose();\n }\n show() {\n if (this._element.style.display === 'none') {\n throw new Error('Please use show on visible elements');\n }\n if (!(this._isWithContent() && this._isEnabled)) {\n return;\n }\n const showEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOW$2));\n const shadowRoot = findShadowRoot(this._element);\n const isInTheDom = (shadowRoot || this._element.ownerDocument.documentElement).contains(this._element);\n if (showEvent.defaultPrevented || !isInTheDom) {\n return;\n }\n\n // TODO: v6 remove this or make it optional\n this._disposePopper();\n const tip = this._getTipElement();\n this._element.setAttribute('aria-describedby', tip.getAttribute('id'));\n const {\n container\n } = this._config;\n if (!this._element.ownerDocument.documentElement.contains(this.tip)) {\n container.append(tip);\n EventHandler.trigger(this._element, this.constructor.eventName(EVENT_INSERTED));\n }\n this._popper = this._createPopper(tip);\n tip.classList.add(CLASS_NAME_SHOW$2);\n\n // If this is a touch-enabled device we add extra\n // empty mouseover listeners to the body's immediate children;\n // only needed because of broken event delegation on iOS\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\n if ('ontouchstart' in document.documentElement) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.on(element, 'mouseover', noop);\n }\n }\n const complete = () => {\n EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOWN$2));\n if (this._isHovered === false) {\n this._leave();\n }\n this._isHovered = false;\n };\n this._queueCallback(complete, this.tip, this._isAnimated());\n }\n hide() {\n if (!this._isShown()) {\n return;\n }\n const hideEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDE$2));\n if (hideEvent.defaultPrevented) {\n return;\n }\n const tip = this._getTipElement();\n tip.classList.remove(CLASS_NAME_SHOW$2);\n\n // If this is a touch-enabled device we remove the extra\n // empty mouseover listeners we added for iOS support\n if ('ontouchstart' in document.documentElement) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.off(element, 'mouseover', noop);\n }\n }\n this._activeTrigger[TRIGGER_CLICK] = false;\n this._activeTrigger[TRIGGER_FOCUS] = false;\n this._activeTrigger[TRIGGER_HOVER] = false;\n this._isHovered = null; // it is a trick to support manual triggering\n\n const complete = () => {\n if (this._isWithActiveTrigger()) {\n return;\n }\n if (!this._isHovered) {\n this._disposePopper();\n }\n this._element.removeAttribute('aria-describedby');\n EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDDEN$2));\n };\n this._queueCallback(complete, this.tip, this._isAnimated());\n }\n update() {\n if (this._popper) {\n this._popper.update();\n }\n }\n\n // Protected\n _isWithContent() {\n return Boolean(this._getTitle());\n }\n _getTipElement() {\n if (!this.tip) {\n this.tip = this._createTipElement(this._newContent || this._getContentForTemplate());\n }\n return this.tip;\n }\n _createTipElement(content) {\n const tip = this._getTemplateFactory(content).toHtml();\n\n // TODO: remove this check in v6\n if (!tip) {\n return null;\n }\n tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2);\n // TODO: v6 the following can be achieved with CSS only\n tip.classList.add(`bs-${this.constructor.NAME}-auto`);\n const tipId = getUID(this.constructor.NAME).toString();\n tip.setAttribute('id', tipId);\n if (this._isAnimated()) {\n tip.classList.add(CLASS_NAME_FADE$2);\n }\n return tip;\n }\n setContent(content) {\n this._newContent = content;\n if (this._isShown()) {\n this._disposePopper();\n this.show();\n }\n }\n _getTemplateFactory(content) {\n if (this._templateFactory) {\n this._templateFactory.changeContent(content);\n } else {\n this._templateFactory = new TemplateFactory({\n ...this._config,\n // the `content` var has to be after `this._config`\n // to override config.content in case of popover\n content,\n extraClass: this._resolvePossibleFunction(this._config.customClass)\n });\n }\n return this._templateFactory;\n }\n _getContentForTemplate() {\n return {\n [SELECTOR_TOOLTIP_INNER]: this._getTitle()\n };\n }\n _getTitle() {\n return this._resolvePossibleFunction(this._config.title) || this._element.getAttribute('data-bs-original-title');\n }\n\n // Private\n _initializeOnDelegatedTarget(event) {\n return this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig());\n }\n _isAnimated() {\n return this._config.animation || this.tip && this.tip.classList.contains(CLASS_NAME_FADE$2);\n }\n _isShown() {\n return this.tip && this.tip.classList.contains(CLASS_NAME_SHOW$2);\n }\n _createPopper(tip) {\n const placement = execute(this._config.placement, [this, tip, this._element]);\n const attachment = AttachmentMap[placement.toUpperCase()];\n return Popper.createPopper(this._element, tip, this._getPopperConfig(attachment));\n }\n _getOffset() {\n const {\n offset\n } = this._config;\n if (typeof offset === 'string') {\n return offset.split(',').map(value => Number.parseInt(value, 10));\n }\n if (typeof offset === 'function') {\n return popperData => offset(popperData, this._element);\n }\n return offset;\n }\n _resolvePossibleFunction(arg) {\n return execute(arg, [this._element]);\n }\n _getPopperConfig(attachment) {\n const defaultBsPopperConfig = {\n placement: attachment,\n modifiers: [{\n name: 'flip',\n options: {\n fallbackPlacements: this._config.fallbackPlacements\n }\n }, {\n name: 'offset',\n options: {\n offset: this._getOffset()\n }\n }, {\n name: 'preventOverflow',\n options: {\n boundary: this._config.boundary\n }\n }, {\n name: 'arrow',\n options: {\n element: `.${this.constructor.NAME}-arrow`\n }\n }, {\n name: 'preSetPlacement',\n enabled: true,\n phase: 'beforeMain',\n fn: data => {\n // Pre-set Popper's placement attribute in order to read the arrow sizes properly.\n // Otherwise, Popper mixes up the width and height dimensions since the initial arrow style is for top placement\n this._getTipElement().setAttribute('data-popper-placement', data.state.placement);\n }\n }]\n };\n return {\n ...defaultBsPopperConfig,\n ...execute(this._config.popperConfig, [defaultBsPopperConfig])\n };\n }\n _setListeners() {\n const triggers = this._config.trigger.split(' ');\n for (const trigger of triggers) {\n if (trigger === 'click') {\n EventHandler.on(this._element, this.constructor.eventName(EVENT_CLICK$1), this._config.selector, event => {\n const context = this._initializeOnDelegatedTarget(event);\n context.toggle();\n });\n } else if (trigger !== TRIGGER_MANUAL) {\n const eventIn = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSEENTER) : this.constructor.eventName(EVENT_FOCUSIN$1);\n const eventOut = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSELEAVE) : this.constructor.eventName(EVENT_FOCUSOUT$1);\n EventHandler.on(this._element, eventIn, this._config.selector, event => {\n const context = this._initializeOnDelegatedTarget(event);\n context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true;\n context._enter();\n });\n EventHandler.on(this._element, eventOut, this._config.selector, event => {\n const context = this._initializeOnDelegatedTarget(event);\n context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget);\n context._leave();\n });\n }\n }\n this._hideModalHandler = () => {\n if (this._element) {\n this.hide();\n }\n };\n EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler);\n }\n _fixTitle() {\n const title = this._element.getAttribute('title');\n if (!title) {\n return;\n }\n if (!this._element.getAttribute('aria-label') && !this._element.textContent.trim()) {\n this._element.setAttribute('aria-label', title);\n }\n this._element.setAttribute('data-bs-original-title', title); // DO NOT USE IT. Is only for backwards compatibility\n this._element.removeAttribute('title');\n }\n _enter() {\n if (this._isShown() || this._isHovered) {\n this._isHovered = true;\n return;\n }\n this._isHovered = true;\n this._setTimeout(() => {\n if (this._isHovered) {\n this.show();\n }\n }, this._config.delay.show);\n }\n _leave() {\n if (this._isWithActiveTrigger()) {\n return;\n }\n this._isHovered = false;\n this._setTimeout(() => {\n if (!this._isHovered) {\n this.hide();\n }\n }, this._config.delay.hide);\n }\n _setTimeout(handler, timeout) {\n clearTimeout(this._timeout);\n this._timeout = setTimeout(handler, timeout);\n }\n _isWithActiveTrigger() {\n return Object.values(this._activeTrigger).includes(true);\n }\n _getConfig(config) {\n const dataAttributes = Manipulator.getDataAttributes(this._element);\n for (const dataAttribute of Object.keys(dataAttributes)) {\n if (DISALLOWED_ATTRIBUTES.has(dataAttribute)) {\n delete dataAttributes[dataAttribute];\n }\n }\n config = {\n ...dataAttributes,\n ...(typeof config === 'object' && config ? config : {})\n };\n config = this._mergeConfigObj(config);\n config = this._configAfterMerge(config);\n this._typeCheckConfig(config);\n return config;\n }\n _configAfterMerge(config) {\n config.container = config.container === false ? document.body : getElement(config.container);\n if (typeof config.delay === 'number') {\n config.delay = {\n show: config.delay,\n hide: config.delay\n };\n }\n if (typeof config.title === 'number') {\n config.title = config.title.toString();\n }\n if (typeof config.content === 'number') {\n config.content = config.content.toString();\n }\n return config;\n }\n _getDelegateConfig() {\n const config = {};\n for (const [key, value] of Object.entries(this._config)) {\n if (this.constructor.Default[key] !== value) {\n config[key] = value;\n }\n }\n config.selector = false;\n config.trigger = 'manual';\n\n // In the future can be replaced with:\n // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]])\n // `Object.fromEntries(keysWithDifferentValues)`\n return config;\n }\n _disposePopper() {\n if (this._popper) {\n this._popper.destroy();\n this._popper = null;\n }\n if (this.tip) {\n this.tip.remove();\n this.tip = null;\n }\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Tooltip.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n });\n }\n}\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Tooltip);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap popover.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$3 = 'popover';\nconst SELECTOR_TITLE = '.popover-header';\nconst SELECTOR_CONTENT = '.popover-body';\nconst Default$2 = {\n ...Tooltip.Default,\n content: '',\n offset: [0, 8],\n placement: 'right',\n template: '
' + '
' + '

' + '
' + '
',\n trigger: 'click'\n};\nconst DefaultType$2 = {\n ...Tooltip.DefaultType,\n content: '(null|string|element|function)'\n};\n\n/**\n * Class definition\n */\n\nclass Popover extends Tooltip {\n // Getters\n static get Default() {\n return Default$2;\n }\n static get DefaultType() {\n return DefaultType$2;\n }\n static get NAME() {\n return NAME$3;\n }\n\n // Overrides\n _isWithContent() {\n return this._getTitle() || this._getContent();\n }\n\n // Private\n _getContentForTemplate() {\n return {\n [SELECTOR_TITLE]: this._getTitle(),\n [SELECTOR_CONTENT]: this._getContent()\n };\n }\n _getContent() {\n return this._resolvePossibleFunction(this._config.content);\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Popover.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n });\n }\n}\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Popover);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap scrollspy.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$2 = 'scrollspy';\nconst DATA_KEY$2 = 'bs.scrollspy';\nconst EVENT_KEY$2 = `.${DATA_KEY$2}`;\nconst DATA_API_KEY = '.data-api';\nconst EVENT_ACTIVATE = `activate${EVENT_KEY$2}`;\nconst EVENT_CLICK = `click${EVENT_KEY$2}`;\nconst EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$2}${DATA_API_KEY}`;\nconst CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item';\nconst CLASS_NAME_ACTIVE$1 = 'active';\nconst SELECTOR_DATA_SPY = '[data-bs-spy=\"scroll\"]';\nconst SELECTOR_TARGET_LINKS = '[href]';\nconst SELECTOR_NAV_LIST_GROUP = '.nav, .list-group';\nconst SELECTOR_NAV_LINKS = '.nav-link';\nconst SELECTOR_NAV_ITEMS = '.nav-item';\nconst SELECTOR_LIST_ITEMS = '.list-group-item';\nconst SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_NAV_ITEMS} > ${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}`;\nconst SELECTOR_DROPDOWN = '.dropdown';\nconst SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle';\nconst Default$1 = {\n offset: null,\n // TODO: v6 @deprecated, keep it for backwards compatibility reasons\n rootMargin: '0px 0px -25%',\n smoothScroll: false,\n target: null,\n threshold: [0.1, 0.5, 1]\n};\nconst DefaultType$1 = {\n offset: '(number|null)',\n // TODO v6 @deprecated, keep it for backwards compatibility reasons\n rootMargin: 'string',\n smoothScroll: 'boolean',\n target: 'element',\n threshold: 'array'\n};\n\n/**\n * Class definition\n */\n\nclass ScrollSpy extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n\n // this._element is the observablesContainer and config.target the menu links wrapper\n this._targetLinks = new Map();\n this._observableSections = new Map();\n this._rootElement = getComputedStyle(this._element).overflowY === 'visible' ? null : this._element;\n this._activeTarget = null;\n this._observer = null;\n this._previousScrollData = {\n visibleEntryTop: 0,\n parentScrollTop: 0\n };\n this.refresh(); // initialize\n }\n\n // Getters\n static get Default() {\n return Default$1;\n }\n static get DefaultType() {\n return DefaultType$1;\n }\n static get NAME() {\n return NAME$2;\n }\n\n // Public\n refresh() {\n this._initializeTargetsAndObservables();\n this._maybeEnableSmoothScroll();\n if (this._observer) {\n this._observer.disconnect();\n } else {\n this._observer = this._getNewObserver();\n }\n for (const section of this._observableSections.values()) {\n this._observer.observe(section);\n }\n }\n dispose() {\n this._observer.disconnect();\n super.dispose();\n }\n\n // Private\n _configAfterMerge(config) {\n // TODO: on v6 target should be given explicitly & remove the {target: 'ss-target'} case\n config.target = getElement(config.target) || document.body;\n\n // TODO: v6 Only for backwards compatibility reasons. Use rootMargin only\n config.rootMargin = config.offset ? `${config.offset}px 0px -30%` : config.rootMargin;\n if (typeof config.threshold === 'string') {\n config.threshold = config.threshold.split(',').map(value => Number.parseFloat(value));\n }\n return config;\n }\n _maybeEnableSmoothScroll() {\n if (!this._config.smoothScroll) {\n return;\n }\n\n // unregister any previous listeners\n EventHandler.off(this._config.target, EVENT_CLICK);\n EventHandler.on(this._config.target, EVENT_CLICK, SELECTOR_TARGET_LINKS, event => {\n const observableSection = this._observableSections.get(event.target.hash);\n if (observableSection) {\n event.preventDefault();\n const root = this._rootElement || window;\n const height = observableSection.offsetTop - this._element.offsetTop;\n if (root.scrollTo) {\n root.scrollTo({\n top: height,\n behavior: 'smooth'\n });\n return;\n }\n\n // Chrome 60 doesn't support `scrollTo`\n root.scrollTop = height;\n }\n });\n }\n _getNewObserver() {\n const options = {\n root: this._rootElement,\n threshold: this._config.threshold,\n rootMargin: this._config.rootMargin\n };\n return new IntersectionObserver(entries => this._observerCallback(entries), options);\n }\n\n // The logic of selection\n _observerCallback(entries) {\n const targetElement = entry => this._targetLinks.get(`#${entry.target.id}`);\n const activate = entry => {\n this._previousScrollData.visibleEntryTop = entry.target.offsetTop;\n this._process(targetElement(entry));\n };\n const parentScrollTop = (this._rootElement || document.documentElement).scrollTop;\n const userScrollsDown = parentScrollTop >= this._previousScrollData.parentScrollTop;\n this._previousScrollData.parentScrollTop = parentScrollTop;\n for (const entry of entries) {\n if (!entry.isIntersecting) {\n this._activeTarget = null;\n this._clearActiveClass(targetElement(entry));\n continue;\n }\n const entryIsLowerThanPrevious = entry.target.offsetTop >= this._previousScrollData.visibleEntryTop;\n // if we are scrolling down, pick the bigger offsetTop\n if (userScrollsDown && entryIsLowerThanPrevious) {\n activate(entry);\n // if parent isn't scrolled, let's keep the first visible item, breaking the iteration\n if (!parentScrollTop) {\n return;\n }\n continue;\n }\n\n // if we are scrolling up, pick the smallest offsetTop\n if (!userScrollsDown && !entryIsLowerThanPrevious) {\n activate(entry);\n }\n }\n }\n _initializeTargetsAndObservables() {\n this._targetLinks = new Map();\n this._observableSections = new Map();\n const targetLinks = SelectorEngine.find(SELECTOR_TARGET_LINKS, this._config.target);\n for (const anchor of targetLinks) {\n // ensure that the anchor has an id and is not disabled\n if (!anchor.hash || isDisabled(anchor)) {\n continue;\n }\n const observableSection = SelectorEngine.findOne(decodeURI(anchor.hash), this._element);\n\n // ensure that the observableSection exists & is visible\n if (isVisible(observableSection)) {\n this._targetLinks.set(decodeURI(anchor.hash), anchor);\n this._observableSections.set(anchor.hash, observableSection);\n }\n }\n }\n _process(target) {\n if (this._activeTarget === target) {\n return;\n }\n this._clearActiveClass(this._config.target);\n this._activeTarget = target;\n target.classList.add(CLASS_NAME_ACTIVE$1);\n this._activateParents(target);\n EventHandler.trigger(this._element, EVENT_ACTIVATE, {\n relatedTarget: target\n });\n }\n _activateParents(target) {\n // Activate dropdown parents\n if (target.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) {\n SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, target.closest(SELECTOR_DROPDOWN)).classList.add(CLASS_NAME_ACTIVE$1);\n return;\n }\n for (const listGroup of SelectorEngine.parents(target, SELECTOR_NAV_LIST_GROUP)) {\n // Set triggered links parents as active\n // With both