-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathplotband.py
executable file
·343 lines (257 loc) · 10.6 KB
/
plotband.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
#!/usr/bin/env python
#
# plotband.py
#
# Simple script to visualize phonon dispersion relations
#
# Copyright (c) 2014 Terumasa Tadano
#
# This file is distributed under the terms of the MIT license.
# Please see the file 'LICENCE.txt' in the root directory
# or http://opensource.org/licenses/mit-license.php for information.
#
import numpy as np
import optparse
import matplotlib as mpl
import mpl_toolkits
from matplotlib.gridspec import GridSpec
try:
mpl.use("Qt5agg")
except:
pass
import matplotlib.pyplot as plt
# parser options
usage = "usage: %prog [options] file1.bands file2.bands ... "
parser = optparse.OptionParser(usage=usage)
parser.add_option("--nokey", action="store_false", dest="print_key", default=True,
help="don't print the key in the figure")
parser.add_option("-u", "--unit", action="store", type="string", dest="unitname", default="kayser",
help="print the band dispersion in units of UNIT. Available options are kayser, meV, and THz", metavar="UNIT")
parser.add_option("--emin", action="store", type="float", dest="emin",
help="minimum value of the energy axis")
parser.add_option("--emax", action="store", type="float", dest="emax",
help="maximum value of the energy axis")
parser.add_option("--normalize", action="store_true", dest="normalize_xaxis", default=False,
help="normalize the x axis to unity.")
# font styles
mpl.rc('font', **{'family': 'Times New Roman', 'sans-serif': ['Helvetica']})
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=16)
mpl.rc('axes', labelsize=16)
mpl.rc('lines', linewidth=1.5)
mpl.rc('legend', fontsize='small')
# line colors and styles
color = ['b', 'g', 'r', 'm', 'k', 'c', 'y', 'r']
lsty = ['-', '-', '-', '-', '--', '--', '--', '--']
bn = [0, 300, 400]
def get_kpath_and_kval(file_in):
ftmp = open(file_in, 'r')
kpath = ftmp.readline().rstrip('\n').split()
kval = ftmp.readline().rstrip('\n').split()
ftmp.close()
if kpath[0] == '#' and kval[0] == '#':
kval_float = [float(val) for val in kval[1:]]
kpath_list = []
for i in range(len(kpath[1:])):
if kpath[i + 1] == 'G':
kpath_list.append('$\Gamma$')
else:
kpath_list.append("$\mathrm{%s}$" % kpath[i + 1])
return kpath_list, kval_float
else:
return [], []
def change_scale(array, str_scale):
str_tmp = str_scale.lower()
if str_tmp == 'kayser':
print("Band structure will be shown in units of cm^{-1}")
return array
elif str_tmp == 'mev':
print("Band structure will be shown in units of meV")
kayser_to_mev = 0.0299792458 * 1.0e+12 * \
6.62606896e-34 / 1.602176565e-19 * 1000
for i in range(len(array)):
for j in range(len(array[i])):
for k in range(1, len(array[i][j])):
array[i][j][k] *= kayser_to_mev
return array
elif str_tmp == 'thz':
print("Band structure will be shown in units of THz")
kayser_to_thz = 0.0299792458
for i in range(len(array)):
for j in range(len(array[i])):
for k in range(1, len(array[i][j])):
array[i][j][k] *= kayser_to_thz
return array
else:
print("Unrecognizable option for --unit %s" % str_scale)
print("Band structure will be shown in units of cm^{-1}")
return array
def normalize_to_unity(array, array_axis):
for i in range(len(array)):
max_val = array[i][-1][0]
factor_normalize = 1.0 / max_val
for j in range(len(array[i])):
array[i][j][0] *= factor_normalize
max_val = array_axis[-1]
factor_normalize = 1.0 / max_val
for i in range(len(array_axis)):
array_axis[i] *= factor_normalize
return array, array_axis
def get_xy_minmax(array):
xmin, xmax, ymin, ymax = [0, 0, 0, 0]
for i in range(len(array)):
xtmp = array[i][-1][0]
xmax = max(xmax, xtmp)
for i in range(len(array)):
for j in range(len(array[i])):
for k in range(1, len(array[i][j])):
ytmp = array[i][j][k]
ymin = min(ymin, ytmp)
ymax = max(ymax, ytmp)
return xmin, xmax, ymin, ymax
def gridspec_setup(data_merged, xtickslabels, xticksvars):
xmaxs = []
xmins = []
xticks_grids = []
xticklabels_grids = []
xticklabels_tmp = []
xticks_tmp = []
for i in range(len(xtickslabels)):
if i == 0:
xmins.append(xticksvars[0])
else:
if xticksvars[i] == xticksvars[i-1]:
xmaxs.append(xticksvars[i - 1])
xmins.append(xticksvars[i])
xticks_grids.append(xticks_tmp)
xticklabels_grids.append(xticklabels_tmp)
xticklabels_tmp = []
xticks_tmp = []
xticklabels_tmp.append(xtickslabels[i])
xticks_tmp.append(xticksvars[i])
xticks_grids.append(xticks_tmp)
xticklabels_grids.append(xticklabels_tmp)
xmaxs.append(xticksvars[-1])
naxes = len(xticks_grids)
nfiles = len(data_merged)
data_all_axes = []
for i in range(naxes):
data_ax = []
xmin_ax = xmins[i]
xmax_ax = xmaxs[i]
for j in range(nfiles):
kval = np.array(data_merged[j][0:, 0])
ix_xmin_arr = np.where(kval <= xmin_ax)
ix_xmax_arr = np.where(kval >= xmax_ax)
if len(ix_xmin_arr[0]) > 0:
ix_xmin = int(ix_xmin_arr[0][-1])
else:
ix_xmin = 0
if len(ix_xmax_arr[0]) > 0:
ix_xmax = int(ix_xmax_arr[0][0])
else:
ix_xmax = -2
data_ax.append(data_merged[j][ix_xmin:(ix_xmax+1), :])
data_all_axes.append(data_ax)
return naxes, xticks_grids, xticklabels_grids, xmins, xmaxs, data_all_axes
def preprocess_data(files, unitname, normalize_xaxis):
xtickslabels, xticksvars = get_kpath_and_kval(files[0])
data_merged = []
for file in files:
data_tmp = np.loadtxt(file, dtype=float)
data_merged.append(data_tmp)
data_merged = change_scale(data_merged, unitname)
if normalize_xaxis:
data_merged, xticksvars = normalize_to_unity(data_merged, xticksvars)
xmin, xmax, ymin, ymax = get_xy_minmax(data_merged)
if options.emin is None and options.emax is None:
factor = 1.05
ymin *= factor
ymax *= factor
else:
if options.emin is not None:
ymin = options.emin
if options.emax is not None:
ymax = options.emax
if ymin > ymax:
print("Warning: emin > emax")
naxes, xticks_grids, xticklabels_grids, xmins, xmaxs, data_merged_grids \
= gridspec_setup(data_merged, xtickslabels, xticksvars)
return naxes, xticks_grids, xticklabels_grids, \
xmins, xmaxs, ymin, ymax, data_merged_grids
def run_plot(nax, xticks_ax, xticklabels_ax, xmin_ax, xmax_ax, ymin, ymax, data_merged_ax):
fig = plt.figure()
width_ratios = []
used_colors = []
for xmin, xmax in zip(xmin_ax, xmax_ax):
width_ratios.append(xmax - xmin)
gs = GridSpec(nrows=1, ncols=nax, width_ratios=width_ratios)
gs.update(wspace=0.1)
for iax in range(nax):
ax = plt.subplot(gs[iax])
for i in range(len(data_merged_ax[iax])):
if len(data_merged_ax[iax][i]) > 0:
ax.plot(data_merged_ax[iax][i][0:, 0], data_merged_ax[iax][i][0:, 1],
linestyle=lsty[i], color=color[i], label=files[i])
used_colors.append(color[i])
for j in range(2, len(data_merged_ax[iax][i][0][0:])):
ax.plot(data_merged_ax[iax][i][0:, 0], data_merged_ax[iax][i][0:, j],
linestyle=lsty[i], color=color[i])
# # ax_0 = plt.subplot(gs[0,:])
# # ax_0.set_axis_off()
# cmp = mpl.colors.ListedColormap(used_colors)
# norm = mpl.colors.BoundaryNorm(boundaries=bn, ncolors=cmp.N)
# #fig.subplots_adjust(top=0.9)
#
# p0 = ax.get_position().get_points().flatten()
# # l, b, w = [0.15, 0.92, 0.7]
# # cax = fig.add_axes([0.15, 0.9, 0.2, 0.05])
# # cax = fig.add_axes([p0[0], 1, p0[2]-p0[0], 0.05])
# # cb_ax = mpl_toolkits.axes_grid1.inset_locator.inset_axes(ax, loc=3)
# cb =fig.colorbar(mappable=mpl.cm.ScalarMappable(norm=norm, cmap=cmp), use_gridspec=False,
# ax=ax, orientation='horizontal',shrink=1, fraction=0.1, pad=0.1)
if iax == 0:
if options.unitname.lower() == "mev":
ax.set_ylabel("Frequency (meV)", labelpad=20)
elif options.unitname.lower() == "thz":
ax.set_ylabel("Frequency (THz)", labelpad=20)
else:
ax.set_ylabel("Frequency (cm${}^{-1}$)", labelpad=10)
else:
ax.set_yticklabels([])
ax.set_yticks([])
plt.axis([xmin_ax[iax], xmax_ax[iax], ymin, ymax])
ax.set_xticks(xticks_ax[iax])
ax.set_xticklabels(xticklabels_ax[iax])
ax.xaxis.grid(True, linestyle='-')
if options.print_key and iax == 0:
ax.legend(loc='best', prop={'size': 10})
plt.show()
if __name__ == '__main__':
'''
Simple script for visualizing phonon dispersion relations.
Usage:
$ python plot_band.py [options] file1.bands file2.bands ...
For details of available options, please type
$ python plot_band.py -h
'''
"""
Test arguments:
./BrCsSn/scfph/300/pc_disp.bands
./BrCsSn/scfph/400/pc_disp.bands
"""
fakeArgs = ['-u', 'Thz', './BrCsSn/phonons/pc_disp.bands', './Br3Ca1Cs1/phonons/pc_disp.bands',]
options, args = parser.parse_args(fakeArgs)
files = args[0:]
nfiles = len(files)
if nfiles == 0:
print("Usage: plotband.py [options] file1.bands file2.bands ...")
print("For details of available options, please type\n$ python plotband.py -h")
exit(1)
else:
print("Number of files = %d" % nfiles)
nax, xticks_ax, xticklabels_ax, xmin_ax, xmax_ax, ymin, ymax, \
data_merged_ax = preprocess_data(
files, options.unitname, options.normalize_xaxis)
run_plot(nax, xticks_ax, xticklabels_ax,
xmin_ax, xmax_ax, ymin, ymax, data_merged_ax)