-
Notifications
You must be signed in to change notification settings - Fork 21
/
converter.py
2098 lines (1805 loc) · 89.6 KB
/
converter.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
"""
A module for performing various species-related format conversions.
"""
import numpy as np
import os
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Union
import qcelemental as qcel
from ase import Atoms
from openbabel import openbabel as ob
from openbabel import pybel
from rdkit import Chem
from rdkit.Chem import rdMolTransforms as rdMT
from rdkit.Chem import SDWriter
from rdkit.Chem.rdchem import AtomValenceException
from arkane.common import get_element_mass, mass_by_symbol, symbol_by_number
import rmgpy.constants as constants
from rmgpy.exceptions import AtomTypeError
from rmgpy.molecule.molecule import Atom, Bond, Molecule
from rmgpy.quantity import ArrayQuantity
from rmgpy.species import Species
from rmgpy.statmech import Conformer
from arc.common import (almost_equal_lists,
calc_rmsd,
get_atom_radius,
get_logger,
generate_resonance_structures,
is_str_float,
)
from arc.exceptions import ConverterError, InputError, SanitizationError, SpeciesError
from arc.species.xyz_to_2d import MolGraph
from arc.species.xyz_to_smiles import xyz_to_smiles
from arc.species.zmat import (KEY_FROM_LEN,
_compare_zmats,
get_all_neighbors,
get_atom_indices_from_zmat_parameter,
get_parameter_from_atom_indices,
zmat_to_coords,
xyz_to_zmat)
if TYPE_CHECKING:
from arc.species.species import ARCSpecies
ob.obErrorLog.SetOutputLevel(0)
logger = get_logger()
def str_to_xyz(xyz_str: str,
project_directory: Optional[str] = None,
) -> dict:
"""
Convert a string xyz format to the ARC dict xyz style.
Note: The ``xyz_str`` argument could also direct to a file path to parse the data from.
The xyz string format may have optional Gaussian-style isotope specification, e.g.::
C(Iso=13) 0.6616514836 0.4027481525 -0.4847382281
N -0.6039793084 0.6637270105 0.0671637135
H -1.4226865648 -0.4973210697 -0.2238712255
H -0.4993010635 0.6531020442 1.0853092315
H -2.2115796924 -0.4529256762 0.4144516252
H -1.8113671395 -0.3268900681 -1.1468957003
which will also be parsed into the ARC xyz dictionary format, e.g.::
{'symbols': ('C', 'N', 'H', 'H', 'H', 'H'),
'isotopes': (13, 14, 1, 1, 1, 1),
'coords': ((0.6616514836, 0.4027481525, -0.4847382281),
(-0.6039793084, 0.6637270105, 0.0671637135),
(-1.4226865648, -0.4973210697, -0.2238712255),
(-0.4993010635, 0.6531020442, 1.0853092315),
(-2.2115796924, -0.4529256762, 0.4144516252),
(-1.8113671395, -0.3268900681, -1.1468957003))}
Args:
xyz_str (str): The string xyz format to be converted.
project_directory (str, optional): The path to the project directory.
Raises:
ConverterError: If xyz_str is not a string or does not have four space-separated entries per non-empty line.
Returns: dict
The ARC xyz format.
"""
if isinstance(xyz_str, dict):
return xyz_str
if not isinstance(xyz_str, str):
raise ConverterError(f'Expected a string input, got {type(xyz_str)}')
if project_directory is not None and os.path.isfile(os.path.join(project_directory, xyz_str)):
xyz_str = os.path.join(project_directory, xyz_str)
if os.path.isfile(xyz_str):
from arc.parser import parse_xyz_from_file
return parse_xyz_from_file(xyz_str)
xyz_str = xyz_str.replace(',', ' ')
if len(xyz_str.splitlines()) and len(xyz_str.splitlines()[0]) == 1:
# this is a zmat
return zmat_to_xyz(zmat=str_to_zmat(xyz_str), keep_dummy=False)
xyz_dict = {'symbols': tuple(), 'isotopes': tuple(), 'coords': tuple()}
if all([len(line.split()) == 6 for line in xyz_str.splitlines() if line.strip()]):
# Convert Gaussian output format, e.g., " 1 8 0 3.132319 0.769111 -0.080869"
# not considering isotopes in this method!
for line in xyz_str.splitlines():
if line.strip():
splits = line.split()
symbol = symbol_by_number[int(splits[1])]
coord = (float(splits[3]), float(splits[4]), float(splits[5]))
xyz_dict['symbols'] += (symbol,)
xyz_dict['isotopes'] += (get_most_common_isotope_for_element(symbol),)
xyz_dict['coords'] += (coord,)
else:
# this is a "regular" string xyz format, if it has isotope information it will be preserved
for line in xyz_str.strip().splitlines():
if len(line.split()) in [0, 1]:
continue
if line.strip():
splits = line.split()
if len(splits) != 4:
raise ConverterError(f'xyz_str has an incorrect format, expected 4 elements in each line, '
f'got "{line}" in:\n{xyz_str}')
symbol = splits[0]
if '(iso=' in symbol.lower():
isotope = int(symbol.split('=')[1].strip(')'))
symbol = symbol.split('(')[0]
else:
# no specific isotope is specified in str_xyz
isotope = get_most_common_isotope_for_element(symbol)
coord = (float(splits[1]), float(splits[2]), float(splits[3]))
xyz_dict['symbols'] += (symbol,)
xyz_dict['isotopes'] += (isotope,)
xyz_dict['coords'] += (coord,)
return xyz_dict
def xyz_to_str(xyz_dict: dict,
isotope_format: Optional[str] = None,
) -> Optional[str]:
"""
Convert an ARC xyz dictionary format, e.g.::
{'symbols': ('C', 'N', 'H', 'H', 'H', 'H'),
'isotopes': (13, 14, 1, 1, 1, 1),
'coords': ((0.6616514836, 0.4027481525, -0.4847382281),
(-0.6039793084, 0.6637270105, 0.0671637135),
(-1.4226865648, -0.4973210697, -0.2238712255),
(-0.4993010635, 0.6531020442, 1.0853092315),
(-2.2115796924, -0.4529256762, 0.4144516252),
(-1.8113671395, -0.3268900681, -1.1468957003))}
to a string xyz format with optional Gaussian-style isotope specification, e.g.::
C(Iso=13) 0.6616514836 0.4027481525 -0.4847382281
N -0.6039793084 0.6637270105 0.0671637135
H -1.4226865648 -0.4973210697 -0.2238712255
H -0.4993010635 0.6531020442 1.0853092315
H -2.2115796924 -0.4529256762 0.4144516252
H -1.8113671395 -0.3268900681 -1.1468957003
Args:
xyz_dict (dict): The ARC xyz format to be converted.
isotope_format (str, optional): The format for specifying the isotope if it is not the most abundant one.
By default, isotopes will not be specified. Currently the only supported
option is 'gaussian'.
Raises:
ConverterError: If input is not a dict or does not have all attributes.
Returns: Optional[str]
The string xyz format.
"""
if xyz_dict is None:
return None
xyz_dict = check_xyz_dict(xyz_dict)
recognized_isotope_formats = ['gaussian']
if any([key not in list(xyz_dict.keys()) for key in ['symbols', 'isotopes', 'coords']]):
raise ConverterError(f'Missing keys in the xyz dictionary. Expected to find "symbols", "isotopes", and '
f'"coords", but got {list(xyz_dict.keys())} in\n{xyz_dict}')
if any([len(xyz_dict['isotopes']) != len(xyz_dict['symbols']),
len(xyz_dict['coords']) != len(xyz_dict['symbols'])]):
raise ConverterError(f'Got different lengths for "symbols", "isotopes", and "coords": '
f'{len(xyz_dict["symbols"])}, {len(xyz_dict["isotopes"])}, and {len(xyz_dict["coords"])}, '
f'respectively, in xyz:\n{xyz_dict}')
if any([len(xyz_dict['coords'][i]) != 3 for i in range(len(xyz_dict['coords']))]):
raise ConverterError(f'Expected 3 coordinates for each atom (x, y, and z), got:\n{xyz_dict}')
xyz_list = list()
for symbol, isotope, coord in zip(xyz_dict['symbols'], xyz_dict['isotopes'], xyz_dict['coords']):
common_isotope = get_most_common_isotope_for_element(symbol)
if isotope_format is not None and common_isotope != isotope:
# consider the isotope number
if isotope_format == 'gaussian':
element_with_isotope = '{0}(Iso={1})'.format(symbol, isotope)
row = '{0:14}'.format(element_with_isotope)
else:
raise ConverterError('Recognized isotope formats for printing are {0}, got: {1}'.format(
recognized_isotope_formats, isotope_format))
else:
# don't consider the isotope number
row = '{0:4}'.format(symbol)
row += '{0:14.8f}{1:14.8f}{2:14.8f}'.format(*coord)
xyz_list.append(row)
return '\n'.join(xyz_list)
def xyz_to_x_y_z(xyz_dict: dict) -> Optional[Tuple[tuple, tuple, tuple]]:
"""
Get the X, Y, and Z coordinates separately from the ARC xyz dictionary format.
Args:
xyz_dict (dict): The ARC xyz format.
Returns: Optional[Tuple[tuple, tuple, tuple]]
The X coordinates, the Y coordinates, the Z coordinates.
"""
if xyz_dict is None:
return None
xyz_dict = check_xyz_dict(xyz_dict)
x, y, z = tuple(), tuple(), tuple()
for coord in xyz_dict['coords']:
x += (coord[0],)
y += (coord[1],)
z += (coord[2],)
return x, y, z
def xyz_to_coords_list(xyz_dict: dict) -> Optional[List[List[float]]]:
"""
Get the coords part of an xyz dict as a (mutable) list of lists (rather than a tuple of tuples).
Args:
xyz_dict (dict): The ARC xyz format.
Returns: Optional[List[List[float]]]
The coordinates.
"""
if xyz_dict is None:
return None
xyz_dict = check_xyz_dict(xyz_dict)
coords_tuple = xyz_dict['coords']
coords_list = list()
for coords_tup in coords_tuple:
coords_list.append([coords_tup[0], coords_tup[1], coords_tup[2]])
return coords_list
def xyz_to_np_array(xyz_dict: dict) -> Optional[np.ndarray]:
"""
Get the coords part of an xyz dict as a numpy array.
Args:
xyz_dict (dict): The ARC xyz format.
Returns: Optional[np.ndarray]
The coordinates.
"""
return np.array(xyz_to_coords_list(xyz_dict), dtype=np.float64) if xyz_dict is not None else None
def xyz_to_xyz_file_format(xyz_dict: dict,
comment: str = '',
) -> Optional[str]:
"""
Get the `XYZ file format <https://en.wikipedia.org/wiki/XYZ_file_format>`_ representation
from the ARC xyz dictionary format.
This function does not consider isotopes.
Args:
xyz_dict (dict): The ARC xyz format.
comment (str, optional): A comment to be shown in the output's 2nd line.
Raises:
ConverterError: If ``xyz_dict`` is of wrong format or ``comment`` is a multiline string.
Returns: Optional[str]
The XYZ file format.
"""
if xyz_dict is None:
return None
xyz_dict = check_xyz_dict(xyz_dict)
if len(comment.splitlines()) > 1:
raise ConverterError('The comment attribute cannot be a multiline string, got:\n{0}'.format(list(comment)))
return str(len(xyz_dict['symbols'])) + '\n' + comment.strip() + '\n' + xyz_to_str(xyz_dict) + '\n'
def xyz_to_turbomol_format(xyz_dict: dict,
charge: Optional[int] = None,
unpaired: Optional[int] = None,
) -> Optional[str]:
"""
Get the respective Turbomole coordinates format.
$eht charge=0 unpaired=0
Args:
xyz_dict (dict): The ARC xyz format.
charge (int, optional): The net charge.
unpaired (int, optional): The number of unpaired electrons.
Returns:
str: The respective Turbomole coordinates.
"""
if xyz_dict is None:
return None
xyz_dict = check_xyz_dict(xyz_dict)
coords_list = ['$coord angs']
for symbol, coord in zip(xyz_dict['symbols'], xyz_dict['coords']):
row = '{0:11.8f}{1:14.8f}{2:14.8f}'.format(*coord)
row += f' {symbol.lower()}'
coords_list.append(row)
if charge is not None and unpaired is not None:
coords_list.append(f'$eht charge={charge} unpaired={unpaired}')
coords_list.append('$end\n')
return '\n'.join(coords_list)
def xyz_to_coords_and_element_numbers(xyz: dict) -> Tuple[list, list]:
"""
Convert xyz to a coords list and an atomic number list.
Args:
xyz (dict): The coordinates.
Returns:
Tuple[list, list]: Coords and atomic numbers.
"""
coords = xyz_to_coords_list(xyz)
z_list = [qcel.periodictable.to_Z(symbol) for symbol in xyz['symbols']]
return coords, z_list
def xyz_to_kinbot_list(xyz_dict: dict) -> List[Union[str, float]]:
"""
Get the KinBot xyz format of a single running list of:
[symbol0, x0, y0, z0, symbol1, x1, y1, z1,...]
Args:
xyz_dict (dict): The ARC xyz format.
Returns: List[Union[str, float]]
The respective KinBot xyz format.
"""
kinbot_xyz = list()
for symbol, coords in zip(xyz_dict['symbols'], xyz_dict['coords']):
kinbot_xyz.extend([symbol, coords[0], coords[1], coords[2]])
return kinbot_xyz
def xyz_to_dmat(xyz_dict: dict) -> Optional[np.array]:
"""
Convert Cartesian coordinates to a distance matrix.
Args:
xyz_dict (dict): The Cartesian coordinates.
Returns:
Optional[np.array]: The distance matrix.
"""
if xyz_dict is None or isinstance(xyz_dict, dict) and any(not val for val in xyz_dict.values()):
return None
xyz_dict = check_xyz_dict(xyz_dict)
dmat = qcel.util.misc.distance_matrix(a=np.array(xyz_to_coords_list(xyz_dict)),
b=np.array(xyz_to_coords_list(xyz_dict)))
return dmat
def xyz_file_format_to_xyz(xyz_file: str) -> dict:
"""
Get the ARC xyz dictionary format from an
`XYZ file format <https://en.wikipedia.org/wiki/XYZ_file_format>`_ representation.
Args:
xyz_file (str): The content of an XYZ file
Raises:
ConverterError: If cannot identify the number of atoms entry, or if it is different that the actual number.
Returns: dict
The ARC dictionary xyz format.
"""
lines = xyz_file.strip().splitlines()
if not lines[0].isdigit():
raise ConverterError('Cannot identify the number of atoms from the XYZ file format representation. '
'Expected a number, got: {0} of type {1}'.format(lines[0], type(lines[0])))
number_of_atoms = int(lines[0])
lines = lines[2:]
if len(lines) != number_of_atoms:
raise ConverterError('The actual number of atoms ({0}) does not match the expected number parsed ({1}).'.format(
len(lines), number_of_atoms))
xyz_str = '\n'.join(lines)
return str_to_xyz(xyz_str)
def xyz_from_data(coords, numbers=None, symbols=None, isotopes=None) -> dict:
"""
Get the ARC xyz dictionary format from raw data.
Either ``numbers`` or ``symbols`` must be specified.
If ``isotopes`` isn't specified, the most common isotopes will be assumed for all elements.
Args:
coords (tuple, list): The xyz coordinates.
numbers (tuple, list, optional): Element nuclear charge numbers.
symbols (tuple, list, optional): Element symbols.
isotopes (tuple, list, optional): Element isotope numbers.
Raises:
ConverterError: If neither ``numbers`` nor ``symbols`` are specified, if both are specified,
or if the input lengths aren't consistent.
Returns:
dict: The ARC dictionary xyz format.
"""
if isinstance(coords, np.ndarray):
coords = tuple(tuple(coord.tolist()) for coord in coords)
elif isinstance(coords, list):
coords = tuple(tuple(coord) for coord in coords)
if numbers is not None and isinstance(numbers, np.ndarray):
numbers = tuple(numbers.tolist())
elif numbers is not None and isinstance(numbers, list):
numbers = tuple(numbers)
if symbols is not None and isinstance(symbols, list):
symbols = tuple(symbols)
if isotopes is not None and isinstance(isotopes, list):
isotopes = tuple(isotopes)
if not isinstance(coords, tuple):
raise ConverterError('Expected coords to be a tuple, got {0} which is a {1}'.format(coords, type(coords)))
if numbers is not None and not isinstance(numbers, tuple):
raise ConverterError('Expected numbers to be a tuple, got {0} which is a {1}'.format(numbers, type(numbers)))
if symbols is not None and not isinstance(symbols, tuple):
raise ConverterError('Expected symbols to be a tuple, got {0} which is a {1}'.format(symbols, type(symbols)))
if isotopes is not None and not isinstance(isotopes, tuple):
raise ConverterError('Expected isotopes to be a tuple, got {0} which is a {1}'.format(isotopes, type(isotopes)))
if numbers is None and symbols is None:
raise ConverterError('Must set either "numbers" or "symbols". Got neither.')
if numbers is not None and symbols is not None:
raise ConverterError('Must set either "numbers" or "symbols". Got both.')
if numbers is not None:
symbols = tuple(symbol_by_number[number] for number in numbers)
if len(coords) != len(symbols):
raise ConverterError(f'The length of the coordinates ({len(coords)}) is different than the length of the '
f'numbers/symbols ({len(symbols)}).')
if isotopes is not None and len(coords) != len(isotopes):
raise ConverterError(f'The length of the coordinates ({len(coords)}) is different than the length of isotopes '
f'({len(isotopes)}).')
if isotopes is None:
isotopes = tuple(get_most_common_isotope_for_element(symbol) for symbol in symbols)
xyz_dict = {'symbols': symbols, 'isotopes': isotopes, 'coords': coords}
return xyz_dict
def species_to_sdf_file(species: 'ARCSpecies',
path: str,
):
"""
Write an SDF file with coordinates and connectivity information.
Args:
species (ARCSpecies): The ARCSpecies object instance.
path (str): The full path to the .sdf file that will be saved.
"""
if species.mol is None:
species.mol_from_xyz()
if species.mol is not None:
rdkit_mol = rdkit_conf_from_mol(species.mol, species.get_xyz())[1]
w = SDWriter(path)
w.write(rdkit_mol)
w.close()
def sort_xyz_using_indices(xyz_dict: dict,
indices: Optional[List[int]],
) -> dict:
"""
Sort the tuples in an xyz dict according to the given indices.
Args:
xyz_dict (dict): The Cartesian coordinates.
indices (Optional[List[int]]): Entries are 0-indices of the desired order.
Returns:
dict: The ordered xyz.
"""
if indices is None:
logger.error('Cannot sort xyz without a map.')
return xyz_dict
if len(indices) != len(xyz_dict['coords']):
raise ValueError(f"The number of indices {len(indices)} does not match "
f"the number of coordinates {len(xyz_dict['coords'])}")
if any(i >= len(xyz_dict['coords']) for i in indices):
raise ValueError(f"All indices must be lower than the length of the coordinates tuple. "
f"Got {len(xyz_dict['coords'])} coordinates, and indices of:\n{indices}")
coords, symbols, isotopes = list(), list(), list()
for i in indices:
coords.append(xyz_dict['coords'][i])
symbols.append(xyz_dict['symbols'][i])
isotopes.append(xyz_dict['isotopes'][i])
return xyz_from_data(coords=coords, symbols=symbols, isotopes=isotopes)
def xyz_to_ase(xyz_dict: dict) -> Atoms:
"""
Convert an xyz dict to an ASE Atoms object.
Args:
xyz_dict (dict): The ARC xyz format.
Returns:
Type[Atoms]: The corresponding ASE Atom object.
"""
return Atoms(xyz_dict['symbols'], xyz_dict['coords'])
def translate_xyz(xyz_dict: dict,
translation: Tuple[float, float, float],
) -> dict:
"""
Translate xyz.
Args:
xyz_dict (dict): The ARC xyz format.
translation (Tuple[float, float, float]): The x, y, z translation vector.
Returns:
dict: The translated xyz.
"""
if all(t == 0 for t in translation):
return xyz_dict
coords = list()
for coord in xyz_dict['coords']:
coords.append(tuple(coord[i] + translation[i] for i in range(3)))
new_xyz = {'symbols': xyz_dict['symbols'],
'isotopes': xyz_dict['isotopes'],
'coords': tuple(coords),
}
return new_xyz
def displace_xyz(xyz: dict,
displacement: np.ndarray,
amplitude: float = 0.25,
use_weights: bool = True,
) -> Tuple[dict, dict]:
"""
Displace the coordinates using the ``displacement`` by the requested ``amplitude`` using atom mass weights.
Args:
xyz (dict): The coordinates.
displacement (list): The corresponding xyz displacement for each atom.
amplitude (float, optional): The factor multiplication for the displacement.
use_weights( bool, optional): Whether to scale displacements by the square root of the respective element mass.
Returns:
Tuple[dict, dict]:
The two displaced xyz's, one for each direction (+/-) of the weighted ``displacement``.
"""
coords = xyz_to_coords_list(xyz)
weights = [mass ** 0.5 for mass in get_element_mass_from_xyz(xyz)] if use_weights else [1] * len(xyz['symbols'])
coords_1 = [[float(coord[0] + amplitude * displacement[i][0] * weights[i]),
float(coord[1] + amplitude * displacement[i][1] * weights[i]),
float(coord[2] + amplitude * displacement[i][2] * weights[i])] for i, coord in enumerate(coords)]
coords_2 = [[float(coord[0] - amplitude * displacement[i][0] * weights[i]),
float(coord[1] - amplitude * displacement[i][1] * weights[i]),
float(coord[2] - amplitude * displacement[i][2] * weights[i])] for i, coord in enumerate(coords)]
xyz_1 = xyz_from_data(coords=coords_1, symbols=xyz['symbols'], isotopes=xyz['isotopes'])
xyz_2 = xyz_from_data(coords=coords_2, symbols=xyz['symbols'], isotopes=xyz['isotopes'])
return xyz_1, xyz_2
def get_element_mass_from_xyz(xyz: dict) -> List[float]:
"""
Get a list of element masses corresponding to the given ``xyz`` considering isotopes.
Args:
xyz (dict): The coordinates.
Returns:
List[float]: The corresponding list of mass in amu.
"""
return [get_element_mass(symbol, isotope)[0] for symbol, isotope in zip(xyz['symbols'], xyz['isotopes'])]
def hartree_to_si(e: float,
kilo: bool = True,
) -> float:
"""
Convert Hartree units into J/mol or into kJ/mol.
Args:
e (float): Energy in Hartree.
kilo (bool, optional): Whether to return kJ/mol units. ``True`` by default.
"""
if not isinstance(e, (int, float)):
raise ValueError(f'Expected a float, got {e} which is a {type(e)}.')
factor = 0.001 if kilo else 1
return e * constants.E_h * constants.Na * factor
def rmg_conformer_to_xyz(conformer):
"""
Convert xyz coordinates from an rmgpy.statmech.Conformer object into the ARC dict xyz style.
Notes:
Only the xyz information (symbols and coordinates) will be taken from the Conformer object. Other properties
such as electronic energy will not be converted.
We also assume that we can get the isotope number by rounding the mass
Args:
conformer (Conformer): An rmgpy.statmech.Conformer object containing the desired xyz coordinates
Raises:
TypeError: If conformer is not an rmgpy.statmech.Conformer object
Returns:
dict: The ARC xyz format
"""
if not isinstance(conformer, Conformer):
raise TypeError(f'Expected conformer to be an rmgpy.statmech.Conformer object but instead got {conformer}, '
f'which is a {type(conformer)} object.')
symbols = tuple(symbol_by_number[n] for n in conformer.number.value)
isotopes = tuple(int(round(m)) for m in conformer.mass.value)
coords = tuple(tuple(coord) for coord in conformer.coordinates.value)
xyz_dict = {'symbols': symbols, 'isotopes': isotopes, 'coords': coords}
return xyz_dict
def xyz_to_rmg_conformer(xyz_dict: dict) -> Optional[Conformer]:
"""
Convert the Arc dict xyz style into an rmgpy.statmech.Conformer object containing these coordinates.
Notes:
Only the xyz information will be supplied to the newly created Conformer object
Args:
xyz_dict (dict): The ARC dict xyz style coordinates
Returns:
Optional[Conformer]: An rmgpy.statmech.Conformer object containing the desired xyz coordinates.
"""
if xyz_dict is None:
return None
xyz_dict = check_xyz_dict(xyz_dict)
mass_and_number = (get_element_mass(*args) for args in zip(xyz_dict['symbols'], xyz_dict['isotopes']))
mass, number = zip(*mass_and_number)
mass = ArrayQuantity(mass, 'amu')
number = ArrayQuantity(number, '')
coordinates = ArrayQuantity(xyz_dict['coords'], 'angstroms')
conformer = Conformer(number=number, mass=mass, coordinates=coordinates)
return conformer
def standardize_xyz_string(xyz_str, isotope_format=None):
"""
A helper function to correct xyz string format input (string to string).
Usually empty lines are added by the user either in the beginning or the end,
here we remove them along with other common issues.
Args:
xyz_str (str): The string xyz format, or a Gaussian output format.
isotope_format (str, optional): The format for specifying the isotope if it is not the most abundant one.
By default, isotopes will not be specified. Currently the only supported
option is 'gaussian'.
Returns:
str: The string xyz format in standardized format.
Raises:
ConverterError: If ``xyz_str`` is of wrong type.
"""
if not isinstance(xyz_str, str):
raise ConverterError('Expected a string format, got {0}'.format(type(xyz_str)))
xyz_dict = str_to_xyz(xyz_str)
return xyz_to_str(xyz_dict=xyz_dict, isotope_format=isotope_format)
def check_xyz_dict(xyz: Union[dict, str],
project_directory: Optional[str] = None,
) -> Optional[dict]:
"""
Check that the xyz dictionary entered is valid.
If it is a string, convert it.
If it is a Z matrix, convert it to cartesian coordinates,
If isotopes are not in xyz_dict, common values will be added.
If a part of the xyz structure is a np.ndarray type, convert it by always calling xyz_from_data().
Args:
xyz (Union[dict, str]): The xyz dictionary.
project_directory (str, optional): The path to the project directory.
Raises:
ConverterError: If ``xyz`` is of wrong type or is missing symbols or coords.
Returns: Optional[dict]
The cartesian coordinates in a dictionary format.
"""
if xyz is None:
return None
xyz_dict = str_to_xyz(xyz, project_directory) if isinstance(xyz, str) else xyz
if not isinstance(xyz_dict, dict):
raise ConverterError(f'Expected a dictionary, got {type(xyz_dict)}')
if 'vars' in list(xyz_dict.keys()):
# this is a zmat, convert to cartesian
xyz_dict = zmat_to_xyz(zmat=xyz_dict, keep_dummy=False)
if 'symbols' not in list(xyz_dict.keys()):
raise ConverterError(f'XYZ dictionary is missing symbols. Got:\n{xyz_dict}')
if 'coords' not in list(xyz_dict.keys()):
raise ConverterError(f'XYZ dictionary is missing coords. Got:\n{xyz_dict}')
if len(xyz_dict['symbols']) != len(xyz_dict['coords']):
raise ConverterError(f'Got {len(xyz_dict["symbols"])} symbols and {len(xyz_dict["coords"])} '
f'coordinates:\n{xyz_dict}')
xyz_dict = xyz_from_data(coords=xyz_dict['coords'],
symbols=xyz_dict['symbols'],
isotopes=xyz_dict['isotopes'] if 'isotopes' in list(xyz_dict.keys()) else None)
if len(xyz_dict['symbols']) != len(xyz_dict['isotopes']):
raise ConverterError(f'Got {len(xyz_dict["symbols"])} symbols and {len(xyz_dict["isotopes"])} '
f'isotopes:\n{xyz_dict}')
return xyz_dict
def check_zmat_dict(zmat: Union[dict, str]) -> dict:
"""
Check that the zmat dictionary entered is valid.
If it is a string, convert it.
If it represents cartesian coordinates, convert it to internal coordinates.
If a map isn't given, a trivial one will be added.
Args:
zmat (dict, str): The zmat dictionary.
Raises:
ConverterError: If ``zmat`` is of wrong type or is missing vars or coords.
"""
zmat_dict = str_to_zmat(zmat) if isinstance(zmat, str) else zmat
if not isinstance(zmat_dict, dict):
raise ConverterError(f'Expected a dictionary, got {type(zmat_dict)}')
if 'vars' not in list(zmat_dict.keys()):
# this is probably a representation of cartesian coordinates, convert to zmat
zmat_dict = zmat_from_xyz(xyz=check_xyz_dict(zmat_dict), consolidate=True)
if 'symbols' not in list(zmat_dict.keys()):
raise ConverterError(f'zmat dictionary is missing symbols. Got:\n{zmat_dict}')
if 'coords' not in list(zmat_dict.keys()):
raise ConverterError(f'zmat dictionary is missing coords. Got:\n{zmat_dict}')
if len(zmat_dict['symbols']) != len(zmat_dict['coords']):
raise ConverterError(f'Got {len(zmat_dict["symbols"])} symbols and {len(zmat_dict["coords"])} '
f'coordinates:\n{zmat_dict}')
if 'map' not in list(zmat_dict.keys()):
# add a trivial map
zmat_dict['map'] = {i: i for i in range(len(zmat_dict['symbols']))}
if len(zmat_dict['symbols']) != len(zmat_dict['map']):
raise ConverterError(f'Got {len(zmat_dict["symbols"])} symbols and {len(zmat_dict["isotopes"])} '
f'isotopes:\n{zmat_dict}')
for i, coord in enumerate(zmat_dict['coords']):
for j, param in enumerate(coord):
if param is not None:
indices = get_atom_indices_from_zmat_parameter(param)
if not any(i == index_tuple[0] for index_tuple in indices):
raise ConverterError(f'The {param} parameter in the zmat is ill-defined:\n{zmat_dict}')
if (i == 0 or i == 1 and j in [1, 2] or i == 2 and j == 3) and param is not None:
raise ConverterError(f'The zmat is ill-defined:\n{zmat_dict}')
return zmat_dict
def remove_dummies(xyz):
"""
Remove dummy ('X') atoms from cartesian coordinates.
Args:
xyz (dict, str): The cartesian coordinate, either in a dict or str format.
Returns:
dict: The coordinates w/o dummy atoms.
Raises:
InputError: If ``xyz`` if of wrong type.
"""
if isinstance(xyz, str):
xyz = str_to_xyz(xyz)
if not isinstance(xyz, dict):
raise InputError(f'xyz must be a dictionary, got {type(xyz)}')
symbols, isotopes, coords = list(), list(), list()
for symbol, isotope, coord in zip(xyz['symbols'], xyz['isotopes'], xyz['coords']):
if symbol != 'X':
symbols.append(symbol)
isotopes.append(isotope)
coords.append(coord)
return xyz_from_data(coords=coords, symbols=symbols, isotopes=isotopes)
def zmat_from_xyz(xyz: Union[dict, str],
mol: Optional[Molecule] = None,
constraints: Optional[dict] = None,
consolidate: bool = True,
consolidation_tols: dict = None,
is_ts: bool = False,
) -> dict:
"""
Generate a Z matrix from xyz.
Args:
xyz (Union[dict, str]): The cartesian coordinate, either in a dict or str format.
mol (Molecule, optional): The corresponding RMG Molecule with connectivity information.
constraints (dict, optional): Accepted keys are:
'R_atom', 'R_group', 'A_atom', 'A_group', 'D_atom', 'D_group', or 'D_groups'.
'R', 'A', and 'D' constrain distances, angles, and dihedrals, respectively.
Values are lists of atom indices (0-indexed) tuples.
The atom indices order matters.
Specifying '_atom' will cause only the last atom in the specified list values
to translate/rotate if the corresponding zmat parameter is changed.
Specifying '_group' will cause the entire group connected to the last atom
to translate/rotate if the corresponding zmat parameter is changed.
Specifying '_groups' (only valid for D) will cause the groups connected to
the last two atoms to translate/rotate if the corresponding parameter is changed.
consolidate (bool, optional): Whether to consolidate the zmat after generation, ``True`` to consolidate.
consolidation_tols (dict, optional): Keys are 'R', 'A', 'D', values are floats representing absolute tolerance
for consolidating almost equal internal coordinates.
is_ts (bool, optional): Whether this is a representation of a TS.
If it is not, a ``mol`` object will be generated if not given.
Raises:
InputError: If ``xyz`` if of a wrong type.
Returns:
dict: The Z matrix.
"""
xyz = str_to_xyz(xyz) if isinstance(xyz, str) else xyz
if not isinstance(xyz, dict):
raise InputError(f'xyz must be a dictionary, got {type(xyz)}')
xyz = remove_dummies(xyz)
if mol is None and not is_ts:
mol = molecules_from_xyz(xyz=xyz)[1]
return xyz_to_zmat(xyz,
mol=mol,
constraints=constraints,
consolidate=consolidate,
consolidation_tols=consolidation_tols,
)
def zmat_to_xyz(zmat, keep_dummy=False, xyz_isotopes=None):
"""
Generate the xyz dict coordinates from a zmat dict.
Most common isotopes assumed, unless a reference xyz dict is given.
Args:
zmat (dict): The zmat.
keep_dummy (bool): Whether to keep dummy atoms ('X'), ``True`` to keep, default is ``False``.
xyz_isotopes (dict): A reference xyz dictionary to take isotope information from.
Must be ordered as the original mol/xyz used to create ``zmat``.
Returns:
dict: The xyz cartesian coordinates.
"""
coords, symbols = zmat_to_coords(zmat, keep_dummy=keep_dummy)
isotopes = xyz_isotopes['isotopes'] if xyz_isotopes is not None else None
xyz_dict = translate_to_center_of_mass(xyz_from_data(coords=coords, symbols=symbols, isotopes=isotopes))
return xyz_dict
def zmat_to_str(zmat, zmat_format='gaussian', consolidate=True):
"""
Convert a zmat to a string format.
Args:
zmat (dict): The Z Matrix to convert.
zmat_format (str, optional): The requested format to output (varies by ESS).
Allowed values are: 'gaussian', 'qchem', 'molpro', 'orca', 'cfour', or 'psi4'.
The default format is 'gaussian'.
consolidate (bool): Whether to return a consolidated zmat (geometry optimization will be more efficient).
Returns:
str: The string representation of the zmat in the requested format.
Raises:
ConverterError: If ``zmat`` is of wrong type or missing keys, or if ``zmat_format`` is not recognized.
"""
if not isinstance(zmat, dict):
raise ConverterError(f'zmat has to be a dict, got: {type(zmat)}')
if 'symbols' not in zmat or 'coords' not in zmat or 'vars' not in zmat:
raise ConverterError(f'zmat must contain the "symbols", "coords", and "vars" keys, got: '
f'{list(zmat.keys())}.')
if zmat_format == 'terachem':
raise ConverterError('TeraChem does not accept a zmat as input (it has its own internal conversions).')
if zmat_format not in ['gaussian', 'qchem', 'molpro', 'orca', 'psi4', 'cfour']:
raise ConverterError(f'zmat_format must be either gaussian, qchem, molpro, orca, cfour, or psi4, '
f'got: {zmat_format}.')
if zmat_format == 'orca':
# replace dummy atom symbols
symbols = list()
for symbol in zmat['symbols']:
symbols.append(symbol if symbol != 'X' else 'DA')
else:
symbols = zmat['symbols']
if zmat_format == 'orca':
# Redundant internal coordinates are automatically used by Orca,
# parametarized internal coordinates are hence not supported
consolidate = False
separator = ',' if zmat_format in ['molpro'] else ''
var_separator = '=' if zmat_format in ['gaussian', 'molpro', 'qchem', 'psi4', 'cfour'] else ' '
zmat_str, variables_str, variables = '', '', list()
type_indices = {'R': 1, 'A': 1, 'D': 1} # consolidation counters
variables_dict = dict() # keys are coord (e.g., 'R_2|4_0|0'), values are vars (e.g., 'R1')
for i, (symbol, coords) in enumerate(zip(symbols, zmat['coords'])):
line = f'{symbol:>3}'
for coord in coords:
if coord is not None:
index_tuples = get_atom_indices_from_zmat_parameter(coord)
for indices in index_tuples:
if indices[0] == i:
break
if consolidate:
if coord in list(variables_dict.keys()):
var_str = variables_dict[coord]
else:
var_type = coord[0] # 'R', 'A', or 'D'
var_str = f'{var_type}{type_indices[var_type]}'
type_indices[var_type] += 1
variables_dict[coord] = var_str
variables.append(f'{var_str}{var_separator}{zmat["vars"][coord]:.4f}\n')
line += f'{separator}{indices[-1] + 1:8d}{separator}{var_str:>8}' # convert to 1-indexed
else:
line += f'{separator}{indices[-1] + 1:8d}{separator}{zmat["vars"][coord]:10.4f}'
if zmat_format == 'orca' and consolidate:
symbol, indices, coordinates = '', '', ''
for j, entry in enumerate(line.split()):
if j == 0:
symbol = entry + ' '
elif j % 2 == 0:
coordinates += entry + ' '
else:
indices += entry + ' '
while len(indices.split()) < 3:
indices += '0 '
while len(coordinates.split()) < 3:
coordinates += '0.0 '
line = symbol + indices + coordinates[:-1]
zmat_str += line + '\n'
if zmat_format in ['gaussian']:
variables_str = ''.join(sorted(variables))
result = f'{zmat_str}Variables:\n{variables_str}' if consolidate else zmat_str
elif zmat_format in ['qchem', 'psi4', 'orca', 'cfour']:
variables_str = ''.join(sorted(variables))
result = f'{zmat_str}\n{variables_str}' if consolidate else zmat_str
elif zmat_format in ['molpro']:
variables_str = ''.join(sorted(variables))
result = f'{variables_str}\n{zmat_str}' if consolidate else zmat_str
else:
result = zmat_str + variables_str
return result
def str_to_zmat(zmat_str):
"""
Convert a string Z Matrix format to the ARC dict zmat style.
Note: The ``zmat_str`` argument could also direct to a file path to parse the data from.
A typical zmat string format may look like this::
C
H 1 R1
H 1 R1 2 A1
H 1 R1 2 A1 3 D1
H 1 R1 2 A1 3 D2
A1=109.4712
D1=120.0000
D2=240.0000
R1=1.0912
The resulting zmat for the above example is::
{'symbols': ('C', 'H', 'H', 'H', 'H'),
'coords': ((None, None, None),
('R_1_0', None, None),
('R_2_1', 'A_2_1_0', None),
('R_3_2', 'A_3_2_0', 'D_3_2_0_1'), ('R_4_3', 'A_4_3_0', 'D_4_3_0_2')),
'vars': {'R_1_0': 1.0912, 'R_2_1': 1.782, 'A_2_1_0': 35.2644, 'R_3_2': 1.782, 'A_3_2_0': 35.2644,
'D_3_2_0_1': 120.0, 'R_4_3': 1.782, 'A_4_3_0': 35.2644, 'D_4_3_0_2': 240.0},
'map': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}}
Args:
zmat_str (str): The string zmat format to be converted.
Returns:
dict: The ARC zmat format.
Raises:
ConverterError: If zmat_str is not a string or does not have enough values per line.
"""
if not isinstance(zmat_str, str):
raise ConverterError(f'Expected a string input, got {type(zmat_str)}')
if os.path.isfile(zmat_str):
with open(zmat_str, 'r') as f:
zmat_str = f.read()
symbols, coords, variables = list(), list(), dict()
coords_str = split_str_zmat(zmat_str)[0]
index = 1
for i, line in enumerate(coords_str.splitlines()):
splits = line.split()
if i == 1:
# the atom index in this line must point to the first atom in the zmat,