-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatompacking_functions.py
1397 lines (1147 loc) · 53.6 KB
/
atompacking_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import math
import numpy as np
import subprocess
import shlex
import time
import os
import datetime
import re
###### Geometric functions
def distance_1(atom1,atom2):
dist = math.sqrt(math.pow(atom1[0] - atom2[0], 2) +
math.pow(atom1[1] - atom2[1], 2) +
math.pow(atom1[2] - atom2[2], 2))
return dist
#This function generate coordinates using distribution over spheric coordinates and the making them Euclidean
def generate_coordinates(r_min=0,r_max=1):
theta = random.uniform(0, 2 * math.pi)
phi = random.uniform(0, 2 * math.pi)
r = random.uniform(r_min,r_max)
x = (r * math.cos(theta) * math.sin(phi))
y = (r * math.sin(theta) * math.sin(phi))
z = (r * math.cos(phi))
vector = [x,y,z]
return vector
#This Function sorts atoms
def select_atom(atoms =[]):
at = np.array(atoms)
shape = np.shape(at)
dim = shape[1]
number =shape[0]
if number >=2 :
rm = random.randint(0,number-1)
selection = atoms[rm]
else :
selection = atoms[0]
return selection
def add_coordinates(vector1, vector2):
result =[]
if vector1 ==[]:
result =vector2
else:
for i in range(len(vector2)):
result = [vector1[i] + vector2[i] for i in range(len(vector2))];
return result
def proof_distance(atom1, atom2, r_min=0,r_max=10):
distance = distance_1(atom1, atom2)
condition = None
if distance <= r_min:
condition = False
elif distance >= r_max:
condition = False
else:
condition = True
return condition
def generate_atom (atoms=[],r_min = 2.0,r_max = 7,num_decimals =4,dist_min =2, dist_max =7):
condition =0
#print("r_max ", r_max, " dist_max", dist_max)
if atoms == [] :
at1 =[0,0,0]
else :
temporal_atom = None
num_atoms = len(atoms)
while condition ==0:
random_coordinates =generate_coordinates(r_min,r_max)
base_atom = select_atom(atoms)
temporal_atom = add_coordinates(base_atom,random_coordinates)
at = np.array(atoms)
number = at.ndim
if number !=1 :
for atom in atoms:
condition =proof_distance(atom, temporal_atom,dist_min ,dist_max)
if condition == 0:
break
else:
condition = 1
else:
atom = atoms
condition =proof_distance(atom, temporal_atom,dist_min ,dist_max)
if condition == 0:
break
else:
condition = 1
at1 = temporal_atom;
return at1
def print_xyz(size , matrix, atom , path=""):
# print("shape: "+ str(shape[0]))
Path_xyz = path
number= size
file_name = Path_xyz+"/" + atom + str(number)
print(Path_xyz)
print(file_name)
lines_of_text =[]
for x in matrix:
temp_string = "atom\t" +str(x[0])+"\t"+ str(x[1])+"\t"+str(x[2])+"\t"+ atom+ "\n"
lines_of_text.append(temp_string)
with open("%s.xyz"%file_name, "w") as fh :
fh.write(str(number)+ "\n")
fh.write("\n")
fh.writelines(lines_of_text)
fh.close()
return("Done")
def print_matrix_geometryin(matrix =[[],[]],name = "", path= ""):
print(matrix)
at = np.array(matrix)
shape = np.shape(at)
number =shape[0]
create_folder(name="", path=path)
file_name = path + "/" + name
lines_of_text =[]
for x in matrix:
temp_string = "atom " + str(x[0]) + " " + str(x[1]) + " " + str(x[2]) + " " + str(x[3])+ "\n"
lines_of_text.append(temp_string)
with open(file_name, "w") as fh :
#fh.write(str(number)+ "\n")
#fh.write("\n")
fh.writelines(lines_of_text)
fh.close()
def print_geometryin(matrix,atom ="Au",path=""):
file_name = path + "/geometry.in"
lines_of_text=[]
for x in matrix:
temp_string = "atom"+" "+str(x[0]) +" "+str(x[1])+" "+str(x[2])+" " +atom + "\n"
lines_of_text.append(temp_string)
with open(file_name, "w") as fh :
fh.writelines(lines_of_text)
fh.close()
return "Done"
def create_cluster(size =55, atom="Au",path ="", R_min = 2.0,R_max = 7,Num_decimals =4,Dist_min =2, Dist_max =7,cores =16, vdw = False):
cluster =[]
Size = size
Atom = atom
Path_cluster= path
print("size : ", Size , "atom : ",Atom,"r_max",R_max ,"dist = ", Dist_max )
for i in range(int(size)):
at=generate_atom(cluster,r_min = R_min,r_max = R_max , dist_max = Dist_max )
cluster.append(at)
print_geometryin(cluster,Atom ,Path_cluster)
print_xyz(size,cluster, Atom, Path_cluster)
#create_shforrunning(size,Atom,Path_cluster,cores =cores)
create_shforrunning_name(name= Atom+str(size),path = path, cores=cores)
create_control_in(path =Path_cluster, vdw=vdw)
return "Done"
#########################################################
# qsub is for queue miztli
#########################################################
def create_qsub(name= "",nodes = "", cores = 16, queue = "q_residual", path =""):
file_name_out = name +".out"
file_name_sh = path + "/qsub_fhi.sh"
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
complete_path = os.path.join(THIS_FOLDER,path)
print("Creating :" + file_name_sh)
text = ["!/bin/bash \n",
"#BSUB -q {} \n".format(queue),
"#BSUB -oo fhi-aims.%J.o \n",
"#BSUB -eo fhi-aims.%J.e \n",
# num cores
"#BSUB -n {} \n".format(cores),
#nodos
'#BSUB -m "{}" \n'.format(nodes),
"module purge \n",
"module load use.own\n",
"module load fhi-aims/1\n",
"mpirun aims.171221_1.scalapack.mpi.x < control.in > " + file_name_out]
with open(file_name_sh, "w") as fh:
fh.writelines(text)
subprocess.call(["chmod", "754",file_name_sh], universal_newlines=True)
return file_name_sh
###########################################################
#########################################################
# runsh is for not queue ela
#########################################################
def create_runsh(size =55, atom ="Au", path =""):
file_name_out = atom + str(size) +".out"
file_name_sh = path + "/run.sh"
print("Creating :" + file_name_sh)
text = ["nohup mpiexec -np 24 -f /home/raet/machinefiles.txt /opt/fhi-aims/bin/aims.171221_1.scalapack.mpi.x < control.in"]
with open(file_name_sh, "w") as fh :
fh.writelines(text)
subprocess.call(["chmod", "754",file_name_sh], universal_newlines=True)
#fh.close;
return "run.sh"
##########################################################
def create_shforrunning(size =55, atom ="Au", path ="", cores = "16"):
file_name_out = atom + str(size) +".out"
file_name_sh = path + "/shforrunning.sh"
print("Creating :" + file_name_sh)
root_dir = os.path.dirname(os.path.abspath(__file__))
complete_dir = os.path.join(root_dir, path)
text = ["#!/bin/bash \n",
"mpirun -np " + str(cores)+ " aims.171221_1.scalapack.mpi.x < "+complete_dir +"/control.in > "+ complete_dir + "/" +file_name_out+"\n"]
with open(file_name_sh, "w") as fh:
fh.writelines(text)
fh.close()
subprocess.call(["chmod", "754",file_name_sh], universal_newlines=True)
return "shforrunning.sh"
def create_shforrunning_name(name="Name.out", path ="", cores = "16"):
file_name_out = name +".out"
file_name_sh = path + "/shforrunning.sh"
print("Creating :" + file_name_sh)
root_dir = os.path.dirname(os.path.abspath(__file__))
complete_dir = os.path.join(root_dir, path)
text = ["#!/bin/bash \n",
"mpirun -np " + str(cores)+ " aims.171221_1.scalapack.mpi.x < "+complete_dir +"/control.in > "+ complete_dir + "/" +file_name_out+"\n"]
with open(file_name_sh, "w") as fh:
fh.writelines(text)
fh.close()
subprocess.call(["chmod", "754",file_name_sh], universal_newlines=True)
return "shforrunning.sh"
def check_and_rename(file, add=0):
original_file = file
if add != 0:
split = file.split("_")
part_1 = split[0] + "_" + str(add)
file = "_".join([part_1, split[1]])
if not os.path.exists(file):
os.mkdir(file)
# save here
else:
check_and_rename(original_file, add= add + 1)
def create_control_in(path ="", vdw = False):
vdw_str =""
if vdw==True:
vdw_str='vdw_correction_hirshfeld'
text = [' # DFT details\n',
'xc pbe\n',
'{} \n'.format(vdw_str),
'spin collinear # non-collinear spin\n',
'relativistic atomic_zora scalar # basis set (used zora for single-point, atomic_zora for opt)\n',
'charge 0.\n',
'default_initial_moment 1\n',
'\n',
'# SCF CONVERGENCE\n',
'occupation_type gaussian 0.01 # this is required for metals\n',
'charge_mix_param 0.2\n',
'sc_accuracy_rho 1E-4\n',
'sc_accuracy_eev 5E-3\n',
'sc_accuracy_etot 5E-4\n',
'sc_iter_limit 1000\n',
'\n',
'# Relaxation\n',
'relax_geometry bfgs 5.e-2\n',
'hessian_to_restart_geometry .false.\n',
'write_restart_geometry .true.\n',
'\n',
'\n',
'################################################################################\n',
'#\n',
'# FHI-aims code project\n',
'# VB, Fritz-Haber Institut, 2009\n',
'#\n',
'# Suggested "light" defaults for Au atom (to be pasted into control.in file)\n',
'# Be sure to double-check any results obtained with these settings for post-processing,\n',
'# e.g., with the "tight" defaults and larger basis sets.\n',
'#\n',
'################################################################################\n',
' species Au\n',
'# global species definitions\n',
' nucleus 79\n',
' mass 196.966569\n',
'#\n',
' l_hartree 4\n',
'#\n',
' cut_pot 3.5 1.5 1.0\n',
' basis_dep_cutoff 1e-4\n',
'#\n',
' radial_base 73 5.0\n',
' radial_multiplier 1\n',
' angular_grids specified\n',
' division 0.5066 50\n',
' division 0.9861 110\n',
' division 1.2821 194\n',
' division 1.5344 302\n',
'# division 2.0427 434\n',
'# division 2.1690 590\n',
'# division 2.2710 770\n',
'# division 2.3066 974\n',
'# division 2.7597 1202\n',
'# outer_grid 974\n',
' outer_grid 302\n',
'################################################################################\n',
'#\n',
'# Definition of "minimal" basis\n',
'#\n',
'################################################################################\n',
'# valence basis states\n',
' valence 6 s 1.\n',
' valence 5 p 6.\n',
' valence 5 d 10.\n',
' valence 4 f 14.\n',
'# ion occupancy\n',
' ion_occ 6 s 0.\n',
' ion_occ 5 p 6.\n',
' ion_occ 5 d 9.\n',
' ion_occ 4 f 14.\n',
'################################################################################\n',
'#\n',
'# Suggested additional basis functions. For production calculations, \n',
'# uncomment them one after another (the most important basis functions are\n',
'# listed first).\n',
'#\n',
'# Constructed for dimers: 2.10, 2.45, 3.00, 4.00 AA\n',
'#\n',
'################################################################################\n',
'# "First tier" - max. impr. -161.60 meV, min. impr. -4.53 meV\n',
' ionic 6 p auto\n',
' hydro 4 f 7.4\n',
' ionic 6 s auto\n',
'# hydro 5 g 10\n',
'# hydro 6 h 12.8\n',
' hydro 3 d 2.5\n',
'# "Second tier" - max. impr. -2.46 meV, min. impr. -0.28 meV\n',
'# hydro 5 f 14.8\n',
'# hydro 4 d 3.9\n',
'# hydro 3 p 3.3\n',
'# hydro 1 s 0.45\n',
'# hydro 5 g 16.4\n',
'# hydro 6 h 13.6\n',
'# "Third tier" - max. impr. -0.49 meV, min. impr. -0.09 meV\n',
'# hydro 4 f 5.2\n',
'# hydro 4 d 5\n',
'# hydro 5 g 8\n',
'# hydro 5 p 8.2\n',
'# hydro 6 d 12.4\n',
'# hydro 6 s 14.8\n',
'# Further basis functions: -0.08 meV and below\n',
'# hydro 5 f 18.8\n',
'# hydro 5 g 20\n',
'# hydro 5 g 15.2']
file_controlin = path + "/control.in"
with open(file_controlin, "w") as fh:
fh.writelines(text)
fh.close()
subprocess.call(["chmod", "754",file_controlin], universal_newlines=True)
return "Done"
def get_hostname():
host = subprocess.check_output(["hostname"], universal_newlines=True)
print(" You're currently in %s"%host)
return host
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
def check_if_files_exists(path="", filename=""):
if os.path.isfile(filename):
print ("File exist")
else:
print ("File not exist")
def Cluster_size(N=55, R_ws=1.44):
##Revisar bibliografia de esto
dist_max = round(2 * R_ws* math.pow(int(N) , 1/3), 4)
print("For ", N , "atoms distance is : ", dist_max)
return dist_max
def Pool_size(N= 55):
##Revisar bibliografia de esto
pool = int(math.pow(int(N),2/3))
return pool
def Number_ofGenerations(N=55):
##Revisar bibliografia de esto
generations = int(math.pow(int(N),3/2))
return generations
def Convergence(path):
file = path+ "/geometry.in.next_step"
if not os.path.exists(file):
last_dir = str(path.split("/")[-1])
command = "rm -r " + last_dir
run_command = shlex.split(command)
subprocess.call(run_command, universal_newlines = True, shell = True)
return False
else:
return True
def create_files(Size = 55, Atom = "Au", Path ="", r_min = 2.0,r_max = 7,num_decimals =4,dist_min =2, dist_max =7,cores =16, vdw = False):
atom = Atom
size = Size
path = Path
dist_max = Cluster_size(Size, R_ws= 1.44)
#directory_name =create_directory(size, atom, path)
directory_name = create_folder(name=Atom+str(Size), path=path)
create_cluster(size, atom, path = directory_name, R_min = r_min,R_max = r_max,Num_decimals =num_decimals,Dist_min =dist_min, Dist_max =dist_max, cores=cores , vdw = vdw)
return directory_name
def check_convergence(filename="",path =""):
converged = False
energy = 0
path.replace("\n", "")
try :
grep_cmd ='grep "Total energy of the DFT / Hartree-Fock s.c.f. calculation" {}/{}'.format(path.replace("\n", ""), filename)
output =subprocess.check_output(grep_cmd,shell=True)
output_string=str(output)
vec1=output_string.split(" : ")
energy = float(vec1[1].split("eV")[0])
converged = True
except :
print("Cluster didn't converged")
command = "rm -r " + path
print("Run: " , command)
return converged, energy
def Proof_convergence(atom, size, complete_path):
converged = False
energy = 0
complete_path.replace("\n", "")
try :
#with cd(complete_path):
#grep_cmd =shlex.split('grep " Total energy of the DFT / Hartree-Fock s.c.f. calculation" {}/nohup.out'.format(directory_name))
grep_cmd ='grep "Total energy of the DFT / Hartree-Fock s.c.f. calculation" {}/{}{}.out'.format(complete_path.replace("\n", ""), atom, str(size))
#process =subprocess.run(grep_cmd,shell=True, check=True, universal_newlines=True,stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
#output = process.stdout
#print(output)
#ster = process.stderr
#print(ster)
output =subprocess.check_output(grep_cmd,shell=True)
output_string=str(output)
vec1=output_string.split(" : ")
energy = float(vec1[1].split("eV")[0])
converged = True
except :
print("Cluster didn't converged")
#last_dir = str(complete_path.split("/")[-1])
command = "rm -r " + complete_path
print("Run: " , command)
#run_command = shlex.split(command)
#subprocess.call(command, universal_newlines = True, shell = True)
return converged, energy
def print_wami():
process= subprocess.run(["pwd"], check=True, stdout=subprocess.PIPE, universal_newlines=True)
output = process.stdout
print("I am here :", output)
a_string = output.rstrip("\n")
return a_string
def create_pool(N= 55, atom = "Au", path = "", R_min = 2.0, Num_decimals =4, Dist_min= 2 ,generation =0, cores = 16, vdw = False):
pool_size = Pool_size(N)
dist = Cluster_size(N)
directories =[]
for x in range(pool_size):
directory= create_files(Size = N, Atom = atom, Path = path, r_min = R_min ,r_max = dist ,num_decimals =Num_decimals ,dist_min =Dist_min , dist_max =dist, vdw = vdw)
directories.append(directory)
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
print("\n directories : ")
#for x in directories:
# print(x , "\n ")
#time.sleep(20)
used_directories =[]
for x in directories:
path_dum = os.path.join(THIS_FOLDER, x)
dir_list = os.listdir(path_dum)
#print("Files and directories in '", path_dum, "' :", dir_list)
file_running = path_dum +'/shforrunning.sh'
if os.path.exists(file_running) == True:
#print("sh created")
used_directories.append(path_dum)
return used_directories
#########################################################Normalization
def Normalization(E_i, E_min, E_max):
p_i = (E_i - E_min)/(E_max - E_min)
return round(p_i,5)
def Normalize_energies(Energies):
E_max = max(Energies)
E_min = min(Energies)
Normalized_energies = [round((E_i - E_min)/(E_max - E_min),5) for E_i in Energies]
return Normalized_energies
####################################################### Fitness
def f_exp(alpha, p_i):
f_i =math.pow(math.e, -alpha* p_i)
return round(f_i,5)
def f_tanh( p_i):
f_i = (1/2)*(1-math.tanh(2*p_i -1))
return round(f_i, 5)
def f_lin(p_i,b =0.7 ):
f_i = 1- b*p_i
return round(f_i,5)
def calculate_fitness(Normalized_energies,func = "tanh", alpha = 1):
fitnessed_energies =[]
if func == "tanh":
fitnessed_energies = [ f_tanh(e_i) for e_i in Normalized_energies ]
elif func == "exp":
fitnessed_energies = [ f_exp(alpha,e_i) for e_i in Normalized_energies ]
elif func == "lin":
fitnessed_energies = [ f_lin(e_i, alpha) for e_i in Normalized_energies ]
else:
print("Undefined fitness function using tanh")
fitnessed_energies = [ f_tanh(e_i) for e_i in Normalized_energies ]
return fitnessed_energies
##################################################### Probability
#### p_i = f_i /sum(f_i)
###1 == sum(p_i)
##### random
def probability_i(fitnessed):
sum_fit = sum(fitnessed)
p =[round((p_i/sum_fit),5) for p_i in fitnessed]
return p
def selection_energy(Energies, Probabilities ):
energies_rand= random.choices(Energies,weights =Probabilities)
return energies_rand
def select_mutate_or_mate(percentage_of_mating):
float_mating = percentage_of_mating /100
random_number = random.random()
response =""
if random_number <= float_mating:
response ="Mate"
else:
response ="Mutate"
return response
########################################################## code for Mutate
def kick_atom(atom,r_min=0, r_max=1):
x_i = atom[0]
y_i = atom[1]
z_i= atom[2]
theta = random.uniform(0, 2 * math.pi)
phi = random.uniform(0, 2 * math.pi)
r = random.uniform(r_min,r_max)
resize = 0.8
x =round(resize*(r * math.cos(theta) * math.sin(phi)) +x_i,5)
y =round(resize*(r * math.sin(theta) * math.sin(phi)) + y_i,5)
z =round(resize*(r * math.cos(phi)) + z_i,5)
vector = [x,y,z]
return vector
def recenter_cluster(filename = ""):
matriz = read_geometry_nextstep(filename=filename)
center_monoatomic = [round(sum([float(x[i]) for x in matriz])/(len(matriz)),4) for i in range(3)]
recentered_matrix_num = [[round(float(x[i]) - center_monoatomic[i],4)for i in range(3)] for x in matriz]
recentered_matrix = [[str(recentered_matrix_num[i][0]),str(recentered_matrix_num[i][1]),str(recentered_matrix_num[i][2]),matriz[i][3]] for i in range(len(matriz))]
return recentered_matrix
def read_geometry_nextstep(filename=""):
matriz=[]
lineas =[]
with open(filename, "r") as fh:
lineas = fh.readlines()
fh.close()
lineas_utiles= lineas[5:]
for i in range(len(lineas_utiles)):
atomo=lineas_utiles[i].replace("atom", "").replace("\n","").split(" ")
str_list = list(filter(None, atomo))
matriz.append(str_list)
return matriz
def kick(filename = ""):
lineas= recenter_cluster(filename=filename)
coord_txt = [linea[:-1] for linea in lineas]
atom_list = [linea[-1] for linea in lineas]
coordenadas= [[float(texto) for texto in linea] for linea in coord_txt]
nuevas_coordenadas =[kick_atom(coordenada) for coordenada in coordenadas]
[nuevas_coordenadas[i].append(atom_list[i]) for i in range(len(atom_list))]
return nuevas_coordenadas
def kick_mutation(filename_mutated = "geometry.in", path="", original_file=""):
print("path:",path,"file",original_file, "filename_mutated", filename_mutated)
matrix_used= kick(filename = original_file)
print_matrix_geometryin(matrix= matrix_used, name=filename_mutated, path=path)
def choose_mutation(mutation ="",filename_mutated = "geometry.in", path="", original_file=""):
if mutation =="kick":
kick_mutation(filename_mutated = filename_mutated, path=path, original_file=original_file)
def create_files_mutation(size=52, atom="",path ="",cores =16, vdw= False):
create_control_in(path =path, vdw=vdw)
create_shforrunning_name(name=atom+ str(size), path=path ,cores =cores)
#################################################### code for rotations
def rotate_over_z(point,angle):
if angle == 0:
new_point = point
else:
psi = angle
qx = math.cos(psi) * point[0] - math.sin(psi) * point[1]
qy = math.sin(psi) * point[0] + math.cos(psi) * point[1]
qz = point[2]
new_point= [qx,qy,qz]
return new_point
def rotate_over_x(point,angle):
if angle == 0:
new_point = point
else:
phi= angle
qx = point[0]
qy = math.cos(phi) * point[1] - math.sin(phi) * point[2]
qz = math.sin(phi) * point[1] + math.cos(phi) * point[2]
new_point= [qx,qy,qz]
return new_point
def rotate_over_y(point,angle):
if angle == 0:
new_point = point
else:
theta =angle
qx = math.cos(theta) * point[0] + math.sin(theta) * point[2]
qz = -math.sin(theta) * point[0] + math.cos(theta) * point[2]
qy = point[1]
new_point= [qx,qy,qz]
return new_point
def choose_rotations(number_of_rotations =2):
list_of_rotations= list(range(3))
choices_of_rotations = random.sample(list_of_rotations,number_of_rotations)
#print(choices_of_rotations)
#angle 1 is over x , angle 2 is over y and angle3 is over z
if 0 in choices_of_rotations:
angle1 = random.uniform(0, 2 * math.pi)
else:
angle1 = 0
if 1 in choices_of_rotations:
angle2 = random.uniform(0, 2 * math.pi)
else:
angle2 =0
if 2 in choices_of_rotations:
angle3= random.uniform(0, 2 * math.pi)
else:
angle3 =0
angles=[angle1, angle2, angle3]
return angles
def rotate_overxyz(point ,angles):
point_x = rotate_over_x(point, angles[0])
point_y= rotate_over_y(point_x, angles[1])
point_z = rotate_over_z(point_y,angles[2])
return point_z
def radius(point):
r = math.sqrt(point[0]**2 + point[1]**2 + point[2]**2)
return r
def rotate_matrix_over_xyz(matrix):
angles_for_rotation = choose_rotations(number_of_rotations=2)
print(angles_for_rotation)
matrix_rotated=[]
for point_str in matrix:
point = []
for i in range(3):
point.append(float(point_str[i]))
vector = rotate_overxyz(point, angles=angles_for_rotation)
vector_str=[ str(round(x,4)) for x in vector]
vector_str.append(point_str[3])
matrix_rotated.append(vector_str)
return matrix_rotated
#### 3 angle rotation must be applied AzAyAx to preserve orientation
################################################################# code for Mating
def order_matrix(matrix):
order_z = [x[2] for x in matrix]
order_z.sort(reverse = True)
ordered_matrix=[]
for order_i in order_z:
#print(order_i)
for x in matrix:
if order_i == x[2]:
ordered_matrix.append(x)
return ordered_matrix
def cut_n_splice(matrix1, matrix2, percentage_cut):
if len(matrix1) == len(matrix2) and len(matrix1[0])== len(matrix2[0]):
size_of_cut_int_1= int(round(len(matrix1)*(percentage_cut/100),0))
print("size1",size_of_cut_int_1)
size_of_cut_int_2 = len(matrix1)-size_of_cut_int_1
print("size2",size_of_cut_int_2)
new_matrix =[]
for i in range(size_of_cut_int_1):
new_matrix.append(matrix1[i])
for j in range(size_of_cut_int_2):
new_matrix.append(matrix2[j+ size_of_cut_int_1])
return new_matrix;
def Mating( file1 , file2, percentage_cut=50, filename_mated="", path=""):
matrix= recenter_cluster(file1)
matrix2= recenter_cluster(file2)
rotated_matrix = rotate_matrix_over_xyz(matrix)
rotated_matrix_2 = rotate_matrix_over_xyz(matrix2)
ordered_matrix = order_matrix(rotated_matrix)
ordered_matrix_2 = order_matrix(rotated_matrix_2)
new_matrix = cut_n_splice(ordered_matrix, ordered_matrix_2, percentage_cut = percentage_cut)
print_matrix_geometryin(matrix= new_matrix, name=filename_mated, path=path)
########################################################################
def create_py(size=55, atom="Au", path="", cores =16, vdw= False):
today = datetime.datetime.now()
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
file_name_out = path +"/"+ "run_"+atom + str(size) +".py"
text=["#this will create the python file to run \n",
"#Ga generated BY Rodrigo Espinola \n",
"#created on {} \n".format(today),
"import sys\n",
"sys.path.append('{}')\n".format(THIS_FOLDER),
'import atompacking_functions as af \n',
'print("running python for run dirs ") \n'
'af.run_dirs("{}/{}") \n'.format(THIS_FOLDER, path),
'af.complete_cicle_ga(file_dirs ="{}/{}/file_dirs.txt", Atom = "{}", Size = {}, path = "{}", cores ={},percentage_of_mating=80, vdw= {}) \n'.format(THIS_FOLDER, path,atom,size,path,cores, vdw )
]
with open(file_name_out, "w") as fh:
fh.writelines(text)
fh.close()
subprocess.call(["chmod", "754",file_name_out], universal_newlines=True)
def create_reinit_py(size=55, atom="Au", path="", cores =16, data_last_step="", file_energies="", vdw = False):
today = datetime.datetime.now()
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
file_name_out = path +"/"+ "rerun_"+atom + str(size) +".py"
text=["#this will create the python file to run \n",
"#Ga generated BY Rodrigo Espinola \n",
"#created on {} \n".format(today),
"import sys\n",
"sys.path.append('{}')\n".format(THIS_FOLDER),
'import atompacking_functions as af \n',
'af.reinit_cicle_ga(file_dirs ="{}/{}/file_dirs.txt",data_last_step="{}", file_energies="{}", Atom = "{}", Size = {}, path = "{}", cores ={},percentage_of_mating=80, vdw= {}) \n'.format(THIS_FOLDER, path,data_last_step, file_energies,atom,size,path,cores, vdw )
]
with open(file_name_out, "w") as fh:
fh.writelines(text)
fh.close()
subprocess.call(["chmod", "754",file_name_out], universal_newlines=True)
def create_qsub_init(size =55, atom ="Au", path ="", cores ="16", node= "g1", queue = "q_residual"):
#queue = "q_residual"
file_name_sh = path+"/" + "qsub_fhi.sh"
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
complete_path = os.path.join(THIS_FOLDER,path)
text = ["#!/bin/bash \n",
#'''#BSUB -R "same[model] span[ptile='!',Intel_EM64T:16,Intel_a:20,Intel_b:20,Intel_c:32,Intel_d:32]" \n''',
"#BSUB -q {} \n".format(queue),
"#BSUB -oo fhi-aims.%J.o \n",
"#BSUB -eo fhi-aims.%J.e \n",
# num cores
"#BSUB -n {} \n".format(cores),
#nodos
'#BSUB -m "{}"\n'.format(node),
"module purge \n",
"module load use.own\n",
"module load fhi-aims/1\n",
"module load mpi/intel-2017_update3 \n",
"module load python/3.7.6 \n",
"python3 {}/run_{}.py \n".format(complete_path,atom + str(size))]
#"mpirun aims.171221_1.scalapack.mpi.x < control.in > " + file_name_out]
with open(file_name_sh, "w") as fh:
fh.writelines(text)
subprocess.call(["chmod", "777",file_name_sh], universal_newlines=True)
return file_name_sh
def create_qsub_reinit(size =55, atom ="Au", path ="", cores ="16", node= "g1", queue = "q_residual"):
file_name_sh = path+"/" + "qsub_fhi_rerun.sh"
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
complete_path = os.path.join(THIS_FOLDER,path)
queue = "q_residual"
text = ["#!/bin/bash \n",
#'''#BSUB -R "same[model] span[ptile='!',Intel_EM64T:16,Intel_a:20,Intel_b:20,Intel_c:32,Intel_d:32]" \n''',
"#BSUB -q {} \n".format(queue),
"#BSUB -oo fhi-aims.%J.o \n",
"#BSUB -eo fhi-aims.%J.e \n",
# num cores
"#BSUB -n {} \n".format(cores),
#nodos
'#BSUB -m "{}"\n'.format(node),
"module purge \n",
"module load use.own\n",
"module load fhi-aims/1\n",
"module load mpi/intel-2017_update3 \n",
"module load python/3.7.6 \n",
"python3 {}/rerun_{}.py \n".format(complete_path,atom + str(size))]
#"mpirun aims.171221_1.scalapack.mpi.x < control.in > " + file_name_out]
with open(file_name_sh, "w") as fh:
fh.writelines(text)
subprocess.call(["chmod", "777",file_name_sh], universal_newlines=True)
return file_name_sh
def run_calc(filename):
host =get_hostname()
if host == "basie":
run_raw = "./" + filename
else:
run_raw = "bsub < " + filename
#subprocess.call(run_raw,universal_newlines = True, shell = True)
process= subprocess.run(run_raw, check=True, stdout=subprocess.PIPE, universal_newlines=True)
output = process.stdout
print("Output", output)
def init_calc(Size =55, Atom ="Au", Path ="", Cores ="16", Node= "g1", queue = "q_residual"):
Path = create_folder(name=Atom+str(Size), path= Path)
#create_init_py(size=Size, atom=Atom, path=Path, cores =int(Cores))
file_bsub = create_qsub_init(size=Size, atom=Atom,path=Path,cores=Cores, node=Node,queue=queue)
print("file bsub:", file_bsub)
run_calc(file_bsub)
def create_folder( name ="Au_6", path ="", add =0):
count = add
original_name = name
original_path = path
directory_name =original_name
directory_path = original_path +"/"+ directory_name
answer = "not changing answer"
if count != 0:
directory_path = original_path+"/" + directory_name + "_" + str(count)
answer = directory_path
if not os.path.exists(directory_path):
os.mkdir(directory_path)
answer = directory_path
else:
directory_path=create_folder( original_name, original_path, count +1)
answer = directory_path
return answer
def create_all_files(Size =55, Atom ="Au", Path ="", Cores ="16", Node= "g1", queue = "q_residual", vdw = False):
path_master = create_folder(name=Atom+str(Size), path= Path)
print("Path :", path_master)
dirs = create_pool(N= Size, atom = Atom, path =path_master, R_min = 2.0, Num_decimals =4, Dist_min= 2 ,generation =0, cores = int(Cores), vdw = vdw)
print("Creating : file of directories" )
file_dirs= path_master + "/file_dirs.txt"
with open(file_dirs, "w") as fh:
for x in dirs:
fh.write(x + "\n")
fh.close()
create_py(size=Size, atom=Atom, path=path_master, cores =int(Cores))
file_bsub = create_qsub_init(size=Size, atom=Atom,path=path_master,cores=Cores, node=Node, queue=queue)
print("For running write: bsub < ", file_bsub)
return file_dirs
def create_all_files_reinit(Size =55, Atom ="Au", path_master ="", Cores ="16", Node= "g1", queue = "q_residual", data_last_step="",file_energies="", vdw = False):
create_reinit_py(size=Size, atom=Atom, path=path_master, cores =int(Cores),data_last_step=data_last_step, file_energies=file_energies, vdw = False)
file_bsub = create_qsub_reinit(size=Size, atom=Atom,path=path_master,cores=Cores, node=Node, queue = queue)
print("For running write: bsub < ", file_bsub)
return None
def append_file(text_to_append="", file_to_append=""):
with open(file_to_append, "a") as fh:
fh.write(text_to_append + "\n")
fh.close()
def read_files(file_dirs):
with open(file_dirs, "r") as fh:
directories = fh.readlines()
fh.close()
return directories
def check_convergence_pool_first_step( file_dirs ="", Atom = "Au", Size = 52, path ="",cores= 16 ):
name = Atom + str(Size)
directories = read_files(file_dirs)
Energies =[]
Converged = []
Normalized_energies =[]
for x in directories:
#print("currently in ", x)
converged = False
energy =0