Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev/sym opt #111

Merged
merged 26 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f6a3282
Interface for the qm program turbomole
jonathan-schoeps Dec 18, 2024
d6c60c2
support for turbomole
jonathan-schoeps Jan 8, 2025
eefcb3f
Merge branch 'main' into dev/tm_interface
jonathan-schoeps Jan 8, 2025
0a20340
corrected some typos
jonathan-schoeps Jan 8, 2025
e4f79b7
structure_mod baseline
jonathan-schoeps Jan 10, 2025
44cec38
Merge branch 'main' into dev/symmetrie_operations
jonathan-schoeps Jan 10, 2025
a1f9716
baseline for the symmetrie class
jonathan-schoeps Jan 10, 2025
144e309
Implementation of the structur modification module containing Cn rota…
jonathan-schoeps Jan 17, 2025
6e2c63f
merged recent changes
jonathan-schoeps Jan 21, 2025
e5513ec
update to the structure_modification routine and implemented unit tests.
jonathan-schoeps Jan 22, 2025
7d0e5b2
removal of left over dead code snippets
jonathan-schoeps Jan 22, 2025
6c099b0
changed a typo in the change log
jonathan-schoeps Jan 23, 2025
245c915
Re structerization of Structure_modification
jonathan-schoeps Jan 24, 2025
90fad3e
Merge branch 'main' into dev/sym_opt
jonathan-schoeps Jan 24, 2025
36cb528
bug fixes to get the structure mod classes working
jonathan-schoeps Jan 27, 2025
a7ae337
changed a word in mindlessgen.toml
jonathan-schoeps Jan 27, 2025
c7b1bf3
reorganize translation and initialization
marcelmbn Jan 27, 2025
09c6f73
refactored object-orientation of structure modification classes; fixe…
marcelmbn Jan 27, 2025
a6b61d5
abstract structure merge; minor revisions for config
marcelmbn Jan 28, 2025
d5b5fc8
Fix to print the correct output of tm and remove of a redundant singl…
jonathan-schoeps Jan 28, 2025
f7599c8
distance check for clashes and iterative distance increase if too low
marcelmbn Jan 28, 2025
76b06ff
rename some file and Class names to typical conventions
marcelmbn Jan 28, 2025
2fe6b50
further variable renaming; config clean-up
marcelmbn Jan 28, 2025
4b25ca4
add CLI access for arguments and minor adaptions
marcelmbn Jan 28, 2025
3354eac
update default TOML file
marcelmbn Jan 28, 2025
379b6ab
some renamings, better docstrings, remove useless variable copies
marcelmbn Jan 28, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `GXTBConfig` class for the g-xTB method, supporting SCF cycles check
- support for TURBOMOLE as QM engine.
- updated the parallelization to work over the number of molecules
- posibillity to generate NCI complexes with symmetrie as mindless molecules.

### Fixed
- version string is now correctly formatted and printed
Expand Down
15 changes: 15 additions & 0 deletions mindlessgen.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ num_molecules = 1
postprocess = false
# > Switch molecule structure XYZ writing on and off. Default: true. Options: <bool>
write_xyz = true
# > Switch structure modification on and off. Defaul: false. Options: <bool>
# > postprocess has to be turned on and the postprocess engine has to be turbomole.
structure_mod = false

[generate]
# > Minimum number of atoms in the generated molecule. Options: <int>
Expand Down Expand Up @@ -104,3 +107,15 @@ functional = "PBE"
basis = "def2-SVP"
# > Maximum number of SCF cycles: Options: <int>
scf_cycles = 100

[modification]
# > There is only the posibillity to do one modification at one molecule.
# > define the distance of the opposit NCI fragments. Options: <float>
distance = 3.0
# > mirror the molecule along the y,z plane.
mirror = false
# > rotate the molecule around the z axis. n is the Cn rotaion. Options: rotation: <bool>, n_fold_rotation: <int> (2, 3, 4...)
rotation = false
n_fold_rotation = 2
# > inverts the molecule through the origin.
inversion = false
25 changes: 20 additions & 5 deletions src/mindlessgen/generator/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from tqdm import tqdm

# Internal modules
from ..molecules import generate_random_molecule, Molecule
from ..molecules import generate_random_molecule, Molecule, structure_modification_mol
from ..qm import (
XTB,
get_xtb_path,
Expand Down Expand Up @@ -191,12 +191,12 @@ def single_molecule_generator(
with resources.occupy_cores(ncores):
# print a decent header for each molecule iteration
if config.general.verbosity > 0:
print(f"\n{'='*80}")
print(f"\n{'=' * 80}")
print(
f"{'='*22} Generating molecule {molcount + 1:<4} of "
+ f"{config.general.num_molecules:<4} {'='*24}"
f"{'=' * 22} Generating molecule {molcount + 1:<4} of "
+ f"{config.general.num_molecules:<4} {'=' * 24}"
)
print(f"{'='*80}")
print(f"{'=' * 80}")

with setup_managers(ncores, ncores) as (executor, manager, resources_local):
stop_event = manager.Event()
Expand Down Expand Up @@ -315,6 +315,21 @@ def single_molecule_step(
if config.refine.debug:
stop_event.set()

if config.general.structure_mod:
# raise SystemExit("Structure modification is not implemented yet.")
try:
optimized_molecule = structure_modification_mol(
optimized_molecule, config.modification, config.general.verbosity
)
except RuntimeError as e:
if config.general.verbosity > 0:
print(f"Structure modification failed for cycle {cycle + 1}.")
if config.general.verbosity > 1:
print(e)
return None
if config.general.verbosity > 1:
print("Structure modification successful.")

if config.general.postprocess:
try:
optimized_molecule = postprocess_mol(
Expand Down
2 changes: 2 additions & 0 deletions src/mindlessgen/molecules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
)
from .refinement import iterative_optimization, detect_fragments
from .postprocess import postprocess_mol
from .structure_modification import structure_modification_mol
from .miscellaneous import (
set_random_charge,
get_three_d_metals,
Expand Down Expand Up @@ -43,4 +44,5 @@
"ati_to_atlist",
"atlist_to_ati",
"postprocess_mol",
"structure_modification_mol",
]
96 changes: 96 additions & 0 deletions src/mindlessgen/molecules/structure_modification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""
Modifies the generated molecules to get symmetric NCI structures.
"""

import numpy as np
from .molecule import Molecule
from ..prog import StructureModConfig


def structure_modification_mol(
mol: Molecule, config: StructureModConfig, verbosity: int = 1
) -> Molecule:
"""
Modifies the generated molecules to get symmetric NCI structures.

Arguments:
mol (Molecule): Molecule to modify

Returns:
Molecule: Modified molecule
"""

if verbosity > 2:
print("Modifying molecule structure...")

xyz = mol.xyz
translation_vector = xyz.min()
for i in range(mol.num_atoms):
if translation_vector < 0:
xyz[i, 0] += (
-translation_vector + config.distance / 2
) # extra distance to avoid that an atom is at 0
mol.xyz = xyz

if config.mirror:
mirror_matrix = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, 1]])
xyz_mirror = xyz.copy()
modified_molecule = mol.copy()
for i in range(mol.num_atoms):
xyz_mirror[i] = np.dot(mirror_matrix, xyz[i])

# Combine the original and the mirror image
xyz_combined = np.vstack((xyz, xyz_mirror))
modified_molecule = update_molecule_objekt(modified_molecule, mol, xyz_combined)
modified_molecule.set_name_from_formula()
return modified_molecule
elif config.rotation:
n = config.n_fold_rotation
rotation_matrix = np.array(
[
[np.cos((2 * np.pi) / n), -np.sin((2 * np.pi) / n), 0],
[np.sin((2 * np.pi) / n), np.cos((2 * np.pi) / n), 0],
[0, 0, 1],
]
)
xyz_rotation = xyz.copy()
modified_molecule = mol.copy()
# For loop to get n times the molecule
for i in range(1, n):
for k in range(mol.num_atoms):
xyz_rotation[k] = np.dot(rotation_matrix, xyz_rotation[k])
xyz = np.vstack((xyz, xyz_rotation))
modified_molecule = update_molecule_objekt(modified_molecule, mol, xyz)

modified_molecule.set_name_from_formula()
return modified_molecule
elif config.inversion:
inversion_matrix = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, -1]])
xyz_inversion = xyz.copy()
modified_molecule = mol.copy()
for i in range(mol.num_atoms):
xyz_inversion[i] = np.dot(inversion_matrix, xyz[i])

xyz_combined = np.vstack((xyz, xyz_inversion))
modified_molecule = update_molecule_objekt(modified_molecule, mol, xyz_combined)
modified_molecule.set_name_from_formula()
return modified_molecule

print("structure_modification_mol is now working as a function")

return mol


def update_molecule_objekt(
modified_molecule: Molecule, mol: Molecule, xyz: np.ndarray
) -> Molecule:
"""
Updates the molecule object to the new twice as large molecule objekt.
"""
modified_molecule.xyz = xyz
modified_molecule.num_atoms += mol.num_atoms
modified_molecule.ati = np.hstack((modified_molecule.ati, mol.ati))
modified_molecule.charge += mol.charge
modified_molecule.uhf += mol.uhf
modified_molecule.atlist += mol.atlist
return modified_molecule
2 changes: 2 additions & 0 deletions src/mindlessgen/prog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
GenerateConfig,
RefineConfig,
PostProcessConfig,
StructureModConfig,
)
from .parallel import setup_managers, ResourceMonitor, setup_blocks

Expand All @@ -29,4 +30,5 @@
"setup_managers",
"ResourceMonitor",
"setup_blocks",
"StructureModConfig",
]
118 changes: 118 additions & 0 deletions src/mindlessgen/prog/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def __init__(self: GeneralConfig) -> None:
self._num_molecules: int = 1
self._postprocess: bool = False
self._write_xyz: bool = True
self._structure_mod: bool = False

def get_identifier(self) -> str:
return "general"
Expand Down Expand Up @@ -189,6 +190,22 @@ def check_config(self, verbosity: int = 1) -> None:
+ "Set '--verbosity 0' or '-P 1' to avoid this warning, or simply ignore it."
)

@property
def structure_mod(self):
"""
Get the structure_mod flag.
"""
return self._structure_mod

@structure_mod.setter
def structure_mod(self, structure_mod: bool):
"""
Set the structure_mod flag.
"""
if not isinstance(structure_mod, bool):
raise TypeError("Structure modification should be a boolean.")
self._structure_mod = structure_mod


class GenerateConfig(BaseConfig):
"""
Expand Down Expand Up @@ -1104,6 +1121,106 @@ def scf_cycles(self, max_scf_cycles: int):
self._scf_cycles = max_scf_cycles


class StructureModConfig(BaseConfig):
"""
Configuration class for structure modification settings.
"""

def __init__(self: StructureModConfig) -> None:
self.distance: float = 3.0
self._rotation: bool = False
self._n_fold_rotation: int = 4
self._mirror: bool = False
self._inversion: bool = False

def get_identifier(self) -> str:
return "modification"

@property
def distance(self):
"""
Get the distance.
"""
return self._distance

@distance.setter
def distance(self, distance: float):
"""
Set the distance.
"""
if not isinstance(distance, float):
raise TypeError("Distance should be a float.")
if distance <= 0:
raise ValueError("Distance should be greater than 0.")
self._distance = distance

@property
def rotation(self):
"""
Get the rotations flag.
"""
return self._rotation

@rotation.setter
def rotation(self, rotation: bool):
"""
Set the rotation flag.
"""
if not isinstance(rotation, bool):
raise TypeError("Rotation should be a boolean.")
self._rotation = rotation

@property
def n_fold_rotation(self):
"""
Get the number of the rotation axis.
"""
return self._n_fold_rotation

@n_fold_rotation.setter
def n_fold_rotation(self, n_fold_rotation: int):
"""
Set the number of rotations.
"""
if not isinstance(n_fold_rotation, int):
raise TypeError("Number of rotations should be an integer.")
if n_fold_rotation < 1:
raise ValueError("Number of rotations should be greater than 0.")
self._n_fold_rotation = n_fold_rotation

@property
def mirror(self):
"""
Get the mirror flag.
"""
return self._mirror

@mirror.setter
def mirror(self, mirror: bool):
"""
Set the mirror flag.
"""
if not isinstance(mirror, bool):
raise TypeError("Mirror should be a boolean.")
self._mirror = mirror

@property
def inversion(self):
"""
Get the inversion flag.
"""
return self._inversion

@inversion.setter
def inversion(self, inversion: bool):
"""
Set the inversion flag.
"""
if not isinstance(inversion, bool):
raise TypeError("Inversion should be a boolean.")
self._inversion = inversion


class ConfigManager:
"""
Overall configuration manager for the program.
Expand All @@ -1121,6 +1238,7 @@ def __init__(self, config_file: str | Path | None = None):
self.postprocess = PostProcessConfig()
self.generate = GenerateConfig()
self.gxtb = GXTBConfig()
self.modification = StructureModConfig()

if config_file:
self.load_from_toml(config_file)
Expand Down
9 changes: 8 additions & 1 deletion src/mindlessgen/qm/tm.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ def optimize(
with open(temp_path / inputname, "w", encoding="utf8") as f:
f.write(tm_input)

singlepoint_logout = self.singlepoint(molecule, ncores, verbosity)
if verbosity > 2:
print(singlepoint_logout)

# Setup the turbomole optimization command including the max number of optimization cycles
arguments = [f"PARNODES={ncores} {self.jobex_path} -c {max_cycles}"]
if verbosity > 2:
Expand Down Expand Up @@ -207,7 +211,10 @@ def _run_opt(self, temp_path: Path, arguments: list[str]) -> tuple[str, str, int
)
return tm_log_out, tm_log_err, 0
except sp.CalledProcessError as e:
tm_log_out = e.stdout.decode("utf8", errors="replace")
output_file = temp_path / "job.last"
if output_file.exists():
with open(output_file, encoding="utf-8") as file:
tm_log_out = file.read()
tm_log_err = e.stderr.decode("utf8", errors="replace")
return tm_log_out, tm_log_err, e.returncode

Expand Down
Loading
Loading