forked from grimme-lab/MindlessGen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
1699 lines (1488 loc) · 54.3 KB
/
config.py
File metadata and controls
1699 lines (1488 loc) · 54.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Contains the configuration Class for the program.
"""
from __future__ import annotations
from pathlib import Path
from abc import ABC, abstractmethod
from dataclasses import dataclass
import warnings
import multiprocessing as mp
from typing import Mapping, Sequence, Any
import numpy as np
import toml
from mindlessgen.data.constants import PSE_SYMBOLS, PSE_NUMBERS, PSE
# abstract base class for configuration
class BaseConfig(ABC):
"""
Abstract base class for configuration settings.
"""
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_identifier(self) -> str:
"""
Get the identifier of the configuration.
"""
def _symbol_to_atomic_number(symbol: str) -> int:
"""
Convert an element symbol to its atomic number.
"""
if not isinstance(symbol, str):
raise TypeError("Element symbol must be a string.")
normalized = symbol.strip().lower()
atomic_number = PSE_NUMBERS.get(normalized)
if atomic_number is None:
raise ValueError(f"Element '{symbol}' not found in the periodic table.")
return atomic_number
def _parse_distance(value: Any) -> float:
"""
Convert a user-provided distance into a validated float.
"""
if isinstance(value, (float, int)):
distance = float(value)
elif isinstance(value, str):
try:
distance = float(value)
except ValueError as exc:
raise ValueError(
f"Distance '{value}' could not be parsed as float."
) from exc
else:
raise TypeError("Distance must be a float-compatible value.")
if distance <= 0:
raise ValueError("Distance must be greater than 0.")
return distance
@dataclass
class DistanceConstraint:
"""
Representation of an atom-type distance constraint.
"""
atom_a: int
atom_b: int
distance: float
def __post_init__(self) -> None:
for attr in ("atom_a", "atom_b"):
value = getattr(self, attr)
if not isinstance(value, int):
raise TypeError("Atomic numbers must be integers.")
if value <= 0 or value not in PSE:
raise ValueError("Atomic numbers must reference known elements.")
if not isinstance(self.distance, (float, int)):
raise TypeError("Distance must be a float.")
self.distance = float(self.distance)
if self.distance <= 0:
raise ValueError("Distance must be greater than 0.")
@property
def element_a(self) -> str:
"""
Canonical symbol of the first atom type.
"""
return PSE[self.atom_a]
@property
def element_b(self) -> str:
"""
Canonical symbol of the second atom type.
"""
return PSE[self.atom_b]
@property
def atomic_numbers(self) -> tuple[int, int]:
"""
Atomic numbers of the constrained atom pair.
"""
return (self.atom_a, self.atom_b)
def required_counts(self) -> dict[int, int]:
"""
Minimum number of atoms required in the molecule for this constraint.
"""
if self.atom_a == self.atom_b:
return {self.atom_a: 2}
return {self.atom_a: 1, self.atom_b: 1}
def symbol_for(self, atomic_number: int) -> str:
"""
Return the canonical element symbol for a stored atomic number.
"""
return PSE[atomic_number]
@classmethod
def from_mapping(cls, data: Mapping[str, Any]) -> DistanceConstraint:
"""
Build a constraint from TOML data.
"""
if "pair" in data:
pair = data["pair"]
elif "elements" in data:
pair = data["elements"]
elif all(key in data for key in ("element_a", "element_b")):
pair = [data["element_a"], data["element_b"]]
else:
raise KeyError(
"Distance constraint requires either 'pair', 'elements', or "
+ "both 'element_a'/'element_b'."
)
if not isinstance(pair, Sequence) or len(pair) != 2:
raise TypeError("Constraint pair must contain two entries.")
distance = data.get("distance")
if distance is None:
raise KeyError("Distance constraint requires a 'distance' value.")
atom_a = _symbol_to_atomic_number(str(pair[0]))
atom_b = _symbol_to_atomic_number(str(pair[1]))
return cls(atom_a, atom_b, _parse_distance(distance))
@classmethod
def from_cli_string(cls, spec: str) -> DistanceConstraint:
"""
Parse a CLI constraint string formatted as 'A,B,distance'.
"""
if not isinstance(spec, str):
raise TypeError("Constraint specification must be a string.")
parts = [part.strip() for part in spec.split(",")]
if len(parts) != 3:
raise ValueError(
"Constraint specification must be formatted as 'ElementA,ElementB,distance'."
)
atom_a = _symbol_to_atomic_number(parts[0])
atom_b = _symbol_to_atomic_number(parts[1])
return cls(atom_a, atom_b, _parse_distance(parts[2]))
def __str__(self) -> str:
return f"{self.element_a}-{self.element_b}: {self.distance:g} Å"
class GeneralConfig(BaseConfig):
"""
Configuration class for general settings.
"""
def __init__(self: GeneralConfig) -> None:
self._verbosity: int = 1
self._max_cycles: int = 200
self._print_config: bool = False
self._parallel: int = 4
self._num_molecules: int = 1
self._postprocess: bool = False
self._write_xyz: bool = True
self._symmetrization: bool = False
self._tmp_dir: None | str | Path = None
def get_identifier(self) -> str:
return "general"
@property
def verbosity(self):
"""
Get the verbosity level.
"""
return self._verbosity
@verbosity.setter
def verbosity(self, verbosity: int):
"""
Set the verbosity level.
"""
if not isinstance(verbosity, int):
raise TypeError("Verbosity should be an integer.")
if verbosity not in [-1, 0, 1, 2, 3]:
raise ValueError("Verbosity can only be -1, 0, 1, 2, or 3.")
self._verbosity = verbosity
@property
def max_cycles(self):
"""
Get the maximum number of cycles.
"""
return self._max_cycles
@max_cycles.setter
def max_cycles(self, max_cycles: int):
"""
Set the maximum number of cycles.
"""
if not isinstance(max_cycles, int):
raise TypeError("Max cycles should be an integer.")
if max_cycles < 1:
raise ValueError("Max cycles should be greater than 0.")
self._max_cycles = max_cycles
@property
def print_config(self):
"""
Get the print config flag.
"""
return self._print_config
@print_config.setter
def print_config(self, print_config: bool):
"""
Set the print config flag.
"""
if not isinstance(print_config, bool):
raise TypeError("Print config should be a boolean.")
self._print_config = print_config
@property
def parallel(self):
"""
Get the parallel flag.
"""
return self._parallel
@parallel.setter
def parallel(self, parallel: int):
"""
Set the parallel flag.
"""
if not isinstance(parallel, int):
raise TypeError("Parallel should be an integer.")
if parallel < 1:
raise ValueError("Parallel should be greater than 0.")
self._parallel = parallel
@property
def num_molecules(self):
"""
Get the number of molecules.
"""
return self._num_molecules
@num_molecules.setter
def num_molecules(self, num_molecules: int):
"""
Set the number of molecules.
"""
if not isinstance(num_molecules, int):
raise TypeError("Number of molecules should be an integer.")
if num_molecules < 1:
raise ValueError("Number of molecules should be greater than 0.")
self._num_molecules = num_molecules
@property
def postprocess(self):
"""
Get the postprocess flag.
"""
return self._postprocess
@postprocess.setter
def postprocess(self, postprocess: bool):
"""
Set the postprocess flag.
"""
if not isinstance(postprocess, bool):
raise TypeError("Postprocess should be a boolean.")
self._postprocess = postprocess
@property
def write_xyz(self):
"""
Get the write xyz flag.
"""
return self._write_xyz
@write_xyz.setter
def write_xyz(self, write_xyz: bool):
"""
Set the write xyz flag.
"""
if not isinstance(write_xyz, bool):
raise TypeError("Write xyz should be a boolean.")
self._write_xyz = write_xyz
@property
def symmetrization(self):
"""
Get the symmetrization flag.
"""
return self._symmetrization
@symmetrization.setter
def symmetrization(self, symmetrization: bool):
"""
Set the symmetrization flag.
"""
if not isinstance(symmetrization, bool):
raise TypeError("Symmetrization should be a boolean.")
self._symmetrization = symmetrization
@property
def tmp_dir(self):
"""
Get the temporary directory.
"""
return self._tmp_dir
@tmp_dir.setter
def tmp_dir(self, tmp_dir: str | Path):
"""
Set the temporary directory.
"""
if not isinstance(tmp_dir, (str, Path)):
raise TypeError("Temporary directory should be a string or a Path object.")
if isinstance(tmp_dir, str):
if tmp_dir == "" or tmp_dir.lower() == "none":
self._tmp_dir = None
return
tmp_dir = Path(tmp_dir).resolve()
elif isinstance(tmp_dir, Path):
tmp_dir = tmp_dir.resolve()
# raise error if value is a file
if tmp_dir.is_file():
raise ValueError("Temporary directory should not be a file.")
self._tmp_dir = tmp_dir
def check_config(self, verbosity: int = 1) -> None:
### GeneralConfig checks ###
# lower number of the available cores and the configured parallelism
num_cores = min(mp.cpu_count(), self.parallel)
if self.parallel > mp.cpu_count() and verbosity > -1:
warnings.warn(
f"Number of cores requested ({self.parallel}) is greater "
+ f"than the number of available cores ({mp.cpu_count()})."
+ f"Using {num_cores} cores instead."
)
if num_cores > 1 and verbosity > 0:
# raise warning that parallelization will disable verbosity
warnings.warn(
"Parallelization will disable verbosity during iterative search. "
+ "Set '--verbosity 0' or '-P 1' to avoid this warning, or simply ignore it."
)
# Symmetrization without postprocessing
if self.symmetrization and not self.postprocess:
if verbosity > 0:
warnings.warn(
"Postprocessing is turned off. The structure will not be relaxed."
)
class GenerateConfig(BaseConfig):
"""
Configuration for the "generate" section responsible for setting up an initial Molecule type.
"""
def __init__(self: GenerateConfig) -> None:
self._min_num_atoms: int = 5
self._max_num_atoms: int = 10
self._init_coord_scaling: float = 3.0
self._increase_scaling_factor: float = 1.1
self._element_composition: dict[int, tuple[int | None, int | None]] = {}
self._forbidden_elements: list[int] | None = None
self._scale_fragment_detection: float = 1.25
self._scale_minimal_distance: float = 0.8
self._contract_coords: bool = True
self._molecular_charge: int | None = None
self._fixed_composition: bool = False
def get_identifier(self) -> str:
return "generate"
@property
def min_num_atoms(self):
"""
Get the minimum number of atoms.
"""
return self._min_num_atoms
@min_num_atoms.setter
def min_num_atoms(self, min_num_atoms: int):
"""
Set the minimum number of atoms.
"""
if not isinstance(min_num_atoms, int):
raise TypeError("Min num atoms should be an integer.")
if min_num_atoms < 1:
raise ValueError("Min num atoms should be greater than 0.")
self._min_num_atoms = min_num_atoms
@property
def max_num_atoms(self):
"""
Get the maximum number of atoms.
"""
return self._max_num_atoms
@max_num_atoms.setter
def max_num_atoms(self, max_num_atoms: int):
"""
Set the maximum number of atoms.
"""
if not isinstance(max_num_atoms, int):
raise TypeError("Max num atoms should be an integer.")
if max_num_atoms < 1:
raise ValueError("Max num atoms should be greater than 0.")
self._max_num_atoms = max_num_atoms
@property
def init_coord_scaling(self):
"""
Get the initial coordinate scaling.
"""
return self._init_coord_scaling
@init_coord_scaling.setter
def init_coord_scaling(self, init_coord_scaling: float):
"""
Set the initial coordinate scaling.
"""
if not isinstance(init_coord_scaling, float):
raise TypeError("Initial coordinate scaling should be a float.")
if init_coord_scaling <= 0:
raise ValueError("Initial coordinate scaling should be greater than 0.")
self._init_coord_scaling = init_coord_scaling
@property
def increase_scaling_factor(self):
"""
Get the increase scaling factor.
"""
return self._increase_scaling_factor
@increase_scaling_factor.setter
def increase_scaling_factor(self, increase_scaling_factor: float):
"""
Set the increase scaling factor.
"""
if not isinstance(increase_scaling_factor, float):
raise TypeError("Increase scaling factor should be a float.")
if increase_scaling_factor <= 1:
raise ValueError("Increase scaling factor should be greater than 1.")
self._increase_scaling_factor = increase_scaling_factor
@property
def element_composition(self):
"""
Return the element composition.
"""
return self._element_composition
@element_composition.setter
def element_composition(
self, composition: None | str | dict[int | str, tuple[int | None, int | None]]
) -> None:
"""
If composition: str:
Parses the element_composition string and stores the parsed data
in the _element_composition dictionary.
Format: "C:2-10, H:10-20, O:1-5, N:1-*"
If composition: dict:
Should be a dictionary with integer/string keys and tuple values. Will be stored as is.
Arguments:
composition_str (str): String with the element composition
composition_str (dict): Dictionary with integer/str keys and tuple values
Raises:
TypeError: If composition_str is not a string or a dictionary
AttributeError: If the element is not found in the periodic table
ValueError: If the minimum count is larger than the maximum count
Returns:
None
"""
if not composition:
return
# Will return if composition dict does not contain either int or str keys and tuple[int | None, int | None] values
# Will also return if dict is valid after setting property
if isinstance(composition, dict):
tmp = {}
# Check validity and also convert str keys into atomic numbers
for key, value in composition.items():
if (
not (isinstance(key, int) or isinstance(key, str))
or not isinstance(value, tuple)
or len(value) != 2
or not all(isinstance(val, int) or val is None for val in value)
):
raise TypeError(
"Element composition dictionary should be a dictionary with either integer or string keys and tuple values (int, int)."
)
# Convert str keys
if isinstance(key, str):
element_number = PSE_NUMBERS.get(key.lower(), None)
if element_number is None:
raise KeyError(
f"Element {key} not found in the periodic table."
)
tmp[element_number - 1] = composition[key]
# Check int keys
else:
if key + 1 in PSE_SYMBOLS:
tmp[key] = composition[key]
else:
raise KeyError(
f"Element with atomic number {key + 1} (provided key: {key}) not found in the periodic table."
)
self._element_composition = tmp
return
if not isinstance(composition, str):
raise TypeError(
"Element composition should be a string (will be parsed) or "
+ "a dictionary with integer/string keys and tuple values."
)
# Parsing composition string
element_dict: dict[int, tuple[int | None, int | None]] = {}
elements = composition.split(",")
# remove leading and trailing whitespaces
elements = [element.strip() for element in elements]
min_count: int | str | None
max_count: int | str | None
for element in elements:
element_type, range_str = element.split(":")
min_count, max_count = range_str.split("-")
element_number = PSE_NUMBERS.get(element_type.lower(), None)
if element_number is None:
raise AttributeError(
f"Element {element_type} not found in the periodic table."
)
# correct for 1- vs. 0-based indexing
element_number = element_number - 1
# Convert counts, handle wildcard '*'
min_count = None if min_count == "*" else int(min_count)
max_count = None if max_count == "*" else int(max_count)
if (
min_count is not None
and max_count is not None
and min_count > max_count
):
raise ValueError(
f"Minimum count ({min_count}) is larger than maximum count ({max_count})."
)
element_dict[element_number] = (min_count, max_count)
self._element_composition = element_dict
@property
def forbidden_elements(self):
"""
Return sorted list of forbidden elements.
"""
return self._forbidden_elements
@forbidden_elements.setter
def forbidden_elements(
self: GenerateConfig, forbidden: None | str | list[int]
) -> None:
"""
If forbidden: str:
Parses the forbidden_elements string and stores the parsed data
in the _forbidden_elements set.
Format: "57-71, 8, 1" or "19-*"
If forbidden: list:
Stores the forbidden elements as is.
Arguments:
forbidden (str): String with the forbidden elements
forbidden (list): List with integer values
Raises:
TypeError: If forbidden is not a string or a list of integers
ValueError: If both start and end are wildcard '*'
Returns:
None
"""
# if string is empty or None, set to None
if not forbidden:
self._forbidden_elements = None
return
if isinstance(forbidden, list):
if all(isinstance(elem, int) for elem in forbidden):
self._forbidden_elements = sorted(forbidden)
return
raise TypeError("Forbidden elements should be a list of integers.")
if not isinstance(forbidden, str):
raise TypeError(
"Forbidden elements should be a string or a list of integers."
)
forbidden_set: set[int] = set()
elements = forbidden.split(",")
elements = [element.strip() for element in elements]
for item in elements:
if "-" in item:
start: str | int
end: str | int
start, end = item.split("-")
if end == "*" and start == "*":
raise ValueError("Both start and end cannot be wildcard '*'.")
if end == "*":
end = 103 # Set to a the maximum atomic number in mindlessgen
if start == "*":
start = 0
forbidden_set.update(
range(int(start) - 1, int(end))
) # Subtract 1 to convert to 0-based indexing
else:
forbidden_set.add(
int(item) - 1
) # Subtract 1 to convert to 0-based indexing
self._forbidden_elements = sorted(list(forbidden_set))
@property
def scale_fragment_detection(self):
"""
Get the scaling factor for the fracment detection based on the van der Waals radii.
"""
return self._scale_fragment_detection
@scale_fragment_detection.setter
def scale_fragment_detection(self, scale_fragment_detection: float):
"""
Set the scaling factor for van der Waals radii.
"""
if not isinstance(scale_fragment_detection, float):
raise TypeError("Scale van der Waals radii should be a float.")
if scale_fragment_detection <= 0:
raise ValueError("Scale van der Waals radii should be greater than 0.")
self._scale_fragment_detection = scale_fragment_detection
@property
def scale_minimal_distance(self):
"""
Get the scaling factor for minimal distance between two atoms.
"""
return self._scale_minimal_distance
@scale_minimal_distance.setter
def scale_minimal_distance(self, scale_minimal_distance: float):
"""
Set the scaling factor for minimal distance between two atoms.
"""
if not isinstance(scale_minimal_distance, float):
raise TypeError("Scale minimal distance should be a float.")
if scale_minimal_distance <= 0:
raise ValueError("Scale minimal distance should be greater than 0.")
self._scale_minimal_distance = scale_minimal_distance
@property
def contract_coords(self):
"""
Get the contract_coords flag.
"""
return self._contract_coords
@contract_coords.setter
def contract_coords(self, contract_coords: bool):
"""
Set the contract_coords flag.
"""
if not isinstance(contract_coords, bool):
raise TypeError("Contract coords should be a boolean.")
self._contract_coords = contract_coords
@property
def molecular_charge(self):
"""
Get the molecular_charge.
"""
return self._molecular_charge
@molecular_charge.setter
def molecular_charge(self, molecular_charge: str | int):
"""
Set the molecular_charge.
"""
if isinstance(molecular_charge, str):
if molecular_charge.lower() == "none" or molecular_charge == "":
self._molecular_charge = None
else:
self._molecular_charge = int(molecular_charge)
elif isinstance(molecular_charge, int):
self._molecular_charge = molecular_charge
else:
raise TypeError("Molecular charge should be a string or an integer.")
@property
def fixed_composition(self):
"""
Get the fixed_composition flag.
"""
return self._fixed_composition
@fixed_composition.setter
def fixed_composition(self, fixed_composition: bool):
"""
Set the fixed_composition flag.
"""
if not isinstance(fixed_composition, bool):
raise TypeError("Fixed composition should be a boolean.")
self._fixed_composition = fixed_composition
def check_config(self, verbosity: int = 1) -> None:
"""
GenerateConfig checks for any incompatibilities that are imaginable
"""
# - Check if the minimum number of atoms is smaller than the maximum number of atoms
if self.min_num_atoms is not None and self.max_num_atoms is not None:
if self.min_num_atoms > self.max_num_atoms:
raise ValueError(
"The minimum number of atoms is larger than the maximum number of atoms."
)
# - Check if the summed number of minimally required atoms from cfg.element_composition
# is larger than the maximum number of atoms
if self.max_num_atoms is not None:
if (
np.sum(
[
(
self.element_composition.get(i, (0, 0))[0]
if self.element_composition.get(i, (0, 0))[0] is not None
else 0
)
for i in self.element_composition
]
)
> self.max_num_atoms
):
raise ValueError(
"The summed number of minimally required atoms "
+ "from the fixed composition is larger than the maximum number of atoms."
)
if self.fixed_composition:
# - Check if all defintions in cfg.element_composition
# are completely fixed (min and max are equal)
for elem, count_range in self.element_composition.items():
# check if for all entries: min and max are both not None, and if min and max are equal.
if (
(count_range[0] is None)
or (count_range[1] is None)
or (count_range[0] != count_range[1])
):
raise ValueError(
f"Element {elem} is not completely fixed in the element composition. "
+ "Usage together with fixed_composition is not possible."
)
# Check if the summed number of fixed atoms
# is within the defined overall limits
sum_fixed_atoms = np.sum(
[
self.element_composition.get(i, (0, 0))[0]
for i in self.element_composition
]
)
if self.min_num_atoms is not None and not (
self.min_num_atoms <= sum_fixed_atoms
):
raise ValueError(
"The summed number of fixed atoms from the fixed composition "
+ "is not within the range of min_num_atoms and max_num_atoms."
)
class RefineConfig(BaseConfig):
"""
Configuration class for refinement settings.
"""
def __init__(self: RefineConfig) -> None:
self._max_frag_cycles: int = 10
self._engine: str = "xtb"
self._hlgap: float = 0.5
self._debug: bool = False
self._ncores: int = 2
def get_identifier(self) -> str:
return "refine"
@property
def max_frag_cycles(self):
"""
Get the maximum number of fragment cycles.
"""
return self._max_frag_cycles
@max_frag_cycles.setter
def max_frag_cycles(self, max_frag_cycles: int):
"""
Set the maximum number of fragment cycles.
"""
if not isinstance(max_frag_cycles, int):
raise TypeError("Max fragment cycles should be an integer.")
if max_frag_cycles < 1:
raise ValueError("Max fragment cycles should be greater than 0.")
self._max_frag_cycles = max_frag_cycles
@property
def engine(self):
"""
Get the engine.
"""
return self._engine
@engine.setter
def engine(self, engine: str):
"""
Set the engine.
"""
if not isinstance(engine, str):
raise TypeError("Refinement engine should be a string.")
if engine not in ["xtb", "orca", "turbomole"]:
raise ValueError("Refinement engine can only be xtb, orca or turbomole.")
self._engine = engine
@property
def hlgap(self):
"""
Get the minimum HOM
"""
return self._hlgap
@hlgap.setter
def hlgap(self, hlgap: float):
"""
Set the minimum HOM
"""
if not isinstance(hlgap, float):
raise TypeError("Minimum HL gap should be a float.")
if hlgap < 0:
raise ValueError("Minimum HL gap should be greater than 0.")
self._hlgap = hlgap
@property
def debug(self):
"""
Get the debug flag for refinement.
"""
return self._debug
@debug.setter
def debug(self, debug: bool):
"""
Set the debug flag for refinement.
"""
if not isinstance(debug, bool):
raise TypeError("Debug should be a boolean.")
self._debug = debug
@property
def ncores(self):
"""
Get the number of cores to be used for geometry optimizations in refinement.
"""
return self._ncores
@ncores.setter
def ncores(self, ncores: int):
"""
Set the number of cores to be used for geometry optimizations in refinement.
"""
if not isinstance(ncores, int):
raise TypeError("Number of cores should be an integer.")
self._ncores = ncores
class PostProcessConfig(BaseConfig):
"""
Configuration class for post-processing settings.
"""
def __init__(self: PostProcessConfig) -> None:
self._engine: str = "orca"
self._opt_cycles: int | None = None
self._optimize: bool = True
self._debug: bool = False
self._ncores: int = 4
def get_identifier(self) -> str:
return "postprocess"
@property
def engine(self):
"""
Get the postprocess engine.
"""
return self._engine
@engine.setter
def engine(self, engine: str):
"""
Set the postprocess engine.
"""
if not isinstance(engine, str):
raise TypeError("Postprocess engine should be a string.")
if engine not in ["xtb", "orca", "gxtb", "turbomole"]:
raise ValueError("Postprocess engine can only be xtb, orca or turbomole.")
self._engine = engine
@property
def optimize(self):
"""
Get the optimization flag for post-processing.
"""
return self._optimize
@optimize.setter
def optimize(self, optimize: bool):
"""
Set the optimization flag for post-processing.
"""
if not isinstance(optimize, bool):
raise TypeError("Optimize should be a boolean.")
self._optimize = optimize
@property
def opt_cycles(self):
"""
Get the optimization cycles for post-processing.
"""
return self._opt_cycles
@opt_cycles.setter
def opt_cycles(self, opt_cycles: int):
"""
Set the optimization cycles for post-processing.
"""
if not isinstance(opt_cycles, (int, str)):
raise TypeError("Optimization cycles can only be an integer or a string.")
if isinstance(opt_cycles, str):
if opt_cycles.lower() != "none":
raise ValueError(
"Optimization cycles can only be an integer or 'none'."
)
self._opt_cycles = None
return
if opt_cycles == 0:
self._opt_cycles = None
return
if opt_cycles < 0:
raise ValueError("Optimization cycles can only be 0 or greater.")
self._opt_cycles = opt_cycles
@property
def debug(self):
"""
Get the debug flag for post-processing.
"""
return self._debug
@debug.setter
def debug(self, debug: bool):
"""
Set the debug flag for post-processing.
"""
if not isinstance(debug, bool):
raise TypeError("Debug should be a boolean.")
self._debug = debug
@property
def ncores(self):
"""
Get the number of cores to be used in post-processing.
"""