-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbipartite_calc.py
More file actions
executable file
·387 lines (309 loc) · 9.92 KB
/
bipartite_calc.py
File metadata and controls
executable file
·387 lines (309 loc) · 9.92 KB
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
import os, subprocess
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as mplcm
import itertools, re, glob
import time
pre_dup = input("Would you like to delete any duplicated aims structures? \
(type rank of aims (delimeter whitespace) : ")
if len(pre_dup) > 0:
pre_dup = pre_dup.split(',')
else:
pre_dup = []
radius = input("set hashkey radius (this can be vary depends on the size of clusters) : ")
#SIZE = input("What is the size of the cluster : ")
TOP_10 = input("Would you like to plot top 10 aims to klmc connection only ? (y or default n) : ")
yes = ['yes', 'y']
NUM_COLOURS = input("How many colour would you like to use? : (default 100) ")
start = time.time()
if len(str(NUM_COLOURS)) == 0:
NUM_COLOURS = 100
else:
NUM_COLOURS = int(NUM_COLOURS)
def get_dir(A='./'):
global dir_
try:
dir_ = [str(os.path.join(A, x)) for x in os.listdir(A) if os.path.isdir(os.path.join(A, x))]
dir_.sort()
except FileNotFoundError:
print("Probably you are in wrong directory to run the code")
return dir_
def get_files(A='./', B=''):
global files
files = [x for x in os.listdir(A) if B in x]
return(files)
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
return [ atoi(c) for c in re.split(r'(\d+)', text)]
###########
# hashkey #
###########
def get_xyz(A='./', B='.xyz'):
global xyz
xyz = [x for x in os.listdir(A) if B in x]
return xyz
#radius = input("set hashkey radius : ")
get_xyz('./xyzFiles')
xyz.sort()
pairing = [['./xyzFiles/' + xyz[i], './xyzFiles/' + xyz[i+1]] for i in range(0, len(xyz), 2)]
hkg_path = '/home/uccatka/software/hkg/hkg.py'
print()
print("----aims----")
aims = []
for i in pairing:
AIMS = subprocess.check_output(["python", hkg_path, i[0], radius])
AIMS = str(AIMS)
#AIMS = AIMS[2:-3]
print(i[0], AIMS)
aims.append(AIMS)
print()
with open('aims_hashkey.txt', 'w') as f:
for i in range(len(aims)):
f.write(aims[i]+'\n')
'''
print("----klmc----")
klmc = []
for j in pairing:
KLMC = subprocess.check_output(["python", hkg_path, j[0], radius])
KLMC = str(KLMC)
KLMC = KLMC[2:-3]
print(j[0], KLMC)
klmc.append(KLMC)
print()
'''
aims.append(pre_dup)
print("print aims")
aims = aims[:-1]
print(aims)
print(len(aims))
duplicates = list(set([x for x in aims if aims.count(x) > 1]))
Pairs = []
if len(duplicates) == 0:
print("There is no duplicated structures among the 'aims' set")
else:
print(f"Lists of duplicated structures :")
unique_pair = [(i+1, aims.index(aims[i])+1) for i in range(len(aims)) if not i == aims.index(aims[i])]
#dummy = [i+1 for i in range(len(aims)) if not i == aims.index(aims[i])]
#print("print dummy")
#print(dummy)
#print(len(dummy))
for num_el, el in enumerate(aims):
for num_a, a in enumerate(aims):
if el == a: # if hashkey is identical
if num_el != num_a: # elimininate the case that recognise the same
# ranked structure as duplicated case e.g. 1 = 1, 2 = 2
Pairs.append([num_a+1, num_el+1]) # paired as tuple
unique_pair = list(set((a,b) if a <= b else (b, a) for a, b in Pairs))
# sort as (lesser rank, higher rank)
unique_pair.sort(key=lambda x:x[0])
result = []
l = unique_pair
if len(l) > 1:
tmp = [l[0]]
for i in range(1,len(l)):
if l[i][0] == l[i-1][1] or l[i][1] == l[i-1][0] or l[i][1] == l[i-1][1] or l[i][0] == l[i-1][0]:
tmp.append(l[i])
else:
result.append(tmp)
tmp = [l[i]]
result.append(tmp)
else:
result = l
for elem in result:
print(elem)
print()
#############
# bipartite #
#############
get_dir('./ranked')
files_ = [get_files(x, 'aims.out') for x in dir_]
files_ = list(itertools.chain(*files_))
files_ = list(set(files_))
files_.sort(key=natural_keys)
frame_df = pd.DataFrame(columns={'aims_R','klmc_R', 'aims_E'})
range_ = [x for x in os.listdir('./xyzFiles/')]
range_ = list(set(x.split('_')[0] for x in range_))
for i in range_:
for j in files_:
aim = os.path.join(f'./ranked/{i}/{j}')
for name in glob.glob(aim):
with open(name) as f:
lines = f.readlines()
for line in lines:
if '| Total energy of the DFT / Hartree-Fock s.c.f. calculation :' in line:
aims_e = line.split(' ')[1]
aims_e = aims_e.split(' ')[0]
klmc_R = name.split('/')[2]
frame_df = frame_df.append({'klmc_R': int(klmc_R), 'aims_E':aims_e},
ignore_index=True)
frame_df = frame_df.sort_values(by=['aims_E'], ascending=False)
frame_df = frame_df.reset_index()
frame_df['aims_R'] = frame_df.index + 1
frame_df = frame_df.drop(columns=['index'])
frame_df = frame_df[['aims_E', 'aims_R', 'klmc_R']]
print("### After {aims} optimisation ###")
print(frame_df)
print()
frame_df.to_csv('for_bipartite.csv', index = False)
##########################
# unique structures only #
##########################
temp_df = frame_df
top_str = './xyzFiles/'
top_xyz = [ top_str + x for x in os.listdir(top_str) if 'klmc.xyz' in x]
top_xyz.sort()
K_energy = []
for x in top_xyz:
with open(x, 'r') as f:
for num, line in enumerate(f):
if num == 0:
k_energy = f.readline()
k_energy = k_energy.split()[2]
K_energy.append(k_energy)
temp_df = temp_df.sort_values(by=['klmc_R'], ascending=True)
temp_df['klmc_E'] = np.array(K_energy)
temp_df = temp_df.sort_values(by=['aims_R'], ascending=True)
temp_df = temp_df[['aims_R', 'aims_E', 'klmc_R', 'klmc_E']]
dummy = []
if len(result) == 1:
dummy.append(elem[1])
else:
for elem in result:
for a, b in elem:
dummy.append(b)
del_list = []
for index, row in temp_df.iterrows():
for e in dummy:
if e == row['aims_R']:
try:
del_list.append(e)
temp_df.drop(index, inplace = True)
except Exception:
pass
for i in del_list:
try:
temp_df.drop(index, inplace = True)
except Exception:
pass
temp_df.reset_index(drop=True, inplace=True)
temp_df.to_csv('unique_energy.csv', index = False)
#print("### duplicated {aims} rank ###")
#print(aims)
print("### Unique set ###")
print(len(list(set(del_list))), list(set(del_list)))
print()
print(temp_df)
######################
# Call the .csv file #
######################
# Generated from 'get_energy.py' (alias: rank (thomas))
data = './for_bipartite.csv'
####################
# Helper Functions #
####################
def addconnection(i,j,c):
return [((-1,1),(i,j),c)]
def drawnodes(s,i):
global ax
if(i==1): # right-hand side
color='g'
posx=1
elif (i==2):
color='b' # left-hand side
posx=-1
posy=0
for n in s:
plt.gca().add_patch(plt.Rectangle((posx,posy+0.85),width=0.02,height=0.3,fc=color)) # tick marks (patch)
###############################
# position of label of marker #
###############################
if posx==1:
if int(n) % 100 == 0:
ax.annotate(n,xy=(posx+0.08,posy+1)) # label of tick marks
elif posx==-1: # location of left-hand side
if int(n) % 100 == 0:
#ax.annotate(n,xy=(posx-len(n)*0.043,posy+1))
ax.annotate(n,xy=(posx-0.1, posy+1))
posy+=1
####################################################
fig = plt.figure(figsize=(30, 16)) #15, 8))
ax = fig.add_subplot(111)
ax.axis("off")
######################
# Actual rank data #
######################
df = pd.read_csv(data) #'aims_klmc.csv')
aims_rank = df['aims_R']
aims_max = np.array(aims_rank)
A = aims_rank
klmc_rank = df['klmc_R']
klmc_rank = np.array(klmc_rank)
K = klmc_rank
############
# MARKER #
############
klmc_order = range(1, len(klmc_rank)+1)
klmc_set=[]
for r in klmc_order:
klmc= f'{r}'
klmc_set.append(klmc)
aims_order = range(1, len(aims_rank)+1)
aims_set=[]
for r in aims_order:
aims = f'{r}'
aims_set.append(aims)
plt.axis([-1.5,1.5,-1,max(len(klmc_order),len(aims_order))+1])
frame=plt.gca()
frame.axes.get_xaxis().set_ticks([])
frame.axes.get_yaxis().set_ticks([])
drawnodes(klmc_set,1)
drawnodes(aims_set,2)
################################
# axis title position settings #
################################
ax.text(-1.3, 20, 'PBEsol\n rank', style='italic', fontsize = 15)
ax.text(1.2, 20, 'Shell model\n rank', style='italic', fontsize = 15)
#########################################
# concatenate aims rank and klmc rank #
#########################################
connections = []
for i, j in zip(A, K):
a = str(i) + ',' + str(j)
connections.append(a)
b = ','.join(connections)
c = b.split(',')
klmc_ = []
aims_ = []
for count, i in enumerate(c):
if (count % 2 != 0): # even numbered elements are the klmc rank
klmc_.append(i)
else:
aims_.append(i) # odd numbered elements are the aims rank
#########################################
# Drawing lines #
#########################################
cm = plt.get_cmap('gist_rainbow')
cNorm = colors.Normalize(vmin=0, vmax=NUM_COLOURS-1)
scalarMap = mplcm.ScalarMappable(norm=cNorm, cmap=cm)
connections = []
for count, i in enumerate(range(1,len(aims_rank)+1)):
elements = (-0.97, 0.99), (int(aims_[i-1]), int(klmc_[i-1]))
# position of right-end of the line
connections.append(elements)
for count, c in enumerate(connections):
fig = plt.plot(c[0],c[1]) #,c[2])
fig[0].set_color(cm(count//3*3.0/NUM_COLOURS))
if TOP_10 in yes:
if count == 9:
print(f"plot bipartite up to {count}")
break
else:
continue
file_name = os.getcwd().split('/')[-1]
#plt.show()
plt.savefig(f'{file_name}_RchangingAnalysis.pdf')
end = time.time()
print(f'\nTotal time: {end}')