forked from duartegroup/autodE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atoms.py
1865 lines (1570 loc) · 45 KB
/
atoms.py
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
import numpy as np
from copy import deepcopy
from typing import Union, Optional, List, Sequence, Any
from autode.log import logger
from autode.geom import get_rot_mat_euler
from autode.values import (
Distance,
Angle,
Mass,
Coordinate,
Coordinates,
MomentOfInertia,
)
class Atom:
def __init__(
self,
atomic_symbol: str,
x: Any = 0.0,
y: Any = 0.0,
z: Any = 0.0,
atom_class: Optional[int] = None,
partial_charge: Optional[float] = None,
):
"""
Atom class. Centered at the origin by default. Can be initialised from
positional or keyword arguments:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('H')
Atom(H, 0.0000, 0.0000, 0.0000)
>>>
>>> ade.Atom('H', x=1.0, y=1.0, z=1.0)
Atom(H, 1.0000, 1.0000, 1.0000)
>>>
>>> ade.Atom('H', 1.0, 1.0, 1.0)
Atom(H, 1.0000, 1.0000, 1.0000)
-----------------------------------------------------------------------
Arguments:
atomic_symbol: Symbol of an element e.g. 'C' for carbon
x: x coordinate in 3D space (Å)
y: y coordinate in 3D space (Å)
z: z coordinate in 3D space (Å)
atom_class: Fictitious additional labels to distinguish otherwise
identical atoms. Useful in finding bond isomorphisms
over identity reactions
partial_charge: Partial atomic charge in units of e, determined by
the atomic envrionment. Not an observable property.
"""
assert atomic_symbol in elements
self.label = atomic_symbol
self._coord = Coordinate(float(x), float(y), float(z))
self.atom_class = atom_class
self.partial_charge = (
None if partial_charge is None else float(partial_charge)
)
def __repr__(self):
"""
Representation of this atom
-----------------------------------------------------------------------
Returns:
(str): Representation
"""
x, y, z = self.coord
return f"Atom({self.label}, {x:.4f}, {y:.4f}, {z:.4f})"
def __str__(self):
return self.__repr__()
def __eq__(self, other: Any):
"""Equality of another atom to this one"""
are_equal = (
isinstance(other, Atom)
and other.label == self.label
and other.atom_class == self.atom_class
and isinstance(other.partial_charge, type(self.partial_charge))
and (
(other.partial_charge is None and self.partial_charge is None)
or np.isclose(other.partial_charge, self.partial_charge)
)
and np.allclose(other._coord, self._coord)
)
return are_equal
@property
def atomic_number(self) -> int:
"""
Atomic numbers are the position in the elements (indexed from zero),
plus one. Example:
.. code-block:: Python
>>> import autode as ade
>>> atom = ade.Atom('C')
>>> atom.atomic_number
6
-----------------------------------------------------------------------
Returns:
(int): Atomic number
"""
return elements.index(self.label) + 1
@property
def atomic_symbol(self) -> str:
"""
A more interpretable alias for Atom.label. Should be present in the
elements. Example:
.. code-block:: Python
>>> import autode as ade
>>> atom = ade.Atom('Zn')
>>> atom.atomic_symbol
'Zn'
-----------------------------------------------------------------------
Returns:
(str): Atomic symbol
"""
return self.label
@property
def coord(self) -> Coordinate:
"""
Position of this atom in space. Coordinate has attributes x, y, z
for the Cartesian displacements. Example:
.. code-block:: Python
>>> import autode as ade
>>> atom = ade.Atom('H')
>>> atom.coord
Coordinate([0. 0. 0.] Å)
To initialise at a different position away from the origin
.. code-block:: Python
>>> ade.Atom('H', x=1.0).coord
Coordinate([1. 0. 0.] Å)
>>> ade.Atom('H', x=1.0).coord.x
1.0
Coordinates are instances of autode.values.ValueArray, so can
be converted from the default angstrom units to e.g. Bohr
.. code-block:: Python
>>> ade.Atom('H', x=1.0, y=-1.0).coord.to('a0')
Coordinate([1.889 -1.889 0. ] bohr)
-----------------------------------------------------------------------
Returns:
(autode.values.Coordinate): Coordinate
"""
return self._coord
@coord.setter
def coord(self, *args):
"""
Coordinate setter
-----------------------------------------------------------------------
Arguments:
*args (float | list(float) | np.ndarray(float)):
Raises:
(ValueError): If the arguments cannot be coerced into a (3,) shape
"""
self._coord = Coordinate(*args)
@property
def is_metal(self) -> bool:
"""
Is this atom a metal? Defines metals to be up to and including:
Ga, Sn, Bi. Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('C').is_metal
False
>>> ade.Atom('Zn').is_metal
True
-----------------------------------------------------------------------
Returns:
(bool):
"""
return self.label in metals
@property
def group(self) -> int:
"""
Group of the periodic table is this atom in. 0 if not found. Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('C').group
14
-----------------------------------------------------------------------
Returns:
(int): Group
"""
for group_idx in range(1, 18):
if self.label in PeriodicTable.group(group_idx):
return group_idx
return 0
@property
def period(self) -> int:
"""
Period of the periodic table is this atom in. 0 if not found. Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('C').period
2
-----------------------------------------------------------------------
Returns:
(int): Period
"""
for period_idx in range(1, 7):
if self.label in PeriodicTable.period(period_idx):
return period_idx
return 0
@property
def tm_row(self) -> Optional[int]:
"""
Row of transition metals that this element is in. Returns None if
this atom is not a metal. Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('Zn').tm_row
1
-----------------------------------------------------------------------
Returns:
(int | None): Transition metal row
"""
for row in [1, 2, 3]:
if self.label in PeriodicTable.transition_metals(row):
return row
return None
@property
def weight(self) -> Mass:
"""
Atomic weight. Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('C').weight
Mass(12.0107 amu)
>>>
>>> ade.Atom('C').weight == ade.Atom('C').mass
True
-----------------------------------------------------------------------
Returns:
(autode.values.Mass): Weight
"""
try:
return Mass(atomic_weights[self.label])
except KeyError:
logger.warning(
f"Could not find a valid weight for {self.label}. "
f"Guessing at 70"
)
return Mass(70)
@property
def mass(self) -> Mass:
"""Alias of weight. Returns Atom.weight an so can be converted
to different units. For example, to convert the mass to electron masses:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('H').mass.to('me')
Mass(1837.36222 m_e)
-----------------------------------------------------------------------
Returns:
(autode.values.Mass): Mass
"""
return self.weight
@property
def maximal_valance(self) -> int:
"""
The maximum/maximal valance that this atom supports in any charge
state (most commonly). i.e. for H the maximal_valance=1. Useful for
generating molecular graphs
-----------------------------------------------------------------------
Returns:
(int): Maximal valance
"""
if self.is_metal:
return 6
if self.label in _max_valances:
return _max_valances[self.label]
logger.warning(
f"Could not find a valid valance for {self}. " f"Guessing at 6"
)
return 6
@property
def vdw_radius(self) -> Distance:
"""
Van der Waals radius for this atom. Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('H').vdw_radius
Distance(1.1 Å)
-----------------------------------------------------------------------
Returns:
(autode.values.Distance): Van der Waals radius
"""
if self.label in vdw_radii:
radius = vdw_radii[self.label]
else:
logger.error(
f"Couldn't find the VdV radii for {self}. "
f"Guessing at 2.3 Å"
)
radius = 2.3
return Distance(radius, "Å")
@property
def covalent_radius(self) -> Distance:
"""
Covalent radius for this atom. Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('H').covalent_radius
Distance(0.31 Å)
-----------------------------------------------------------------------
Returns:
(autode.values.Distance): Van der Waals radius
"""
radius = Distance(
_covalent_radii_pm[self.atomic_number - 1], units="pm"
)
return radius.to("Å")
def is_pi(self, valency: int) -> bool:
"""
Determine if this atom is a 'π-atom' i.e. is unsaturated. Only
approximate! Example:
.. code-block:: Python
>>> import autode as ade
>>> ade.Atom('C').is_pi(valency=3)
True
>>> ade.Atom('H').is_pi(valency=1)
False
-----------------------------------------------------------------------
Arguments:
valency (int):
Returns:
(bool):
"""
if self.label in non_pi_elements:
return False
if self.label not in pi_valencies:
logger.warning(
f"{self.label} not found in π valency dictionary - "
f"assuming not a π-atom"
)
return False
if valency in pi_valencies[self.label]:
return True
return False
def translate(self, *args, **kwargs) -> None:
"""
Translate this atom by a vector in place. Arguments should be
coercible into a coordinate (i.e. length 3). Example:
.. code-block:: Python
>>> import autode as ade
>>> atom = ade.Atom('H')
>>> atom.translate(1.0, 0.0, 0.0)
>>> atom.coord
Coordinate([1. 0. 0.] Å)
Atoms can also be translated using numpy arrays:
.. code-block:: Python
>>> import autode as ade
>>> import numpy as np
>>>
>>> atom = ade.Atom('H')
>>> atom.translate(np.ones(3))
>>> atom.coord
Coordinate([1. 1. 1.] Å)
>>>
>>> atom.translate(vec=-atom.coord)
>>> atom.coord
Coordinate([0. 0. 0.] Å)
-----------------------------------------------------------------------
Arguments:
*args (float | np.ndarray | list(float)):
Keyword Arguments:
vec (np.ndarray): Shape = (3,)
"""
if "vec" in kwargs:
# Assume the vec is cast-able to a numpy array which can be added
self.coord += np.asarray(kwargs["vec"])
elif len(kwargs) > 0:
raise ValueError(
f"Expecting only a vec keyword argument. " f"Had {kwargs}"
)
else:
self.coord += Coordinate(*args)
return None
def rotate(
self,
axis: Union[np.ndarray, Sequence],
theta: Union[Angle, float],
origin: Union[np.ndarray, Sequence, None] = None,
) -> None:
"""
Rotate this atom theta radians around an axis given an origin. By
default the rotation is applied around the origin with the angle
in radians (unless an autode.values.Angle). Rotation is applied in
place. To rotate a H atom around the z-axis:
.. code-block:: Python
>>> import autode as ade
>>> atom = ade.Atom('H', x=1.0)
>>> atom.rotate(axis=[0.0, 0.0, 1.0], theta=3.14)
>>> atom.coord
Coordinate([-1. 0. 0.] Å)
With an origin:
.. code-block:: Python
>>> import autode as ade
>>> atom = ade.Atom('H')
>>> atom.rotate(axis=[0.0, 0.0, 1.0], theta=3.14, origin=[1.0, 0.0, 0.0])
>>> atom.coord
Coordinate([2. 0. 0.] Å)
And with an angle not in radians:
.. code-block:: Python
>>> import autode as ade
>>> from autode.values import Angle
>>>
>>> atom = ade.Atom('H', x=1.0)
>>> atom.rotate(axis=[0.0, 0.0, 1.0], theta=Angle(180, units='deg'))
>>> atom.coord
Coordinate([-1. 0. 0.] Å)
-----------------------------------------------------------------------
Arguments:
axis: Axis to rotate in. shape = (3,)
theta: Angle to rotate by
origin: Rotate about this origin. shape = (3,) if no origin is
specified then the atom is rotated without translation.
"""
# If specified, shift so that the origin is at (0, 0, 0)
if origin is not None:
self.translate(vec=-np.asarray(origin))
# apply the rotation
rot_matrix = get_rot_mat_euler(axis=axis, theta=theta)
self.coord = np.matmul(rot_matrix, self.coord)
# and shift back, if required
if origin is not None:
self.translate(vec=np.asarray(origin))
return None
def copy(self) -> "Atom":
return deepcopy(self)
# --- Method aliases ---
coordinate = coord
class DummyAtom(Atom):
def __init__(self, x, y, z):
"""
Dummy atom
-----------------------------------------------------------------------
Arguments:
x (float): x coordinate in 3D space (Å)
y (float): y
z (float): z
"""
# Superclass constructor called with a valid element...
super().__init__("H", x, y, z)
# then re-assigned
self.label = "D"
@property
def atomic_number(self):
"""The atomic number is defined as 0 for a dummy atom"""
return 0
@property
def weight(self) -> Mass:
"""Dummy atoms do not have any weight/mass"""
return Mass(0.0)
@property
def mass(self) -> Mass:
"""Dummy atoms do not have any weight/mass"""
return Mass(0.0)
@property
def vdw_radius(self) -> Distance:
"""Dummy atoms have no radius"""
return Distance(0.0, units="Å")
@property
def covalent_radius(self) -> Distance:
"""Dummy atoms have no radius"""
return Distance(0.0, units="Å")
class Atoms(list):
def __repr__(self):
"""Representation"""
return f"Atoms(n_atoms={len(self)}, {super().__repr__()})"
def __add__(self, other):
"""Add another set of Atoms to this one. Can add None"""
if other is None:
return self
return super().__add__(other)
def __radd__(self, other):
"""Add another set of Atoms to this one. Can add None"""
return self.__add__(other)
def copy(self) -> "Atoms":
"""
Copy these atoms, deeply
-----------------------------------------------------------------------
Returns:
(autode.atoms.Atoms):
"""
return deepcopy(self)
def remove_dummy(self) -> None:
"""Remove all the dummy atoms from this list of atoms"""
for i, atom in enumerate(self):
if isinstance(atom, DummyAtom):
del self[i]
return
@property
def coordinates(self) -> Coordinates:
return Coordinates(np.array([a.coord for a in self]))
@coordinates.setter
def coordinates(self, value: np.ndarray):
"""Set the coordinates from a numpy array
-----------------------------------------------------------------------
Arguments:
value (np.ndarray): Shape = (n_atoms, 3) or (3*n_atoms) as a
row major vector
"""
if value.ndim == 1:
assert value.shape == (3 * len(self),)
value = value.reshape((-1, 3))
elif value.ndim == 2:
assert value.shape == (len(self), 3)
else:
raise AssertionError(
"Cannot set coordinates from a array with"
f"shape: {value.shape}. Must be 1 or 2 "
f"dimensional"
)
for i, atom in enumerate(self):
atom.coord = Coordinate(*value[i])
@property
def com(self) -> Coordinate:
r"""
Centre of mass of these coordinates
.. math::
\text{COM} = \frac{1}{M} \sum_i m_i R_i
where M is the total mass, m_i the mass of atom i and R_i it's
coordinate
-----------------------------------------------------------------------
Returns:
(autode.values.Coordinate): COM
"""
if len(self) == 0:
raise ValueError("Undefined centre of mass with no atoms")
com = Coordinate(0.0, 0.0, 0.0)
for atom in self:
com += atom.mass * atom.coord
return Coordinate(com / sum(atom.mass for atom in self))
@property
def moi(self) -> MomentOfInertia:
"""
Moment of inertia matrix (I)::
(I_00 I_01 I_02)
I = (I_10 I_11 I_12)
(I_20 I_21 I_22)
Returns:
(autode.values.MomentOfInertia):
"""
moi = MomentOfInertia(np.zeros(shape=(3, 3)), units="amu Å^2")
for atom in self:
mass, (x, y, z) = atom.mass, atom.coord
moi[0, 0] += mass * (y**2 + z**2)
moi[0, 1] -= mass * (x * y)
moi[0, 2] -= mass * (x * z)
moi[1, 0] -= mass * (y * x)
moi[1, 1] += mass * (x**2 + z**2)
moi[1, 2] -= mass * (y * z)
moi[2, 0] -= mass * (z * x)
moi[2, 1] -= mass * (z * y)
moi[2, 2] += mass * (x**2 + y**2)
return moi
@property
def contain_metals(self) -> bool:
"""
Do these atoms contain at least a single metal atom?
-----------------------------------------------------------------------
Returns:
(bool):
"""
return any(atom.label in metals for atom in self)
def idxs_are_present(self, *args: int) -> bool:
"""Are all these indexes present in this set of atoms"""
return set(args).issubset(set(range(len(self))))
def eqm_bond_distance(self, i: int, j: int) -> Distance:
"""
Equilibrium distance between two atoms. If known then use the
experimental dimer distance, otherwise estimate if from the
covalent radii of the two atoms. Example
Example:
.. code-block:: Python
>>> import autode as ade
>>> mol = ade.Molecule(atoms=[ade.Atom('H'), ade.Atom('H')])
>>> mol.distance(0, 1)
Distance(0.0 Å)
>>> mol.eqm_bond_distance(0, 1)
Distance(0.741 Å)
-----------------------------------------------------------------------
Returns:
(autode.values.Distance): Equlirbium distance
"""
if not self.idxs_are_present(i, j):
raise ValueError(
f"Cannot calculate the equilibrium distance "
f"between {i}-{j}. At least one atom not present"
)
if i == j:
return Distance(0.0, units="Å")
symbols = f"{self[i].atomic_symbol}{self[j].atomic_symbol}"
if symbols in _bond_lengths:
return Distance(_bond_lengths[symbols], units="Å")
# TODO: Something more accurate here
return self[i].covalent_radius + self[j].covalent_radius
def distance(self, i: int, j: int) -> Distance:
"""
Distance between two atoms (Å), indexed from 0.
.. code-block:: Python
>>> import autode as ade
>>> mol = ade.Molecule(atoms=[ade.Atom('H'), ade.Atom('H', x=1.0)])
>>> mol.distance(0, 1)
Distance(1.0 Å)
-----------------------------------------------------------------------
Arguments:
i (int): Atom index of the first atom
j (int): Atom index of the second atom
Returns:
(autode.values.Distance): Distance
Raises:
(ValueError):
"""
if not self.idxs_are_present(i, j):
raise ValueError(
f"Cannot calculate the distance between {i}-{j}. "
f"At least one atom not present"
)
return Distance(np.linalg.norm(self[i].coord - self[j].coord))
def vector(self, i: int, j: int) -> np.ndarray:
"""
Vector from atom i to atom j
-----------------------------------------------------------------------
Arguments:
i (int):
j (int):
Returns:
(np.ndarray):
Raises:
(IndexError): If i or j are not present
"""
return np.asarray(self[j].coord - self[i].coord)
def nvector(self, i: int, j: int) -> np.ndarray:
"""
Normalised vector from atom i to atom j
-----------------------------------------------------------------------
Arguments:
i (int):
j (int):
Returns:
(np.ndarray):
Raises:
(IndexError): If i or j are not present
"""
vec = self.vector(i, j)
return vec / np.linalg.norm(vec)
def are_linear(self, angle_tol: Angle = Angle(1, "º")) -> bool:
"""
Are these set of atoms colinear?
-----------------------------------------------------------------------
Arguments:
angle_tol (autode.values.Angle): Tolerance on the angle
Returns:
(bool): Whether the atoms are linear
"""
if len(self) < 2: # Must have at least 2 atoms colinear
return False
if len(self) == 2: # Two atoms must be linear
return True
tol = np.abs(1.0 - np.cos(angle_tol.to("rad")))
vec0 = self.nvector(0, 1) # Normalised first vector
for atom in self[2:]:
vec = atom.coord - self[0].coord
cos_theta = np.dot(vec, vec0) / np.linalg.norm(vec)
# Both e.g. <179° and >1° should satisfy this condition for
# angle_tol = 1°
if np.abs(np.abs(cos_theta) - 1) > tol:
return False
return True
def are_planar(self, distance_tol: Distance = Distance(1e-3, "Å")) -> bool:
"""
Do all the atoms in this set lie in a single plane?
-----------------------------------------------------------------------
Arguments:
distance_tol (autode.values.Distance):
Returns:
(bool):
"""
if len(self) < 4: # 3 points must lie in a plane
return True
arr = self.coordinates.to("Å")
if isinstance(distance_tol, Distance):
distance_tol_float = float(distance_tol.to("Å"))
else:
logger.warning("Assuming a distance tolerance in units of Å")
distance_tol_float = float(distance_tol)
# Calculate a normal vector to the first two atomic vectors from atom 0
x0 = arr[0, :]
normal_vec = np.cross(arr[1, :] - x0, arr[2, :] - x0)
for i in range(3, len(self)):
# Calculate the 0->i atomic vector, which must not have any
# component in the direction in the normal if the atoms are planar
if np.dot(normal_vec, arr[i, :] - x0) > distance_tol_float:
return False
return True
class AtomCollection:
def __init__(self, atoms: Union[List[Atom], Atoms, None] = None):
"""
Collection of atoms, used as a base class for a species, complex
or transition state.
-----------------------------------------------------------------------
Arguments:
atoms (autode.atoms.Atoms | list(autode.atoms.Atom) | None):
"""
self._atoms = Atoms(atoms) if atoms is not None else None
@property
def n_atoms(self) -> int:
"""Number of atoms in this collection"""
return 0 if self.atoms is None else len(self.atoms)
@property
def coordinates(self) -> Optional[Coordinates]:
"""Numpy array of coordinates"""
if self.atoms is None:
return None
return self.atoms.coordinates
@coordinates.setter
def coordinates(self, value: np.ndarray):
"""Set the coordinates from a numpy array
-----------------------------------------------------------------------
Arguments:
value (np.ndarray): Shape = (n_atoms, 3) or (3*n_atoms) as a
row major vector
"""
if self._atoms is None:
raise ValueError(
"Must have atoms set to be able to set the "
"coordinates of them"
)
self._atoms.coordinates = value
@property
def atoms(self) -> Optional[Atoms]:
"""Constituent atoms of this collection"""
return self._atoms
@atoms.setter
def atoms(self, value: Union[List[Atom], Atoms, None]):
"""Set the constituent atoms of this collection"""
self._atoms = Atoms(value) if value is not None else None
@property
def com(self) -> Optional[Coordinate]:
"""Centre of mass of this atom collection
-----------------------------------------------------------------------
Returns:
(autode.values.Coordinate): COM
Raises:
(ValueError): If there are no atoms
"""
return None if self.atoms is None else self.atoms.com
@property
def moi(self) -> Optional[MomentOfInertia]:
"""
Moment of inertia matrix (I)
-----------------------------------------------------------------------
Returns:
(autode.values.MomentOfInertia):
"""
return None if self.atoms is None else self.atoms.moi
@property
def weight(self) -> Mass:
"""
Molecular weight
-----------------------------------------------------------------------
Returns:
(autode.values.Mass):
"""
if self.n_atoms == 0:
return Mass(0.0)
return sum(atom.mass for atom in self.atoms) # type: ignore
def distance(self, i: int, j: int) -> Distance:
assert self.atoms is not None, "Must have atoms"
return self.atoms.distance(i, j)
def eqm_bond_distance(self, i: int, j: int) -> Distance:
assert self.atoms is not None, "Must have atoms"
return self.atoms.eqm_bond_distance(i, j)
def angle(self, i: int, j: int, k: int) -> Angle:
r"""
Angle between three atoms i-j-k, where the atoms are indexed from
zero::
E_i --- E_j
\
θ E_k