-
Notifications
You must be signed in to change notification settings - Fork 12
/
picture_functions.py
executable file
·1429 lines (989 loc) · 42 KB
/
picture_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
# -*- coding: utf-8 -*-
from __future__ import division, unicode_literals, absolute_import
import sys, os
import copy
# import header
# from operator import itemgetter
# from classes import res_loop , add_loop
# from pairs import
# from functions import image_distance, local_surrounding
# from chargeden.functions import chg_at_point, cal_chg_diff
# from dos.functions import plot_dos
# from ase.utils.eos import EquationOfState
import scipy
from scipy import interpolate
from scipy.interpolate import spline
# print (scipy.__version__)
# print (dir(interpolate))
try:
from scipy.interpolate import CubicSpline
except:
print('scipy.interpolate.CubicSpline is not avail')
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
try:
from adjustText import adjust_text
adjustText_installed = True
except:
adjustText_installed = False
import header
from header import print_and_log, printlog
from header import calc
from inout import write_xyz
from small_functions import makedir
from geo import replic
def plot_mep(atom_pos, mep_energies, image_name = None, filename = None, show = None, plot = 1, fitplot_args = None, style_dic = None):
"""
Used for NEB method
atom_pos (list) - xcart positions of diffusing atom along the path,
mep_energies (list) - full energies of the system corresponding to atom_pos
image_name - deprecated, use filename
style_dic - dictionary with styles
'p' - style of points
'l' - style of labels
'label' - label of points
plot - if plot or not
"""
from analysis import determine_barrier
if filename is None:
filename = image_name
#Create
if not style_dic:
style_dic = {'p':'ro', 'l':'b-', 'label':None}
if not fitplot_args:
fitplot_args = {}
atom_pos = np.array(atom_pos)
data = atom_pos.T #
tck, u= interpolate.splprep(data) #now we get all the knots and info about the interpolated spline
path = interpolate.splev(np.linspace(0,1,500), tck) #increase the resolution by increasing the spacing, 500 in this example
path = np.array(path)
diffs = np.diff(path.T, axis = 0)
path_length = np.linalg.norm( diffs, axis = 1).sum()
mep_pos = np.array([p*path_length for p in u])
if 0: #plot the path in 3d
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(data[0], data[1], data[2], label='originalpoints', lw =2, c='Dodgerblue')
ax.plot(path[0], path[1], path[2], label='fit', lw =2, c='red')
ax.legend()
plt.show()
# if '_mep' not in calc:
calc['_mep'] = [atom_pos, mep_energies] # just save in temp list to use the results in neb_wrapper
if hasattr(header, 'plot_mep_invert') and header.plot_mep_invert: # for vacancy
mep_energies = list(reversed(mep_energies) )
mine = min(mep_energies)
eners = np.array(mep_energies)-mine
xnew = np.linspace(0, path_length, 1000)
# ynew = spline(mep_pos, eners, xnew )
# spl = CubicSpline(mep_pos, eners, bc_type = 'natural' ) # second-derivative zero
# spl = CubicSpline(mep_pos, eners,) #
# spl = CubicSpline(mep_pos, eners, bc_type = 'periodic')
# spl = CubicSpline(mep_pos, eners, bc_type = 'clamped' ) #first derivative zero
spl = scipy.interpolate.PchipInterpolator(mep_pos, eners)
ynew = spl(xnew)
diff_barrier = determine_barrier(mep_pos, eners)
print_and_log('plot_mep(): Diffusion barrier =',round(diff_barrier, 2),' eV', imp = 'y')
# sys.exit()
# print()
path2saved = None
if plot:
# print(image_name)
path2saved = fit_and_plot(orig = (mep_pos, eners, style_dic['p'], style_dic['label']),
spline = (xnew, ynew, style_dic['l'], None),
xlim = (-0.05, None ),
xlabel = 'Reaction coordinate ($\AA$)', ylabel = 'Energy (eV)', image_name = image_name, filename = filename, show = show,
fig_format = 'eps', **fitplot_args)
# print(image_name, filename)
if 0:
with open(filename+'.txt', 'w') as f:
f.write('DFT points:\n')
for m, e in zip(mep_pos, eners):
f.write('{:10.5f}, {:10.5f} \n'.format(m, e))
f.write('Spline:\n')
for m, e in zip(xnew, ynew):
f.write('{:10.5f}, {:10.5f} \n'.format(m, e))
return path2saved, diff_barrier
def process_fig_filename(image_name, fig_format):
makedir(image_name)
if fig_format in image_name:
path2saved = str(image_name)
elif str(image_name).split('.')[-1] in ['eps', 'png', 'pdf']:
path2saved = str(image_name)
fig_format = str(image_name).split('.')[-1]
else:
path2saved = str(image_name)+'.'+fig_format
dirname = os.path.dirname(image_name)
if not dirname:
dirname+='.'
path2saved_png = dirname+'/png/'+os.path.basename(image_name)+'.png'
makedir(path2saved_png)
return path2saved, path2saved_png
def fit_and_plot(ax = None, power = None, xlabel = None, ylabel = None,
image_name = None, filename = None,
show = None, pad = None,
xlim = None, ylim = None, title = None, figsize = None,
xlog = False,ylog = False, scatter = False,
legend = False, ncol = 1,
fontsize = None, legend_fontsize=None, markersize = None,
linewidth = None, hor = False, fig_format = 'eps', dpi = 300,
ver_lines = None, xy_line = None, x_nbins = None,
alpha = 0.8, fill = False,
first = True, last = True,
convex = None, dashes = None,
corner_letter = None, hide_ylabels = None, hide_xlabels= None, annotate = None,
**data):
"""
Plot multiple plots on one axes using *data*
return filename of saved plot
ax (axes) - matplotlib axes object - to create multiple axes plots
data - each entry should be
(X, Y, fmt)
or
(X, Y, fmt, label)
or
{'x':,'y':, 'fmt':, 'label', 'xticks' } not implemented for powers and scatter yet
or
(X, Y, R, fmt) - for scatter = 1, R - size of spots
first, last - allows to call this function multiple times to put several plots on one axes. Use first = 1, last = 0 for the first plot, 0, 0 for intermidiate, and 0, 1 for last
power (int) - the power of polynom, turn on fitting
scatter (bool) - plot scatter points - the data format is slightly different - see *data*
convex (bool) - plot convex hull around points like in ATAT
fill (bool) - fill under the curves
filename (str) - name of file with figure, image_name - deprecated
fig_format (str) - format of saved file.
dpi - resolution of saved file
ver_lines - list of dic args for vertical lines {'x':, 'c', 'lw':, 'ls':}
hide_ylabels - just hide numbers
ncol - number of legend columns
corner_letter - letter in the corner of the plot
pad - additional padding, experimental
annotate - annotate each point, 'annotates' list should be in data dic!
linewidth - was 3 !
markersize - was 10
x_nbins - number of ticks
TODO:
remove some arguments that can be provided in data dict
"""
if image_name == None:
image_name = filename
if fontsize:
header.mpl.rcParams.update({'font.size': fontsize+4})
if legend_fontsize is None:
legend_fontsize = fontsize
header.mpl.rc('legend', fontsize= legend_fontsize)
if hasattr(header, 'first'):
first = header.first
if hasattr(header, 'last'):
last = header.last
# print('fit_and_plot, first and last', first, last)
if ax is None:
if first:
# fig, ax = plt.subplots(1,1,figsize=figsize)
plt.figure(figsize=figsize)
ax = plt.gca() # get current axes )))
# ax = fig.axes
if title:
ax.title(title)
# print(dir(plt))
# print(ax)
# plt.ylabel(ylabel, axes = ax)
# print(ylabel)
if ylabel != None:
ax.set_ylabel(ylabel)
if xlabel != None:
''
# plt.xlabel(xlabel, axes = ax)
ax.set_xlabel(xlabel)
if corner_letter:
# print(corner_letter)
sz = header.mpl.rcParams['font.size']
ax.text(0.05, 0.85, corner_letter, size = sz*1.5, transform=ax.transAxes) # transform = None - by default in data coordinates!
# text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
if convex:
from scipy.spatial import ConvexHull
for key in sorted(data):
if scatter:
ax.scatter(data[key][0], data[key][1], s = data[key][2], c = data[key][-1], alpha = alpha, label = key)
else:
con = data[key]
# print(con)
# sys.exit()
if type(con) == list or type(con) == tuple:
try:
label = con[3]
except:
label = key
try:
fmt = con[2]
except:
fmt = ''
xyf = [con[0], con[1], fmt]
con = {'label':label} #fmt -color style
elif type(con) == dict:
if 'fmt' not in con:
con['fmt'] = ''
# print(con)
if 'x' not in con:
l = len(con['y'])
con['x'] = list(range(l))
if 'xticks' in con:
# print(con['xticks'])
ax.set_xticklabels(con['xticks'])
ax.set_xticks(con['x'])
del con['xticks']
xyf = [con['x'], con['y'], con['fmt']]
# if 'lw' in
if linewidth:
con['lw'] = linewidth
# print(con)
# sys.exit()
if markersize:
con['ms'] = markersize
# print('key is ', key)
# print('x ', xyf[0])
con_other_args = copy.deepcopy(con)
for k in ['x', 'y', 'fmt', 'annotates']:
if k in con_other_args:
del con_other_args[k]
ax.plot(*xyf, alpha = alpha, **con_other_args)
if power:
coeffs1 = np.polyfit(xyf[0], xyf[1], power)
fit_func1 = np.poly1d(coeffs1)
x_range = np.linspace(min(xyf[0]), max(xyf[0]))
fit_y1 = fit_func1(x_range);
ax.plot(x_range, fit_y1, xyf[2][0], )
# x_min = fit_func2.deriv().r[power-2] #derivative of function and the second cooffecient is minimum value of x.
# y_min = fit_func2(x_min)
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(xyf[0], xyf[1])
print ('R^2 = {:5.2f} for {:s}'.format(r_value**2, key))
if annotate:
if adjustText_installed:
ts = []
for t, x, y in zip(con['annotates'], con['x'], con['y']):
ts.append(ax.text(x, y, t, size = 10, alpha = 0.5, color = con['fmt'][0]))
adjust_text(ts, ax = ax,
# force_points=10, force_text=10, force_objects = 0.5,
expand_text=(2, 2),
expand_points=(2, 2),
# lim = 150,
expand_align=(2, 2),
# expand_objects=(0, 0),
text_from_text=1, text_from_points=1,
# arrowprops=dict(arrowstyle='->', color='black')
)
else:
for name, x, y in zip(con['annotates'], con['x'], con['y']):
ax.annotate(name, xy=(x, y),
xytext=(-20, 20), fontsize = 9,
textcoords='offset points', ha='center', va='bottom',
# bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',
color='black'))
# print(key)
# print(con)
if fill:
''
ax.fill(xyf[0], xyf[1], facecolor = con['c'], alpha = 0.6)
if convex:
points = np.asarray(list(zip(xyf[0], xyf[1])))
hull = ConvexHull(points)
for simplex in hull.simplices:
if max(points[simplex, 1]) > 0:
continue
ax.plot(points[simplex, 0], points[simplex, 1], 'k-')
if hor:
ax.axhline(color = 'k') #horizontal line
ax.axvline(color='k') # vertical line at 0 always
if ver_lines:
for line in ver_lines:
ax.axvline(**line)
if xy_line:
ylim = ax.get_ylim()
# print(ylim)
x = np.linspace(*ylim)
# print(x)
ax.plot(x,x)
if x_nbins:
ax.locator_params(nbins=x_nbins, axis='x')
if xlim:
ax.set_xlim(xlim)
if ylim:
ax.set_ylim(ymin=ylim[0])
if ylim[1]:
ax.set_ylim(ymax=ylim[1])
if xlog:
ax.set_xscale('log')
if ylog:
if "sym" in str(ylog):
ax.set_yscale('symlog', linthreshx=0.1)
else:
ax.set_yscale('log')
if hide_ylabels:
ax.yaxis.set_major_formatter(plt.NullFormatter())
# ax.yaxis.set_ticklabels([])
if hide_xlabels:
ax.xaxis.set_major_formatter(plt.NullFormatter())
if legend:
scatterpoints = 1 # for legend
ax.legend(loc = legend, scatterpoints = scatterpoints, ncol = ncol)
# plt.legend()
# plt.tight_layout(pad = 2, h_pad = 0.5)
plt.tight_layout()
if pad:
plt.subplots_adjust(left=0.13, bottom=None, right=None, top=None,
wspace=0.07, hspace=None)
path2saved = ''
if last:
if image_name:
# plt.subplots_adjust(hspace=0.1)
path2saved, path2saved_png = process_fig_filename(image_name, fig_format)
plt.savefig(path2saved, dpi = dpi, format=fig_format)
plt.savefig(path2saved_png, dpi = 300)
print_and_log("Image saved to ", path2saved, imp = 'y')
elif show is None:
show = True
# print_and_log(show)
if show:
plt.show()
plt.clf()
plt.close('all')
else:
printlog('Attention! last = False, no figure is saved')
return path2saved
def plot_bar(xlabel = "xlabel", ylabel = "ylabel",
xlim = None, ylim = None,
image_name = None, title = None, bottom = 0.18, hspace = 0.15, barwidth = 0.2,
data1 = [],data2 = [],data3 = [],data4 = [],
**data):
width = barwidth # the width of the bars
if data:
N = len(data.values()[0][0])
key = data.keys()[0]
xlabels = data[key][0]
# print N
ind = np.arange(N) # the x locations for the groups
shift = 0
fig, ax = plt.subplots()
for key in sorted(data):
# print 'color', data[key][2]
ax.bar(ind+shift, data[key][1], width, color = data[key][2], label = data[key][-1])# yerr=menStd)
# print ind
shift+=width
elif data1 and data4:
fig = plt.figure(figsize=(10,5)) #5:7 ratio for A4,
gs = gridspec.GridSpec(2, 2,
width_ratios =[5,1],
height_ratios=[1,1]
)
gs.update(top=0.98, bottom=bottom, left=0.1, right=0.98, wspace=0.15, hspace=hspace)
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
ax4 = plt.subplot(gs[3])
# fig, ax = plt.subplots()
# fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col')#, sharey='row') equal
for ax, data in (ax1, data1), (ax2,data2), (ax3,data3), (ax4, data4):
N = len(data[0][0])
xlabels = data[0][0]
ind = np.arange(N) # the x locations for the groups
shift = 0
for d in data:
ax.bar(ind+shift, d[1], width, color = d[2], label = d[-1])# yerr=menStd)
# print ind
shift+=width
ax.axhline(y=0, color='black')
# ax.set_xticklabels(xlabels , rotation=70 )
ax.set_xticks(ind+width)
ax3.set_xticklabels(data3[0][0] , rotation=80 )
ax4.set_xticklabels(data4[0][0] , rotation=80 )
plt.setp(ax1.get_xticklabels(), visible=False)
plt.setp(ax2.get_xticklabels(), visible=False)
ax3.set_ylabel(ylabel)
ax3.yaxis.set_label_coords(-0.1, 1.1)
# plt.ylabel(ylabel)
ax1.legend(loc=2, )
ax3.legend(loc=2, )
# ax1.axis('tight')
# ax2.axis('tight')
# ax3.axis('tight')
# ax4.axis('tight')
ax1.margins(0.0, 0.2)
ax2.margins(0.0, 0.2)
ax3.margins(0.0, 0.2)
ax4.margins(0.0, 0.2)
elif data1 and data2 and not data4:
fig = plt.figure(figsize=(10,5)) #5:7 ratio for A4,
gs = gridspec.GridSpec(1, 2,
width_ratios =[5,1],
height_ratios=[1,0]
)
gs.update(top=0.95, bottom=bottom, left=0.1, right=0.98, wspace=0.15, hspace=hspace)
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
for ax, data in (ax1, data1), (ax2,data2):
N = len(data[0][0])
xlabels = data[0][0]
ind = np.arange(N) # the x locations for the groups
# print ind+width
# print data[0][0]
shift = 0.2
for d in data:
ax.bar(ind+shift, d[1], width, color = d[2], label = d[-1])# yerr=menStd)
# print ind
shift+=width
ax.axhline(y=0, color='black')
# ax.set_xticklabels(xlabels , rotation=70 )
ax.set_xticks(ind+width+len(data)*width/2)
names1 = [ n1 for n1, n2 in zip( data1[0][0], data1[1][0] ) ] #
names2 = [ n1 for n1, n2 in zip( data2[0][0], data2[1][0] ) ]
ax1.set_xticklabels( names1, rotation = 80 ) # Names of configurations on x axis
ax2.set_xticklabels( names2, rotation = 80 )
ax1.set_ylabel(ylabel)
ax1.legend(loc=2, )
ax1.axis('tight')
ax2.axis('tight')
elif data1 and not data2:
# fig = plt.figure(figsize=(10,5)) #5:7 ratio for A4,
gs = gridspec.GridSpec(1,2, width_ratios =[9,1],
height_ratios=[1,0])
gs.update(top=0.95, bottom=bottom, left=0.1, right=0.98, wspace=0.15, hspace=hspace)
ax1 = plt.subplot(gs[0])
# ax2 = plt.subplot(gs[1])
for ax, data in (ax1, data1),:
N = len(data[0][0])
xlabels = data[0][0]
ind = np.arange(N) # the x locations for the groups
# print ind+width
# print data[0][0]
shift = 0.2
for d in data:
ax.bar(ind+shift, d[1], width, color = d[2], label = d[-1])# yerr=menStd)
# print ind
shift+=width
ax.axhline(y=0, color='black')
# ax.set_xticklabels(xlabels , rotation=70 )
ax.set_xticks(ind+width+len(data)*width/2)
names1 = [ n1 + '; ' + n2 for n1, n2 in zip( data1[0][0], data1[1][0] ) ] #
ax1.set_xticklabels( names1, rotation = 80 ) # Names of configurations on x axis
ax1.set_ylabel(ylabel)
ax1.legend(loc=2, )
ax1.axis('tight')
# ax2.axis('tight')
# ax.set_yscale('log')
# plt.yscale('symlog', linthreshx=0.1)
# ax.set_title('Scores by group and gender')
def autolabel(rects):
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
ha='center', va='bottom')
# autolabel(rects1)
# autolabel(rects2)
# plt.axis('tight')
# plt.margins(0.05, 0)
# plt.tight_layout()
# elif data1: gs.tight_layout(fig)
if image_name:
print_and_log( "Saving image ...", str(image_name), imp = 'y')
plt.savefig(str(image_name)+'.png', dpi = 200, format='png')
else:
plt.show()
return
def plot_and_annotate(power = 2, xlabel = "xlabel", ylabel = "ylabel", image_name = None,
xlim = None, ylim = None, title = None, fit = None,
legend = None,
**data):
"""Should be used in two below sections!
Creates one plot with two dependecies and fit them;
return minimum fitted value of x2 and corresponding valume of y2;
if name == "" image will not be plotted
power - the power of polynom
data - each entry should be (X, Y, 'r-')
"""
# print data
# coeffs1 = np.polyfit(x1, y1, power)
# coeffs2 = np.polyfit(x2, y2, power)
# fit_func1 = np.poly1d(coeffs1)
# fit_func2 = np.poly1d(coeffs2)
#x_min = fit_func2.deriv().r[power-2] #derivative of function and the second cooffecient is minimum value of x.
#y_min = fit_func2(x_min)
if 1:
# x_range = np.linspace(min(x2), max(x2))
# fit_y1 = fit_func1(x_range);
# fit_y2 = fit_func2(x_range);
plt.figure()
if title: plt.title(title)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
for key in data:
plt.plot(data[key][0], data[key][1], data[key][-1], markersize = 15, label = key)
for x, y, name in zip(data[key][0], data[key][1], data[key][2]):
xytext = (-20,20)
if 'T1m' in name: xytext = (20,20)
plt.annotate(name, xy=(x, y), xytext=xytext,
textcoords='offset points', ha='center', va='bottom',
bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',
color='red'))
if fit:
for key in data:
f1 = interp1d(data[key][0], data[key][1], kind='cubic')
x = np.linspace(data[key][0][0], data[key][0][-1], 100)
plt.plot(x, f1(x), '-', label = key+'fit')
plt.axvline(color='k')
if xlim:
plt.xlim(xlim)
# axes = plt.gca()
# axes.set_xlim([xmin,xmax])
# axes.set_ylim([ymin,ymax])
if ylim:
plt.ylim(ymin=ylim[0])
if ylim[1]: plt.ylim(ymax=ylim[1])
# plt.plot(x2, y2, 'bo', label = 'r' )
# plt.plot(x_range, fit_y1, 'r-', label = 'init_fit')
# plt.plot(x_range, fit_y2, 'b-', label = 'r_fit' )
plt.tight_layout()
if legend: plt.legend(loc = 2)
if image_name:
# print "Saving image ..."
if not os.path.exists('images/'):
os.makedirs('images/')
plt.savefig(str(image_name)+'.png', dpi = 300, format='png')
plt.close()
else:
plt.show()
return
def plot_bar_simple(xlabel = "xlabel", ylabel = "ylabel",
xlim = None, ylim = None,
image_name = None, title = None,
data = []):
width = 0.6 # the width of the bars
plt.figure(figsize=(10,5)) #5:7 ratio for A4,
fig, ax = plt.subplots()
N = len(data[0])
xlabels = data[0]
# print xlabels
ind = np.arange(N) # the x locations for the groups
shift = 0
# for d in data:
d = data
# print d[2]
rects = ax.bar(ind+shift, d[1], width, color = d[2], label = d[-1],align="center" )# yerr=menStd)
rects[0].set_color('g')
rects[-1].set_color('g')
# rects[1].set_color('b')
# print ind
shift+=width
ax.axhline(y=0, color='black')
ax.set_xticks(ind)#+width)
ax.set_xticklabels(xlabels , rotation=50 )
ax.set_ylabel(ylabel)
handles, labels = ax.get_legend_handles_labels()
import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='red', label='Substitutional')
ax.legend(handles+[red_patch], labels+['Substitutional'], loc = 4)
# ax.legend(handles=[red_patch], loc = 8)
# ax.legend(loc=2, )
# ax.set_yscale('log')
# plt.yscale('symlog', linthreshx=0.1)
# ax.set_title('Scores by group and gender')
if xlim:
plt.xlim(xlim)
# axes = plt.gca()
# axes.set_xlim([xmin,xmax])
# axes.set_ylim([ymin,ymax])
if ylim:
plt.ylim(ymin=ylim[0])
if ylim[1]: plt.ylim(ymax=ylim[1])
def autolabel(rects):
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., -1.05*height, '%.0f'%float(height),
ha='center', va='top')
autolabel(rects)
# autolabel(rects2)
plt.tight_layout()
if image_name:
# print "Saving image ..."
if not os.path.exists('images/'):
os.makedirs('images/')
plt.savefig('images/'+str(image_name)+'.png', dpi = 200, format='png')
plt.close()
else:
plt.show()
return
def plot_conv(list_of_calculations = None, calc = None,
type_of_plot = None, conv_ext = [], labelnames = None, cl = None,
plot = 1, filename = None):
"""
Allows to fit and plot different properties;
Input:
'type_of_plot' - ("fit_gb_volume"-fits gb energies and volume and plot dependencies without relaxation and after it,
'dimer'
cl - calculation to use - new interface, please rewrite the old one
"""
def fit_and_plot(x1, y1, x2, y2, power, name = "", xlabel = "", ylabel = "", image_name = "test", lines = None):
"""Should be used in two below sections!
Creates one plot with two dependecies and fit them;
return minimum fitted value of x2 and corresponding valume of y2;
if name == "" image will not be plotted
power - the power of polynom
lines - add lines at x = 0 and y = 0
"""
coeffs1 = np.polyfit(x1, y1, power)
coeffs2 = np.polyfit(x2, y2, power)
fit_func1 = np.poly1d(coeffs1)
fit_func2 = np.poly1d(coeffs2)
#x_min = fit_func2.deriv().r[power-2] #derivative of function and the second cooffecient is minimum value of x.
#y_min = fit_func2(x_min)
if name:
x_range = np.linspace(min(x2), max(x2))
fit_y1 = fit_func1(x_range);
fit_y2 = fit_func2(x_range);
plt.figure(figsize=(8,6.1))
# plt.title(name)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.xlim(min(x2)-0.1*abs(min(x2) ), max(x2)+0.1*abs(min(x2)))
plt.plot(x1, y1, 'ro', label = 'initial')
plt.plot(x2, y2, 'bo', label = 'relaxed' )
plt.plot(x_range, fit_y1, 'r-',) #label = 'init_fit')
plt.plot(x_range, fit_y2, 'b-',) #label = 'r_fit' )
plt.legend(loc =9)
if lines == 'xy':
plt.axvline(color='k')
plt.axhline(color='k')
plt.tight_layout()
#plt.savefig('images/'+image_name)
file = header.path_to_images+'/'+str(image_name)+'.png'
makedir(file)
print_and_log( 'Saving file ...',file, imp = 'y' )
plt.savefig(file,format='png', dpi = 300)
return fit_func2
if list_of_calculations:
conv = list_of_calculations
n = conv[0]
name = [];
name.append( n[0] )
image_name = n[0]+'_'+n[1]+'_'+str(n[2])
energies = []; init_energies = []
volumes = []
gb_volumes = []
pressures = []
pressures_init = []
sigma_xx = []
sigma_yy = []
sigma_zz = []
e_gbs = []