-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2048 lines (1781 loc) · 74.2 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/env python3
import glob
import os
import re
import shutil
import ase
import ase.io.castep
import ase.optimize
import matplotlib.pyplot as plt
import numpy as np
from ase import io
from ase.calculators.castep import Castep
from ase.calculators.emt import EMT
from ase.calculators.nwchem import NWChem
from ase.calculators.onetep import Onetep
from ase.dimer import DimerControl, MinModeAtoms, MinModeTranslate
from ase.io import read
from ase.io import write
from ase.neb import NEBTools
from ase.optimize import BFGS
from ase.optimize import (FIRE, LBFGS, LBFGSLineSearch, BFGSLineSearch,
GPMin)
from ase.optimize.precon import Exp, PreconLBFGS
from ase.visualize import view
from ase.visualize.plot import plot_atoms
def reduced_mass(mass, reac_co, poss_co, acc=4):
"""
:param mass:
:param reac_co:
:param poss_co:
:param acc:
:return:
"""
from findiff import FinDiff
# Inverse mass
mass = np.power(mass, -1)
poss_co = np.array(poss_co)
msum = np.zeros(np.shape(mass)[-1])
plt.close()
# Loop over elemental masses
for i in range(np.shape(mass)[-1]):
# Define the partial derivative
r = np.linalg.norm(poss_co[:, i, :] - poss_co[0, i, :], axis=-1) # -poss_co[0,i,:]
d_dx = FinDiff(0, r, 1, acc=acc)
# Apply the derivative
pdiv = d_dx(np.array(reac_co))
plt.figure(1)
plt.plot(reac_co, r)
plt.figure(2)
plt.plot(reac_co, pdiv)
pdiv_norm = np.linalg.norm(pdiv)
print(pdiv_norm)
# determine sum elements
msum[i] = mass[0, i] * np.square(np.abs(pdiv_norm))
# Determine the full sum
plt.figure(1)
n_plot(r'Path $\AA$', 'Image vector, r')
plt.savefig('path_vs_r.pdf')
plt.close()
plt.figure(2)
n_plot(r'Path $\AA$', r'$\frac{\partial q}{\partial r}$')
plt.savefig('path_vs_dq_dr.pdf')
plt.close()
mu = 1.0 / np.sum(msum)
return mu
def new_reduced_mass(mass, reac_co, poss_co, acc=4):
from findiff import FinDiff
reac_co = np.array(reac_co)
poss_co = np.array(poss_co)
num_atoms = len(mass)
num_images = len(reac_co)
print(reac_co)
r_arr = np.zeros([num_images, num_atoms])
r_arr_n = np.zeros([num_images, num_atoms])
for i in range(num_atoms):
r_arr[:, i] = np.linalg.norm(poss_co[:, i, :], axis=-1) # - poss_co[0, i, :]
r_arr_n[:, i] = np.linalg.norm(poss_co[:, i, :] - poss_co[0, i, :], axis=-1)
for i in range(num_atoms):
plt.plot(reac_co, r_arr[:, i], label='%s%i' % (E[i], i))
plt.legend(loc='best')
n_plot(r'Reaction path, s [$\AA$]', 'Image coordinate vector, r [$\AA$]')
plt.savefig('path_vs_r.pdf')
plt.show()
for i in range(num_atoms):
plt.plot(reac_co, r_arr_n[:, i], label='%s%i' % (E[i], i))
plt.legend(loc='best')
n_plot(r'Reaction path, s [$\AA$]', 'Normalised image coordinate vector, r [$\AA$]')
plt.savefig('path_vs_r_norm.pdf')
plt.show()
rm = np.zeros([num_atoms, num_images])
for i in range(num_atoms):
x_i = r_arr[:, i]
d_dx = FinDiff(0, x_i, 1, acc=acc)
pdiv = d_dx(reac_co)
rm[i, :] = 1 / mass[i] * np.dot(pdiv, pdiv)
mu = 1 / np.sum(rm, axis=0)
plt.plot(reac_co, mu)
n_plot(r'Reaction path, s [$\AA$]', 'reduced mass, $\mu$ [amu]')
plt.savefig('path_vs_mu.pdf')
plt.show()
return mu
# Performs NEB analysis
def neb_anal_cont(nebtools, name):
# Plot the NEB diagram
try:
# Get the calculated barrier and the energy change of the reaction.
Ef, dE = nebtools.get_barrier()
print('Calculated barrier and the energy change:', Ef, dE)
# Get the barrier without any interpolation between highest images.
Ef, dE = nebtools.get_barrier(fit=False)
print('(w/o any interpolation) Calculated barrier and the energy change:', Ef, dE)
# Get the actual maximum force at this point in the simulation.
max_force = nebtools.get_fmax()
print('Max force:', max_force)
# Create a figure with custom parameters.
fig = plt.figure(figsize=(5.5, 4.0))
ax = fig.add_axes((0.15, 0.15, 0.8, 0.75))
nebtools.plot_band(ax)
fig.savefig('NEB.pdf')
os_plot_show()
except:
print('problem')
try:
# Grab the fitting parameters
fitting = nebtools.get_fit() # s, E, Sfit, Efit, lines
s = fitting[0]
E = fitting[1]
Sfit = fitting[2]
Efit = fitting[3]
lines = fitting[4]
plt.plot(Sfit, Efit)
plt.savefig('Sfit_vs_Efit.pdf')
os_plot_show()
plt.scatter(s, E)
plt.savefig('s_vs_E.pdf')
os_plot_show()
# Grab the images
images = nebtools._images
R = [atoms.positions for atoms in images]
# Need to work on an animation
mass = [atoms.get_masses() for atoms in images]
print('R shape:', np.shape(R))
print('mass shape:', np.shape(mass))
print('mass matrix:\n', mass)
mu = reduced_mass(mass, s, R, acc=4)
print('Reduced mass:', mu)
except:
print('problem')
# Plot the convergence
try:
files = sub_file_list(os.getcwd(), '.log')
file = [i for i in files if name in i]
for ii, val in enumerate(file):
A = np.genfromtxt(val, skip_header=1, usecols=(1, 2, 3, 4))
plt.plot(A[:, 0], A[:, -1], marker='o')
n_plot('Iteration number', 'Max force')
plt.savefig('%s__N_vs_dF.pdf' % val)
os_plot_show()
except:
print('Plot the convergence problem')
return None
# Performs NEB analysis
def neb_anal(N_images, title='NEB'):
try:
# Grab the files
files = sub_file_list(os.getcwd(), '.traj')
file = 'a2b.traj'
# Read in the images
images = read(file + '@-' + str(N_images) + ':')
# Grab the tool box
nebtools = NEBTools(images)
# Get the calculated barrier and the energy change of the reaction.
Ef, dE = nebtools.get_barrier()
print('Calculated barrier and the energy change:', Ef, dE)
# Get the barrier without any interpolation between highest images.
Ef, dE = nebtools.get_barrier(fit=False)
print('(w/o any interpolation) Calculated barrier and the energy change:', Ef, dE)
# Get the actual maximum force at this point in the simulation.
max_force = nebtools.get_fmax()
print('Max force:', max_force)
# Create a figure with custom parameters.
fig = plt.figure(figsize=(5.5, 4.0))
ax = fig.add_axes((0.15, 0.15, 0.8, 0.75))
nebtools.plot_band(ax)
fig.savefig('NEB.pdf')
os_plot_show()
except:
print('problem')
# Grab the fitting parameters
fitting = nebtools.get_fit() # s, E, Sfit, Efit, lines
s = fitting[0]
E = fitting[1]
Sfit = fitting[2]
Efit = fitting[3]
lines = fitting[4]
plt.plot(Sfit, Efit)
plt.savefig('test.pdf')
os_plot_show()
plt.scatter(s, E)
plt.savefig('test1.pdf')
os_plot_show()
# Grab the images
images = nebtools._images
R = [atoms.positions for atoms in images]
mass = [atoms.get_masses() for atoms in images]
print('R shape:', np.shape(R))
print('mass shape:', np.shape(mass))
print(mass)
mu = reduced_mass(mass, s, R, acc=4)
print('Reduced mass:', mu)
# Plot the convergence
files = sub_file_list(os.getcwd(), '.log')
file = 'a2b.log'
A = np.genfromtxt(file, skip_header=1, usecols=(1, 2, 3, 4))
plt.plot(A[:, 0], A[:, -1], marker='o')
plt.title(title)
n_plot('Iteration number', 'Max force')
plt.savefig('N_vs_dF.pdf')
os_plot_show()
return None
def gen_names(xc_list, gold_list, ele_list):
f_type = '' # xyz
"""
xc_list = ['B3LYP']
xc_list = ['B3LYP', 'PBE0']
gold_list = ['gold', 'gold_impsol']
ele_list = ['GC']
ele_list = ['AT']
ele_list = ['A', 'T', 'G', 'C']
ele_list = ['GC']
"""
# post_fix = '_fix_align'
post_fix = '_ase'
names_list = []
for e in ele_list: # Loop over elements
for gold in gold_list: # Loop over standards
for xc in xc_list: # loop over exchange correlation functionals
# Fix the PBE0 case
if xc.upper() == 'PBE0':
a = gold.split('_')
if len(a) == 1:
gold = a[0] + '_mbd'
else:
gold = ''
for i, val in enumerate(a):
if i == 1:
gold += 'mbd' + '_'
gold += val + '_'
# strip the trailing _
gold = gold[:-1]
rect_xyz_file = r'%s_%s_%s%s%s' % (e.upper(), xc.upper(), gold.upper(), post_fix, f_type)
prod_xyz_file = r'%s_taut_%s_%s%s%s' % (e.upper(), xc.upper(), gold.upper(), post_fix, f_type)
print(rect_xyz_file)
print(prod_xyz_file)
names_list.append(rect_xyz_file)
names_list.append(prod_xyz_file)
return names_list
def bodge():
xyz_folder = r'/users/ls00338/xyz/Gold'
file = 'bodge_list.txt'
reac = 'react.traj'
prod = 'prod.traj'
# load the files
f_names = np.genfromtxt(file, dtype=str, delimiter='\n')
f_names = gen_names(['B3LYP', 'PBE0'], ['gold', 'gold_impsol'], ['GC']) + gen_names(['B3LYP'],
['gold', 'gold_impsol'],
['AT']) + gen_names(
['B3LYP', 'PBE0'], ['gold', 'gold_impsol'], ['A', 'T', 'G', 'C'])
# Make the list of work dirs
work_dirs = ['W00299', 'W00300', 'W00305', 'W00306', 'W00307', 'W00308']
work_dirs = [os.path.join(os.getcwd(), i) for i in work_dirs]
# make the list of job dirs
a = []
for i in work_dirs:
job_dirs = folder_list(i)
job_dirs.sort(key=natural_keys)
for j in job_dirs:
a.append(os.path.join(os.path.join(i, j), reac))
a.append(os.path.join(os.path.join(i, j), prod))
assert len(f_names) == len(a)
num = 0
for i in range(len(f_names)):
target = os.path.join(xyz_folder, f_names[i] + '.traj')
if os.path.exists(a[i]) == True and int(os.path.getsize(a[i])) > 0:
num += 1
print(a[i])
print(target)
shutil.copy(a[i], target)
print(num)
return None
def harm_correc(g_omega, omega, T):
"""
Determines the harmonic free energy correction.
From slide 9/20 of:
http://www.tcm.phy.cam.ac.uk/castep/CASTEP_talks_06/refson2.pdf
:param g_omega: DOS
:param omega: Phonon eigenvalues
:param T: Temperature of the system
:return: The correction X, in the free energy equation F = E + X
"""
from scipy.integrate import simps
h_bar = 6.582119569e-16 # eV s https://en.wikipedia.org/wiki/Planck_constant
k_b = 8.617333262145e-5 # eV k^-1 https://en.wikipedia.org/wiki/Boltzmann_constant
beta = 1 / (k_b * T)
internal = g_omega * np.log(2 * np.sinh(0.5 * beta * h_bar * omega))
return 1 / beta * simps(internal, omega)
#### autoNEB/NEB functions ####
# Gold standard params
def cas_in_prep(c_ob, xc_func, settings='gold', f_flush=False):
"""
:param c_ob:
:param xc_func:
:param set: expected: gold, dev, mbd, impsol
:return:
"""
set_list = settings.split('_')
c_ob.param.xc_functional = xc_func.upper()
if 'gold' in set_list:
print('Using gold settings', flush=f_flush)
# Set the param file keywords
c_ob.param.cut_off_energy = 1100
c_ob.param.elec_energy_tol = 1.0E-8
c_ob.param.elec_eigenvalue_tol = 1.0E-8
c_ob.param.fine_grid_scale = 2.0
c_ob.param.geom_energy_tol = 1.0E-6
c_ob.param.geom_force_tol = 0.01
c_ob.param.geom_stress_tol = 0.02
c_ob.param.geom_disp_tol = 5.0E-4
c_ob.param.geom_max_iter = 500
elif 'extreme' in set_list:
print('Using extreme settings', flush=f_flush)
# Set the param file keywords
c_ob.param.elec_method = 'EDFT'
c_ob.param.cut_off_energy = 1500
c_ob.param.elec_energy_tol = 5.0E-7
c_ob.param.elec_eigenvalue_tol = 5.0E-7
c_ob.param.fine_grid_scale = 2.0
else:
print('Warning not in settings...', flush=f_flush)
c_ob.param.cut_off_energy = float(settings)
c_ob.param.num_dump_cycles = 0
c_ob.param.fix_occupancy = True
c_ob.param.max_scf_cycles = 300
c_ob.param.mixing_scheme = 'pulay'
c_ob.param.opt_strategy = "speed"
c_ob.param.reuse = True
# Check to see if settings are given
if 'dev' in set_list:
c_ob.param.devel_code = "improve_wvfn"
if 'mbd' in set_list:
c_ob.param.sedc_apply = True
c_ob.param.sedc_scheme = 'MBD'
if 'impsol' in set_list:
c_ob.param.implicit_solvent_apolar_term = True
# Set the cell file keywords
c_ob.cell.symmetry_generate = True
c_ob.cell.fix_com = False
c_ob.cell.fix_all_cell = True
return c_ob
# Set a bunch of calculator settings for CASTEP
def set_settings(atoms, seed, xc_func, settings, ps_type='NCP'):
ps_type = ps_type.upper()
# Attach the calculator
calc = ase.calculators.castep.Castep(keyword_tolerance=1)
# include interface settings in .param file
calc._export_settings = True
calc._pedantic = True
# Set working directory
calc._seed = seed
calc._label = seed
calc._directory = seed
# Set the parameters
calc = cas_in_prep(calc, xc_func, settings)
# Set the calculator
atoms.set_calculator(calc)
# Set the psudopot xc type
xc_use = xc_func.upper()
if xc_func == 'PBE' or xc_func == 'PBE0':
xc_use = 'PBE'
elif xc_func == 'B3LYP' or xc_func == 'BLYP':
xc_use = 'BLYP'
# Use custom pseudo-potential
atoms.calc.set_pspot('%s19_%s_OTF' % (ps_type, xc_use))
return atoms
def cal_attach(atoms, calc, calc_args):
"""
Attaches calculators to an atoms object, can be used to attach
:param atoms:
:param calc:
:param calc_args:
:return:
"""
calc = calc.upper()
if calc == 'EMT':
atoms.set_calculator(EMT())
elif calc == 'CASTEP':
# print('Using Castep')
atoms = set_settings(atoms, *calc_args)
elif calc == 'ONETEP':
# print('Using Onetep')
calc = onetep_settings(*calc_args)
atoms.set_calculator(calc)
else:
exit('Problem with calculator name!')
return atoms
def onetep_imp_sol(calc):
"""
ONETEP implicit solvent settings
Taken from:
https://www.onetep.org/pmwiki/uploads/Main/MasterClass2019/impsolventCC-GAB.pdf
:param calc:
:return:
"""
calc.set(is_implicit_solvent=True)
calc.set(is_smeared_ion_rep=True)
calc.set(is_include_apolar=True)
calc.set(mg_defco_fd_order=8)
calc.set(is_autosolvation=True)
calc.set(is_dielectric_model="FIX_INITIAL") # SELF_CONSISTENT
# calc.set(is_solvent_surf_tension="0.0000133859 ha/bohr**2")
# calc.set(is_density_threshold=0.00035)
# calc.set(is_solvation_beta=1.3)
# calc.set()
return calc
def onetep_settings(seed='data', xc_func='pbe', ps_type='abinit', f_imp_sol=False, e_cut=600, f_paw=True, p_t=None,
disper=0):
"""
:param seed:
:param xc_func:
:param ps_type:
:param p_t:
:param f_imp_sol:
:param e_cut:
:return:
"""
# Set up a command to invoke the ONETEP calculator
if p_t is None: # on 4 processes of 6 threads each
procs = 20
threads = 1
else: # Pick up from command line
procs = p_t[0]
threads = p_t[1]
ps_pot_path = r'/mnt/beegfs/users/ls00338/ps_pots/'
"""
onetep_cmd = '/users/ls00338/onetep/bin/onetep.eureka'
environ[
"ASE_ONETEP_COMMAND"] = f'export OMP_NUM_THREADS={threads}; mpirun -n {procs} {onetep_cmd} PREFIX.dat >> PREFIX.out 2> PREFIX.err'
"""
# Determine the calculator
calc = Onetep(label=seed)
# Sort the ps pots
if ps_type == 'abinit':
calc.set(pseudo_path=os.path.join(ps_pot_path, 'JTH-PBE-atomicdata-1.0'))
calc.set(pseudo_suffix=r'.PBE-paw.abinit')
elif ps_type == 'recpot':
calc.set(pseudo_path=ps_pot_path)
calc.set(pseudo_suffix=r'-onetep.recpot')
f_paw = False
else:
exit('ps type not recognised!')
# Core settings
calc.set(paw=f_paw, xc=xc_func, cutoff_energy=str(e_cut) + ' eV', dispersion=disper)
# calc.set(ngwf_threshold_orig=1.0e-6,elec_energy_tol="1.0e-5 eV",elec_force_tol ="1.0e-2 eV/ang")
if f_imp_sol:
onetep_imp_sol(calc)
return calc
def taut_mid(atoms, idx):
"""
For a given input of atoms object moves the middle index atom to the middle point of the out two idexes
:param atoms: atoms object
:param idx: list of indexes [mol1, proton, mol2]
:return: atoms object with the proton moved
"""
# Get the atom positions
moved = atoms.copy()
pos = moved.get_positions()
# Find the mid point location
mid = 0.5 * (pos[idx[0], :] + pos[idx[2], :])
# Move the atom
moved.positions[idx[1]] = mid
return moved
def neb_folder_cleanup(dir=os.getcwd(), sub='data'):
"""
Finds subfolders with a given substring in a dir and removes the subfolders
:param dir: directory to look
:param sub: substring to filter by
:return:
"""
f_list = sub_folder_list(dir, sub)
print('Folders to be removed:\n', f_list)
# loop over list and remove each folder
for i in f_list:
os.rmdir(i)
assert len(sub_folder_list(dir, sub)) == 0
return None
def rm_neb_files(dir=os.getcwd(), neb_str='neb0', exclude=None):
"""
Removes any neb files, prevents conflicts.
:param dir: input directory
:param neb_str: substring used to highlight the neb trajectory files
:param exclude: list of substrings which you dont want to remove
:return: list of file paths
"""
onlyfiles = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))]
files = [i for i in onlyfiles if neb_str in i]
if exclude != None: ### FIX ME
files = [element for element in files if element not in exclude]
for i in files:
print('Removing: ', i)
os.remove(os.path.join(dir, i))
# 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
: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
# 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=None, pick=-1):
"""
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_traj)[0] + '.xyz'
file_traj = file_traj.split('.')[0] + '.traj'
if file_xyz is None:
file_xyz = file_traj.split('.')[0] + '.xyz'
else:
# remove and re-apply file ext
file_xyz = os.path.splitext(file_xyz)[0] + '.xyz'
# Grab the traj from file
a = io.read(file_traj + '@:')
a = a[pick]
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 a
def n_plot(xlab, ylab, xs=14, ys=14):
"""
Makes a plot look nice by introducting 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, direction='in', length=6, width=2)
plt.tick_params(axis='both', which='minor', labelsize=ys, 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
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
# Helper to natural_keys
def atoi(text):
"""
helper function of natural_keys
:param text: input text
:return: ??
"""
return int(text) if text.isdigit() else text
# Human sorts a list of strings
def natural_keys(text):
"""
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
:param text:
:return: sorted list
"""
return [atoi(c) for c in re.split(r'(\d+)', text)]
# calculate fmax
def get_fmax(forces):
return np.sqrt((forces ** 2).sum(axis=1).max())
def get_phonon_image(pick, atms):
if pick == 'R': # Reactant
print('Using reactant image')
img = 0
elif pick == 'P':
print('Using product image')
img = -1
elif pick == 'TS':
energy = [i.get_potential_energy() for i in atms]
img = np.argmax(energy)
else: # Assume pick is the image you want
img = pick
print('Image picked = ', img)
return str(img)
def image_picker(name, file_path, rtn_idx=False):
"""
Returns the image of a NEB band from specified name / number
:param name: Name of the image to pick or number
:param file_path: path to find the images
:return: atoms object
"""
if type(name) == str:
# Reactant
if name.lower() == "react" or name.lower() == "r":
idx = 0
# TS
elif name.lower() == "ts":
img = read(file_path, index=':')
# Get the energies of the bands
nebfit = ase.utils.forcecurve.fit_images(img)
e = nebfit[1]
idx = int(np.where(e == max(e))[0])
print("TS image number = ", idx)
# Product
elif name.lower() == "prod" or name.lower() == "p":
idx = -1
# Specific image
else:
idx = name
else:
idx = name
if rtn_idx:
return read(file_path, index=idx), idx
else:
return read(file_path, index=idx)
def remove_pbc(atoms_in, file_tmp="tmp.xyz", f_rm=True):
"""
This function strips away bc information.
TODO
Check for a list of atoms and decide what to do with them!
Example usage:
view(remove_pbc(ase.io.read("G_C_B3LYP_GOLD_IMPSOL_NWC.traj")))
:param atoms_in: atoms object
:param file_tmp: temporary file which is stored to and removed
:param f_rm: logic flag to remove temporary file
:return: atoms object
"""
# Write a temporary xyz file
ase.io.write(file_tmp, atoms_in)
# Load the xyz file
lines = np.loadtxt(file_tmp, dtype=str, delimiter="\n")
# Remove the comment with the extra info
lines[1] = " "
# Save the modified xyz file
np.savetxt(file_tmp, lines, delimiter="\n", fmt="%s")
# Load the modified xyz file to atoms object
atoms_out = ase.io.read(file_tmp)
# Delete the temporary xyz file
if f_rm:
os.remove(file_tmp)
# Return the cleaned atoms
return atoms_out
def traj_clean(name):
"""
Cleans up an input traj filename for use. Stripping off the .traj@: for example
:param name: input trajectory file
:return: cleaned up name
"""
# Split up by . then take the first part
tmp = name.split('.')[0]
# Add the .traj back on
rtn = tmp + '.traj'
return rtn
# Routines
class opti_rout(object):
def __init__(self, file_name):
"""
Example usage
file_path = r'/users/ls00338/xyz/ds_TGT.traj'
ob = ase_common.opti_rout(file_path)
# Get the atoms
atoms = ob.get_atoms()
# Get the calculator settings
calc_args = (seed, xc_func, ps_type, f_imp_sol, e_cut, True, None, disper)
# Attach the calculator
ase_common.cal_attach(atoms, 'onetep', calc_args)
print('Relaxing initial structure', flush=f_flush)
# Minimise!
ob.line_switch(atoms)
:param file_name:
"""
# Init variables
self.calc_name = None
self.xc_func = None
self.settings = None
self.file_name = file_name
self.f_flush = True
self.seed = 'data'
self.logfile = '-'
self.fname = 'data'
self.fname_s = self.fname + '_s'
self.fmax = 0.01
self.fmax_s = 1.0
self.vac = 10
self.xyz_folder = r'/users/ls00338/xyz/'
def get_atoms(self):
# Get the atoms
atoms = io.read(os.path.join(self.xyz_folder, self.file_name))
atoms.get_cell()
atoms.center(vacuum=self.vac)
return atoms
def ini_standard_calc(self, atoms):
self.calc_name = 'castep'
self.settings = 'gold_impsol'
self.xc_func = 'pbe'
self.ps_type = 'NCP'
calc_args = (self.seed, self.xc_func, self.settings, self.ps_type)
cal_attach(atoms, self.calc_name, calc_args)
return atoms
def relax(self, atm):
dyn = BFGS(atm, trajectory=self.fname + '.traj', logfile=self.fname + '.log', restart=self.fname + '.pckl')
dyn.run(fmax=self.fmax)
def fire(self, atm):
dyn = FIRE(atm, trajectory=self.fname + '.traj', logfile=self.fname + '.log', restart=self.fname + '.pckl')
dyn.run(fmax=self.fmax)
def precon(self, atm):
# Run preconditioned
opt = PreconLBFGS(atm, precon=Exp(A=3), use_armijo=True,
trajectory=self.fname_s + '.traj',
logfile=self.fname_s + '.log',
restart=self.fname_s + '.pckl')
opt.run(fmax=self.fmax_s)
def gaus_pro(self, atm):
dyn = GPMin(atm, trajectory=self.fname + '.traj',
logfile=self.fname + '.log',
restart=self.fname + '.pckl')
dyn.run(fmax=self.fmax)
def line(self, atm):
dyn = BFGSLineSearch(atm, trajectory=self.fname + '.traj', logfile=self.fname + '.log')
dyn.run(fmax=self.fmax)
def line_switch(self, atm):
dyn = BFGS(atm, trajectory=self.fname_s + '.traj', logfile=self.fname_s + '.log')
dyn.run(fmax=self.fmax_s)
dyn1 = BFGSLineSearch(atm, trajectory=self.fname + '.traj', logfile=self.fname + '.log')
dyn1.run(fmax=self.fmax)
def low_line_switch(self, atm):
dyn = LBFGS(atm, trajectory=self.fname_s + '.traj', logfile=self.fname_s + '.log')
dyn.run(fmax=self.fmax_s)
dyn1 = LBFGSLineSearch(atm, trajectory=self.fname + '.traj', logfile=self.fname + '.log')
dyn1.run(fmax=self.fmax)
def fire_switch(self, atm):
dyn = FIRE(atm, trajectory=self.fname_s + '.traj', logfile=self.fname_s + '.log')
dyn.run(fmax=self.fmax_s)
dyn1 = LBFGS(atm, trajectory=self.fname + '.traj', logfile=self.fname + '.log')
dyn1.run(fmax=self.fmax)
def precon_switch(self, atm):
# Run preconditioned
dyn = PreconLBFGS(atm, precon=Exp(A=3), use_armijo=True,
trajectory=self.fname_s + '.traj',
logfile=self.fname_s + '.log')
dyn.run(fmax=self.fmax_s)
# Switch to normal
dyn1 = LBFGS(atm, trajectory=self.fname + '.traj',
logfile=self.fname + '.log')
dyn1.run(fmax=self.fmax)
def gaus_switch(self, atm):
dyn = GPMin(atm, trajectory=self.fname_s + '.traj',
logfile=self.fname_s + '.log',
restart=self.fname_s + '.pckl')
dyn.run(fmax=self.fmax_s)
# Switch to normal
dyn = LBFGS(atm, trajectory=self.fname + '.traj',
logfile=self.fname + '.log',
restart=self.fname + '.pckl')
dyn.run(fmax=self.fmax)
class dft_calc(object):
def __init__(self, calc_type, seed, xc_f, settings, ele, ps_type='NCP', charge=None, mult=1, unixsocket=None):
"""
defines the CASTEP and ONETEP DFT code calculator
"""