-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2670 lines (2298 loc) · 77.9 KB
/
utils.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
#!/usr/bin/python3
import os
import re
import shutil
import subprocess
import numpy as np
import scipy
import scipy.ndimage.filters as filters
import scipy.ndimage.morphology as morphology
from ase import io
from ase.visualize.plot import plot_atoms
from scipy import signal
from scipy import special
if os.name == 'nt':
from findiff import FinDiff
import sympy as sym
from matplotlib import pyplot as plt
from scipy import linalg
import math
# import numba
from scipy.signal import find_peaks
# import cupy as cp
# import pyfftw
import multiprocessing
#######################################################################################################################
# USEFUL PLOTTING and I/O
# nice plot
def n_plot(xlab, ylab, xs=14, ys=14):
"""
Makes a plot look nice by introducing ticks, labels, and making it tight
:param xlab: x axis label
:param ylab: y axis label
:param xs: x axis text size
:param ys: y axis text size
:return: None
"""
plt.minorticks_on()
plt.tick_params(axis='both', which='major', labelsize=ys - 2, direction='in', length=6, width=2)
plt.tick_params(axis='both', which='minor', labelsize=ys - 2, direction='in', length=4, width=2)
plt.tick_params(axis='both', which='both', top=True, right=True)
plt.xlabel(xlab, fontsize=xs)
plt.ylabel(ylab, fontsize=ys)
plt.tight_layout()
return None
# Check OS then plot
def os_plot_show(os_name='nt'):
"""
Checks the system OS. This is to prevent plotting to HPC.
nt is windows
Can trick by making the OS name something else to prevent it from plotting to screen
:param os_name: The name of the operating system
:return: None
"""
# Check if the os is windows
if os.name == os_name:
plt.show()
plt.close()
return None
# Save 3d
def save_3d(data, dir, header):
"""
Save 3d data to a given directory
Taken from:
https://stackoverflow.com/questions/3685265/how-to-write-a-multidimensional-array-to-a-text-file
:param data: input 3d data
:param dir: directory to save to
:param header: any comments to save to file
:return:
"""
# Write the array to disk
with open(dir, 'w') as outfile:
# I'm writing a header here just for the sake of readability
# Any line starting with "#" will be ignored by numpy.loadtxt
outfile.write('# Array shape :' + str(list(np.shape(data))) + ': ' + header + '\n')
# Iterating through a ndimensional array produces slices along
# the last axis. This is equivalent to data[i,:,:] in this case
for data_slice in data:
# The formatting string indicates that I'm writing out
# the values in left-justified columns 7 characters in width
# with 2 decimal places.
np.savetxt(outfile, data_slice) # , fmt='%-7.2f')
# Writing out a break to indicate different slices...
outfile.write('# New slice\n')
return None
# Plotting 3D scatter plots
def scatter_3d(xx, yy, zz, x_lab='X', y_lab='Y', z_lab='Z', fig_name=None):
"""
Now replaces plot_3d_xyz
Plots given 3D data
:param xx: x data
:param yy: y data
:param zz: z data
:param x_lab: x label
:param y_lab: y label
:param z_lab: z label
:param fig_name: file to save to
:return:
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xx, yy, zz, c='r', marker='o')
ax.set_xlabel(x_lab)
ax.set_ylabel(y_lab)
ax.set_zlabel(z_lab)
if fig_name != None:
plt.savefig(fig_name)
os_plot_show()
return None
# Pull specific data by using a sub string as a keyword
def pull(Arr, sub):
"""
If there is a list of strings it pulls out numerical values from lines which contain the substring
:param Arr: input array
:param sub: sub string
:return: list of values
"""
# Strip all the non-numbers
return [re.sub("[^0123456789\.]", "", i) for i in Arr if sub in i]
# plots the last image from a traj file
def plot_traj(file_traj='prod.traj', rad=.8):
"""
Plots a .traj file and saves as a pdf to the current working dir
:param file_traj: input file
:param rad: radii of each atom
:return: None
"""
# remove and re-apply file extenstions
file_traj = os.path.splitext(file_traj)[0] + '.traj'
atoms = io.read(file_traj, -1)
fig, axarr = plt.subplots(1, 4, figsize=(15, 5))
plot_atoms(atoms, axarr[0], radii=rad, rotation=('0x,0y,0z'))
plot_atoms(atoms, axarr[1], radii=rad, rotation=('90x,45y,0z'))
plot_atoms(atoms, axarr[2], radii=rad, rotation=('45x,45y,0z'))
plot_atoms(atoms, axarr[3], radii=rad, rotation=('90x,0y,0z'))
axarr[0].set_axis_off()
axarr[1].set_axis_off()
axarr[2].set_axis_off()
axarr[3].set_axis_off()
fig.savefig(os.path.splitext(file_traj)[0] + ".pdf")
os_plot_show()
return None
# converts a .traj to a xyz file
def convert_traj_2_xyz(file_traj='react.traj', file_xyz='test.xyz'):
"""
Converts a .traj file to a .xyz formatted file
:param file_traj: trajectory file
:param file_xyz: xyz file to save to
:return:
"""
# remove and re-apply file extenstions
file_traj = os.path.splitext(file_traj)[0] + '.traj'
file_xyz = os.path.splitext(file_xyz)[0] + '.xyz'
# Grab the cell from file
a = io.read(file_traj)
symbols = a.get_chemical_symbols()
N = len(symbols)
positions = a.get_positions()
A = [str(N)]
A.append(' ')
# loop over the elements
for i in range(N):
# put together the symbol and the xyz on one string line
A.append(str(symbols[i]) + ' ' + str(positions[i]).strip('[]'))
# Save the file
np.savetxt(file_xyz, A, format('%s'))
return None
# Fixes the time axis, giving a good prefix
# Converts the time array to something that is more manageable
def time_axis_fix(t_arr, implied_units=1.0):
max_val = max(t_arr) * implied_units
min_val = max(t_arr) * implied_units
# predefined prefixes
prefix = {'y': 1e-24, # yocto
'z': 1e-21, # zepto
'a': 1e-18, # atto
'f': 1e-15, # femto
'p': 1e-12, # pico
'n': 1e-9, # nano
'u': 1e-6, # micro
'm': 1e-3, # mili
'c': 1e-2, # centi
'd': 1e-1, # deci
'k': 1e3, # kilo
'M': 1e6, # mega
'G': 1e9, # giga
'T': 1e12, # tera
'P': 1e15, # peta
'E': 1e18, # exa
'Z': 1e21, # zetta
'Y': 1e24, # yotta
}
# grab vals and keys
vals = [i for i in prefix.values()]
keys = [i for i in prefix.keys()]
# Find the closest value
dif = abs(np.log(vals) - np.log(max_val))
# Find the location
loc = np.where(dif == min(dif))[0][0]
# Fix the time axis
t_arr = t_arr * implied_units / vals[loc]
return np.array(t_arr), keys[loc]
#######################################################################################################################
# COORDINATE TRANSFORMS AND CLUSTERING
# Collect up arrays of x,y,z and outputs a 2D array of coordinate triplets
def collect_xyz_2_coords(x, y, z):
"""
Collect up arrays of x,y,z and outputs a 2D array of coordinate triplets
:param x: x data
:param y: y data
:param z: z data
:return: array of [x,z,y]
"""
return np.stack((np.array(x), np.array(y), np.array(z), np.ones(len(x))), axis=-1)
# Splits up 2D array of coordinate triplets into rows of x,y,z
def uncollect_xyz_2_coords(arr):
"""
Splits up 2D array of coordinate triplets into rows of x,y,z
:param arr: 2d array
:return: x,y,z
"""
# Find the shape
sh = arr.shape
# Check if the matrix has the stack of ones at the end
if sh[1] == 4:
x, y, z, ones = np.split(arr, 4, axis=1)
return np.transpose(x)[0], np.transpose(y)[0], np.transpose(z)[0]
# Doesnt have ones
elif sh[1] == 3:
x, y, z = np.split(arr, 3, axis=1)
return np.ravel(x), np.ravel(y), np.ravel(z)
# Plane polar coordinates converter
def plane_polar_coords(A):
"""
cartesian coordinates to Plane polar coordinates converter
:param A: input vector of cartesian coordinates
:return: polar coordinates vector
"""
# Handles different array shapes and ranks
sh = A.shape
if A.ndim == 2 and (sh[0] > 1) and (sh[1] >= 2):
xx = A[:, 0]
yy = A[:, 1]
zz = A[:, 2]
else:
xx = A[0]
yy = A[1]
zz = A[2]
r = np.sqrt(np.square(xx) + np.square(yy))
phi = np.arctan2(yy, xx)
# Handles different array shapes and ranks
if A.ndim == 2 and (sh[0] > 1) and (sh[1] >= 3):
return np.column_stack((r, phi))
else:
return [r, phi]
# Inverse plane polar coordinates converter
def i_plane_polar_coords(A):
"""
plane polar coordinates to cartesian coordinates
:param A: input vector
:return: output vector
"""
# Handles different array shapes and ranks
sh = A.shape
if A.ndim == 2 and (sh[0] > 1) and (sh[1] >= 2):
r = A[:, 0]
phi = A[:, 1]
else:
r = A[0]
phi = A[1]
xx = r * np.cos(phi)
yy = r * np.sin(phi)
zz = 0.0
# Handles different array shapes and ranks
if A.ndim == 2 and (sh[0] > 1) and (sh[1] >= 3):
return np.column_stack((xx, yy, zz, np.ones(len(xx))))
else:
return [xx, yy, zz]
# Spherical polar coordinates converter
def spherical_coords(A):
"""
Cartesian coordinates to spherical polar coordinates
:param A: input vector
:return: output vector
"""
# Handles different array shapes and ranks
sh = A.shape
if A.ndim == 2 and (sh[0] > 1) and (sh[1] >= 3):
xx = A[:, 0]
yy = A[:, 1]
zz = A[:, 2]
else:
xx = A[0]
yy = A[1]
zz = A[2]
r = np.sqrt(np.square(xx) + np.square(yy) + np.square(zz))
theta = np.arccos(np.divide(zz, r))
phi = np.arctan2(yy, xx)
# Handles different array shapes and ranks
if A.ndim == 2 and (sh[0] > 1) and (sh[1] >= 3):
return np.column_stack((r, phi, theta))
else:
return [r, phi, theta]
# Inverse spherical polar coordinates converter
def i_spherical_coords(A):
"""
spherical polar coordinates to cartesian coordinates
:param A: input vector
:return: output vector
"""
# Handles different array shapes and ranks
sh = np.shape(A)
if np.ndim(A) == 2 and (sh[0] > 1) and (sh[1] >= 3):
r = A[:, 0]
phi = A[:, 1]
theta = A[:, 2]
else:
r = A[0]
phi = A[1]
theta = A[2]
xx = r * np.sin(theta) * np.cos(phi)
yy = r * np.sin(theta) * np.sin(phi)
zz = r * np.cos(theta)
# Handles different array shapes and ranks
if np.ndim(A) == 2 and (sh[0] > 1) and (sh[1] >= 3):
return np.column_stack((xx, yy, zz, np.ones(len(xx))))
else:
return [xx, yy, zz]
# Deals with stacks of coordinates in applies np.dot
def trans_mat_stacks(A, x):
"""
helper function which deals with stacks of coordinates in applies np.dot
in the form A.x
:param A: input array
:param x: transformation array
:return: translated
"""
mat_shape = np.shape(x)
if mat_shape[0] > 0 and mat_shape[1] == 4:
rtn = np.zeros_like(x)
for i, val in enumerate(x):
rtn[i, :] = np.dot(A, val)
else:
rtn = np.dot(A, x)
return rtn
# Performs a transformation using a, b, c
def trans_mat_tran(x, vec):
"""
Performs a transformation using an input vector of [a, b, c]
Taken from:
https://www.tutorialspoint.com/computer_graphics/3d_transformation.htm
:param x: input vector
:param vec: translation vector
:return: translated vector
"""
a = vec[0]
b = vec[1]
c = vec[2]
# translation matrix
T = np.zeros([4, 4])
T[0][0] = 1.0
T[0][1] = 0.0
T[0][2] = 0.0
T[0][3] = a
T[1][0] = 0.0
T[1][1] = 1.0
T[1][2] = 0.0
T[1][3] = b
T[2][0] = 0.0
T[2][1] = 0.0
T[2][2] = 1.0
T[2][3] = c
T[3][0] = 0.0
T[3][1] = 0.0
T[3][2] = 0.0
T[3][3] = 1.0
return trans_mat_stacks(T, x)
# Roation about the x axis
def trans_mat_rot_x(x, theta):
"""
Performs a rotation about the x axis
Taken from:
https://www.tutorialspoint.com/computer_graphics/3d_transformation.htm
:param x: input array
:param theta: degree to rotate by
:return: transformed result
"""
# Rotation matrix
T = np.zeros([4, 4])
T[0][0] = 1.0
T[0][1] = 0.0
T[0][2] = 0.0
T[0][3] = 0.0
T[1][0] = 0.0
T[1][1] = np.cos(theta)
T[1][2] = -np.sin(theta)
T[1][3] = 0.0
T[2][0] = 0.0
T[2][1] = np.sin(theta)
T[2][2] = np.cos(theta)
T[2][3] = 0.0
T[3][0] = 0.0
T[3][1] = 0.0
T[3][2] = 0.0
T[3][3] = 1.0
return trans_mat_stacks(T, x)
# Roation about the y axis
def trans_mat_rot_y(x, theta):
"""
Performs a rotation about the y axis
Taken from:
https://www.tutorialspoint.com/computer_graphics/3d_transformation.htm
:param x: input array
:param theta: degree to rotate by
:return: transformed result
"""
# Rotation matrix
T = np.zeros([4, 4])
T[0][0] = np.cos(theta)
T[0][1] = 0.0
T[0][2] = np.sin(theta)
T[0][3] = 0.0
T[1][0] = 0.0
T[1][1] = 1.0
T[1][2] = 0.0
T[1][3] = 0.0
T[2][0] = -np.sin(theta)
T[2][1] = 0.0
T[2][2] = np.cos(theta)
T[2][3] = 0.0
T[3][0] = 0.0
T[3][1] = 0.0
T[3][2] = 0.0
T[3][3] = 1.0
return trans_mat_stacks(T, x)
# Roation about the z axis
def trans_mat_rot_z(x, theta):
"""
Performs a rotation about the z axis
Taken from:
https://www.tutorialspoint.com/computer_graphics/3d_transformation.htm
:param x: input array
:param theta: degree to rotate by
:return: transformed result
"""
# Rotation matrix
T = np.zeros([4, 4])
T[0][0] = np.cos(theta)
T[0][1] = -np.sin(theta)
T[0][2] = 0.0
T[0][3] = 0.0
T[1][0] = np.sin(theta)
T[1][1] = np.cos(theta)
T[1][2] = 0.0
T[1][3] = 0.0
T[2][0] = 0.0
T[2][1] = 0.0
T[2][2] = 1.0
T[2][3] = 0.0
T[3][0] = 0.0
T[3][1] = 0.0
T[3][2] = 0.0
T[3][3] = 1.0
return trans_mat_stacks(T, x)
# Calculates COM for given mass and position
def com_basic(mass, pos):
"""
Calculates the center of mass for given vectors of mass and position
:param mass: mass vector
:param pos: position vector
:return: center of mass
"""
return np.divide(np.sum(np.dot(mass, pos)), np.sum(mass))
# Determines the COM for a given set of coordinates
def trans_mat_com(x):
"""
Helper function which determines the COM for a given set of collected coordinates [x,y,z]
ASSUMES THE MASS VECTOR IS UNITY
:param x: [x,y,z]
:return: com in the form [x,y,z]
"""
x, y, z = uncollect_xyz_2_coords(x)
com_x = com_basic(np.ones_like(x), x)
com_y = com_basic(np.ones_like(y), y)
com_z = com_basic(np.ones_like(z), z)
return [com_x, com_y, com_z]
# Moves things to origin using com, translates by a vector, then transforms back away from origin
def trans_mat_com_tran(x, vec):
"""
Moves things to origin using com, translates by a vector, then transforms back away from origin
:param x: [x,y,z]
:param vec: translation vector
:return: Transformed vector
"""
# Determine com location
com = trans_mat_com(x)
# Move com to origin
x = trans_mat_tran(x, np.dot(-1.0, com))
# Translate by input vector
x = trans_mat_tran(x, vec)
# Move com back to original com location
x = trans_mat_tran(x, np.dot(+1, com))
return com, x
# Moves things to origin using com, rotates by theta, then transforms back away from origin
def trans_mat_com_rot(x, theta, axis):
"""
Moves things to origin using com, rotates by theta, then transforms back away from origin
:param x: [x,y,z]
:param theta: degree to rotate by
:param axis: axis to perform the rotation
:return: Transformed vector
"""
# Determine com location
com = trans_mat_com(x)
# Move com to origin
x = trans_mat_tran(x, np.dot(-1, com))
# Rotates
if axis == 'x':
x = trans_mat_rot_x(x, theta)
elif axis == 'y':
x = trans_mat_rot_y(x, theta)
elif axis == 'z':
x = trans_mat_rot_z(x, theta)
else:
print('Problem...')
# Move com back to original com location
x = trans_mat_tran(x, np.dot(+1, com))
return com, x
# Find the optimal rigid transformation
def rigid_transform_3d_find(A, B):
"""
Finding the optimal rotation and translation between
two sets of corresponding 3D point data, so that they are aligned
Adapted from https://nghiaho.com/?page_id=671
:param A: vector A expects Nx3 matrix of points
:param B: vector B expects Nx3 matrix of points
:return: R,t
R = 3x3 rotation matrix
t = 3x1 column vector
"""
# Ensure that the shape is the same
assert A.shape == B.shape
# Assert matrix type
A = np.matrixlib.defmatrix.matrix(A)
B = np.matrixlib.defmatrix.matrix(B)
N = A.shape[0] # total points
# Find the centre of A and B
centroid_A = np.mean(A, axis=0)
centroid_B = np.mean(B, axis=0)
# Centre the points
AA = A - np.tile(centroid_A, (N, 1))
BB = B - np.tile(centroid_B, (N, 1))
# dot is matrix multiplication for array
H = np.transpose(AA) * BB
# H = AA.T * BB
U, S, Vt = np.linalg.svd(H)
R = Vt.T * U.T
# special reflection case
if np.linalg.det(R) < 0:
print("Reflection detected")
Vt[2, :] *= -1
R = Vt.T * U.T
t = -R * centroid_A.T + centroid_B.T
return R, t
# Apply the optimal rigid transformation
def rigid_transform_3d_apply(A, B, R, t):
"""
Applies a rigid transformation of A to try and match B, a comparison of the new vector and B is then made
https://en.wikipedia.org/wiki/Rigid_transformation
Adapted from https://nghiaho.com/?page_id=671
:param A: vector to move
:param B: Exemplar vector
:param R: optimum rotation
:param t: Optimum translation
:return: Moved vector A and the rmse
"""
# Assert matrix type
A = np.matrixlib.defmatrix.matrix(A)
B = np.matrixlib.defmatrix.matrix(B)
# Find the size
n = A.shape[0]
# Apply the optimal transform
A2 = (R * A.T) + np.tile(t, (1, n))
A2 = A2.T
# Find the error
err = np.subtract(A2, B)
rmse = np.sqrt(np.sum(np.square(err)) / n)
return A2, rmse
# Random rigid scramble transformation
def rigid_transform_3d_scramble(A):
"""
Applies a rigid rotation and translation scramble to input vector A
Adapted from https://nghiaho.com/?page_id=671
:param A: Input vector to scramble
:return: Scrambled input vector, rotation, and translation
"""
# Assert matrix type
A = np.matrixlib.defmatrix.matrix(A)
# Random rotation and translation
R = np.mat(np.random.rand(3, 3))
t = np.mat(np.random.rand(3, 1))
# Make R a proper rotation matrix, force orthonormal
U, S, Vt = np.linalg.svd(R)
R = U * Vt
# Remove reflection
if np.linalg.det(R) < 0:
Vt[2, :] *= -1
R = U * Vt
# Find the size
n = A.shape[0]
# Apply the scramble
B = R * A.T + np.tile(t, (1, n))
return B.T, R, t
# for a given set of coordinates clusters into two molecules
def cluster(x, y, z, ad_locs):
"""
For a given set of coordinates clusters into two molecules
Improvements:
Needs improvements in the checking algo
Needs better way to output data
Generalise to auto-detect Hbonds or from given bond length
Generalise to work for any number of clusters
:param x: x vector
:param y: y vector
:param z: z vector
:param ad_locs: H-bonds to fragment by
:return: the locations of two clusters and the cutoff radius to fragment the clusters
"""
n_atoms = len(x)
# Collect data into coords
tmp = collect_xyz_2_coords(x, y, z)
coords = tmp[:, :-1]
# Determine the shortest bond of the hydrogen bonds given
r = []
for val in ad_locs:
tmp = spherical_coords(abs(coords[val[1]] - coords[val[2]]))[0]
tmp1 = spherical_coords(abs(coords[val[0]] - coords[val[2]]))[0]
r.append(max(tmp, tmp1))
print('')
# Pick the smallest one
r_cutoff = min(r)
# pick some location
a = [0]
flags = 0
# Outer loop over kill, confirm nothing is missed
while True:
l1 = len(a)
# Loop over the atoms
for j in a:
# Loop over all the atoms in the list
for i in range(n_atoms):
select = j
# Avoid re-adding of values
if i in a:
continue
# Calculate the distance between the two chosen sites
dist = spherical_coords(abs(coords[select] - coords[i]))[0]
# Check if the distance is less than the cut off
if dist < r_cutoff:
a.append(i)
l2 = len(a)
# check if the appended atoms changes
if l1 == l2:
flags += 1
# Dont leave until nothing changes for 5 iterations, overkill...
if flags == 5:
break
# Select the rest of the atoms
b = [i for i in range(n_atoms) if i not in a]
# returns the locations of two clusters and the cutoff radius
return a, b, r_cutoff
#######################################################################################################################
# FILE PATH MANIPULATION STUFF
# List only the files in a directory
def file_list(mypath=os.getcwd()):
"""
List only the files in a directory given by mypath
:param mypath: specified directory, defaults to current directory
:return: returns a list of files
"""
onlyfiles = [f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
return onlyfiles
# List only the top level folders in a directory
def folder_list(mypath=os.getcwd()):
"""
List only the top level folders in a directory given by mypath
NOTE THIS IS THE SAME AS top_dirs_list
:param mypath: specified directory, defaults to current directory
:return: returns a list of folders
"""
onlyfolders = [f for f in os.listdir(mypath) if os.path.isdir(os.path.join(mypath, f))]
return onlyfolders
# List only files which contain a substring
def sub_file_list(mypath, sub_str):
"""
List only files which contain a given substring
:param mypath: specified directory
:param sub_str: string to filter by
:return: list of files which have been filtered
"""
return [i for i in file_list(mypath) if sub_str in i]
# List only folders which contain a substring
def sub_folder_list(mypath, sub_str):
"""
List only folders which contain a given substring
:param mypath: specified directory
:param sub_str: string to filter by
:return: list of folders which have been filtered
"""
return [i for i in folder_list(mypath) if sub_str in i]
# Bring the path back one
def parent_folder(mypath=os.getcwd()):
"""
Bring the path back by one
:param mypath: specified directory, defaults to current directory
:return: parent path
"""
return os.path.abspath(os.path.join(mypath, os.pardir))
# Backs up a file if it exists
def file_bck(fpath):
"""
Backs up a file if it exists
:param fpath: file to check/backup
:return: None
"""
if os.path.exists(fpath) == True:
bck = fpath.split('.')
assert len(bck) == 2
dst = bck[0] + '_bck.' + bck[1]
shutil.copyfile(fpath, dst)
return None
# Removes all files in a given directory
def file_remove(fpath, f_exit=True):
"""
Removes all files in a given directory. Can abort if failure detected
:param fpath:
:return: None
"""
for filename in os.listdir(fpath):
file_path = os.path.join(fpath, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
# Leaves if failure
if f_exit:
exit()
return None
#######################################################################################################################
# MATHS
# Normalise a vector
def normalise(vec):
"""
Normalises a given eigenvector
:param vec: input vector of which to normalise
:return: normalised vector
"""
# Finds the magnitude by self dot then sqrt
mag = np.sqrt(np.dot(vec, vec))
# Normalises
vec = np.divide(vec, mag)
return vec
def norm_wf(psi, x):
"""
Normalises a set of wavefunctions
:param psi: (list of several or just one) wavefunction
:param x: x range to integrate over
:return: normalised wavefunction
"""
rank = len(np.shape(psi))
# Enforce normalisation
if rank == 2:
# psi = np.array([(p / np.sqrt(np.trapz(p * p.conj(), x))).real for p in psi], dtype=complex)
psi = np.array([(p / np.sqrt(scipy.integrate.simps(p * p.conj(), x))).real for p in psi], dtype=complex)
else:
# psi = np.array((psi / np.sqrt(np.trapz(psi * psi.conj(), x))).real, dtype=complex)
psi = np.array((psi / np.sqrt(scipy.integrate.simps(psi * psi.conj(), x))).real, dtype=complex)
return psi
# Determines the probability
def prob(l_low, u_lim, f_rho, x):
"""
# extract the real diagonal terms
# tmp = np.diag(np.real(A*np.conjugate(A)))
tmp = np.diag(np.real(A))
# Need to pick the location
tmp = tmp[l_low:u_lim]
# Integrate over the required range
# p = scipy.integrate.simps(tmp)
p = np.sum(tmp)
"""
p = np.real(scipy.integrate.simps(np.diag(f_rho)[l_low:u_lim], x[l_low:u_lim]))
return p
def expect_x(f_rho, x): # expect_x
# return np.real(np.trace(np.multiply(f_rho, A)))
return np.real(scipy.integrate.simps(np.multiply(np.diag(f_rho), x), x))
def trace(f_rho, x):
# pick out the psi components
# psi = np.diag(mat)
# tr = np.real(np.sqrt(np.trapz(np.diag(mat), x)))
tr = np.real(scipy.integrate.simps(np.diag(f_rho), x))
return tr
def vn_entropy(f_rho, x):
f_rho = f_rho * np.log(f_rho)
rtn = -np.trace(f_rho)
rtn = -trace(f_rho, x)
return rtn
def von_neumann_entropy(density_matrix, cutoff=10):
"""
https://arxiv.org/pdf/1209.2575.pdf
https://cs.stackexchange.com/questions/56261/computing-von-neumann-entropy-efficiently
https://en.wikipedia.org/wiki/Von_Neumann_entropy
:param density_matrix:
:param cutoff:
:return:
"""
x = np.mat(density_matrix)
one = np.identity(x.shape[0])
base = one - x
power = base * base
result = np.trace(base)
for k in range(2, cutoff):
result -= np.trace(power) / (k * k - k)
power = power.dot(base)
# Twiddly hacky magic.
a = cutoff
for k in range(3):
d = (a + 1) / (4 * a * (a - 1))
result -= np.trace(power) * d
power = power.dot(power)
result -= np.trace(power) * d
a *= 2
result -= np.trace(power) / (a - 1) * 0.75
return result / np.log(2) # convert from nats to bits
def trace_ratio(f_rho, x):
rat = trace(np.square(f_rho), x) / np.square(trace(f_rho, x))
rat = np.trace(np.square(f_rho)) / np.square(np.trace(f_rho))
return rat
# Check if a matrix is symmetric
def check_symmetric(a, rtol=1e-05, atol=1e-08):
"""
Check if the input matrix is symmetric, compares real to real and imag to imag!
https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html
:param a: input matrix
:param rtol: The relative tolerance parameter
:param atol: The absolute tolerance parameter
:return: bool, true or false
"""
val = np.real(a)
comp_real = np.allclose(val, val.T, rtol=rtol, atol=atol)
val = np.imag(a)
comp_imag = np.allclose(val, val.T, rtol=rtol, atol=atol)
return comp_real, comp_imag
# matrix logarithm via eigen decomposition
def logm_eigen(A):
"""
Calculate the matrix logarithm using the eigen decomposition method
:param A: Input matrix
:return:
"""
_, V = np.linalg.eig(A)
V_inv = np.linalg.inv(V)
A_dash = np.matmul(np.matmul(V_inv, A), V)