-
Notifications
You must be signed in to change notification settings - Fork 0
/
Firefly_Al42-_nonplannar.py
214 lines (194 loc) · 5.93 KB
/
Firefly_Al42-_nonplannar.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
import threading
import numpy as np
import time
import os
import math
import os.path
charge=-2
spin=1
molname="Al"
numtimes=100
count=0
norm_energies=0
best_energy=0
num_calls=0
time_in_secs=time.time()
#Checks if the termination is normal(returns 1) or error(returns 2) or incomplete(returns 0)
def normal_term(file_to_open):
file=open(file_to_open,'r+')
X=file.readlines()
for i in range(len(X)):
Y=[]
Y=X[i].split(" ")
if len(Y)>=3 and Y[2]=="termination":
if Y[1]=='Normal':
file.close()
return 1
elif Y[1]=="Error":
file.close()
return 2
file.close()
return 0
#Returns the energy. Also appends the different values.
def energy(name,X,partnum):
file_to_open=name[:-3]+"log"
if(normal_term(file_to_open)==2):
return X
file=open(file_to_open,'r+')
Y=file.readlines()
for i in range(len(Y)):
Z=[]
Z=Y[i].split(" ")
for j in range(len(Z)):
if "E(" in Z[j]:
X=Z[j+3]
file.close()
lock.acquire()
valuesnow[partnum]=float(X)
global norm_energies
norm_energies +=1
lock.release()
return X
file.close()
#Creates the required gjf format with dynamic threads
def gjfconvert(X,iternum,partnum,threadnums,whereto):
molname="Al"
name="str"+str(partnum)+"__"+str(whereto)+"_"+str(iternum)+".gjf"
file=open(name,"w+")
file.write("%nprocshared="+str(int(30/threadnums))+"\n")
file.write("%mem=2GB\n")
file.write("%nosave\n")
file.write("# b3lyp/6-311+g*\n\n")#CCSD(T)/6-311g*
file.write("Al struct\n\n")
file.write(str(charge)+" "+str(spin)+"\n")
for i in range(int(len(X)/3)):
string=" "+molname+"\t\t\t\t\t"+str(round(X[i*3],8))+"\t"+str(round(X[i*3+1],8))+"\t"+str(round(X[i*3+2],8))+"\n"
file.write(string)
file.write("\n\n\n\n")
file.close()
return name
#Checks if the files are created or not and removes the gjf files
def function(position,iternum,partnum,threadnums,whereto):
name=gjfconvert(position,iternum,partnum,threadnums,whereto)
os.system("g09 "+name+" &")
#time.sleep(3)
while (os.path.isfile(name[:-3]+"log")) is False:
pass
while normal_term(name[:-3]+"log")==0:
pass
energy(name,valuesnow[partnum],partnum)
os.remove(name)
os.remove(name[:-3]+"log")
#hyperparameters
'''
num_feat=int(input("Enter the number of particles each cluster has:"))
num_units=int(input("Enter the number of particle clusters:"))
c1=float(input("Enter positional dependence:"))
c2=float(input("Enter global dependence:"))
n=int(input("Enter the number of times it will run:"))
'''
num_feat=4
num_units=4
c1=0.2
c2=0.9/12
a=0.1
p=0.97
n=1000
num_feat=3*num_feat
#initialisation
position=(np.random.random((num_units,num_feat))-0.5)*6
#Checks if any Present values are there. If present,it uses them
if(os.path.isfile("PresentValues.txt")):
position=position.reshape((-1,))
file=open("PresentValues.txt",'r+')
count=0
X=file.readlines()
for i in range(len(X)):
X[i]=X[i][:-1]
Y=X[i].split("\t")
for j in range(len(Y)):
try:
position[count]=float(Y[j])
count +=1
except:
pass
position=position.reshape((num_units,num_feat))
file.close()
best_individual=np.copy(position)
valuesnow=np.zeros((num_units,1),dtype=float)
#Creates the Threads
print("Iteration starts at "+time.ctime(time.time()))
t=[]
lock=threading.Lock()
for i in range(num_units):
t.append(threading.Thread(target=function,args=(position[i],0,i,num_units,i)))
t[i].start()
for i in range(num_units):
t[i].join()
best_pos=np.copy(position[np.argmin(valuesnow),:].reshape(1,num_feat))
temp=np.zeros((num_units,1),dtype=int)
indibestnow=np.copy(valuesnow)
best_energy=min(valuesnow)
#Creates a Folder to save the files
foldertosave="valueAl_"
u=0
while(os.path.exists(foldertosave+str(u))):
u =u+1
os.mkdir(foldertosave+str(u))
foldertosave="valueAl_"+str(u)
#Saves the values
k=0
init=open(foldertosave+"/initialvalues.txt","w")
for i in range(num_units):
init.write("\n\n"+str(i)+"\n")
for j in range(int(num_feat/3)):
init.write(" "+molname+"\t\t\t\t\t"+str(position[i][j*3])+"\t"+str(position[i][j*3+1])+"\t"+str(position[i][j*3+1])+"\t\n")
init.close()
count=0
#Creates the main part of Firefly
num_calls +=num_units
k=0
print("\n............\n.............\nThe best pos of iteration "+str(k) +"is:\n")
for i in range(int(num_feat/3)):
string=str(round(best_pos[0][i*3],8))+"\t"+str(round(best_pos[0][i*3+1],8))+"\t"+str(round(best_pos[0][i*3+2],8))+"\n"
print(string)
print("The best energy is"+str(min(valuesnow)))
print("\nThe time from start is: ")
print(time.time()-time_in_secs)
for k in range(1,n):
p=p*0.999
for i in range(num_units):
toedit=[]
for j in range(num_units):
if(valuesnow[i]<valuesnow[j]):
dist=np.dot((position[j]-position[i]).T,(position[j]-position[i]))
position[j]= position[j]+c1*(position[i]-position[j])*((math.e)**(-c2*dist))+0.1*(np.random.random((1,num_feat))-0.5)*p
toedit.append(j)
t=[]
num_calls +=len(toedit)
for j in range(len(toedit)):
t.append(threading.Thread(target=function,args=(position[toedit[j]],k,toedit[j],len(toedit),i)))
t[j].start()
for j in range(len(t)):
t[j].join()
best_pos=np.copy(best_individual[np.argmin(indibestnow),:].reshape(1,num_feat))
print("\n............\n.............\nThe best pos of iteration "+str(k) +" is:\n")
for i in range(int(num_feat/3)):
string=" Al\t\t\t\t"+str(round(best_pos[0][i*3],8))+"\t"+str(round(best_pos[0][i*3+1],8))+"\t"+str(round(best_pos[0][i*3+2],8))+"\n"
print(string)
print("The best energy is"+str(min(valuesnow)))
print("\nThe time from start is :")
print(time.time()-time_in_secs)
if(float(min(valuesnow))<(float(best_energy)-0.00001)):
count =0
best_energy=min(valuesnow)
else:
count +=1
if(count>=numtimes):
print("No improvement. Program closed.")
break
print("--------------\n------------------\nThe number of calls made is "+str(num_calls)+"\nThe number of normal termination is "+str(norm_energies))
os.system("mv output.txt "+foldertosave+"/output.txt")
time.sleep(3)
#uncomment to run again
os.system("nohup python -u FireflyAl.py &> output.txt &")